repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
midjuly/cordova-plugin-iosrtc
refs/heads/master
src/PluginRTCPeerConnection.swift
mit
1
import Foundation class PluginRTCPeerConnection : NSObject, RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate { var rtcPeerConnectionFactory: RTCPeerConnectionFactory var rtcPeerConnection: RTCPeerConnection! var pluginRTCPeerConnectionConfig: PluginRTCPeerConnectionConfig var pluginRTCPeerConnectionConstraints: PluginRTCPeerConnectionConstraints // PluginRTCDataChannel dictionary. var pluginRTCDataChannels: [Int : PluginRTCDataChannel] = [:] var eventListener: (data: NSDictionary) -> Void var eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void var eventListenerForRemoveStream: (id: String) -> Void var onCreateDescriptionSuccessCallback: ((rtcSessionDescription: RTCSessionDescription) -> Void)! var onCreateDescriptionFailureCallback: ((error: NSError) -> Void)! var onSetDescriptionSuccessCallback: (() -> Void)! var onSetDescriptionFailureCallback: ((error: NSError) -> Void)! init( rtcPeerConnectionFactory: RTCPeerConnectionFactory, pcConfig: NSDictionary?, pcConstraints: NSDictionary?, eventListener: (data: NSDictionary) -> Void, eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void, eventListenerForRemoveStream: (id: String) -> Void ) { NSLog("PluginRTCPeerConnection#init()") self.rtcPeerConnectionFactory = rtcPeerConnectionFactory self.pluginRTCPeerConnectionConfig = PluginRTCPeerConnectionConfig(pcConfig: pcConfig) self.pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: pcConstraints) self.eventListener = eventListener self.eventListenerForAddStream = eventListenerForAddStream self.eventListenerForRemoveStream = eventListenerForRemoveStream } deinit { NSLog("PluginRTCPeerConnection#deinit()") } func run() { NSLog("PluginRTCPeerConnection#run()") self.rtcPeerConnection = self.rtcPeerConnectionFactory.peerConnectionWithICEServers( self.pluginRTCPeerConnectionConfig.getIceServers(), constraints: self.pluginRTCPeerConnectionConstraints.getConstraints(), delegate: self ) } func createOffer( options: NSDictionary?, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#createOffer()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options) self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in NSLog("PluginRTCPeerConnection#createOffer() | success callback [type:\(rtcSessionDescription.type)]") let data = [ "type": rtcSessionDescription.type, "sdp": rtcSessionDescription.description ] callback(data: data) } self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#createOffer() | failure callback: \(error)") errback(error: error) } self.rtcPeerConnection.createOfferWithDelegate(self, constraints: pluginRTCPeerConnectionConstraints.getConstraints()) } func createAnswer( options: NSDictionary?, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#createAnswer()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options) self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in NSLog("PluginRTCPeerConnection#createAnswer() | success callback [type:\(rtcSessionDescription.type)]") let data = [ "type": rtcSessionDescription.type, "sdp": rtcSessionDescription.description ] callback(data: data) } self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#createAnswer() | failure callback: \(error)") errback(error: error) } self.rtcPeerConnection.createAnswerWithDelegate(self, constraints: pluginRTCPeerConnectionConstraints.getConstraints()) } func setLocalDescription( desc: NSDictionary, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#setLocalDescription()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let type = desc.objectForKey("type") as? String ?? "" let sdp = desc.objectForKey("sdp") as? String ?? "" let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp) self.onSetDescriptionSuccessCallback = { () -> Void in NSLog("PluginRTCPeerConnection#setLocalDescription() | success callback") let data = [ "type": self.rtcPeerConnection.localDescription.type, "sdp": self.rtcPeerConnection.localDescription.description ] callback(data: data) } self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#setLocalDescription() | failure callback: \(error)") errback(error: error) } self.rtcPeerConnection.setLocalDescriptionWithDelegate(self, sessionDescription: rtcSessionDescription ) } func setRemoteDescription( desc: NSDictionary, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#setRemoteDescription()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let type = desc.objectForKey("type") as? String ?? "" let sdp = desc.objectForKey("sdp") as? String ?? "" let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp) self.onSetDescriptionSuccessCallback = { () -> Void in NSLog("PluginRTCPeerConnection#setRemoteDescription() | success callback") let data = [ "type": self.rtcPeerConnection.remoteDescription.type, "sdp": self.rtcPeerConnection.remoteDescription.description ] callback(data: data) } self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#setRemoteDescription() | failure callback: \(error)") errback(error: error) } self.rtcPeerConnection.setRemoteDescriptionWithDelegate(self, sessionDescription: rtcSessionDescription ) } func addIceCandidate( candidate: NSDictionary, callback: (data: NSDictionary) -> Void, errback: () -> Void ) { NSLog("PluginRTCPeerConnection#addIceCandidate()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let sdpMid = candidate.objectForKey("sdpMid") as? String ?? "" let sdpMLineIndex = candidate.objectForKey("sdpMLineIndex") as? Int ?? 0 let candidate = candidate.objectForKey("candidate") as? String ?? "" let result: Bool = self.rtcPeerConnection.addICECandidate(RTCICECandidate( mid: sdpMid, index: sdpMLineIndex, sdp: candidate )) var data: NSDictionary if result == true { if self.rtcPeerConnection.remoteDescription != nil { data = [ "remoteDescription": [ "type": self.rtcPeerConnection.remoteDescription.type, "sdp": self.rtcPeerConnection.remoteDescription.description ] ] } else { data = [ "remoteDescription": false ] } callback(data: data) } else { errback() } } func addStream(pluginMediaStream: PluginMediaStream) -> Bool { NSLog("PluginRTCPeerConnection#addStream()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return false } return self.rtcPeerConnection.addStream(pluginMediaStream.rtcMediaStream) } func removeStream(pluginMediaStream: PluginMediaStream) { NSLog("PluginRTCPeerConnection#removeStream()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } self.rtcPeerConnection.removeStream(pluginMediaStream.rtcMediaStream) } func createDataChannel( dcId: Int, label: String, options: NSDictionary?, eventListener: (data: NSDictionary) -> Void, eventListenerForBinaryMessage: (data: NSData) -> Void ) { NSLog("PluginRTCPeerConnection#createDataChannel()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDataChannel = PluginRTCDataChannel( rtcPeerConnection: rtcPeerConnection, label: label, options: options, eventListener: eventListener, eventListenerForBinaryMessage: eventListenerForBinaryMessage ) // Store the pluginRTCDataChannel into the dictionary. self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel // Run it. pluginRTCDataChannel.run() } func RTCDataChannel_setListener( dcId: Int, eventListener: (data: NSDictionary) -> Void, eventListenerForBinaryMessage: (data: NSData) -> Void ) { NSLog("PluginRTCPeerConnection#RTCDataChannel_setListener()") weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } // Set the eventListener. pluginRTCDataChannel!.setListener(eventListener, eventListenerForBinaryMessage: eventListenerForBinaryMessage ) } func close() { NSLog("PluginRTCPeerConnection#close()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } self.rtcPeerConnection.close() } func RTCDataChannel_sendString( dcId: Int, data: String, callback: (data: NSDictionary) -> Void ) { NSLog("PluginRTCPeerConnection#RTCDataChannel_sendString()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } pluginRTCDataChannel!.sendString(data, callback: callback) } func RTCDataChannel_sendBinary( dcId: Int, data: NSData, callback: (data: NSDictionary) -> Void ) { NSLog("PluginRTCPeerConnection#RTCDataChannel_sendBinary()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } pluginRTCDataChannel!.sendBinary(data, callback: callback) } func RTCDataChannel_close(dcId: Int) { NSLog("PluginRTCPeerConnection#RTCDataChannel_close()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } weak var pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } pluginRTCDataChannel!.close() // Remove the pluginRTCDataChannel from the dictionary. self.pluginRTCDataChannels[dcId] = nil } /** * Methods inherited from RTCPeerConnectionDelegate. */ func peerConnection(peerConnection: RTCPeerConnection!, signalingStateChanged newState: RTCSignalingState) { let state_str = PluginRTCTypes.signalingStates[newState.rawValue] as String! NSLog("PluginRTCPeerConnection | onsignalingstatechange [signalingState:\(state_str)]") self.eventListener(data: [ "type": "signalingstatechange", "signalingState": state_str ]) } func peerConnection(peerConnection: RTCPeerConnection!, iceGatheringChanged newState: RTCICEGatheringState) { let state_str = PluginRTCTypes.iceGatheringStates[newState.rawValue] as String! NSLog("PluginRTCPeerConnection | onicegatheringstatechange [iceGatheringState:\(state_str)]") self.eventListener(data: [ "type": "icegatheringstatechange", "iceGatheringState": state_str ]) if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } // Emit an empty candidate if iceGatheringState is "complete". if newState.rawValue == RTCICEGatheringComplete.rawValue && self.rtcPeerConnection.localDescription != nil { self.eventListener(data: [ "type": "icecandidate", // NOTE: Cannot set null as value. "candidate": false, "localDescription": [ "type": self.rtcPeerConnection.localDescription.type, "sdp": self.rtcPeerConnection.localDescription.description ] ]) } } func peerConnection(peerConnection: RTCPeerConnection!, gotICECandidate candidate: RTCICECandidate!) { NSLog("PluginRTCPeerConnection | onicecandidate [sdpMid:\(candidate.sdpMid), sdpMLineIndex:\(candidate.sdpMLineIndex), candidate:\(candidate.sdp)]") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } self.eventListener(data: [ "type": "icecandidate", "candidate": [ "sdpMid": candidate.sdpMid, "sdpMLineIndex": candidate.sdpMLineIndex, "candidate": candidate.sdp ], "localDescription": [ "type": self.rtcPeerConnection.localDescription.type, "sdp": self.rtcPeerConnection.localDescription.description ] ]) } func peerConnection(peerConnection: RTCPeerConnection!, iceConnectionChanged newState: RTCICEConnectionState) { let state_str = PluginRTCTypes.iceConnectionStates[newState.rawValue] as String! NSLog("PluginRTCPeerConnection | oniceconnectionstatechange [iceConnectionState:\(state_str)]") self.eventListener(data: [ "type": "iceconnectionstatechange", "iceConnectionState": state_str ]) } func peerConnection(rtcPeerConnection: RTCPeerConnection!, addedStream rtcMediaStream: RTCMediaStream!) { NSLog("PluginRTCPeerConnection | onaddstream") let pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream) pluginMediaStream.run() // Let the plugin store it in its dictionary. self.eventListenerForAddStream(pluginMediaStream: pluginMediaStream) // Fire the 'addstream' event so the JS will create a new MediaStream. self.eventListener(data: [ "type": "addstream", "stream": pluginMediaStream.getJSON() ]) } func peerConnection(rtcPeerConnection: RTCPeerConnection!, removedStream rtcMediaStream: RTCMediaStream!) { NSLog("PluginRTCPeerConnection | onremovestream") // Let the plugin remove it from its dictionary. self.eventListenerForRemoveStream(id: rtcMediaStream.label) self.eventListener(data: [ "type": "removestream", "streamId": rtcMediaStream.label // NOTE: No "id" property yet. ]) } func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) { NSLog("PluginRTCPeerConnection | onnegotiationeeded") self.eventListener(data: [ "type": "negotiationneeded" ]) } func peerConnection(peerConnection: RTCPeerConnection!, didOpenDataChannel rtcDataChannel: RTCDataChannel!) { NSLog("PluginRTCPeerConnection | ondatachannel") let dcId = PluginUtils.randomInt(10000, max:99999) let pluginRTCDataChannel = PluginRTCDataChannel( rtcDataChannel: rtcDataChannel ) // Store the pluginRTCDataChannel into the dictionary. self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel // Run it. pluginRTCDataChannel.run() // Fire the 'datachannel' event so the JS will create a new RTCDataChannel. self.eventListener(data: [ "type": "datachannel", "channel": [ "dcId": dcId, "label": rtcDataChannel.label, "ordered": rtcDataChannel.isOrdered, "maxPacketLifeTime": rtcDataChannel.maxRetransmitTime, "maxRetransmits": rtcDataChannel.maxRetransmits, "protocol": rtcDataChannel.`protocol`, "negotiated": rtcDataChannel.isNegotiated, "id": rtcDataChannel.streamId, "readyState": PluginRTCTypes.dataChannelStates[rtcDataChannel.state.rawValue] as String!, "bufferedAmount": rtcDataChannel.bufferedAmount ] ]) } /** * Methods inherited from RTCSessionDescriptionDelegate. */ func peerConnection(rtcPeerConnection: RTCPeerConnection!, didCreateSessionDescription rtcSessionDescription: RTCSessionDescription!, error: NSError!) { if error == nil { self.onCreateDescriptionSuccessCallback(rtcSessionDescription: rtcSessionDescription) } else { self.onCreateDescriptionFailureCallback(error: error) } } func peerConnection(peerConnection: RTCPeerConnection!, didSetSessionDescriptionWithError error: NSError!) { if error == nil { self.onSetDescriptionSuccessCallback() } else { self.onSetDescriptionFailureCallback(error: error) } } }
85144503d161558ac41d30c516c1ff32
27.396853
150
0.755402
false
false
false
false
wibosco/WhiteBoardCodingChallenges
refs/heads/main
WhiteBoardCodingChallenges/Challenges/HackerRank/RunningTime/RunningTime.swift
mit
1
// // InsertionSort.swift // WhiteBoardCodingChallenges // // Created by Boles on 15/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit //https://www.hackerrank.com/challenges/runningtime class RunningTime: NSObject { class func numberOfShiftsToSort(array: [Int]) -> Int { var numberOfShiftsToSort = 0 var sortingArray = array for index in 1..<array.count { let value = array[index] for sortingIndex in (0..<index).reversed() { let comparisonValue = sortingArray[sortingIndex] if comparisonValue > value { sortingArray[sortingIndex] = value sortingArray[sortingIndex + 1] = comparisonValue numberOfShiftsToSort += 1 } else { break } } } return numberOfShiftsToSort } }
be329c8fe5c5168f10d493edb2f9a966
23.931818
68
0.476755
false
false
false
false
Eonil/EditorLegacy
refs/heads/master
Modules/Monolith.Swift/UIKitExtras/TestdriveApp/ViewController.swift
mit
3
// // ViewController.swift // TestdriveApp // // Created by Hoon H. on 11/28/14. // // import UIKit import EonilUIKitExtras func makeLabelForTest() -> UILabel { let v = UILabel() v.backgroundColor = UIColor.redColor() let a1 = v.addConstraintsWithLayoutAnchoring([ v.bottomAnchor == v.topAnchor + CGSize(width: 0, height: 100) ], priority: 750) // v.invalidateIntrinsicContentSize() return v } func makeViewForTest() -> UIView { let v = UISegmentedControl() v.insertSegmentWithTitle("AAAA", atIndex: 0, animated: false) v.insertSegmentWithTitle("AAAA", atIndex: 0, animated: false) v.insertSegmentWithTitle("AAAA", atIndex: 0, animated: false) return v } class ViewController: StaticTableViewController { override func viewDidLoad() { super.viewDidLoad() table.appendSection().header = makeLabelForTest() table.sections.last!.appendRow() table.sections.last!.appendRow() table.sections.last!.appendRow() // self.tableView.layoutIfNeeded() // self.tableView.updateConstraints() // table.sections[0].appendRow() // table.sections[0].appendRow() // // // let s = StaticTableSection() // s.appendRow() // s.appendRow() // s.appendRow() // // s.header = makeLabelForTest() // // table.appendSection(s) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.None) // tableView.reloadData() // UIView.setAnimationsEnabled(true) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // assert(table.sections[1].header!.superview !== nil) // self.view.setNeedsDisplay() // self.view.layoutIfNeeded() // self.view.invalidateIntrinsicContentSize() //// assert(v.superview === tableView) // let rs = s.rows // s.deleteAllRows() // // // table.sections[0].rows = rs //// table.replaceSectionAtIndex(0, withSection: s, animation: UITableViewRowAnimation.Fade) // tableView.beginUpdates() // tableView.endUpdates() NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "test:", userInfo: nil, repeats: false) } func test(AnyObject?) { assert(NSThread.mainThread() == NSThread.currentThread()) let s = table.appendSection() // tableView.setNeedsDisplay() tableView.setNeedsLayout() // tableView.setNeedsUpdateConstraints() tableView.layoutIfNeeded() tableView.beginUpdates() // s.header = makeViewForTest() s.setHeaderWithAnimation(makeViewForTest(), animation: UITableViewRowAnimation.Fade) table.sections.last!.appendRow() table.sections.last!.appendRow() table.sections.last!.appendRow() tableView.endUpdates() tableView.setNeedsLayout() tableView.layoutIfNeeded() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
262186b4a275f8f99bbde57700dad955
23
107
0.716253
false
true
false
false
codeOfRobin/Components-Personal
refs/heads/master
Example/PropertiesDataSource.swift
mit
1
// // PropertiesDataSource.swift // Example // // Created by Robin Malhotra on 06/09/17. // Copyright © 2017 BuildingBlocks. All rights reserved. // import AsyncDisplayKit import BuildingBlocks import RxSwift class PropertiesDataSource: NSObject, ASTableDataSource { let disposeBag = DisposeBag() let systemPropertyCollection = SystemPropertyCollection() let customPropertyCollection = CustomPropertyCollection() init(caseEvents: Variable<CaseEvent>) { super.init() caseEvents .asObservable() .subscribe(onNext: { [weak self] (event) in self?.systemPropertyCollection.updateDataIfNecessary(from: event) self?.customPropertyCollection.updateDataIfNecessary(from: event) }).disposed(by: disposeBag) } func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode { let row = indexPath.row switch indexPath.section { case 0: let firstProperty = systemPropertyCollection.first?.value let requesterViewModel: RequesterViewModel? = firstProperty.flatMap { (property) in switch property { case .requester(let requester): return requester default: return nil } } if let model = requesterViewModel, let systemProperty = systemPropertyCollection.first { return PropertyNode(contentNode: RequesterCellNode(model), status: PropertyStatus.status(from: systemProperty), separatorRenderer: RequesterSeparatorRenderer()) } else { return ASCellNode() } case 1: let systemProperty = systemPropertyCollection[row + 1] let contentNode: ASCellNode = { switch systemProperty.value { case .requester(let requester): return RequesterCellNode(requester) case .assignee(let assignee): let heading = "Assignee" if let assignee = assignee { switch assignee { case .agent(let agent): return HeadingContainNode(headingText: heading, containerNode: AgentCellNode(agentViewModel: agent)) case .team(let team): return HeadingContainNode(headingText: heading, containerNode: TeamCellNode(team: team)) } } else { return HeadingTextNode.node(headingText: heading, text: "(Unassigned)") } case .status(let status): let heading = "Status" return HeadingContainNode(headingText: heading, containerNode: StatusCellNode(viewModel: status)) case .type(let type): return HeadingTextNode.node(headingText: "Type", text: type?.label ?? "-") case .priority(let priority): return HeadingTextNode.node(headingText: "Priority", text: priority?.label ?? "-") case .form(let form): return HeadingTextNode.node(headingText: "Form", text: form?.label ?? "-") case .tags(let tags): return HeadingContainNode(headingText: "Tags", containerNode: TagCollectionNode(state: tags)) } }() return PropertyNode(contentNode: contentNode, status: PropertyStatus.status(from: systemProperty)) case 2: let contentNodeClosure: (CustomPropertyData) -> ASCellNode = { propertyData in switch propertyData { case .singleLineText(let value): return HeadingTextNode.node(headingText: "Single Line Text", text: value ?? "-") case .multiLineText(let value): return HeadingTextNode.node(headingText: "Multi Line Text", text: value ?? "-") case .regex(let value): return HeadingTextNode.node(headingText: "Regex", text: value ?? "-") case .radioButton(let value): return HeadingTextNode.node(headingText: "Radio Button", text: value.flatMap{ $0.label } ?? "-") case .dropdown(let value): return HeadingTextNode.node(headingText: "Dropdown Button", text: value.flatMap{ $0.label } ?? "-") case .checkbox(let values): let text: String = { if values.count > 0 { return values.map { $0.label }.joined(separator: ", ") } else { return "-" } }() return HeadingTextNode.node(headingText: "Checkbox", text: text) case .numerical(let value): return HeadingTextNode.node(headingText: "Numerical", text: value.flatMap{ return "\($0)" } ?? "-") case .decimal(let value): return HeadingTextNode.node(headingText: NSLocalizedString("Numerical", comment: ""), text: value.flatMap{ return "\($0)" } ?? "-") case .date(let value): return HeadingTextNode.node(headingText: "Date", text: value.flatMap{ let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full return dateFormatter.string(from: $0) } ?? "-") case .yesNo(let state): return HeadingTextNode.node(headingText: "Yes/No", text: state.flatMap { switch $0 { case false: return "No" case true: return "Yes" } } ?? "-") case .cascade(let value): return HeadingTextNode.node(headingText: "Heading", text: value.flatMap { return $0.label.replacingOccurrences(of: "\\", with: " / ") } ?? "-") } } let property = self.customPropertyCollection[row] let propertyData = property.data.value let contentNode = contentNodeClosure(propertyData) return PropertyNode(contentNode: contentNode, status: PropertyStatus.status(from: property.data)) default: return ASCellNode() } } func numberOfSections(in tableNode: ASTableNode) -> Int { return 3 } func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return systemPropertyCollection.count - 1//for requester! case 2: return customPropertyCollection.count default: return 0 } } }
eea0e6c5d842ef64f3b971c17dca5742
33.78125
164
0.686074
false
false
false
false
randallli/material-components-ios
refs/heads/develop
catalog/MDCDragons/HeaderView.swift
apache-2.0
3
/* Copyright 2015-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. */ import UIKit class HeaderView: UIView { @IBOutlet var containerView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var searchBar: UISearchBar! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { Bundle.main.loadNibNamed("HeaderView", owner: self, options: nil) addSubview(containerView) self.backgroundColor = .clear containerView.backgroundColor = .clear containerView.frame = self.bounds containerView.autoresizingMask = [.flexibleHeight, .flexibleWidth] title.textColor = UIColor(white: 1, alpha: 1) title.font = UIFont.systemFont(ofSize: 20) let image = MDCDrawDragons.image(with: MDCDrawDragons.drawDragon, size: CGSize(width: 40, height: 40), fillColor: .white) imageView.image = image // To make the search icon tinted white we have to reach the internal UITextField of the UISearchBar if let searchBarTextField = self.searchBar.value(forKey: "_searchField") as? UITextField, let glassIconView = searchBarTextField.leftView as? UIImageView { searchBarTextField.tintColor = .white glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate) glassIconView.tintColor = .white } searchBar.scopeBarBackgroundImage = UIImage() } }
6ba778b1caa983e9ee9e92fc267db747
35.196721
104
0.69837
false
false
false
false
kysonyangs/ysbilibili
refs/heads/master
ysbilibili/Classes/HomePage/View/ZHNhomePageFavoriteCell.swift
mit
1
// // ZHNhomePageFavoriteCell.swift // zhnbilibili // // Created by 张辉男 on 17/1/15. // Copyright © 2017年 zhn. All rights reserved. // import UIKit class ZHNhomePageFavoriteCell: ZHNhomePageBaseTableViewCell { var favitateModel: ZHNhomePageFaverateModel? { didSet { contentCollectionView.reloadData() guard let faverateCount = favitateModel?.item?.count else {return} count = faverateCount } } // MARK - 懒加载控件 lazy var contentCollectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: (kScreenWidth - 50)/3, height: 120) flowLayout.minimumLineSpacing = kPadding let contentCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout) contentCollectionView.delegate = self contentCollectionView.dataSource = self contentCollectionView.register(ZHNhomePageFavoriteCollectionViewCell.self, forCellWithReuseIdentifier: "ZHNhomePageFavoriteCollectionViewCell") contentCollectionView.backgroundColor = kHomeBackColor return contentCollectionView }() // MARK - life cycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.backgroundColor = kHomeBackColor name = "TA的收藏夹" self.addSubview(contentCollectionView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() contentCollectionView.snp.makeConstraints { (make) in make.top.equalTo(headNoticeView.snp.bottom) make.bottom.equalTo(lineView.snp.top) make.left.equalTo(self).offset(10) make.right.equalTo(self).offset(-10) } } } //====================================================================== // MARK:- UIcollectionview delegate datasource //====================================================================== extension ZHNhomePageFavoriteCell: UICollectionViewDelegate,UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let count = favitateModel?.item?.count else {return 0} return (count > 3 ? 3 : count) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ZHNhomePageFavoriteCollectionViewCell", for: indexPath) as! ZHNhomePageFavoriteCollectionViewCell cell.detailModel = favitateModel?.item?[indexPath.row] return cell } }
7fa2264b5983735bfe2e883b16e9ba18
38.108108
173
0.664478
false
false
false
false
devcarlos/RappiApp
refs/heads/master
RappiApp/Classes/Transitions/CustomNavigationAnimationController.swift
mit
1
// // CustomNavigationAnimationController.swift // CustomTransitions // // Created by Carlos Alcala on 7/3/16. // Copyright (c) 2015 Appcoda. All rights reserved. // import UIKit class CustomNavigationAnimationController: NSObject, UIViewControllerAnimatedTransitioning { var reverse: Bool = false func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 1.5 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView() let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toView = toViewController.view let fromView = fromViewController.view let direction: CGFloat = reverse ? -1 : 1 let const: CGFloat = -0.005 toView.layer.anchorPoint = CGPointMake(direction == 1 ? 0 : 1, 0.5) fromView.layer.anchorPoint = CGPointMake(direction == 1 ? 1 : 0, 0.5) var viewFromTransform: CATransform3D = CATransform3DMakeRotation(direction * CGFloat(M_PI_2), 0.0, 1.0, 0.0) var viewToTransform: CATransform3D = CATransform3DMakeRotation(-direction * CGFloat(M_PI_2), 0.0, 1.0, 0.0) viewFromTransform.m34 = const viewToTransform.m34 = const containerView!.transform = CGAffineTransformMakeTranslation(direction * containerView!.frame.size.width / 2.0, 0) toView.layer.transform = viewToTransform containerView!.addSubview(toView) UIView.animateWithDuration(transitionDuration(transitionContext), animations: { containerView!.transform = CGAffineTransformMakeTranslation(-direction * containerView!.frame.size.width / 2.0, 0) fromView.layer.transform = viewFromTransform toView.layer.transform = CATransform3DIdentity }, completion: { finished in containerView!.transform = CGAffineTransformIdentity fromView.layer.transform = CATransform3DIdentity toView.layer.transform = CATransform3DIdentity fromView.layer.anchorPoint = CGPointMake(0.5, 0.5) toView.layer.anchorPoint = CGPointMake(0.5, 0.5) if (transitionContext.transitionWasCancelled()) { toView.removeFromSuperview() } else { fromView.removeFromSuperview() } transitionContext.completeTransition(!transitionContext.transitionWasCancelled()) }) } }
0517326ae2cc57cd0ecc7c6d0b6f232d
41.59375
126
0.683419
false
false
false
false
apple/swift
refs/heads/main
test/Constraints/type_inference_from_default_exprs.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %target-build-swift -parse-as-library -emit-library -emit-module-path %t/InferViaDefaults.swiftmodule -module-name InferViaDefaults %S/Inputs/type_inference_via_defaults_other_module.swift -o %t/%target-library-name(InferViaDefaults) // RUN: %target-swift-frontend -typecheck -verify -lInferViaDefaults -module-name main -I %t -L %t %s import InferViaDefaults func testInferFromResult<T>(_: T = 42) -> T { fatalError() } // Ok enum ETest<T> { case test(_: T = 42) // expected-note {{default value declared here}} } func testInferFromOtherPos1<T>(_: T = 42, _: [T]) {} // expected-error@-1 {{cannot use default expression for inference of 'T' because it is inferrable from parameters #0, #1}} func testInferFromOtherPos2<T>(_: T = 42, _: T = 0.0) {} // expected-error@-1 2 {{cannot use default expression for inference of 'T' because it is inferrable from parameters #0, #1}} protocol P { associatedtype X } func testInferFromSameType<T, U: P>(_: T = 42, _: [U]) where T == U.X {} // expected-error@-1 {{cannot use default expression for inference of 'T' because requirement 'T == U.X' refers to other generic parameters}} func test1<T>(_: T = 42) {} // Ok struct S : P { typealias X = Int } func test2<T: P>(_: T = S()) {} // Ok struct A : P { typealias X = Double } class B : P { typealias X = String init() {} } func test2<T: P & AnyObject>(_: T = B()) {} // Ok func test2NonClassDefault<T: P & AnyObject>(_: T = S()) {} // expected-error@-1 {{global function 'test2NonClassDefault' requires that 'S' be a class type}} // expected-note@-2 {{where 'T' = 'S'}} func test2NonConformingDefault<T: P>(_: T = 42.0) {} // expected-error@-1 {{global function 'test2NonConformingDefault' requires that 'Double' conform to 'P'}} // expected-note@-2 {{where 'T' = 'Double'}} func testMultiple<T, U>(a: T = 42.0, b: U = "") {} // Ok // Subscripts extension S { subscript<T: P>(a: T = S()) -> Int { get { return 42 } } subscript<T: P, U: AnyObject>(a: T = S(), b: U = B()) -> Int { get { return 42 } } } // In nested positions func testNested1<T>(_: [T] = [0, 1.0]) {} // Ok (T == Double) func testNested2<T>(_: T? = 42.0) {} // Ok func testNested2NoInference<T>(_: T? = nil) {} // Ok (old semantics) // expected-note@-1 {{in call to function 'testNested2NoInference'}} struct D : P { typealias X = B } func testNested3<T: P>(_: T = B()) where T.X == String {} func testNested4<T: P>(_: T = B()) where T.X == Int {} // expected-error@-1 {{global function 'testNested4' requires the types 'B.X' (aka 'String') and 'Int' be equivalent}} // expected-note@-2 {{where 'T.X' = 'B.X' (aka 'String')}} func testNested5<T: P>(_: [T]? = [D()]) where T.X: P, T.X: AnyObject {} func testNested5Invalid<T: P>(_: [T]? = [B()]) where T.X: P, T.X: AnyObject {} // expected-error@-1 {{global function 'testNested5Invalid' requires that 'B.X' (aka 'String') conform to 'P'}} // expected-error@-2 {{global function 'testNested5Invalid' requires that 'B.X' (aka 'String') be a class type}} // expected-note@-3 2 {{where 'T.X' = 'B.X' (aka 'String')}} // expected-note@-4 {{in call to function 'testNested5Invalid'}} func testNested6<T: P, U>(_: (a: [T?], b: U) = (a: [D()], b: B())) where T.X == U, T.X: P, U: AnyObject { // Ok } // Generic requirements class GenClass<T> {} func testReq1<T, U>(_: T = B(), _: U) where T: GenClass<U> {} // expected-error@-1 {{cannot use default expression for inference of 'T' because requirement 'T : GenClass<U>' refers to other generic parameters}} class E : GenClass<B> { } func testReq2<T, U>(_: (T, U) = (E(), B())) where T: GenClass<U>, U: AnyObject {} // Ok func testReq3<T: P, U>(_: [T?] = [B()], _: U) where T.X == U {} // expected-error@-1 {{cannot use default expression for inference of '[T?]' because requirement 'U == T.X' refers to other generic parameters}} protocol Shape { } struct Circle : Shape { } struct Rectangle : Shape { } struct Figure<S: Shape> { init(_: S = Circle()) {} // expected-note 2 {{default value declared here}} } func main() { _ = testInferFromResult() // Ok T == Int let _: Float = testInferFromResult() // expected-error {{cannot convert value of type 'Int' to specified type 'Float'}} _ = ETest.test() // Ok let _: ETest<String> = .test() // expected-error {{cannot convert default value of type 'String' to expected argument type 'Int' for parameter #0}} test1() // Ok test2() // Ok test2(A()) // Ok as well testMultiple() // Ok (T = Double, U = String) testMultiple(a: 0) // Ok (T = Int, U = String) testMultiple(b: S()) // Ok (T = Double, U = S) testMultiple(a: 0.0, b: "a") // Ok // From a different module InferViaDefaults.with_defaults() // Ok InferViaDefaults.with_defaults("") // Ok _ = S()[] // Ok _ = S()[B()] // Ok testNested1() // Ok testNested2() // Ok testNested2NoInference() // expected-error {{generic parameter 'T' could not be inferred}} testNested3() // Ok testNested5() // Ok testNested5Invalid() // expected-error {{generic parameter 'T' could not be inferred}} testNested6() // Ok testReq2() // Ok func takesFigure<T>(_: Figure<T>) {} func takesCircle(_: Figure<Circle>) {} func takesRectangle(_: Figure<Rectangle>) {} _ = Figure.init() // Ok S == Circle let _: Figure<Circle> = .init() // Ok (S == Circle) let _: Figure<Rectangle> = .init() // expected-error@-1 {{cannot convert default value of type 'Rectangle' to expected argument type 'Circle' for parameter #0}} takesFigure(.init()) // Ok takesCircle(.init()) // Ok takesRectangle(.init()) // expected-error@-1 {{cannot convert default value of type 'Rectangle' to expected argument type 'Circle' for parameter #0}} } func test_magic_defaults() { func with_magic(_: Int = #function) {} // expected-error {{default argument value of type 'String' cannot be converted to type 'Int'}} func generic_with_magic<T>(_: T = #line) -> T {} // expected-error {{default argument value of type 'Int' cannot be converted to type 'T'}} let _ = with_magic() let _: String = generic_with_magic() } // https://github.com/apple/swift/issues/58330 func test_allow_same_type_between_dependent_types() { struct Default : P { typealias X = Int } struct Other : P { typealias X = Int } struct S<T: P> { func test<U: P>(_: U = Default()) where U.X == T.X { // expected-note {{where 'T.X' = 'String', 'U.X' = 'Default.X' (aka 'Int')}} } } func test_ok<T: P>(s: S<T>) where T.X == Int { s.test() // Ok: U == Default } func test_bad<T: P>(s: S<T>) where T.X == String { s.test() // expected-error {{instance method 'test' requires the types 'String' and 'Default.X' (aka 'Int') be equivalent}} } } // Crash when default type is requested before inherited constructor is type-checked protocol StorageType { var identifier: String { get } } class Storage { // expected-note {{class 'Storage' is not public}} } extension Storage { struct Test { static let test = CustomStorage<String>("") // triggers default type request } } class BaseStorage<T> : Storage, StorageType { enum StorageType { case standard } let identifier: String let type: StorageType init(_ id: String, type: StorageType = .standard) { self.identifier = id self.type = type } } final class CustomStorage<T>: BaseStorage<T> { // Ok - no crash typechecking inherited init } // https://github.com/apple/swift/issues/61061 struct S61061<T> where T:Hashable { // expected-note{{'T' declared as parameter to type 'S61061'}} init(x:[[T: T]] = [:]) {} // expected-error{{default argument value of type '[AnyHashable : Any]' cannot be converted to type '[[T : T]]'}} // expected-error@-1{{generic parameter 'T' could not be inferred}} } struct S61061_1<T> where T:Hashable { // expected-note{{'T' declared as parameter to type 'S61061_1'}} init(x:[(T, T)] = [:]) {} // expected-error{{default argument value of type '[AnyHashable : Any]' cannot be converted to type '[(T, T)]'}} // expected-error@-1{{generic parameter 'T' could not be inferred}} } struct S61061_2<T> where T:Hashable { init(x:[(T, T)] = [(1, "")]) {} // expected-error{{conflicting arguments to generic parameter 'T' ('String' vs. 'Int')}} } struct S61061_3<T> where T:Hashable { init(x:[(T, T)] = [(1, 1)]) {} // OK } // https://github.com/apple/swift/issues/62025 // Syntactic checks are not run on the default argument expressions public struct MyStruct {} // expected-note {{initializer 'init()' is not public}} public func issue62025_with_init<T>(_: T = MyStruct()) {} // expected-error@-1 {{initializer 'init()' is internal and cannot be referenced from a default argument value}} public func issue62025_with_type<T>(_: T = Storage.self) {} // expected-error@-1 {{class 'Storage' is internal and cannot be referenced from a default argument value}} do { func default_with_dup_keys<T>(_: T = ["a": 1, "a": 2]) {} // expected-warning@-1 {{dictionary literal of type '[String : Int]' has duplicate entries for string literal key 'a'}} // expected-note@-2 2 {{duplicate key declared here}} }
7c185dc9c8715ff172cf7745ba1df640
33.19403
241
0.63553
false
true
false
false
gmoral/SwiftTraining2016
refs/heads/master
Training_Swift/SkillCell.swift
mit
1
// // SkillCell.swift // Training_Swift // // Created by Guillermo Moral on 2/26/16. // Copyright © 2016 Guillermo Moral. All rights reserved. // import UIKit protocol SkillCellDelegate : class { func didSelectSkill(Cell: SkillCell) } class SkillCell: UITableViewCell { @IBOutlet weak private var category: UILabel! @IBOutlet weak var level: UISegmentedControl! var delegate : SkillCellDelegate? override func awakeFromNib() { super.awakeFromNib() } func configure(Title: String, Level: Int, Type: ViewType) { category.text = Title level.selectedSegmentIndex = Level if Type == ViewType.MySkill { level.hidden = false } else { level.hidden = true } } class func identifier()-> String { return "SkillCell" } @IBAction func didTapLevel(sender: AnyObject) { delegate?.didSelectSkill(self) } }
40ce8eb7a8c39e08a76c056ae88c51a5
18.230769
61
0.597
false
false
false
false
CodaFi/swift
refs/heads/master
stdlib/private/OSLog/OSLogFloatingPointTypes.swift
apache-2.0
8
//===----------------- OSLogFloatingPointTypes.swift ----------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file defines extensions for interpolating floating-point expressions // into an OSLogMesage. It defines `appendInterpolation` functions for standard // floating-point types. It also defines extensions for serializing floating- // point types into the argument buffer passed to os_log ABIs. // // The `appendInterpolation` functions defined in this file accept privacy // options along with the interpolated expression as shown below: // TODO: support floating-point formatting options. // // "\(x, privacy: .private\)" extension OSLogInterpolation { /// Define interpolation for expressions of type Float. /// - Parameters: /// - number: the interpolated expression of type Float, which is autoclosured. /// - privacy: a privacy qualifier which is either private or public. /// It is auto-inferred by default. @_semantics("constant_evaluable") @_semantics("oslog.requires_constant_arguments") @inlinable @_optimize(none) public mutating func appendInterpolation( _ number: @autoclosure @escaping () -> Float, privacy: OSLogPrivacy = .auto ) { appendInterpolation(Double(number()), privacy: privacy) } /// Define interpolation for expressions of type Double. /// - Parameters: /// - number: the interpolated expression of type Double, which is autoclosured. /// - privacy: a privacy qualifier which is either private or public. /// It is auto-inferred by default. @_semantics("constant_evaluable") @_semantics("oslog.requires_constant_arguments") @inlinable @_optimize(none) public mutating func appendInterpolation( _ number: @autoclosure @escaping () -> Double, privacy: OSLogPrivacy = .auto ) { guard argumentCount < maxOSLogArgumentCount else { return } formatString += getDoubleFormatSpecifier(privacy: privacy) addDoubleHeaders(privacy) arguments.append(number) argumentCount += 1 } /// Update preamble and append argument headers based on the parameters of /// the interpolation. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func addDoubleHeaders(_ privacy: OSLogPrivacy) { // Append argument header. let argumentHeader = getArgumentHeader(privacy: privacy, type: .scalar) arguments.append(argumentHeader) // Append number of bytes needed to serialize the argument. let byteCount = doubleSizeInBytes() arguments.append(UInt8(byteCount)) // Increment total byte size by the number of bytes needed for this // argument, which is the sum of the byte size of the argument and // two bytes needed for the headers. totalBytesForSerializingArguments += byteCount + 2 preamble = getUpdatedPreamble(privacy: privacy, isScalar: true) } /// Construct an os_log format specifier from the given parameters. /// This function must be constant evaluable and all its arguments /// must be known at compile time. @inlinable @_semantics("constant_evaluable") @_effects(readonly) @_optimize(none) internal func getDoubleFormatSpecifier(privacy: OSLogPrivacy) -> String { // TODO: this will become more sophisticated when floating-point formatting // options are supported. var specifier = "%" switch privacy { case .private: specifier += "{private}" case .public: specifier += "{public}" default: break } specifier += "f" return specifier } } extension OSLogArguments { /// Append an (autoclosured) interpolated expression of Double type, passed to /// `OSLogMessage.appendInterpolation`, to the array of closures tracked /// by this instance. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func append(_ value: @escaping () -> Double) { argumentClosures.append({ (position, _) in serialize(value(), at: &position) }) } } /// Return the number of bytes needed for serializing a double argument as /// specified by os_log. Note that this is marked transparent instead of /// @inline(__always) as it is used in optimize(none) functions. @_transparent @usableFromInline internal func doubleSizeInBytes() -> Int { return 8 } /// Serialize a double at the buffer location that `position` points to and /// increment `position` by the byte size of the double. @inlinable @_alwaysEmitIntoClient @inline(__always) internal func serialize( _ value: Double, at bufferPosition: inout ByteBufferPointer ) { let byteCount = doubleSizeInBytes() let dest = UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount) withUnsafeBytes(of: value) { dest.copyMemory(from: $0) } bufferPosition += byteCount }
f9b7b482741aef308b98de2a7562e7d4
34.231293
83
0.702645
false
false
false
false
andyshep/DataStructures
refs/heads/master
LinkedList.playground/section-1.swift
mit
1
// LinkedLists // // Basic Operations // // insert(value) -- Inserts a new value into at the end List, by creating a new Node object // insertHead(value) -- Inserts a new value at the start of the List // remove(value) -- Removes the first Node matching value from the List class Node<T: Equatable> { var value: T var next: Node? = nil init(_ value:T) { self.value = value } } class LinkedList<T: Equatable> : Printable { var head: Node<T>? = nil func insert(value:T) { if head == nil { head = Node(value) } else { var lastNode = head while lastNode?.next != nil { lastNode = lastNode?.next } let newNode = Node(value) lastNode?.next = newNode } } func insertHead(value:T) { if head == nil { self.head = Node(value) } else { let newNode = Node(value) newNode.next = head self.head = newNode } } func remove(value:T) { if head != nil { var node = head var previousNode: Node<T>? = nil while node?.value != value && node?.next != nil { previousNode = node node = node?.next } if node?.value == value { if node?.next != nil { previousNode?.next = node?.next } else { previousNode?.next = nil } } } } var description : String { var node = head var description = "\(node!.value)" while node?.next != nil { node = node?.next description += " \(node!.value)" } return description } } var linkedList = LinkedList<Int>() linkedList.insert(10) linkedList.insert(20) linkedList.description linkedList.insertHead(99) linkedList.description linkedList.remove(20) linkedList.remove(10) linkedList.description var linkedList2 = LinkedList<String>() linkedList2.insert("Fred") linkedList2.insert("Jed") linkedList2.insert("Ned") linkedList2.insert("Ted") linkedList2.insert("Red") linkedList2.remove("Ned") linkedList2.description
5525801ba14ef100694bb37f91b5a6f9
21.446602
91
0.525087
false
false
false
false
4np/UitzendingGemist
refs/heads/master
Carthage/Checkouts/realm-cocoa/RealmSwift/LinkingObjects.swift
apache-2.0
8
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /// :nodoc: /// Internal class. Do not use directly. Used for reflection and initialization public class LinkingObjectsBase: NSObject, NSFastEnumeration { internal let objectClassName: String internal let propertyName: String fileprivate var cachedRLMResults: RLMResults<RLMObject>? @objc fileprivate var object: RLMWeakObjectHandle? @objc fileprivate var property: RLMProperty? internal var rlmResults: RLMResults<RLMObject> { if cachedRLMResults == nil { if let object = self.object, let property = self.property { cachedRLMResults = RLMDynamicGet(object.object, property)! as? RLMResults self.object = nil self.property = nil } else { cachedRLMResults = RLMResults.emptyDetached() } } return cachedRLMResults! } init(fromClassName objectClassName: String, property propertyName: String) { self.objectClassName = objectClassName self.propertyName = propertyName } // MARK: Fast Enumeration public func countByEnumerating(with state: UnsafeMutablePointer<NSFastEnumerationState>, objects buffer: AutoreleasingUnsafeMutablePointer<AnyObject?>, count len: Int) -> Int { return Int(rlmResults.countByEnumerating(with: state, objects: buffer, count: UInt(len))) } } /** `LinkingObjects` is an auto-updating container type. It represents zero or more objects that are linked to its owning model object through a property relationship. `LinkingObjects` can be queried with the same predicates as `List<T>` and `Results<T>`. `LinkingObjects` always reflects the current state of the Realm on the current thread, including during write transactions on the current thread. The one exception to this is when using `for...in` enumeration, which will always enumerate over the linking objects that were present when the enumeration is begun, even if some of them are deleted or modified to no longer link to the target object during the enumeration. `LinkingObjects` can only be used as a property on `Object` models. Properties of this type must be declared as `let` and cannot be `dynamic`. */ public final class LinkingObjects<T: Object>: LinkingObjectsBase { /// The type of the objects represented by the linking objects. public typealias Element = T // MARK: Properties /// The Realm which manages the linking objects, or `nil` if the linking objects are unmanaged. public var realm: Realm? { return rlmResults.isAttached ? Realm(rlmResults.realm) : nil } /// Indicates if the linking objects are no longer valid. /// /// The linking objects become invalid if `invalidate()` is called on the containing `realm` instance. /// /// An invalidated linking objects can be accessed, but will always be empty. public var isInvalidated: Bool { return rlmResults.isInvalidated } /// The number of linking objects. public var count: Int { return Int(rlmResults.count) } // MARK: Initializers /** Creates an instance of a `LinkingObjects`. This initializer should only be called when declaring a property on a Realm model. - parameter type: The type of the object owning the property the linking objects should refer to. - parameter propertyName: The property name of the property the linking objects should refer to. */ public init(fromType type: T.Type, property propertyName: String) { let className = (T.self as Object.Type).className() super.init(fromClassName: className, property: propertyName) } /// A human-readable description of the objects represented by the linking objects. public override var description: String { return RLMDescriptionWithMaxDepth("LinkingObjects", rlmResults, RLMDescriptionMaxDepth) } // MARK: Index Retrieval /** Returns the index of an object in the linking objects, or `nil` if the object is not present. - parameter object: The object whose index is being queried. */ public func index(of object: T) -> Int? { return notFoundToNil(index: rlmResults.index(of: object.unsafeCastToRLMObject())) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return notFoundToNil(index: rlmResults.indexOfObject(with: NSPredicate(format: predicateFormat, argumentArray: args))) } // MARK: Object Retrieval /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return unsafeBitCast(rlmResults[UInt(index)], to: T.self) } } /// Returns the first object in the linking objects, or `nil` if the linking objects are empty. public var first: T? { return unsafeBitCast(rlmResults.firstObject(), to: Optional<T>.self) } /// Returns the last object in the linking objects, or `nil` if the linking objects are empty. public var last: T? { return unsafeBitCast(rlmResults.lastObject(), to: Optional<T>.self) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the linking objects. - parameter key: The name of the property whose values are desired. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the linking objects. - parameter keyPath: The key path to the property whose values are desired. */ public override func value(forKeyPath keyPath: String) -> Any? { return rlmResults.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the linking objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The value to set the property to. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return rlmResults.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the linking objects. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> { return Results<T>(rlmResults.objects(with: NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the linking objects. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<T> { return Results<T>(rlmResults.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing all the linking objects, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<T> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing all the linking objects, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ @available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)") public func sorted(byProperty property: String, ascending: Bool = true) -> Results<T> { return sorted(byKeyPath: property, ascending: ascending) } /** Returns a `Results` containing all the linking objects, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { return Results<T>(rlmResults.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the linking objects, or `nil` if the linking objects are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the linking objects, or `nil` if the linking objects are empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func max<U: MinMaxType>(ofProperty property: String) -> U? { return rlmResults.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the linking objects. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return dynamicBridgeCast(fromObjectiveC: rlmResults.sum(ofProperty: property)) } /** Returns the average value of a given property over all the linking objects, or `nil` if the linking objects are empty. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return rlmResults.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<LinkingObjects>) -> Void) -> NotificationToken { return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension LinkingObjects : RealmCollection { // MARK: Sequence Support /// Returns an iterator that yields successive elements in the linking objects. public func makeIterator() -> RLMIterator<T> { return RLMIterator(collection: rlmResults) } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after: Int) -> Int { return after + 1 } public func index(before: Int) -> Int { return before - 1 } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return rlmResults.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: AssistedObjectiveCBridgeable extension LinkingObjects: AssistedObjectiveCBridgeable { internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> LinkingObjects { guard let metadata = metadata as? LinkingObjectsBridgingMetadata else { preconditionFailure() } let swiftValue = LinkingObjects(fromType: T.self, property: metadata.propertyName) switch (objectiveCValue, metadata) { case (let object as RLMObjectBase, .uncached(let property)): swiftValue.object = RLMWeakObjectHandle(object: object) swiftValue.property = property case (let results as RLMResults<RLMObject>, .cached): swiftValue.cachedRLMResults = results default: preconditionFailure() } return swiftValue } internal var bridged: (objectiveCValue: Any, metadata: Any?) { if let results = cachedRLMResults { return (objectiveCValue: results, metadata: LinkingObjectsBridgingMetadata.cached(propertyName: propertyName)) } else { return (objectiveCValue: (object!.copy() as! RLMWeakObjectHandle).object, metadata: LinkingObjectsBridgingMetadata.uncached(property: property!)) } } } internal enum LinkingObjectsBridgingMetadata { case uncached(property: RLMProperty) case cached(propertyName: String) fileprivate var propertyName: String { switch self { case .uncached(let property): return property.name case .cached(let propertyName): return propertyName } } } // MARK: Unavailable extension LinkingObjects { @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: Any...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } }
1f6208d7c1a47f8f316dc2cfb960a22f
40.576687
127
0.674389
false
false
false
false
kcome/SwiftIB
refs/heads/master
SwiftIB/ScannerSubscription.swift
mit
1
// // ScannerSubscription.swift // SwiftIB // // Created by Hanfei Li on 1/01/2015. // Copyright (c) 2014-2019 Hanfei Li. 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 public struct ScannerSubscription { let NO_ROW_NUMBER_SPECIFIED = -1 var numberOfRows: Int = -1 var instrument: String = "" var locationCode: String = "" var scanCode: String = "" var abovePrice: Double = Double.nan var belowPrice: Double = Double.nan var aboveVolume: Int = Int.max var averageOptionVolumeAbove: Int = Int.max var marketCapAbove: Double = Double.nan var marketCapBelow: Double = Double.nan var moodyRatingAbove: String = "" var moodyRatingBelow: String = "" var spRatingAbove: String = "" var spRatingBelow: String = "" var maturityDateAbove: String = "" var maturityDateBelow: String = "" var couponRateAbove: Double = Double.nan var couponRateBelow: Double = Double.nan var excludeConvertible: String = "" var scannerSettingPairs: String = "" var stockTypeFilter: String = "" }
b08d33b20547943b766fd94d80d212a4
40
84
0.723734
false
false
false
false
RMizin/PigeonMessenger-project
refs/heads/main
FalconMessenger/ChatsControllers/ChatLogViewController+PreviewingDelegate.swift
gpl-3.0
1
// // ChatLogViewController+PreviewingDelegate.swift // FalconMessenger // // Created by Roman Mizin on 9/19/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit import AVKit extension ChatLogViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) as? BaseMediaMessageCell else { return nil } guard cell.loadButton.isHidden == true && cell.progressView.isHidden == true else { return nil} let sourcePoint = cell.bubbleView.convert(cell.messageImageView.frame.origin, to: collectionView) let sourceRect = CGRect(x: sourcePoint.x, y: sourcePoint.y, width: cell.messageImageView.frame.width, height: cell.messageImageView.frame.height) previewingContext.sourceRect = sourceRect if let viewController = openSelectedPhoto(at: indexPath) as? INSPhotosViewController { viewController.view.backgroundColor = .clear viewController.overlayView.setHidden(true, animated: false) viewController.currentPhotoViewController?.playerController.player?.play() let imageView = viewController.currentPhotoViewController?.scalingImageView.imageView let radius = (imageView?.image?.size.width ?? 20) * 0.05 viewController.currentPhotoViewController?.scalingImageView.imageView.layer.cornerRadius = radius viewController.currentPhotoViewController?.scalingImageView.imageView.layer.masksToBounds = true return viewController } return nil } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { if let viewController = viewControllerToCommit as? INSPhotosViewController { viewController.view.backgroundColor = .black viewController.currentPhotoViewController?.scalingImageView.imageView.layer.cornerRadius = 0 viewController.currentPhotoViewController?.scalingImageView.imageView.layer.masksToBounds = false viewController.overlayView.setHidden(false, animated: false) present(viewController, animated: true) } else if let viewController = viewControllerToCommit as? AVPlayerViewController { present(viewController, animated: true) } } }
1a4b89d7c45157c96dd5215e1ddf0b4a
53.488889
141
0.777732
false
false
false
false
ben-ng/swift
refs/heads/master
test/stdlib/ErrorBridged.swift
apache-2.0
2
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import StdlibUnittest import Foundation import CoreLocation import Darwin var ErrorBridgingTests = TestSuite("ErrorBridging") var NoisyErrorLifeCount = 0 var NoisyErrorDeathCount = 0 var CanaryHandle = 0 protocol OtherProtocol { var otherProperty: String { get } } protocol OtherClassProtocol : class { var otherClassProperty: String { get } } class NoisyError : Error, OtherProtocol, OtherClassProtocol { init() { NoisyErrorLifeCount += 1 } deinit { NoisyErrorDeathCount += 1 } let _domain = "NoisyError" let _code = 123 let otherProperty = "otherProperty" let otherClassProperty = "otherClassProperty" } @objc enum EnumError : Int, Error { case BadError = 9000 case ReallyBadError = 9001 } ErrorBridgingTests.test("NSError") { NoisyErrorLifeCount = 0 NoisyErrorDeathCount = 0 autoreleasepool { let ns = NSError(domain: "SomeDomain", code: 321, userInfo: nil) objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) let e: Error = ns expectEqual(e._domain, "SomeDomain") expectEqual(e._code, 321) let ns2 = e as NSError expectTrue(ns === ns2) expectEqual(ns2._domain, "SomeDomain") expectEqual(ns2._code, 321) } expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount) } ErrorBridgingTests.test("NSCopying") { autoreleasepool { let orig = EnumError.ReallyBadError as NSError let copy = orig.copy() as! NSError expectEqual(orig, copy) } } func archiveAndUnarchiveObject<T: NSCoding where T: NSObject>( _ object: T ) -> T? { let unarchiver = NSKeyedUnarchiver(forReadingWith: NSKeyedArchiver.archivedData(withRootObject: object) ) unarchiver.requiresSecureCoding = true return unarchiver.decodeObject(of: T.self, forKey: "root") } ErrorBridgingTests.test("NSCoding") { autoreleasepool { let orig = EnumError.ReallyBadError as NSError let unarchived = archiveAndUnarchiveObject(orig)! expectEqual(orig, unarchived) expectTrue(type(of: unarchived) == NSError.self) } } ErrorBridgingTests.test("NSError-to-enum bridging") { NoisyErrorLifeCount = 0 NoisyErrorDeathCount = 0 let testURL = URL(string: "https://swift.org")! autoreleasepool { let underlyingError = CocoaError(.fileLockingError) as Error as NSError let ns = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ AnyHashable(NSFilePathErrorKey): "/dev/null", AnyHashable(NSStringEncodingErrorKey): /*ASCII=*/1, AnyHashable(NSUnderlyingErrorKey): underlyingError, AnyHashable(NSURLErrorKey): testURL ]) objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) let e: Error = ns let cocoaCode: Int? switch e { case let x as CocoaError: cocoaCode = x._code expectTrue(x.isFileError) expectEqual(x.code, CocoaError.fileNoSuchFileError) default: cocoaCode = nil } expectEqual(NSFileNoSuchFileError, cocoaCode) let cocoaCode2: Int? = (ns as? CocoaError)?._code expectEqual(NSFileNoSuchFileError, cocoaCode2) let isNoSuchFileError: Bool switch e { case CocoaError.fileNoSuchFileError: isNoSuchFileError = true default: isNoSuchFileError = false } expectTrue(isNoSuchFileError) // Check the contents of the error. let cocoaError = e as! CocoaError expectOptionalEqual("/dev/null", cocoaError.filePath) expectOptionalEqual(String.Encoding.ascii, cocoaError.stringEncoding) expectOptionalEqual(underlyingError, cocoaError.underlying.map { $0 as NSError }) expectOptionalEqual(testURL, cocoaError.url) // URLError domain let nsURL = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [AnyHashable(NSURLErrorFailingURLErrorKey): testURL]) let eURL: Error = nsURL let isBadURLError: Bool switch eURL { case URLError.badURL: isBadURLError = true default: isBadURLError = false } expectTrue(isBadURLError) let urlError = eURL as! URLError expectOptionalEqual(testURL, urlError.failingURL) expectNil(urlError.failureURLPeerTrust) // CoreLocation error domain let nsCL = NSError(domain: kCLErrorDomain, code: CLError.headingFailure.rawValue, userInfo: [AnyHashable(NSURLErrorKey): testURL]) let eCL: Error = nsCL let isHeadingFailure: Bool switch eCL { case CLError.headingFailure: isHeadingFailure = true default: isHeadingFailure = false } let isCLError: Bool switch eCL { case let error as CLError: isCLError = true expectOptionalEqual(testURL, (error as NSError).userInfo[NSURLErrorKey as NSObject] as? URL) expectOptionalEqual(testURL, error.userInfo[NSURLErrorKey] as? URL) default: isCLError = false } expectTrue(isCLError) // NSPOSIXError domain let nsPOSIX = NSError(domain: NSPOSIXErrorDomain, code: Int(EDEADLK), userInfo: [:]) let ePOSIX: Error = nsPOSIX let isDeadlock: Bool switch ePOSIX { case POSIXError.EDEADLK: isDeadlock = true default: isDeadlock = false } expectTrue(isDeadlock) // NSMachError domain let nsMach = NSError(domain: NSMachErrorDomain, code: Int(KERN_MEMORY_FAILURE), userInfo: [:]) let eMach: Error = nsMach let isMemoryFailure: Bool switch eMach { case MachError.memoryFailure: isMemoryFailure = true default: isMemoryFailure = false } expectTrue(isMemoryFailure) } expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount) } func opaqueUpcastToAny<T>(_ x: T) -> Any { return x } struct StructError: Error { var _domain: String { return "StructError" } var _code: Int { return 4812 } } ErrorBridgingTests.test("Error-to-NSError bridging") { NoisyErrorLifeCount = 0 NoisyErrorDeathCount = 0 autoreleasepool { let e: Error = NoisyError() let ns = e as NSError let ns2 = e as NSError expectTrue(ns === ns2) expectEqual(ns._domain, "NoisyError") expectEqual(ns._code, 123) let e3: Error = ns expectEqual(e3._domain, "NoisyError") expectEqual(e3._code, 123) let ns3 = e3 as NSError expectTrue(ns === ns3) let nativeNS = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: nil) objc_setAssociatedObject(ns, &CanaryHandle, NoisyError(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) let nativeE: Error = nativeNS let nativeNS2 = nativeE as NSError expectTrue(nativeNS === nativeNS2) expectEqual(nativeNS2._domain, NSCocoaErrorDomain) expectEqual(nativeNS2._code, NSFileNoSuchFileError) let any: Any = NoisyError() let ns4 = any as! NSError expectEqual(ns4._domain, "NoisyError") expectEqual(ns4._code, 123) let ao: AnyObject = NoisyError() let ns5 = ao as! NSError expectEqual(ns5._domain, "NoisyError") expectEqual(ns5._code, 123) let any2: Any = StructError() let ns6 = any2 as! NSError expectEqual(ns6._domain, "StructError") expectEqual(ns6._code, 4812) } expectEqual(NoisyErrorDeathCount, NoisyErrorLifeCount) } ErrorBridgingTests.test("enum-to-NSError round trip") { autoreleasepool { // Emulate throwing an error from Objective-C. func throwNSError(_ error: EnumError) throws { throw NSError(domain: "main.EnumError", code: error.rawValue, userInfo: [:]) } var caughtError: Bool caughtError = false do { try throwNSError(.BadError) expectUnreachable() } catch let error as EnumError { expectEqual(.BadError, error) caughtError = true } catch _ { expectUnreachable() } expectTrue(caughtError) caughtError = false do { try throwNSError(.ReallyBadError) expectUnreachable() } catch EnumError.BadError { expectUnreachable() } catch EnumError.ReallyBadError { caughtError = true } catch _ { expectUnreachable() } expectTrue(caughtError) } } class SomeNSErrorSubclass: NSError {} ErrorBridgingTests.test("Thrown NSError identity is preserved") { do { let e = NSError(domain: "ClericalError", code: 219, userInfo: [AnyHashable("yeah"): "yeah"]) do { throw e } catch let e2 as NSError { expectTrue(e === e2) expectTrue(e2.userInfo["yeah"] as? String == "yeah") } catch { expectUnreachable() } } do { let f = SomeNSErrorSubclass(domain: "ClericalError", code: 219, userInfo: [AnyHashable("yeah"): "yeah"]) do { throw f } catch let f2 as NSError { expectTrue(f === f2) expectTrue(f2.userInfo["yeah"] as? String == "yeah") } catch { expectUnreachable() } } } // Check errors customized via protocol. struct MyCustomizedError : Error { let code: Int } extension MyCustomizedError : LocalizedError { var errorDescription: String? { return NSLocalizedString("something went horribly wrong", comment: "") } var failureReason: String? { return NSLocalizedString("because someone wrote 'throw'", comment: "") } var recoverySuggestion: String? { return NSLocalizedString("delete the 'throw'", comment: "") } var helpAnchor: String? { return NSLocalizedString("there is no help when writing tests", comment: "") } } extension MyCustomizedError : CustomNSError { static var errorDomain: String { return "custom" } /// The error code within the given domain. var errorCode: Int { return code } /// The user-info dictionary. var errorUserInfo: [String : Any] { return [NSURLErrorKey : URL(string: "https://swift.org")!] } } extension MyCustomizedError : RecoverableError { var recoveryOptions: [String] { return ["Delete 'throw'", "Disable the test" ] } func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool { return recoveryOptionIndex == 0 } } /// An error type that provides localization and recovery, but doesn't /// customize NSError directly. enum MySwiftCustomizedError : Error { case failed static var errorDescriptionCount = 0 } extension MySwiftCustomizedError : LocalizedError { var errorDescription: String? { MySwiftCustomizedError.errorDescriptionCount = MySwiftCustomizedError.errorDescriptionCount + 1 return NSLocalizedString("something went horribly wrong", comment: "") } var failureReason: String? { return NSLocalizedString("because someone wrote 'throw'", comment: "") } var recoverySuggestion: String? { return NSLocalizedString("delete the 'throw'", comment: "") } var helpAnchor: String? { return NSLocalizedString("there is no help when writing tests", comment: "") } } extension MySwiftCustomizedError : RecoverableError { var recoveryOptions: [String] { return ["Delete 'throw'", "Disable the test" ] } func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool { return recoveryOptionIndex == 0 } } /// Fake definition of the informal protocol /// "NSErrorRecoveryAttempting" that we use to poke at the object /// produced for a RecoverableError. @objc protocol FakeNSErrorRecoveryAttempting { @objc(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:) func attemptRecovery(fromError nsError: Error, optionIndex recoveryOptionIndex: Int, delegate: AnyObject?, didRecoverSelector: Selector, contextInfo: UnsafeMutableRawPointer?) @objc(attemptRecoveryFromError:optionIndex:) func attemptRecovery(fromError nsError: Error, optionIndex recoveryOptionIndex: Int) -> Bool } class RecoveryDelegate { let expectedSuccess: Bool let expectedContextInfo: UnsafeMutableRawPointer? var called = false init(expectedSuccess: Bool, expectedContextInfo: UnsafeMutableRawPointer?) { self.expectedSuccess = expectedSuccess self.expectedContextInfo = expectedContextInfo } @objc func recover(success: Bool, contextInfo: UnsafeMutableRawPointer?) { expectEqual(expectedSuccess, success) expectEqual(expectedContextInfo, contextInfo) called = true } } /// Helper for testing a customized error. func testCustomizedError(error: Error, nsError: NSError) { // LocalizedError if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSLocalizedDescriptionKey as NSObject]) expectNil(nsError.userInfo[NSLocalizedFailureReasonErrorKey as NSObject]) expectNil(nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey as NSObject]) expectNil(nsError.userInfo[NSHelpAnchorErrorKey as NSObject]) } else { expectOptionalEqual("something went horribly wrong", nsError.userInfo[NSLocalizedDescriptionKey as NSObject] as? String) expectOptionalEqual("because someone wrote 'throw'", nsError.userInfo[NSLocalizedFailureReasonErrorKey as NSObject] as? String) expectOptionalEqual("delete the 'throw'", nsError.userInfo[NSLocalizedRecoverySuggestionErrorKey as NSObject] as? String) expectOptionalEqual("there is no help when writing tests", nsError.userInfo[NSHelpAnchorErrorKey as NSObject] as? String) } expectEqual("something went horribly wrong", error.localizedDescription) expectEqual("something went horribly wrong", nsError.localizedDescription) expectEqual("because someone wrote 'throw'", nsError.localizedFailureReason) expectEqual("delete the 'throw'", nsError.localizedRecoverySuggestion) expectEqual("there is no help when writing tests", nsError.helpAnchor) // RecoverableError if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject]) } else { expectOptionalEqual(["Delete 'throw'", "Disable the test" ], nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject] as? [String]) } expectOptionalEqual(["Delete 'throw'", "Disable the test" ], nsError.localizedRecoveryOptions) // Directly recover. let attempter: AnyObject if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSRecoveryAttempterErrorKey as NSObject]) attempter = nsError.recoveryAttempter! as AnyObject } else { attempter = nsError.userInfo[NSRecoveryAttempterErrorKey as NSObject]! as AnyObject } expectOptionalEqual(attempter.attemptRecovery(fromError: nsError, optionIndex: 0), true) expectOptionalEqual(attempter.attemptRecovery(fromError: nsError, optionIndex: 1), false) // Recover through delegate. let rd1 = RecoveryDelegate(expectedSuccess: true, expectedContextInfo: nil) expectEqual(false, rd1.called) attempter.attemptRecovery( fromError: nsError, optionIndex: 0, delegate: rd1, didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)), contextInfo: nil) expectEqual(true, rd1.called) let rd2 = RecoveryDelegate(expectedSuccess: false, expectedContextInfo: nil) expectEqual(false, rd2.called) attempter.attemptRecovery( fromError: nsError, optionIndex: 1, delegate: rd2, didRecoverSelector: #selector(RecoveryDelegate.recover(success:contextInfo:)), contextInfo: nil) expectEqual(true, rd2.called) } ErrorBridgingTests.test("Customizing NSError via protocols") { let error = MyCustomizedError(code: 12345) let nsError = error as NSError // CustomNSError expectEqual("custom", nsError.domain) expectEqual(12345, nsError.code) expectOptionalEqual(URL(string: "https://swift.org")!, nsError.userInfo[NSURLErrorKey as NSObject] as? URL) testCustomizedError(error: error, nsError: nsError) } ErrorBridgingTests.test("Customizing localization/recovery via protocols") { let error = MySwiftCustomizedError.failed let nsError = error as NSError testCustomizedError(error: error, nsError: nsError) } ErrorBridgingTests.test("Customizing localization/recovery laziness") { let countBefore = MySwiftCustomizedError.errorDescriptionCount let error = MySwiftCustomizedError.failed let nsError = error as NSError // RecoverableError if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectNil(nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject]) } else { expectOptionalEqual(["Delete 'throw'", "Disable the test" ], nsError.userInfo[NSLocalizedRecoveryOptionsErrorKey as NSObject] as? [String]) } expectOptionalEqual(["Delete 'throw'", "Disable the test" ], nsError.localizedRecoveryOptions) // None of the operations above should affect the count if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectEqual(countBefore, MySwiftCustomizedError.errorDescriptionCount) } // This one does affect the count. expectEqual("something went horribly wrong", error.localizedDescription) // Check that we did get a call to errorDescription. if #available(OSX 10.11, iOS 9.0, tvOS 9.0, watchOS 2.0, *) { expectEqual(countBefore+1, MySwiftCustomizedError.errorDescriptionCount) } } enum DefaultCustomizedError1 : CustomNSError { case bad case worse } enum DefaultCustomizedError2 : Int, CustomNSError { case bad = 7 case worse = 13 } enum DefaultCustomizedError3 : UInt, CustomNSError { case bad = 9 case worse = 115 static var errorDomain: String { return "customized3" } } ErrorBridgingTests.test("Default-customized via CustomNSError") { expectEqual(1, (DefaultCustomizedError1.worse as NSError).code) expectEqual(13, (DefaultCustomizedError2.worse as NSError).code) expectEqual(115, (DefaultCustomizedError3.worse as NSError).code) expectEqual("customized3", (DefaultCustomizedError3.worse as NSError).domain) } class MyNSError : NSError { } ErrorBridgingTests.test("NSError subclass identity") { let myNSError: Error = MyNSError(domain: "MyNSError", code: 0, userInfo: [:]) let nsError = myNSError as NSError expectTrue(type(of: nsError) == MyNSError.self) } ErrorBridgingTests.test("Wrapped NSError identity") { let nsError = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ AnyHashable(NSFilePathErrorKey) : "/dev/null", AnyHashable(NSStringEncodingErrorKey): /*ASCII=*/1, ]) let error: Error = nsError let nsError2: NSError = error as NSError expectTrue(nsError === nsError2) // Extracting the NSError via the runtime. let cocoaErrorAny: Any = error as! CocoaError let nsError3: NSError = cocoaErrorAny as! NSError expectTrue(nsError === nsError3) if let cocoaErrorAny2: Any = error as? CocoaError { let nsError4: NSError = cocoaErrorAny2 as! NSError expectTrue(nsError === nsError4) } else { expectUnreachable() } // Extracting the NSError via direct call. let cocoaError = error as! CocoaError let nsError5: NSError = cocoaError as NSError expectTrue(nsError === nsError5) if let cocoaError2 = error as? CocoaError { let nsError6: NSError = cocoaError as NSError expectTrue(nsError === nsError6) } else { expectUnreachable() } } extension Error { func asNSError() -> NSError { return self as NSError } } func unconditionalCast<T>(_ x: Any, to: T.Type) -> T { return x as! T } func conditionalCast<T>(_ x: Any, to: T.Type) -> T? { return x as? T } // SR-1562 ErrorBridgingTests.test("Error archetype identity") { let myError = NSError(domain: "myErrorDomain", code: 0, userInfo: [ AnyHashable("one") : 1 ]) expectTrue(myError === myError.asNSError()) expectTrue(unconditionalCast(myError, to: Error.self) as NSError === myError) expectTrue(conditionalCast(myError, to: Error.self)! as NSError === myError) let nsError = NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ AnyHashable(NSFilePathErrorKey) : "/dev/null", AnyHashable(NSStringEncodingErrorKey): /*ASCII=*/1, ]) let cocoaError = nsError as Error as! CocoaError expectTrue(cocoaError.asNSError() === nsError) expectTrue(unconditionalCast(cocoaError, to: Error.self) as NSError === nsError) expectTrue(conditionalCast(cocoaError, to: Error.self)! as NSError === nsError) } runAllTests()
2c20e92305c45aa128716d5af18cd167
29.309353
98
0.688441
false
true
false
false
sourcebitsllc/Asset-Generator-Mac
refs/heads/master
XCAssetGenerator/AssetAttribute.swift
mit
1
// // AssetAttributeProcessor.swift // XCAssetGenerator // // Created by Bader on 6/17/15. // Copyright (c) 2015 Bader Alabdulrazzaq. All rights reserved. // import Cocoa /// A JSON representation of the values in an individual Asset Catalog JSON. /// Will always contains a minimum of the following keys: .Scale and .Idiom /// Other available keys as specified in XCAssetsJSONKeys. typealias XCAssetsJSON = [String: AnyObject] /// Represents the outer JSON of the XCAssetsJSON values. /// Will always contain the following keys: "info", "images". typealias XCAssetsJSONWrapper = [String: AnyObject] func sanitizeJSON(json: [XCAssetsJSON]) -> [XCAssetsJSON] { func removeUnwanted(dict: [String: AnyObject]) -> XCAssetsJSON { var clean = dict clean.removeValueForKey(XCAssetsJSONKeys.Unassigned) return clean } return json.map(removeUnwanted) } struct AssetAttribute: Serializable { var filename: String? let scale: String let idiom: String let size: String? let extent: String? let subtype: String? let orientation: String? let minimumSystemVersion: String? // MARK: - Initializers private init (filename: String?, scale: String, idiom: String, size: String? = nil, subtype: String? = nil, orientation: String? = nil, minimumSystemVersion: String? = nil, extent: String? = nil) { self.filename = filename self.scale = scale self.idiom = idiom self.size = size self.extent = extent self.subtype = subtype self.orientation = orientation self.minimumSystemVersion = minimumSystemVersion } // MARK: - Serializable typealias Serialized = XCAssetsJSON var serialized: Serialized { var s = [XCAssetsJSONKeys.Scale: scale, XCAssetsJSONKeys.Idiom: idiom] if let filename = filename { s[XCAssetsJSONKeys.Filename] = filename } if let size = size { s[XCAssetsJSONKeys.Size] = size } if let extent = extent { s[XCAssetsJSONKeys.Extent] = extent } if let subtype = subtype { s[XCAssetsJSONKeys.Subtype] = subtype } if let orientation = orientation { s[XCAssetsJSONKeys.Orientation] = orientation } if let minimumSystemVersion = minimumSystemVersion { s[XCAssetsJSONKeys.MinimumSystemVersion] = minimumSystemVersion } return s } } struct AssetAttributeProcessor { static func withAsset(path: Path) -> AssetAttribute { let name = path.lastPathComponent let is2x = name.contains(GenerationKeywords.PPI2x) let is3x = name.contains(GenerationKeywords.PPI3x) let scale = is2x ? "2x" : is3x ? "3x" : "1x" let isiPhone = name.contains(GenerationKeywords.iPhone) let isiPad = name.contains(GenerationKeywords.iPad) let isMac = name.contains(GenerationKeywords.Mac) let idiom = isiPhone ? "iphone" : isiPad ? "ipad" : isMac ? "mac" : "universal" return AssetAttribute(filename: name, scale: scale, idiom: idiom) } static func withMacIcon(path: Path) -> AssetAttribute { let imgURL = NSURL(fileURLWithPath: path) let src = CGImageSourceCreateWithURL(imgURL, nil) let result = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as NSDictionary let name = path.lastPathComponent let width = result[kCGImagePropertyPixelWidth as String]! as! Int let is2x = name.contains("@2x") let idiom = "mac" var scale = is2x ? "2x" : "1x" var size = "16x16" switch width { case 16: break case 32: size = is2x ? "16x16" : "32x32" case 64: scale = "2x" size = "32x32" case 128: scale = "1x" size = "128x128" case 256: size = is2x ? "128x128" : "256x256" case 512: size = is2x ? "256x256" : "512x512" case 1024: scale = "2x" size = "512x512" default: break } return AssetAttribute(filename: name, scale: scale, idiom: idiom, size: size) } static func withIcon(path: Path) -> AssetAttribute { let name = path.lastPathComponent if AssetType.isMacIcon(name) { return AssetAttributeProcessor.withMacIcon(path) } let imgURL = NSURL(fileURLWithPath: path) let src = CGImageSourceCreateWithURL(imgURL, nil) let result = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as NSDictionary let width = result[kCGImagePropertyPixelWidth as String]! as! Int var idiom = "iphone" var scale = "1x" var size = "60x60" switch width { case 60: break case 120: idiom = "iphone" let spotlight = name.contains("@3x") || name.contains("Icon-Small") // Spotlight 40@3x or iPhone icon 60@2x scale = spotlight ? "3x" : "2x" size = spotlight ? "40x40" : "60x60" case 180: scale = "3x" case 76: idiom = "ipad" size = "76x76" case 152: idiom = "ipad" scale = "2x" size = "76x76" case 40: idiom = "ipad" scale = "1x" size = "40x40" case 80: idiom = name.contains(GenerationKeywords.iPad) ? "ipad" : "iphone" scale = "2x" size = "40x40" case 29: idiom = "ipad" scale = "1x" size = "29x29" case 58: idiom = name.contains(GenerationKeywords.iPad) ? "ipad" : "iphone" scale = "2x" size = "29x29" case 87: idiom = "iphone" scale = "3x" size = "29x29" default: break } return AssetAttribute(filename: name, scale: scale, idiom: idiom, size: size) } static func withLaunchImage(path: Path) -> AssetAttribute { let imgURL = NSURL(fileURLWithPath: path) let src = CGImageSourceCreateWithURL(imgURL, nil) let result = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as NSDictionary let name = path.lastPathComponent let width = result[kCGImagePropertyPixelWidth as String]! as! Float var idiom = "iphone" var scale = "1x" var subtype = "" var orientation = "portrait" var minimumVersion = "7.0" let extent = "full-screen" switch width { case 320: break case 640: scale = "2x" let height = result[kCGImagePropertyPixelHeight as String]! as! Float if (height == 1136) { subtype = "retina4" } case 1242: scale = "3x" subtype = "736h" minimumVersion = "8.0" case 750: scale = "2x" subtype = "667h" minimumVersion = "8.0" case 2208: scale = "3x" subtype = "736h" minimumVersion = "8.0" case 768: idiom = "ipad" case 1536: idiom = "ipad" scale = "2x" case 1024: idiom = "ipad" orientation = "landscape" case 2048: idiom = "ipad" scale = "2x" orientation = "landscape" default: break } return AssetAttribute(filename: name, scale: scale, idiom: idiom, extent: extent, subtype: subtype, orientation: orientation, minimumSystemVersion: minimumVersion) } }
b4d0951608e506b8107c9b099a816147
30.505976
201
0.557157
false
false
false
false
grandiere/box
refs/heads/master
box/View/Grid/VGridBar.swift
mit
1
import UIKit class VGridBar:UIView { private weak var controller:CGrid! private let kButtonWidth:CGFloat = 60 private let kBorderHeight:CGFloat = 1 private let kBlurAlpha:CGFloat = 0.99 init(controller:CGrid) { super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false self.controller = controller let backButton:UIButton = UIButton() backButton.translatesAutoresizingMaskIntoConstraints = false backButton.setImage( #imageLiteral(resourceName: "assetGenericBack").withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.normal) backButton.setImage( #imageLiteral(resourceName: "assetGenericBack").withRenderingMode(UIImageRenderingMode.alwaysTemplate), for:UIControlState.highlighted) backButton.imageView!.clipsToBounds = true backButton.imageView!.contentMode = UIViewContentMode.center backButton.imageView!.tintColor = UIColor.white backButton.addTarget( self, action:#selector(actionBack(sender:)), for:UIControlEvents.touchUpInside) let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.center imageView.clipsToBounds = true imageView.image = #imageLiteral(resourceName: "assetGenericTheGrid") let border:VBorder = VBorder(color:UIColor(white:1, alpha:0.3)) let blurContainer:UIView = UIView() blurContainer.isUserInteractionEnabled = false blurContainer.translatesAutoresizingMaskIntoConstraints = false blurContainer.clipsToBounds = true blurContainer.alpha = kBlurAlpha let blur:VBlur = VBlur.dark() blurContainer.addSubview(blur) addSubview(blurContainer) addSubview(border) addSubview(imageView) addSubview(backButton) NSLayoutConstraint.equals( view:blur, toView:blurContainer) NSLayoutConstraint.equals( view:blurContainer, toView:self) NSLayoutConstraint.equalsVertical( view:backButton, toView:self) NSLayoutConstraint.leftToLeft( view:backButton, toView:self) NSLayoutConstraint.width( view:backButton, constant:kButtonWidth) NSLayoutConstraint.equals( view:imageView, toView:self) NSLayoutConstraint.bottomToBottom( view:border, toView:self) NSLayoutConstraint.height( view:border, constant:kBorderHeight) NSLayoutConstraint.equalsHorizontal( view:border, toView:self) } required init?(coder:NSCoder) { return nil } //MARK: actions func actionBack(sender button:UIButton) { controller.back() } }
971a4fd615728442ba57275c96a6956b
31.207921
115
0.632032
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/Utilites/3rdParty/InputBar/SAIInputItem.swift
mit
1
// // SAIInputItem.swift // SAIInputBar // // Created by SAGESSE on 8/3/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit public enum SAIInputItemPosition: Int { case top = 0 case left = 1 case right = 3 case bottom = 4 case center = 2 } public enum SAIInputItemAlignment: Int { //0xvvhh case top = 0x0104 // Top + Center(H) case bottom = 0x0204 // Bottom + Center(H) case left = 0x0401 // Center(V) + Left case right = 0x0402 // Center(V) + Right case topLeft = 0x0101 // Top + Left case topRight = 0x0102 // Top + Right case bottomLeft = 0x0201 // Bottom + Left case bottomRight = 0x0202 // Bottom + Right case center = 0x0404 // Center(V) + Center(H) case automatic = 0x0000 } open class SAIInputItem: NSObject { // MARK: property open lazy var identifier: String = UUID().uuidString open var size: CGSize = CGSize.zero // default is CGSizeZero open var image: UIImage? // default is nil open var customView: UIView? // default is nil open var tag: Int = 0 // default is 0 open var title: String? // default is nil open var enabled: Bool = true // default is YES open var font: UIFont? // default is nil open var backgroundColor: UIColor? // default is nil open var handler: ((SAIInputItem) -> Void)? // default is nil open var tintColor: UIColor? open var alignment: SAIInputItemAlignment = .automatic open var imageInsets: UIEdgeInsets = .zero // default is UIEdgeInsetsZero // MARK: setter open func setTitle(_ title: String?, for state: UIControl.State) { _titles[state.rawValue] = title } open func setTitleColor(_ color: UIColor?, for state: UIControl.State) { _titleColors[state.rawValue] = color } open func setTitleShadowColor(_ color: UIColor?, for state: UIControl.State) { _titleShadowColors[state.rawValue] = color } open func setAttributedTitle(_ title: NSAttributedString?, for state: UIControl.State) { _attributedTitles[state.rawValue] = title } open func setImage(_ image: UIImage?, for state: UIControl.State) { _images[state.rawValue] = image } open func setBackgroundImage(_ image: UIImage?, for state: UIControl.State) { _backgroundImages[state.rawValue] = image } // MARK: getter open func title(for state: UIControl.State) -> String? { return _titles[state.rawValue] ?? nil } open func titleColor(for state: UIControl.State) -> UIColor? { return _titleColors[state.rawValue] ?? nil } open func titleShadowColor(for state: UIControl.State) -> UIColor? { return _titleShadowColors[state.rawValue] ?? nil } open func attributedTitle(for state: UIControl.State) -> NSAttributedString? { return _attributedTitles[state.rawValue] ?? nil } open func image(for state: UIControl.State) -> UIImage? { return _images[state.rawValue] ?? nil } open func backgroundImage(for state: UIControl.State) -> UIImage? { return _backgroundImages[state.rawValue] ?? nil } open override var hash: Int { return identifier.hash } // open override var hashValue: Int { // return identifier.hashValue // } // MARK: ivar private var _titles: [UInt: String?] = [:] private var _titleColors: [UInt: UIColor?] = [:] private var _titleShadowColors: [UInt: UIColor?] = [:] private var _attributedTitles: [UInt: NSAttributedString?] = [:] private var _images: [UInt: UIImage?] = [:] private var _backgroundImages: [UInt: UIImage?] = [:] // MARK: create public override init() { super.init() } public convenience init(image: UIImage?, handler: ((SAIInputItem) -> Void)? = nil) { self.init() self.image = image self.handler = handler } public convenience init(title: String?, handler: ((SAIInputItem) -> Void)? = nil) { self.init() self.title = title self.handler = handler } public convenience init(customView: UIView) { self.init() self.customView = customView } } extension SAIInputItemPosition: CustomStringConvertible { public var description: String { switch self { case .top: return "Top(\(rawValue))" case .left: return "Left(\(rawValue))" case .right: return "Right(\(rawValue))" case .bottom: return "Bottom(\(rawValue))" case .center: return "Center(\(rawValue))" } } }
7d2e76ee56ba666336dd77ec211b2276
30.892617
92
0.609848
false
false
false
false
2794129697/-----mx
refs/heads/master
CoolXuePlayer/RegisterViewController.swift
lgpl-3.0
1
// // RegisterViewController.swift // CoolXuePlayer // // Created by lion-mac on 15/6/4. // Copyright (c) 2015年 lion-mac. All rights reserved. // import UIKit class RegisterViewController: UIViewController,UITextFieldDelegate,UIAlertViewDelegate{ @IBOutlet weak var userIdTextField: UITextField! @IBOutlet weak var pwdTextField: UITextField! @IBOutlet weak var pwdAgainTextField: UITextField! @IBOutlet weak var jobTextField: UITextField! @IBOutlet weak var bnSelectJop: UIButton! var alertView:UIAlertView! var popView:uiPopView! var job:Int! //实现job选择后的回调函数 func selectionHandler(selectedItem:NSDictionary){ self.popView = nil jobTextField.text = selectedItem["name"] as! String self.job = selectedItem["id"] as! Int } //展开职业选项 @IBAction func bnSelectJobClicked(sender: UIButton) { let btn = sender if self.popView == nil { self.popView = uiPopView(selectedItemCallBack: self.selectionHandler) self.popView.showDropDown(sender.superview!, frame: sender.frame, bounds: sender.bounds) }else{ self.popView.hideDropDown() self.popView = nil } } func showAlertView(tag _tag:Int,title:String,message:String,delegate:UIAlertViewDelegate,cancelButtonTitle:String){ if alertView == nil { alertView = UIAlertView() } alertView.title = title alertView.message = message alertView.delegate = self alertView.addButtonWithTitle(cancelButtonTitle) alertView.tag = _tag alertView.show() } func textFieldShouldReturn(textField: UITextField) -> Bool { self.registerBnClicked("") self.userIdTextField.resignFirstResponder() self.pwdTextField.resignFirstResponder() self.pwdAgainTextField.resignFirstResponder() return true } @IBAction func registerBnClicked(sender: AnyObject) { var userid = self.userIdTextField.text var pwd = self.pwdTextField.text var pwdAgain = self.pwdAgainTextField.text if userid.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 { self.showAlertView(tag: 0,title: "提示", message: "用户名不能为空!", delegate: self, cancelButtonTitle: "确定") return } if self.job == nil { self.showAlertView(tag: 0,title: "提示", message: "请选择职业!", delegate: self, cancelButtonTitle: "确定") return } if pwd.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 { self.showAlertView(tag: 0,title: "提示", message: "密码不能为空!", delegate: self, cancelButtonTitle: "确定") return } if pwdAgain.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 { self.showAlertView(tag: 0,title: "提示", message: "确认密码不能为空!", delegate: self, cancelButtonTitle: "确定") return } if pwd != pwdAgain { self.showAlertView(tag: 0,title: "提示", message: "两次密码输入不一致!", delegate: self, cancelButtonTitle: "确定") return } var url = "http://www.icoolxue.com/account/register" var bodyParam:NSDictionary = ["username":userid,"job":self.job!,"password":pwd,"passwordAgain":pwdAgain] HttpManagement.requestttt(url, method: "POST",bodyParam: bodyParam as! Dictionary<String, AnyObject>,headParam:nil) { (repsone:NSHTTPURLResponse,data:NSData) -> Void in var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary println(bdict) var code:Int = bdict["code"] as! Int if HttpManagement.HttpResponseCodeCheck(code, viewController: self){ self.showAlertView(tag: 1,title: "提示", message: "注册成功!", delegate: self, cancelButtonTitle: "确定") }else{ self.showAlertView(tag: 0,title: "提示", message: "注册失败!", delegate: self, cancelButtonTitle: "确定") } } } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { println("buttonIndex=\(buttonIndex)") if alertView.tag == 0 { }else if alertView.tag == 1 { self.navigationController?.popViewControllerAnimated(true) } } override func viewDidLoad() { super.viewDidLoad() self.userIdTextField.delegate = self self.pwdTextField.delegate = self self.pwdAgainTextField.delegate = self // Do any additional setup after loading the view. } 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. } */ }
70a13c5eced9f2f524d388d75c6a69be
38.692308
176
0.64845
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Camera/Controller/CameraManager.swift
mit
1
// // CameraManager.swift // HXPHPicker // // Created by Slience on 2021/8/30. // import UIKit import AVFoundation class CameraManager: NSObject { let config: CameraConfiguration lazy var session: AVCaptureSession = { AVCaptureSession() }() lazy var photoOutput: AVCapturePhotoOutput = { let output = AVCapturePhotoOutput() return output }() var didAddVideoOutput = false let outputQueue: DispatchQueue = DispatchQueue(label: "com.hxphpicker.cameraoutput") lazy var videoOutput: AVCaptureVideoDataOutput = { let videoOutput = AVCaptureVideoDataOutput() videoOutput.videoSettings = [ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA ] videoOutput.setSampleBufferDelegate( self, queue: outputQueue ) videoOutput.alwaysDiscardsLateVideoFrames = true return videoOutput }() var didAddAudioOutput = false lazy var audioOutput: AVCaptureAudioDataOutput = { let audioOutput = AVCaptureAudioDataOutput() audioOutput.setSampleBufferDelegate( self, queue: outputQueue ) return audioOutput }() var assetWriter: AVAssetWriter? var assetWriterVideoInput: AVAssetWriterInputPixelBufferAdaptor? var assetWriterAudioInput: AVAssetWriterInput? let sessionQueue: DispatchQueue = .init( label: "com.phpicker.sessionQueue", qos: .background ) var activeVideoInput: AVCaptureDeviceInput? var isRecording: Bool = false var flashModeDidChanged: ((AVCaptureDevice.FlashMode) -> Void)? var captureDidOutput: ((CVPixelBuffer) -> Void)? private(set) var flashMode: AVCaptureDevice.FlashMode private var recordDuration: TimeInterval = 0 private var photoWillCapture: (() -> Void)? private var photoCompletion: ((Data?) -> Void)? private var videoRecordingProgress: ((Float, TimeInterval) -> Void)? private var videoCompletion: ((URL?, Error?) -> Void)? private var timer: Timer? private var dateVideoStarted = Date() private var videoDidStartRecording: ((TimeInterval) -> Void)? private var captureState: CaptureState = .end private var didStartWriter = false private var didWriterVideoInput = false private var videoInpuCompletion = false private var audioInpuCompletion = false let videoFilter: CameraRenderer let photoFilter: CameraRenderer var filterIndex: Int { get { videoFilter.filterIndex } set { videoFilter.filterIndex = newValue photoFilter.filterIndex = newValue } } init(config: CameraConfiguration) { self.flashMode = config.flashMode self.config = config var photoFilters = config.photoFilters photoFilters.insert(OriginalFilter(), at: 0) var videoFilters = config.videoFilters videoFilters.insert(OriginalFilter(), at: 0) var index = config.defaultFilterIndex if index == -1 { index = 0 }else { index += 1 } self.photoFilter = .init(photoFilters, index) self.videoFilter = .init(videoFilters, index) super.init() DeviceOrientationHelper.shared.startDeviceOrientationNotifier() } func startSession() throws { var sessionPreset = config.sessionPreset.system if !session.canSetSessionPreset(sessionPreset) { sessionPreset = .high } session.sessionPreset = sessionPreset let position: AVCaptureDevice.Position = config.position == .back ? .back : .front let videoDevice: AVCaptureDevice if let device = camera(with: position) { videoDevice = device }else if let device = camera(with: .back) { videoDevice = device }else { throw NSError( domain: "Video device is nil", code: 500, userInfo: nil ) } let videoInput = try AVCaptureDeviceInput(device: videoDevice) if !session.canAddInput(videoInput) { throw NSError( domain: "Does not support adding video input", code: 500, userInfo: nil ) } session.addInput(videoInput) activeVideoInput = videoInput } func addAudioInput() throws { guard let audioDevice = AVCaptureDevice.default(for: .audio) else { throw NSError( domain: "Audio device is nil", code: 500, userInfo: nil ) } let audioInput = try AVCaptureDeviceInput(device: audioDevice) if !session.canAddInput(audioInput) { throw NSError( domain: "Does not support adding audio input", code: 500, userInfo: nil ) } session.addInput(audioInput) } func addPhotoOutput() throws { if session.canAddOutput(photoOutput) { session.addOutput(photoOutput) photoOutput.isHighResolutionCaptureEnabled = true // Improve capture time by preparing output with the desired settings. photoOutput.setPreparedPhotoSettingsArray([photoCaptureSettings()], completionHandler: nil) return } throw NSError( domain: "Can't add photo output", code: 500, userInfo: nil ) } func removePhotoOutput() { session.removeOutput(photoOutput) } func startRunning() { if session.isRunning { return } sessionQueue.async { self.session.startRunning() } } func stopRunning() { if !session.isRunning { return } sessionQueue.async { self.session.stopRunning() } } func addVideoOutput() { if session.canAddOutput(videoOutput) { session.addOutput(videoOutput) didAddVideoOutput = true } } func addAudioOutput() { if session.canAddOutput(audioOutput) { session.addOutput(audioOutput) didAddAudioOutput = true } } deinit { if didAddVideoOutput { videoOutput.setSampleBufferDelegate(nil, queue: nil) didAddVideoOutput = false } if didAddAudioOutput { audioOutput.setSampleBufferDelegate(nil, queue: nil) didAddAudioOutput = false } } } extension CameraManager { func discoverySession( with position: AVCaptureDevice.Position = .unspecified ) -> AVCaptureDevice.DiscoverySession { let deviceTypes: [AVCaptureDevice.DeviceType] = [ .builtInWideAngleCamera ] return AVCaptureDevice.DiscoverySession( deviceTypes: deviceTypes, mediaType: .video, position: position ) } func cameraCount() -> Int { discoverySession().devices.count } func camera( with position: AVCaptureDevice.Position ) -> AVCaptureDevice? { let discoverySession = discoverySession( with: position ) for device in discoverySession.devices where device.position == position { return device } return nil } func canSwitchCameras() -> Bool { cameraCount() > 1 } var activeCamera: AVCaptureDevice? { activeVideoInput?.device } func inactiveCamer() -> AVCaptureDevice? { if let device = activeCamera { if device.position == .back { return camera(with: .front) } return camera(with: .back) } return camera(with: .back) } func cameraSupportsTapToFocus() -> Bool { guard let camera = activeCamera else { return false } return camera.isFocusPointOfInterestSupported } func cameraHasFlash() -> Bool { guard let camera = activeCamera else { return false } return camera.hasFlash } @discardableResult func setFlashMode(_ mode: AVCaptureDevice.FlashMode) -> Bool { if flashMode == mode { return true } let contains = flashModeContains(mode) if contains { flashMode = mode flashModeDidChanged?(flashMode) } return contains } func cameraHasTorch() -> Bool { guard let camera = activeCamera else { return false } return camera.hasTorch } func torchMode() -> AVCaptureDevice.TorchMode { guard let camera = activeCamera else { return .auto } return camera.torchMode } func setTorchMode(_ mode: AVCaptureDevice.TorchMode) throws { guard let device = activeCamera else { return } if device.torchMode != mode && device.isTorchModeSupported(mode) { try device.lockForConfiguration() device.torchMode = mode device.unlockForConfiguration() } } var isSupportsZoom: Bool { guard let camera = activeCamera else { return false } return camera.activeFormat.videoMaxZoomFactor > 1.0 } var maxZoomFactor: CGFloat { guard let camera = activeCamera else { return 1 } return min(camera.activeFormat.videoMaxZoomFactor, config.videoMaxZoomScale) } var zoomFacto: CGFloat { get { guard let camera = activeCamera else { return 1 } return camera.videoZoomFactor } set { guard let camera = activeCamera, !camera.isRampingVideoZoom else { return } let zoom = min(newValue, maxZoomFactor) do { try camera.lockForConfiguration() camera.videoZoomFactor = zoom camera.unlockForConfiguration() } catch { print(error) } } } func rampZoom(to value: CGFloat, withRate rate: Float = 1) throws { guard let camera = activeCamera else { return } try camera.lockForConfiguration() camera.ramp(toVideoZoomFactor: value, withRate: rate) camera.unlockForConfiguration() } func cancelZoom() throws { guard let camera = activeCamera else { return } try camera.lockForConfiguration() camera.cancelVideoZoomRamp() camera.unlockForConfiguration() } } extension CameraManager { func switchCameras() throws { if !canSwitchCameras() { throw NSError( domain: "Does not support switch Cameras", code: 500, userInfo: nil ) } guard let device = inactiveCamer() else { throw NSError( domain: "device is nil", code: 500, userInfo: nil ) } let videoInput = try AVCaptureDeviceInput(device: device) session.beginConfiguration() if let input = activeVideoInput { session.removeInput(input) } if !session.canAddInput(videoInput) { session.commitConfiguration() throw NSError( domain: "Does not support adding audio input", code: 500, userInfo: nil ) } session.addInput(videoInput) activeVideoInput = videoInput session.commitConfiguration() } func expose(at point: CGPoint) throws { guard let device = activeCamera else { return } let textureRect = CGRect(origin: point, size: .zero) let deviceRect = videoOutput.metadataOutputRectConverted(fromOutputRect: textureRect) let exposureMode = AVCaptureDevice.ExposureMode.continuousAutoExposure let focusMode = AVCaptureDevice.FocusMode.continuousAutoFocus let canResetFocus = device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) let canResetExposure = device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) try device.lockForConfiguration() if canResetFocus { device.focusPointOfInterest = deviceRect.origin device.focusMode = focusMode } if canResetExposure { device.exposurePointOfInterest = deviceRect.origin device.exposureMode = exposureMode } device.unlockForConfiguration() } func resetFocusAndExposeModes() throws { let centerPoint = CGPoint(x: 0.5, y: 0.5) try expose(at: centerPoint) } } extension CameraManager: AVCapturePhotoCaptureDelegate { func flashModeContains(_ mode: AVCaptureDevice.FlashMode) -> Bool { let supportedFlashModes = photoOutput.__supportedFlashModes switch mode { case .auto: if supportedFlashModes.contains(NSNumber(value: AVCaptureDevice.FlashMode.auto.rawValue)) { return true } case .off: if supportedFlashModes.contains(NSNumber(value: AVCaptureDevice.FlashMode.off.rawValue)) { return true } case .on: if supportedFlashModes.contains(NSNumber(value: AVCaptureDevice.FlashMode.on.rawValue)) { return true } @unknown default: fatalError() } return false } func photoCaptureSettings() -> AVCapturePhotoSettings { let settings = AVCapturePhotoSettings( format: [ kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA) ] ) settings.previewPhotoFormat = [ kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA) ] // Catpure Heif when available. // if #available(iOS 11.0, *) { // if photoOutput.availablePhotoCodecTypes.contains(.hevc) { // settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.hevc]) // } // } // Catpure Highest Quality possible. settings.isHighResolutionPhotoEnabled = true // Set flash mode. if let deviceInput = activeCamera { if deviceInput.isFlashAvailable && flashModeContains(flashMode) { settings.flashMode = flashMode } } return settings } func capturePhoto( willBegin: @escaping () -> Void, completion: @escaping (Data?) -> Void ) { photoWillCapture = willBegin photoCompletion = completion if let connection = photoOutput.connection(with: .video) { connection.videoOrientation = currentOrienation if connection.isVideoMirroringSupported { if activeCamera?.position == .front { connection.isVideoMirrored = true }else { connection.isVideoMirrored = false } } } photoOutput.capturePhoto(with: photoCaptureSettings(), delegate: self) } func photoOutput( _ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings ) { photoWillCapture?() } func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { guard let photoPixelBuffer = photo.previewPixelBuffer else { photoCompletion?(nil) return } var photoFormatDescription: CMFormatDescription? CMVideoFormatDescriptionCreateForImageBuffer( allocator: kCFAllocatorDefault, imageBuffer: photoPixelBuffer, formatDescriptionOut: &photoFormatDescription ) DispatchQueue.global().async { var finalPixelBuffer = photoPixelBuffer if self.photoFilter.filterIndex > 0 { if !self.photoFilter.isPrepared { if let formatDescription = photoFormatDescription { self.photoFilter.prepare( with: formatDescription, outputRetainedBufferCountHint: 2, imageSize: .init( width: CVPixelBufferGetWidth(photoPixelBuffer), height: CVPixelBufferGetHeight(photoPixelBuffer) ) ) } } guard let filteredBuffer = self.photoFilter.render( pixelBuffer: photoPixelBuffer ) else { DispatchQueue.main.async { self.photoCompletion?(nil) } return } finalPixelBuffer = filteredBuffer } let metadataAttachments = photo.metadata as CFDictionary let jpegData = PhotoTools.jpegData( withPixelBuffer: finalPixelBuffer, attachments: metadataAttachments ) DispatchQueue.main.async { self.photoCompletion?(jpegData) } } } } extension CameraManager { enum CaptureState { case start case capturing case end } var currentOrienation: AVCaptureVideoOrientation { let orientation = DeviceOrientationHelper.shared.currentDeviceOrientation switch orientation { case .portrait: return .portrait case .portraitUpsideDown: return .portraitUpsideDown case .landscapeRight: return .landscapeLeft case .landscapeLeft: return .landscapeRight default: return .portrait } } } extension CameraManager: AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate { func captureOutput( _ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection ) { var finalVideoPixelBuffer: CVPixelBuffer? if output == videoOutput { PhotoManager.shared.sampleBuffer = sampleBuffer guard let videoPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer), let formatDescription = CMSampleBufferGetFormatDescription(sampleBuffer) else { return } finalVideoPixelBuffer = videoPixelBuffer if videoFilter.filterIndex > 0 { if !videoFilter.isPrepared { videoFilter.prepare( with: formatDescription, outputRetainedBufferCountHint: 3, imageSize: .init( width: CVPixelBufferGetWidth(videoPixelBuffer), height: CVPixelBufferGetHeight(videoPixelBuffer) ) ) } guard let filteredBuffer = videoFilter.render( pixelBuffer: videoPixelBuffer ) else { return } captureDidOutput?(filteredBuffer) finalVideoPixelBuffer = filteredBuffer }else { captureDidOutput?(videoPixelBuffer) } } if captureState == .start && output == videoOutput { if !CMSampleBufferDataIsReady(sampleBuffer) { return } if !setupWriter(sampleBuffer) { resetAssetWriter() DispatchQueue.main.async { self.videoCompletion?(nil, nil) } return } guard let assetWriter = assetWriter else { return } if !assetWriter.startWriting() { DispatchQueue.main.async { self.videoCompletion?(nil, assetWriter.error) } resetAssetWriter() return } captureState = .capturing }else if captureState == .capturing { if !didStartWriter { guard let assetWriter = assetWriter else { return } DispatchQueue.main.async { self.didStartRecording() } let sampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) assetWriter.startSession(atSourceTime: sampleTime) didStartWriter = true } inputAppend(output, sampleBuffer, finalVideoPixelBuffer) }else if captureState == .end { guard let assetWriter = assetWriter, timer != nil else { return } inputAppend(output, sampleBuffer, finalVideoPixelBuffer) if assetWriter.status != .writing { return } if output == videoOutput { if !videoInpuCompletion { videoInpuCompletion.toggle() assetWriterVideoInput?.assetWriterInput.markAsFinished() } if !audioInpuCompletion { return } }else if output == audioOutput { if !audioInpuCompletion { audioInpuCompletion.toggle() assetWriterAudioInput?.markAsFinished() } if !videoInpuCompletion { return } } invalidateTimer() let videoURL = assetWriter.outputURL assetWriter.finishWriting { [weak self] in guard let self = self else { return } DispatchQueue.main.async { self.didFinishRecording(videoURL) } self.resetAssetWriter() } } } private func inputAppend( _ output: AVCaptureOutput, _ sampleBuffer: CMSampleBuffer, _ pixelBuffer: CVPixelBuffer? ) { if !didStartWriter { return } if output == videoOutput { videoInputAppend(sampleBuffer, pixelBuffer) }else if output == audioOutput { audioInputAppend(sampleBuffer) } } private func audioInputAppend( _ sampleBuffer: CMSampleBuffer ) { if let audioInput = assetWriterAudioInput, audioInput.isReadyForMoreMediaData, didWriterVideoInput { audioInput.append(sampleBuffer) } } private func videoInputAppend( _ sampleBuffer: CMSampleBuffer, _ pixelBuffer: CVPixelBuffer? ) { if let assetWriterVideoInput = assetWriterVideoInput, assetWriterVideoInput.assetWriterInput.isReadyForMoreMediaData { guard let pixelBuffer = pixelBuffer else { return } let sampleTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) if assetWriterVideoInput.append(pixelBuffer, withPresentationTime: sampleTime) { if !didWriterVideoInput { didWriterVideoInput = true } } } } func setupWriter(_ sampleBuffer: CMSampleBuffer) -> Bool { let assetWriter: AVAssetWriter do { assetWriter = try AVAssetWriter( url: PhotoTools.getVideoTmpURL(), fileType: .mp4 ) } catch { return false } let videoWidth: Int let videoHeight: Int if let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) { videoWidth = CVPixelBufferGetWidth(pixelBuffer) videoHeight = CVPixelBufferGetHeight(pixelBuffer) }else { videoWidth = Int(config.sessionPreset.size.height) videoHeight = Int(config.sessionPreset.size.width) } // var bitsPerPixel: Float // let numPixels = videoWidth * videoHeight // var bitsPerSecond: Int // if numPixels < 640 * 480 { // bitsPerPixel = 4.05 // } else { // bitsPerPixel = 10.1 // } // // bitsPerSecond = Int(Float(numPixels) * bitsPerPixel) // // let compressionProperties = [ // AVVideoAverageBitRateKey: bitsPerSecond, // AVVideoExpectedSourceFrameRateKey: 30, // AVVideoMaxKeyFrameIntervalKey: 30 // ] let videoCodecType: AVVideoCodecType if UIDevice.belowIphone7 { videoCodecType = .h264 }else { videoCodecType = config.videoCodecType } let videoInput = AVAssetWriterInput( mediaType: .video, outputSettings: [ AVVideoCodecKey: videoCodecType, AVVideoWidthKey: videoWidth, AVVideoHeightKey: videoHeight ] ) videoInput.expectsMediaDataInRealTime = true // videoInput.transform = .init(rotationAngle: .pi * 0.5) // if currentOrienation == .landscapeRight { // videoInput.transform = videoInput.transform.rotated(by: .pi * -0.5) // }else if currentOrienation == .landscapeLeft { // videoInput.transform = videoInput.transform.rotated(by: .pi * 0.5) // } if let position = activeCamera?.position, position == .front { videoInput.transform = videoInput.transform.scaledBy(x: -1, y: 1) } let audioInput = AVAssetWriterInput( mediaType: .audio, outputSettings: [ AVFormatIDKey: kAudioFormatMPEG4AAC, AVNumberOfChannelsKey: 1, AVSampleRateKey: 44100, AVEncoderBitRateKey: 64000 ] ) audioInput.expectsMediaDataInRealTime = true if !assetWriter.canAdd(videoInput) || !assetWriter.canAdd(audioInput) { return false } let inputPixelBufferInput = AVAssetWriterInputPixelBufferAdaptor( assetWriterInput: videoInput, sourcePixelBufferAttributes: [ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, kCVPixelBufferWidthKey as String: videoWidth, kCVPixelBufferHeightKey as String: videoHeight ] ) assetWriter.add(videoInput) assetWriter.add(audioInput) self.assetWriter = assetWriter assetWriterVideoInput = inputPixelBufferInput assetWriterAudioInput = audioInput return true } func resetFilter() { videoFilter.reset() photoFilter.reset() } } extension CameraManager { func startRecording( didStart: @escaping (TimeInterval) -> Void, progress: @escaping (Float, TimeInterval) -> Void, completion: @escaping (URL?, Error?) -> Void ) { if isRecording { completion(nil, NSError(domain: "is recording", code: 500, userInfo: nil)) return } videoDidStartRecording = didStart videoRecordingProgress = progress videoCompletion = completion if let isSmoothAuto = activeCamera?.isSmoothAutoFocusSupported, isSmoothAuto { try? activeCamera?.lockForConfiguration() activeCamera?.isSmoothAutoFocusEnabled = true activeCamera?.unlockForConfiguration() } if let connection = photoOutput.connection(with: .video) { if connection.isVideoMirroringSupported { connection.isVideoMirrored = false } } recordDuration = 0 captureState = .start isRecording = true } func didStartRecording() { videoDidStartRecording?(config.videoMaximumDuration) let timer = Timer.scheduledTimer( withTimeInterval: 1, repeats: true, block: { [weak self] timer in guard let self = self else { return } let timeElapsed = Date().timeIntervalSince(self.dateVideoStarted) let progress = Float(timeElapsed) / Float(max(1, self.config.videoMaximumDuration)) self.recordDuration = timeElapsed if self.config.takePhotoMode == .press || (self.config.takePhotoMode == .click && self.config.videoMaximumDuration > 0) { if timeElapsed >= self.config.videoMaximumDuration { self.stopRecording() } } DispatchQueue.main.async { self.videoRecordingProgress?(progress, timeElapsed) } } ) dateVideoStarted = Date() self.timer = timer } func stopRecording() { captureState = .end } func didFinishRecording(_ videoURL: URL) { invalidateTimer() if recordDuration < config.videoMinimumDuration { try? FileManager.default.removeItem(at: videoURL) videoCompletion?( nil, NSError( domain: "Recording time is too short", code: 110, userInfo: nil ) ) return } videoCompletion?(videoURL, nil) isRecording = false } func invalidateTimer() { timer?.invalidate() timer = nil } func resetAssetWriter() { didStartWriter = false didWriterVideoInput = false videoInpuCompletion = false audioInpuCompletion = false assetWriterVideoInput = nil assetWriterAudioInput = nil assetWriter = nil invalidateTimer() isRecording = false captureState = .end } }
2125a02c7383b98431bd3c6092bd9c67
32.45943
117
0.570506
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Views/AAStickerView.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import YYImage public class AAStickerView: UIView, YYAsyncLayerDelegate, ACFileEventCallback { private var file: ACFileReference? public init() { super.init(frame: CGRectZero) layer.delegate = self layer.contentsScale = UIScreen.mainScreen().scale backgroundColor = UIColor.clearColor() Actor.subscribeToDownloads(self) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { Actor.unsubscribeFromDownloads(self) } public func onDownloadedWithLong(fileId: jlong) { if self.file?.getFileId() == fileId { dispatchOnUi { if self.file?.getFileId() == fileId { self.layer.setNeedsDisplay() } } } } public func setSticker(file: ACFileReference?) { self.file = file self.layer.setNeedsDisplay() } public override class func layerClass() -> AnyClass { return YYAsyncLayer.self } public func newAsyncDisplayTask() -> YYAsyncLayerDisplayTask { let res = YYAsyncLayerDisplayTask() let _file = file res.display = { (context: CGContext, size: CGSize, isCancelled: () -> Bool) -> () in if _file != nil { let desc = Actor.findDownloadedDescriptorWithFileId(_file!.getFileId()) if isCancelled() { return } if desc != nil { let filePath = CocoaFiles.pathFromDescriptor(desc!) let image = YYImage(contentsOfFile: filePath) if isCancelled() { return } image?.drawInRect(CGRectMake(0, 0, size.width, size.height), withContentMode: UIViewContentMode.ScaleAspectFit, clipsToBounds: true) } else { // Request if not available Actor.startDownloadingWithReference(_file!) } } } return res } }
f54717e075751f62118d7e28fcdb86e8
29.133333
152
0.540505
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripeCardScan/StripeCardScan/Source/CardScan/MLRuntime/ActiveStateComputation.swift
mit
1
/// # Backgrounding and ML /// Our ML algorithms use the GPU and can cause crashes when we run them in the background. Thus, we track the app's /// backgrounding state and stop any tasks before the app reaches the background. /// /// # Correctness criteria /// We have three different functions: `async`, `willResignActive`, and `didBecomeActive` that all run on the main dispatch /// queue. In terms of ordering constraints: /// - The system enforces state transitions such that each time you resign active it'll be paired with a `didBecomeActive` call /// and vice versa. /// /// Given this constraint, you can expect a few different interleavings /// - async, resign, become /// - async, become, resign /// - become, async, resign /// - become, resign, async /// - resign, async, become /// - resign, become, async /// /// In general, we maintain two states: the system's notion of our app's application state and our own notion of active that is a /// subset of the more general active system state. In other words, if our app is inactive then our own internal `isActive` is /// always false, but if the app is active our internal `isActive` may be false or it may be true. However, if it is `false` /// we know that we'll get a become event soon. /// /// Our correctness criterai is that our work items run iff the app is in the active state and each of them runs to completion /// in the same order that they were posted (same semantics as a serial dispatch queue). /// /// The only time that computation can run is in between calls to `become` and `resign` because of our internal `isActive` variable. /// After the system calls resign, then all work items are added to the `pendingComputations` list in order, which are then posted to the `queue` in order on the `become` call before releasing the main queue. Subsequent calls to `async` will post to the `queue` but /// because the posting happens in the main queue, we can ensure correct execution ordering. import Foundation import UIKit class ActiveStateComputation { let queue: DispatchQueue var pendingComputations: [() -> Void] = [] var isActive = false init( label: String ) { self.queue = DispatchQueue(label: "ActiveStateComputation \(label)") DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.isActive = UIApplication.shared.applicationState == .active // We don't need to unregister these functions because the system will clean // them up for us NotificationCenter.default.addObserver( self, selector: #selector(self.willResignActive), name: UIApplication.willResignActiveNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(self.didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil ) } } func async(execute work: @escaping () -> Void) { DispatchQueue.main.async { [weak self] in guard let self = self else { return } let state = UIApplication.shared.applicationState guard state == .active, self.isActive else { self.pendingComputations.append(work) return } self.queue.async { work() } } } @objc func willResignActive() { assert(UIApplication.shared.applicationState == .active) assert(Thread.isMainThread) isActive = false queue.sync {} } @objc func didBecomeActive() { assert(UIApplication.shared.applicationState == .active) assert(Thread.isMainThread) isActive = true for work in pendingComputations { queue.async { work() } } } }
ac8da140bfef30ab938124780b3d744d
42.10989
265
0.654091
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/ViewControllers/Conversation/ConversationMoreViewManager.swift
mit
1
// // ConversationMoreViewManager.swift // Yep // // Created by NIX on 16/3/8. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation import YepKit final class ConversationMoreViewManager { var conversation: Conversation? var showProfileAction: (() -> Void)? var toggleDoNotDisturbAction: (() -> Void)? var reportAction: (() -> Void)? var toggleBlockAction: (() -> Void)? var shareFeedAction: (() -> Void)? var updateGroupAffairAction: (() -> Void)? var afterGotSettingsForUserAction: ((userID: String, blocked: Bool, doNotDisturb: Bool) -> Void)? var afterGotSettingsForGroupAction: ((groupID: String, notificationEnabled: Bool) -> Void)? private var moreViewUpdatePushNotificationsAction: ((notificationEnabled: Bool) -> Void)? var userNotificationEnabled: Bool = true { didSet { if moreViewCreated { moreView.items[1] = makeDoNotDisturbItem(notificationEnabled: userNotificationEnabled) moreView.refreshItems() } } } var userBlocked: Bool = false { didSet { if moreViewCreated { moreView.items[3] = makeBlockItem(blocked: userBlocked) moreView.refreshItems() } } } var groupNotificationEnabled: Bool = true { didSet { if moreViewCreated { moreView.items[0] = makePushNotificationsItem(notificationEnabled: groupNotificationEnabled) moreView.refreshItems() } } } private var moreViewCreated: Bool = false lazy var moreView: ActionSheetView = { let reportItem = ActionSheetView.Item.Default( title: NSLocalizedString("Report", comment: ""), titleColor: UIColor.yepTintColor(), action: { [weak self] in self?.reportAction?() return true } ) let cancelItem = ActionSheetView.Item.Cancel let view: ActionSheetView if let user = self.conversation?.withFriend { view = ActionSheetView(items: [ .Detail( title: NSLocalizedString("View profile", comment: ""), titleColor: UIColor.darkGrayColor(), action: { [weak self] in self?.showProfileAction?() } ), self.makeDoNotDisturbItem(notificationEnabled: user.notificationEnabled), // 1 reportItem, self.makeBlockItem(blocked: user.blocked), // 3 cancelItem, ] ) do { let userID = user.userID settingsForUser(userID: userID, failureHandler: nil, completion: { [weak self] blocked, doNotDisturb in self?.afterGotSettingsForUserAction?(userID: userID, blocked: blocked, doNotDisturb: doNotDisturb) }) } } else if let group = self.conversation?.withGroup { view = ActionSheetView(items: [ self.makePushNotificationsItem(notificationEnabled: group.notificationEnabled), // 0 .Default( title: NSLocalizedString("Share this feed", comment: ""), titleColor: UIColor.yepTintColor(), action: { [weak self] in self?.shareFeedAction?() return true } ), self.updateGroupItem(group: group), // 2 reportItem, cancelItem, ] ) do { self.moreViewUpdatePushNotificationsAction = { [weak self] notificationEnabled in guard let strongSelf = self else { return } strongSelf.moreView.items[0] = strongSelf.makePushNotificationsItem(notificationEnabled: notificationEnabled) strongSelf.moreView.refreshItems() } let groupID = group.groupID settingsForGroup(groupID: groupID, failureHandler: nil, completion: { [weak self] doNotDisturb in self?.afterGotSettingsForGroupAction?(groupID: groupID, notificationEnabled: !doNotDisturb) }) } } else { view = ActionSheetView(items: []) println("lazy ActionSheetView: should NOT be there!") } self.moreViewCreated = true return view }() // MARK: Public func updateForGroupAffair() { if moreViewCreated, let group = self.conversation?.withGroup { moreView.items[2] = updateGroupItem(group: group) moreView.refreshItems() } } // MARK: Private private func makeDoNotDisturbItem(notificationEnabled notificationEnabled: Bool) -> ActionSheetView.Item { return .Switch( title: NSLocalizedString("Do Not Disturb", comment: ""), titleColor: UIColor.darkGrayColor(), switchOn: !notificationEnabled, action: { [weak self] switchOn in self?.toggleDoNotDisturbAction?() } ) } private func makePushNotificationsItem(notificationEnabled notificationEnabled: Bool) -> ActionSheetView.Item { return .Switch( title: NSLocalizedString("Push Notifications", comment: ""), titleColor: UIColor.darkGrayColor(), switchOn: notificationEnabled, action: { [weak self] switchOn in self?.toggleDoNotDisturbAction?() } ) } private func makeBlockItem(blocked blocked: Bool) -> ActionSheetView.Item { return .Default( title: blocked ? NSLocalizedString("Unblock", comment: "") : String.trans_titleBlock, titleColor: UIColor.redColor(), action: { [weak self] in self?.toggleBlockAction?() return false } ) } private func updateGroupItem(group group: Group) -> ActionSheetView.Item { let isMyFeed = group.withFeed?.creator?.isMe ?? false let includeMe = group.includeMe let groupActionTitle: String if isMyFeed { groupActionTitle = NSLocalizedString("Delete", comment: "") } else { if includeMe { groupActionTitle = NSLocalizedString("Unsubscribe", comment: "") } else { groupActionTitle = NSLocalizedString("Subscribe", comment: "") } } return .Default( title: groupActionTitle, titleColor: UIColor.redColor(), action: { [weak self] in self?.updateGroupAffairAction?() return true } ) } }
fef129750f6902db380f8d002b51dcd6
32.229665
129
0.557955
false
false
false
false
fgulan/letter-ml
refs/heads/master
project/LetterML/Extensions/UIBezierPath+Scale.swift
mit
1
// // UIBezierPath+Scale.swift // LetterML // // Created by Filip Gulan on 01/10/2017. // Copyright © 2017 Filip Gulan. All rights reserved. // import UIKit extension UIBezierPath { // Disaster, needs to be refactored func scaleForRect(_ rect: CGRect, offset: CGFloat) { let size: CGFloat let greaterWidth = self.bounds.width > self.bounds.height if greaterWidth { size = self.bounds.width } else { size = self.bounds.height } let factor = (rect.width - 2 * offset) / size scaleAroundCenter(factor: factor, offset: offset) let newSize = bounds.size let diff: CGPoint if greaterWidth { let diffY = ((rect.width - 2 * offset) - newSize.height) / 2 diff = CGPoint(x: 0, y: diffY) } else { let diffX = ((rect.width - 2 * offset) - newSize.width) / 2 diff = CGPoint(x: diffX, y: 0) } let translateTransform = CGAffineTransform(translationX: diff.x, y: diff.y) self.apply(translateTransform) } func scaleAroundCenter(factor: CGFloat, offset: CGFloat) { let scaleTransform = CGAffineTransform(scaleX: factor, y: factor) self.apply(scaleTransform) let diff = CGPoint( x: offset - bounds.origin.x, y: offset - bounds.origin.y) let translateTransform = CGAffineTransform(translationX: diff.x, y: diff.y) self.apply(translateTransform) } } extension CGRect { var center: CGPoint { return CGPoint(x: self.midX, y: self.midY) } }
bdd5598ab810fcc74d3883415ef380d4
28.464286
83
0.584242
false
false
false
false
Jamol/Nutil
refs/heads/master
Sources/http/v2/H2Connection.swift
mit
1
// // H2Connection.swift // Nutil // // Created by Jamol Bao on 12/25/16. // Copyright © 2016 Jamol Bao. All rights reserved. // Contact: [email protected] // import Foundation class H2Connection : TcpConnection, HttpParserDelegate { fileprivate let httpParser = HttpParser() fileprivate let frameParser = FrameParser() fileprivate let hpEncoder = HPacker() fileprivate let hpDecoder = HPacker() fileprivate let flowControl = FlowControl() fileprivate var connKey = "" enum State : Int { case idle case connecting case upgrading case handshake case open case error case closed } fileprivate var state = State.idle var isReady: Bool { return state == .open } fileprivate var streams: H2StreamMap = [:] fileprivate var promisedStreams: H2StreamMap = [:] fileprivate var blockedStreams: [UInt32: UInt32] = [:] var cmpPreface = "" // server only fileprivate var maxLocalFrameSize = 65536 fileprivate var maxRemoteFrameSize = kH2DefaultFrameSize fileprivate var initRemoteWindowSize = kH2DefaultWindowSize fileprivate var initLocalWindowSize = LOCAL_STREAM_INITIAL_WINDOW_SIZE // initial local stream window size fileprivate var nextStreamId: UInt32 = 0 fileprivate var lastStreamId: UInt32 = 0 fileprivate var maxConcurrentStreams = 128 fileprivate var openedStreamCount = 0 fileprivate var expectContinuationFrame = false fileprivate var streamIdOfExpectedContinuation: UInt32 = 0 fileprivate var headersBlockBuffer = [UInt8]() fileprivate var prefaceReceived = false typealias AcceptCallback = (UInt32) -> Bool typealias ErrorCallback = (Int) -> Void typealias ConnectCallback = (KMError) -> Void var cbAccept: AcceptCallback? var cbError: ErrorCallback? fileprivate var connectListeners: [Int : ConnectCallback] = [:] var remoteWindowSize: Int { return flowControl.remoteWindowSize } override init () { super.init() flowControl.initLocalWindowSize(LOCAL_CONN_INITIAL_WINDOW_SIZE) flowControl.setMinLocalWindowSize(initLocalWindowSize); flowControl.setLocalWindowStep(LOCAL_CONN_INITIAL_WINDOW_SIZE) flowControl.cbUpdate = { (delta: UInt32) -> KMError in return self.sendWindowUpdate(0, delta: delta) } frameParser.setMaxFrameSize(maxLocalFrameSize) cmpPreface = kClientConnectionPreface httpParser.delegate = self frameParser.cbFrame = onFrame frameParser.cbError = onFrameError } fileprivate func cleanup() { setState(.closed) super.close() removeSelf() } fileprivate func setState(_ state: State) { self.state = state } func setConnectionKey(_ connKey: String) { self.connKey = connKey } func getConnectionKey() -> String { return connKey; } override func connect(_ addr: String, _ port: Int) -> KMError { if state != .idle { return .invalidState } nextStreamId = 1 setState(.connecting) var port = port if port == 0 { if socket.sslEnabled() { port = 443 } else { port = 80 } } if socket.sslEnabled() { socket.setAlpnProtocols(alpnProtos) } return super.connect(addr, port) } override func attachFd(_ fd: SOCKET_FD, _ initData: UnsafeRawPointer?, _ initSize: Int) -> KMError { nextStreamId = 2 let ret = super.attachFd(fd, initData, initSize) if ret == .noError { if socket.sslEnabled() { // waiting for client preface setState(.handshake) sendPreface() } else { // waiting for http upgrade reuqest setState(.upgrading) } } return ret } func attachStream(streamId: UInt32, rsp: Http2Response) -> KMError { if isPromisedStream(streamId) { return .invalidParam } return rsp.attachStream(self, streamId) } override func close() { infoTrace("H2Connection.close") if state < .open || state == .open{ sendGoaway(.noError) } setState(.closed) cleanup() } func sendH2Frame(_ frame: H2Frame) -> KMError { if !sendBufferEmpty() && !isControlFrame(frame) && !frame.hasEndStream() { appendBlockedStream(frame.streamId) return .again } if isControlFrame(frame) { infoTrace("H2Connection.sendH2Frame, type=\(frame.type()), streamId=\(frame.streamId), flags=\(frame.getFlags())") } else if frame.hasEndStream() { infoTrace("H2Connection.sendH2Frame, end stream, type=\(frame.type()), streamId=\(frame.streamId)") } if frame.type() == .headers { let headersFrame = frame as! HeadersFrame return sendHeadersFrame(headersFrame) } else if frame.type() == .data { if flowControl.remoteWindowSize < frame.getPayloadLength() { infoTrace("H2Connection.sendH2Frame, BUFFER_TOO_SMALL, win=\(flowControl.remoteWindowSize), len=\(frame.getPayloadLength())") appendBlockedStream(frame.streamId) return .bufferTooSmall } flowControl.bytesSent = frame.getPayloadLength() } else if frame.type() == .windowUpdate && frame.streamId != 0 { } let payloadSize = frame.calcPayloadSize() let frameSize = payloadSize + kH2FrameHeaderSize var buf = Array<UInt8>(repeating: 0, count: frameSize) //let ret = frame.encode(&buf, frameSize) let ret = buf.withUnsafeMutableBufferPointer { return frame.encode($0.baseAddress!, frameSize) } if ret < 0 { errTrace("H2Connection.sendH2Frame, failed to encode frame, type=\(frame.type())") return .invalidParam } appendBufferedData(buf) return sendBufferedData() } func sendHeadersFrame(_ frame: HeadersFrame) -> KMError { let pri = H2Priority() frame.pri = pri var len1 = kH2FrameHeaderSize if frame.hasPriority() { len1 += kH2PriorityPayloadSize } let hdrSize = frame.hsize let hpackSize = hdrSize * 3 / 2 let frameSize = len1 + hpackSize var buf = Array<UInt8>(repeating: 0, count: frameSize) let ret = buf.withUnsafeMutableBufferPointer { (base) -> KMError in let ptr = base.baseAddress! var ret = hpEncoder.encode(frame.headers, ptr + len1, frameSize) if ret < 0 { return KMError.failed } let bsize = ret ret = frame.encode(ptr, len1, bsize) assert(ret == len1) let realSize = len1 + bsize appendBufferedData(ptr, realSize) return KMError.noError } if ret != .noError { return ret } return sendBufferedData() } func createStream() -> H2Stream { let stream = H2Stream(nextStreamId, self, initLocalWindowSize, initRemoteWindowSize) nextStreamId += 2 addStream(stream) return stream } fileprivate func createStream(_ streamId: UInt32) -> H2Stream { let stream = H2Stream(streamId, self, initLocalWindowSize, initRemoteWindowSize) addStream(stream) return stream } fileprivate func handleDataFrame(_ frame: DataFrame) { if frame.streamId == 0 { // RFC 7540, 6.1 connectionError(.protocolError) return } flowControl.bytesReceived = frame.getPayloadLength() let stream = getStream(frame.streamId) if let stream = stream { stream.handleDataFrame(frame) } else { warnTrace("H2Connection.handleDataFrame, no stream, streamId=\(frame.streamId)") } } fileprivate func handleHeadersFrame(_ frame: HeadersFrame) { infoTrace("H2Connection.handleHeadersFrame, streamId=\(frame.streamId), flags=\(frame.getFlags())") if frame.streamId == 0 { // RFC 7540, 6.2 connectionError(.protocolError) return } var stream = getStream(frame.streamId) if stream == nil { if frame.streamId < lastStreamId { // RFC 7540, 5.1.1 connectionError(.protocolError) return } if openedStreamCount + 1 > maxConcurrentStreams { warnTrace("handleHeadersFrame, too many concurrent streams, streamId=\(frame.streamId), opened=\(openedStreamCount), max=\(maxConcurrentStreams)") //RFC 7540, 5.1.2 streamError(frame.streamId, .refusedStream) return } if !isServer { warnTrace("H2Connection.handleHeadersFrame, no local stream or promised stream, streamId=\(frame.streamId)") return } } if frame.hasEndHeaders() { if frame.block == nil { return } let hdrData = frame.block!.assumingMemoryBound(to: UInt8.self) var headers: NameValueArray = [] var ret: Int = -1 (ret, headers) = hpDecoder.decode(hdrData, frame.bsize) if ret < 0 { warnTrace("H2Connection.handleHeadersFrame, hpack decode failed") // RFC 7540, 4.3 connectionError(.compressionError) return } frame.setHeaders(headers, 0) } else { expectContinuationFrame = true streamIdOfExpectedContinuation = frame.streamId let hdrData = frame.block!.assumingMemoryBound(to: UInt8.self) headersBlockBuffer = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(hdrData), count: frame.bsize)) } if stream == nil { // new stream arrived on server side stream = createStream(frame.streamId) if cbAccept != nil && !cbAccept!(frame.streamId) { removeStream(frame.streamId) return } lastStreamId = frame.streamId } stream!.handleHeadersFrame(frame) } fileprivate func handlePriorityFrame(_ frame: PriorityFrame) { infoTrace("H2Connection.handlePriorityFrame, streamId=\(frame.streamId), dep=\(frame.pri.streamId), weight=\(frame.pri.weight)") if frame.streamId == 0 { // RFC 7540, 6.3 connectionError(.protocolError) return } let stream = getStream(frame.streamId) stream?.handlePriorityFrame(frame) } fileprivate func handleRSTStreamFrame(_ frame: RSTStreamFrame) { infoTrace("H2Connection.handleRSTStreamFrame, streamId=\(frame.streamId), err=\(frame.errCode)") if frame.streamId == 0 { // RFC 7540, 6.4 connectionError(.protocolError) return } let stream = getStream(frame.streamId) if let stream = stream { stream.handleRSTStreamFrame(frame) } } fileprivate func handleSettingsFrame(_ frame: SettingsFrame) { infoTrace("H2Connection.handleSettingsFrame, streamId=\(frame.streamId), count=\(frame.params.count)") if frame.streamId != 0 { // RFC 7540, 6.5 connectionError(.protocolError) return } if frame.ack { if frame.params.count != 0 { // RFC 7540, 6.5 connectionError(.frameSizeError) return } return } else { // send setings ack let settings = SettingsFrame() settings.streamId = frame.streamId settings.ack = true _ = sendH2Frame(settings) } applySettings(frame.params) if state < .open { // first frame must be SETTINGS prefaceReceived = true if state == .handshake && sendBufferEmpty() { onStateOpen() } } } fileprivate func handlePushFrame(_ frame: PushPromiseFrame) { infoTrace("H2Connection.handlePushFrame, streamId=\(frame.streamId), promStreamId=\(frame.promisedStreamId), bsize=\(frame.bsize), flags=\(frame.getFlags())") if frame.streamId == 0 { // RFC 7540, 6.6 connectionError(.protocolError) return } // TODO: if SETTINGS_ENABLE_PUSH was set to 0 and got the ack, // then response connection error of type PROTOCOL_ERROR if !isPromisedStream(frame.promisedStreamId) { warnTrace("H2Connection.handlePushFrame, invalid stream id") // RFC 7540, 5.1.1 connectionError(.protocolError) return } let associatedStream = getStream(frame.streamId) if associatedStream == nil { connectionError(.protocolError) return } if associatedStream!.state != .open && associatedStream!.state != .halfClosedL { // RFC 7540, 6.6 connectionError(.protocolError) return } if frame.hasEndHeaders() { if frame.block == nil { return } let hdrData = frame.block!.assumingMemoryBound(to: UInt8.self) var headers: NameValueArray = [] var ret: Int = -1 (ret, headers) = hpDecoder.decode(hdrData, frame.bsize) if ret < 0 { warnTrace("H2Connection.handlePushFrame, hpack decode failed") // RFC 7540, 4.3 connectionError(.compressionError) return } frame.setHeaders(headers, 0) } else { expectContinuationFrame = true streamIdOfExpectedContinuation = frame.promisedStreamId let hdrData = frame.block!.assumingMemoryBound(to: UInt8.self) headersBlockBuffer = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(hdrData), count: frame.bsize)) } let stream = createStream(frame.promisedStreamId) stream.handlePushFrame(frame) } fileprivate func handlePingFrame(_ frame: PingFrame) { infoTrace("H2Connection.handlePingFrame, streamId=\(frame.streamId)") if frame.streamId != 0 { // RFC 7540, 6.7 connectionError(.protocolError) return } if !frame.ack { let pingFrame = PingFrame() pingFrame.streamId = 0 pingFrame.ack = true pingFrame.data = frame.data _ = sendH2Frame(pingFrame) } } fileprivate func handleGoawayFrame(_ frame: GoawayFrame) { if frame.streamId != 0 { // RFC 7540, 6.8 connectionError(.protocolError) return } super.close() var sss = streams streams = [:] for kv in sss { kv.value.onError(Int(frame.errCode)) } sss = promisedStreams promisedStreams = [:] for kv in sss { kv.value.onError(Int(frame.errCode)) } let cb = cbError cbError = nil removeSelf() cb?(Int(frame.errCode)) } fileprivate func handleWindowUpdateFrame(_ frame: WindowUpdateFrame) { if frame.windowSizeIncrement == 0 { // RFC 7540, 6.9 streamError(frame.streamId, .protocolError) return } if flowControl.remoteWindowSize + Int(frame.windowSizeIncrement) > kH2MaxWindowSize { if frame.streamId == 0 { connectionError(.flowControlError) } else { streamError(frame.streamId, .flowControlError) } return } if frame.streamId == 0 { infoTrace("handleWindowUpdateFrame, streamId=\(frame.streamId), delta=\(frame.windowSizeIncrement), window=\(flowControl.remoteWindowSize)") if frame.windowSizeIncrement == 0 { connectionError(.protocolError) return } let needNotify = !blockedStreams.isEmpty flowControl.updateRemoteWindowSize(Int(frame.windowSizeIncrement)) if needNotify && flowControl.remoteWindowSize > 0 { notifyBlockedStreams() } } else { var stream = getStream(frame.streamId) if stream == nil && isServer { // new stream arrived on server side stream = createStream(frame.streamId) if cbAccept != nil && !cbAccept!(frame.streamId) { removeStream(frame.streamId) return } lastStreamId = frame.streamId } stream?.handleWindowUpdateFrame(frame) } } fileprivate func handleContinuationFrame(_ frame: ContinuationFrame) { infoTrace("H2Connection.handleContinuationFrame, streamId=\(frame.streamId)") if frame.streamId == 0 { // RFC 7540, 6.10 connectionError(.protocolError) return } if !expectContinuationFrame { // RFC 7540, 6.10 connectionError(.protocolError) return } if let stream = getStream(frame.streamId), frame.bsize > 0 { let hdrData = frame.block!.assumingMemoryBound(to: UInt8.self) headersBlockBuffer += Array(UnsafeBufferPointer(start: hdrData, count: frame.bsize)) if frame.hasEndHeaders() { var headers: NameValueArray = [] var ret: Int = -1 (ret, headers) = hpDecoder.decode(headersBlockBuffer, headersBlockBuffer.count) if ret < 0 { errTrace("H2Connection.handleContinuationFrame, hpack decode failed") // RFC 7540, 4.3 connectionError(.compressionError) return } frame.headers = headers expectContinuationFrame = false headersBlockBuffer = [] } stream.handleContinuationFrame(frame) } } override func handleInputData(_ data: UnsafeMutablePointer<UInt8>, _ len: Int) -> Bool { var data = data var len = len if state == .open { return parseInputData(data, len) } else if state == .upgrading { let ret = httpParser.parse(data: data, len: len) if state == .error { return false } if state == .closed { return true } if ret >= len { return true } // residual data, should be preface len -= ret data += ret } if state == .handshake { if isServer && cmpPreface.utf8.count > 0 { let cmpSize = min(cmpPreface.utf8.count, len) if memcmp(cmpPreface, data, cmpSize) != 0 { errTrace("H2Connection.handleInputData, invalid protocol") setState(.closed) cleanup() return false } let index = cmpPreface.index(cmpPreface.startIndex, offsetBy: cmpSize) cmpPreface = String(cmpPreface[index...]) if !cmpPreface.isEmpty { return true // need more data } len -= cmpSize data += cmpSize } // expect a SETTINGS frame return parseInputData(data, len) } else { warnTrace("H2Connection.handleInputData, invalid state: \(state)") } return true } fileprivate func parseInputData(_ data: UnsafeMutablePointer<UInt8>, _ len: Int) -> Bool { let parseState = frameParser.parseInputData(data, len) if state == .error || state == .closed { return false } if parseState == .failure || parseState == .stopped { errTrace("H2Connection.parseInputData, failed, len=\(len), state=\(state)") setState(.closed) cleanup() return false } return true } fileprivate func onFrame(_ frame: H2Frame) -> Bool { if state == .handshake && frame.type() != .settings { // RFC 7540, 3.5 // the first frame must be SETTINGS, otherwise PROTOCOL_ERROR on connection errTrace("onFrame, the first frame is not SETTINGS, type=\(frame.type())") state = .closed cbError?(Int(H2Error.protocolError.rawValue)) return false } if expectContinuationFrame && (frame.type() != .continuation || frame.streamId != streamIdOfExpectedContinuation) { connectionError(.protocolError) return false } switch frame.type() { case .data: handleDataFrame(frame as! DataFrame) case .headers: handleHeadersFrame(frame as! HeadersFrame) case .priority: handlePriorityFrame(frame as! PriorityFrame) case .rststream: handleRSTStreamFrame(frame as! RSTStreamFrame) case .settings: handleSettingsFrame(frame as! SettingsFrame) case .pushPromise: handlePushFrame(frame as! PushPromiseFrame) case .ping: handlePingFrame(frame as! PingFrame) case .goaway: handleGoawayFrame(frame as! GoawayFrame) case .windowUpdate: handleWindowUpdateFrame(frame as! WindowUpdateFrame) case .continuation: handleContinuationFrame(frame as! ContinuationFrame) } return true } fileprivate func onFrameError(_ hdr: FrameHeader, _ err: H2Error, stream: Bool) -> Bool { errTrace("H2Connection.onFrameError, streamId=\(hdr.streamId), type=\(hdr.type), err=\(err)") if stream { streamError(hdr.streamId, err) } else { connectionError(err) } return true } fileprivate func addStream(_ stream: H2Stream) { infoTrace("H2Connection.addStream, streamId=\(stream.getStreamId())") if isPromisedStream(stream.getStreamId()) { promisedStreams[stream.getStreamId()] = stream } else { streams[stream.getStreamId()] = stream } } func getStream(_ streamId: UInt32) -> H2Stream? { if isPromisedStream(streamId) { return promisedStreams[streamId] } else { return streams[streamId] } } func removeStream(_ streamId: UInt32) { infoTrace("H2Connection.removeStream, streamId=\(streamId)") if isPromisedStream(streamId) { promisedStreams.removeValue(forKey: streamId) } else { streams.removeValue(forKey: streamId) } } func addConnectListener(_ uid: Int, _ cb: @escaping ConnectCallback) { connectListeners[uid] = cb } func removeConnectListener(_ uid: Int) { connectListeners.removeValue(forKey: uid) } func appendBlockedStream(_ streamId: UInt32) { blockedStreams[streamId] = streamId } fileprivate func notifyBlockedStreams() { if !sendBufferEmpty() || remoteWindowSize == 0 { return } var bstreams = blockedStreams blockedStreams = [:] while !bstreams.isEmpty && sendBufferEmpty() && remoteWindowSize > 0 { let streamId = bstreams.first!.key bstreams.removeValue(forKey: streamId) let stream = getStream(streamId) if let stream = stream { stream.onWrite() } } for kv in bstreams { blockedStreams[kv.key] = kv.value } } func sync() -> Bool { return false } func async() -> Bool { return false } fileprivate func buildUpgradeRequest() -> String { var params: H2SettingArray = [] params.append((H2SettingsID.initialWindowSize.rawValue, UInt32(initLocalWindowSize))) params.append((H2SettingsID.maxFrameSize.rawValue, 65536)) let psize = 2 * kH2SettingItemSize var pbuff = Array<UInt8>(repeating: 0, count: psize) let settingsFrame = SettingsFrame() //_ = settingsFrame.encodePayload(&pbuff, psize, params) _ = pbuff.withUnsafeMutableBufferPointer { return settingsFrame.encodePayload($0.baseAddress!, psize, params) } let dd = Data(bytes: pbuff) let settingsStr = dd.base64EncodedString() var req = "GET / HTTP/1.1\r\n" req += "Host: \(super.host)\r\n" req += "Connection: Upgrade, HTTP2-Settings\r\n" req += "Upgrade: h2c\r\n" req += "HTTP2-Settings: \(settingsStr)\r\n" req += "\r\n" return req } fileprivate func buildUpgradeResponse() -> String { var rsp = "HTTP/1.1 101 Switching Protocols\r\n" rsp += "Connection: Upgrade\r\n" rsp += "Upgrade: \(httpParser.headers["Upgrade"]!)\r\n" rsp += "\r\n" return rsp } fileprivate func sendUpgradeRequest() { let req = buildUpgradeRequest() appendBufferedData(req, req.utf8.count) setState(.upgrading) _ = sendBufferedData() } fileprivate func sendUpgradeResponse() { let rsp = buildUpgradeResponse() appendBufferedData(rsp, rsp.utf8.count) setState(.upgrading) _ = sendBufferedData() if sendBufferEmpty() { sendPreface() } } fileprivate func sendPreface() { setState(.handshake) var params: H2SettingArray = [] params.append((H2SettingsID.initialWindowSize.rawValue, UInt32(initLocalWindowSize))) params.append((H2SettingsID.maxFrameSize.rawValue, 65536)) var settingsSize = kH2FrameHeaderSize + params.count * kH2SettingItemSize var encodedLen = 0 if !isServer { appendBufferedData(kClientConnectionPreface, kClientConnectionPreface.utf8.count) encodedLen += kClientConnectionPreface.utf8.count } else { params.append((H2SettingsID.maxConcurrentStreams.rawValue, 128)) settingsSize += kH2SettingItemSize } let settingsFrame = SettingsFrame() settingsFrame.streamId = 0 settingsFrame.params = params var buf = Array<UInt8>(repeating: 0, count: settingsSize) //var ret = settingsFrame.encode(&buf, settingsSize) var ret = buf.withUnsafeMutableBufferPointer { return settingsFrame.encode($0.baseAddress!, settingsSize) } if ret < 0 { errTrace("sendPreface, failed to encode setting frame") return } appendBufferedData(buf) let frame = WindowUpdateFrame() frame.streamId = 0 frame.windowSizeIncrement = UInt32(flowControl.localWindowSize) buf = Array<UInt8>(repeating: 0, count: kH2WindowUpdateFrameSize) ret = buf.withUnsafeMutableBufferPointer { return frame.encode($0.baseAddress!, kH2WindowUpdateFrameSize) } if ret < 0 { errTrace("sendPreface, failed to encode window update frame") return } appendBufferedData(buf) _ = sendBufferedData() if sendBufferEmpty() && prefaceReceived { onStateOpen() } } func sendWindowUpdate(_ streamId: UInt32, delta: UInt32) -> KMError { let frame = WindowUpdateFrame() frame.streamId = streamId frame.windowSizeIncrement = delta return sendH2Frame(frame) } func sendGoaway(_ err: H2Error) { let frame = GoawayFrame() frame.errCode = UInt32(err.rawValue) frame.streamId = 0 frame.lastStreamId = lastStreamId _ = sendH2Frame(frame) } fileprivate func applySettings(_ params: H2SettingArray) { for kv in params { infoTrace("applySettings, id=\(kv.key), value=\(kv.value)") switch kv.key { case H2SettingsID.headerTableSize.rawValue: hpDecoder.setMaxTableSize(Int(kv.value)) case H2SettingsID.initialWindowSize.rawValue: if kv.value > kH2MaxWindowSize { // RFC 7540, 6.5.2 connectionError(.flowControlError) return } updateInitialWindowSize(Int(kv.value)) case H2SettingsID.maxFrameSize.rawValue: if kv.value < kH2DefaultFrameSize || kv.value > kH2MaxFrameSize { // RFC 7540, 6.5.2 connectionError(.protocolError) return } maxRemoteFrameSize = Int(kv.value) case H2SettingsID.maxConcurrentStreams.rawValue: break case H2SettingsID.enablePush.rawValue: if kv.value != 0 && kv.value != 1 { // RFC 7540, 6.5.2 connectionError(.protocolError) return } break default: break } } } fileprivate func updateInitialWindowSize(_ ws: Int) { if ws != initRemoteWindowSize { let delta = ws - initRemoteWindowSize initRemoteWindowSize = ws for kv in streams { kv.value.updateRemoteWindowSize(delta) } for kv in promisedStreams { kv.value.updateRemoteWindowSize(delta) } } } func connectionError(_ err: H2Error) { sendGoaway(err) setState(.closed) cbError?(Int(err.rawValue)) } fileprivate func streamError(_ streamId: UInt32, _ err: H2Error) { let stream = getStream(streamId) if stream != nil { stream!.streamError(err) } else { let frame = RSTStreamFrame() frame.streamId = streamId frame.errCode = UInt32(err.rawValue) _ = sendH2Frame(frame) } } func streamOpened(_ streamId: UInt32) { openedStreamCount += 1 } func streamClosed(_ streamId: UInt32) { openedStreamCount -= 1 } fileprivate func isControlFrame(_ frame: H2Frame) -> Bool { return frame.type() != .data } override func handleOnConnect(err: KMError) { infoTrace("H2Connection.handleOnConnect, err=\(err)") if err != .noError { onConnectError(err) return } if socket.sslEnabled() { sendPreface() return } nextStreamId += 2 // stream id 1 is for upgrade request sendUpgradeRequest() } override func handleOnSend() { // send_buffer_ must be empty if isServer && state == .upgrading { // upgrade response is sent out, waiting for client preface setState(.handshake) sendPreface() } else if state == .handshake && prefaceReceived { onStateOpen() } if state == .open { notifyBlockedStreams() } } override func handleOnError(err: KMError) { onError(err: err) } func onHttpData(data: UnsafeMutableRawPointer, len: Int) { //infoTrace("onData, len=\(len), total=\(parser.bodyBytesRead)") } func onHttpHeaderComplete() { infoTrace("H2Connection.onHttpHeaderComplete") if !httpParser.isUpgradeTo(proto: "h2c") { errTrace("H2Connection.onHeaderComplete, not HTTP2 upgrade response") } } func onHttpComplete() { infoTrace("H2Connection.onHttpComplete") if httpParser.isRequest { _ = handleUpgradeRequest() } else { _ = handleUpgradeResponse() } } func onHttpError(err: KMError) { infoTrace("H2Connection.onHttpError, err=\(err)") setState(.error) onConnectError(.failed) } fileprivate func handleUpgradeRequest() -> KMError { if !httpParser.isUpgradeTo(proto: "h2c") { setState(.error) return .invalidProto } sendUpgradeResponse() return .noError } fileprivate func handleUpgradeResponse() -> KMError { if !httpParser.isUpgradeTo(proto: "h2c") { setState(.error) onConnectError(.invalidProto) return .invalidProto } sendPreface() return .noError } func onError(err: KMError) { infoTrace("H2Connection.onError, err=\(err)") setState(.error) cleanup() cbError?(err.rawValue) } fileprivate func onConnectError(_ err: KMError) { setState(.error) cleanup() notifyListeners(err) } fileprivate func onStateOpen() { infoTrace("H2Connection.onStateOpen") setState(.open) if !isServer { notifyListeners(.noError) } } fileprivate func notifyListeners(_ err: KMError) { let listeners = connectListeners connectListeners = [:] for kv in listeners { kv.value(err) } } fileprivate func removeSelf() { if !connKey.isEmpty { let connMgr = H2ConnectionMgr.getRequestConnMgr(sslEnabled()) connMgr.removeConnection(connKey) } } } let LOCAL_CONN_INITIAL_WINDOW_SIZE = 20*1024*1024 let LOCAL_STREAM_INITIAL_WINDOW_SIZE = 6*1024*1024 let kClientConnectionPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
f17901ec40e48c0b5544e4b5edc30c75
33.168142
166
0.563959
false
false
false
false
damonthecricket/my-json
refs/heads/master
MYJSONTests/TestData/FriendTestClass.swift
mit
1
// // FriendTestClass.swift // MYJSON // // Created by Optimus Prime on 08.05.17. // Copyright © 2017 Trenlab. All rights reserved. // import Foundation import MYJSON // MARK: - FriendTestClass public class FriendTestClass: MYJSONSerizlizable, MYJSONDeserizlizable { public var id: UInt = 0 public var name: String = "" public var json: MYJSON { return MYJSON(rawValue: ["id": id, "name": name]) } // MARK: - Object LifeCycle public required init(json: MYJSON) { id <- json.number(forKey: "id").uintValue name <- json["name"] } } extension FriendTestClass: Equatable { public static func ==(lhs: FriendTestClass, rhs: FriendTestClass) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name } }
66e2d10e291f7d72ee49242138c94079
21.111111
79
0.623116
false
true
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/Extensions/NSAttributedString+StyledHTML.swift
gpl-2.0
2
import UIKit extension NSAttributedString { /// Creates an `NSAttributedString` with the styles defined in `attributes` applied. /// - parameter htmlString: The string to be styled. This can contain HTML /// tags to markup sections of the text to style, but should not be wrapped /// with `<html>`, `<body>` or `<p>` tags. See `HTMLAttributeType` for supported tags. /// - parameter attributes: A collection of style attributes to apply to `htmlString`. /// See `HTMLAttributeType` for supported attributes. To set text alignment, /// add an `NSParagraphStyle` to the `BodyAttribute` type, using the key /// `NSParagraphStyleAttributeName`. /// /// - note: /// - Font sizes will be interpreted as pixel sizes, not points. /// - Font family / name will be discarded (generated strings will always /// use the system font), but font size and bold / italic information /// will be applied. /// class func attributedStringWithHTML(_ htmlString: String, attributes: StyledHTMLAttributes?) -> NSAttributedString { let styles = styleTagTextForAttributes(attributes) let styledString = styles + htmlString guard let data = styledString.data(using: .utf8), let attributedString = try? NSMutableAttributedString( data: data, options: [ .documentType: NSAttributedString.DocumentType.html.rawValue, .characterEncoding: String.Encoding.utf8.rawValue ], documentAttributes: nil) else { // if creating the html-ed string fails (and it has, thus this change) we return the string without any styling return NSAttributedString(string: htmlString) } // We can't apply text alignment through CSS, as we need to add a paragraph // style to set paragraph spacing (which will override any text alignment // set via CSS). So we'll look for a paragraph style specified for the // body of the text, so we can copy it use its text alignment. let paragraphStyle = NSMutableParagraphStyle() if let attributes = attributes, let bodyAttributes = attributes[.BodyAttribute], let pStyle = bodyAttributes[.paragraphStyle] as? NSParagraphStyle { paragraphStyle.setParagraphStyle(pStyle) } // Remove extra padding at the top and bottom of the text. paragraphStyle.paragraphSpacing = 0 paragraphStyle.paragraphSpacingBefore = 0 attributedString.addAttribute(.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attributedString.string.count - 1)) return NSAttributedString(attributedString: attributedString) } fileprivate class func styleTagTextForAttributes(_ attributes: StyledHTMLAttributes?) -> String { let styles: [String]? = attributes?.map { attributeType, attributes in var style = attributeType.tag + " { " for (attributeName, attribute) in attributes { if let attributeStyle = cssStyleForAttributeName(attributeName, attribute: attribute) { style += attributeStyle } } return style + " }" } let joinedStyles = styles?.joined(separator: "") ?? "" return "<style>" + joinedStyles + "</style>" } /// Converts a limited set of `NSAttributedString` attribute types from their /// raw objects (e.g. `UIColor`) into CSS text. fileprivate class func cssStyleForAttributeName(_ attributeKey: NSAttributedString.Key, attribute: Any) -> String? { switch attributeKey { case .font: if let font = attribute as? UIFont { let size = font.pointSize let boldStyle = "font-weight: " + (font.isBold ? "bold;" : "normal;") let italicStyle = "font-style: " + (font.isItalic ? "italic;" : "normal;") return "font-family: -apple-system; font-size: \(size)px; " + boldStyle + italicStyle } case .foregroundColor: if let color = attribute as? UIColor, let colorHex = color.hexString() { return "color: #\(colorHex);" } case .underlineStyle: if let style = attribute as? Int { if style == NSUnderlineStyle([]).rawValue { return "text-decoration: none;" } else { return "text-decoration: underline;" } } default: break } return nil } } public typealias StyledHTMLAttributes = [HTMLAttributeType: [NSAttributedString.Key: Any]] public enum HTMLAttributeType: String { case BodyAttribute case ATagAttribute case EmTagAttribute case StrongTagAttribute var tag: String { switch self { case .BodyAttribute: return "body" case .ATagAttribute: return "a" case .EmTagAttribute: return "em" case .StrongTagAttribute: return "strong" } } } public extension UIFont { var isBold: Bool { return fontDescriptor.symbolicTraits.contains(.traitBold) } var isItalic: Bool { return fontDescriptor.symbolicTraits.contains(.traitItalic) } }
a5aee9eaecc25462baa17c2b6cea2d94
41.769841
137
0.619224
false
false
false
false
mullinswebworx/Treehouse
refs/heads/master
iOS_Swift/SwiftEnumerationsAndOptionals.playground/Pages/Optional Chaining.xcplaygroundpage/Contents.swift
mit
1
class Address { var streetName: String? var buildingNumber: String? var apartmentNumber: String? } class Residence { var address: Address? } class Person { var residence : Residence? } let susan = Person() let address = Address() address.streetName = "1234 Something Street" address.buildingNumber = "Building 10" address.apartmentNumber = "204" let residence = Residence() residence.address = address susan.residence = residence if let apartmentNumber = susan.residence?.address?.apartmentNumber { print(apartmentNumber) } let apart = susan.residence?.address?.apartmentNumber
28295f733e531c9465112a6e0e65991f
19.333333
68
0.740558
false
false
false
false
PureSwift/SDL
refs/heads/master
Sources/SDL/Renderer.swift
mit
1
// // Renderer.swift // SDL // // Created by Alsey Coleman Miller on 6/6/17. // import CSDL2 /// SDL Renderer public final class SDLRenderer { // MARK: - Properties internal let internalPointer: OpaquePointer // MARK: - Initialization deinit { SDL_DestroyRenderer(internalPointer) } /// Create a 2D rendering context for a window. public init(window: SDLWindow, driver: SDLRenderer.Driver = .default, options: BitMaskOptionSet<SDLRenderer.Option> = []) throws { let internalPointer = SDL_CreateRenderer(window.internalPointer, Int32(driver.rawValue), options.rawValue) self.internalPointer = try internalPointer.sdlThrow(type: type(of: self)) } /// The color used for drawing operations (Rect, Line and Clear). public func drawColor() throws -> (red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) { var red: UInt8 = 0 var green: UInt8 = 0 var blue: UInt8 = 0 var alpha: UInt8 = 0 try SDL_GetRenderDrawColor(internalPointer, &red, &green, &blue, &alpha).sdlThrow(type: type(of: self)) return (red, green, blue, alpha) } /// Set the color used for drawing operations (Rect, Line and Clear). public func setDrawColor(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8 = .max) throws { try SDL_SetRenderDrawColor(internalPointer, red, green, blue, alpha).sdlThrow(type: type(of: self)) } /// Current rendering target texture. public private(set) var target: SDLTexture? /// Set a texture as the current rendering target. public func setTarget(_ newValue: SDLTexture?) throws { try SDL_SetRenderTarget(internalPointer, target?.internalPointer).sdlThrow(type: type(of: self)) // hold reference self.target = newValue } /// The blend mode used for drawing operations (Fill and Line). public func drawBlendMode() throws -> BitMaskOptionSet<SDLBlendMode> { var value = SDL_BlendMode(0) SDL_GetRenderDrawBlendMode(internalPointer, &value) return BitMaskOptionSet<SDLBlendMode>(rawValue: value.rawValue) } /// Set the blend mode used for drawing operations (Fill and Line). /// /// - Note: If the blend mode is not supported, the closest supported mode is chosen. public func setDrawBlendMode(_ newValue: BitMaskOptionSet<SDLBlendMode>) throws { try SDL_SetRenderDrawBlendMode(internalPointer, SDL_BlendMode(newValue.rawValue)).sdlThrow(type: type(of: self)) } /// Set a device independent resolution for rendering public func setLogicalSize(width: Int32, height: Int32) throws { try SDL_RenderSetLogicalSize(internalPointer, width, height).sdlThrow(type: type(of: self)) } // MARK: - Methods /// Clear the current rendering target with the drawing color /// This function clears the entire rendering target, ignoring the viewport. public func clear() throws { try SDL_RenderClear(internalPointer).sdlThrow(type: type(of: self)) } /// Update the screen with rendering performed. public func present() { SDL_RenderPresent(internalPointer) } /// Copy a portion of the texture to the current rendering target. public func copy(_ texture: SDLTexture, source: SDL_Rect, destination: SDL_Rect) throws { var s = source var d = destination try SDL_RenderCopy(internalPointer, texture.internalPointer, &s, &d).sdlThrow(type: type(of: self)) } /// Copy a portion of the texture to the current rendering target. public func copy(_ texture: SDLTexture, source s: inout SDL_Rect, destination d: inout SDL_Rect) throws { try SDL_RenderCopy(internalPointer, texture.internalPointer, &s, &d).sdlThrow(type: type(of: self)) } /// Copy a portion of the texture to the current rendering target. public func copy(_ texture: SDLTexture, source: SDL_Rect) throws { var s = source try SDL_RenderCopy(internalPointer, texture.internalPointer, &s, nil).sdlThrow(type: type(of: self)) } /// Copy a portion of the texture to the current rendering target. public func copy(_ texture: SDLTexture, source s: inout SDL_Rect) throws { try SDL_RenderCopy(internalPointer, texture.internalPointer, &s, nil).sdlThrow(type: type(of: self)) } /// Copy a portion of the texture to the current rendering target. public func copy(_ texture: SDLTexture, destination: SDL_Rect) throws { var d = destination try SDL_RenderCopy(internalPointer, texture.internalPointer, nil, &d).sdlThrow(type: type(of: self)) } /// Copy a portion of the texture to the current rendering target. public func copy(_ texture: SDLTexture, destination d: inout SDL_Rect) throws { try SDL_RenderCopy(internalPointer, texture.internalPointer, nil, &d).sdlThrow(type: type(of: self)) } /// Fill a rectangle on the current rendering target with the drawing color. public func fill(rect: SDL_Rect? = nil) throws { let rectPointer: UnsafePointer<SDL_Rect>? if let rect = rect { rectPointer = withUnsafePointer(to: rect) { $0 } } else { rectPointer = nil } try SDL_RenderFillRect(internalPointer, rectPointer).sdlThrow(type: type(of: self)) } } // MARK: - Supporting Types public extension SDLRenderer { /// An enumeration of flags used when creating a rendering context. enum Option: UInt32, BitMaskOption { /// The renderer is a software fallback. case software = 0x00000001 /// The renderer uses hardware acceleration. case accelerated = 0x00000002 /// Present is synchronized with the refresh rate case presentVsync = 0x00000004 /// The renderer supports rendering to texture case targetTexture = 0x00000008 } } public extension SDLRenderer { /// Information on the capabilities of a render driver or context. struct Info { /// The name of the renderer. public let name: String /// Supported options. public let options: BitMaskOptionSet<SDLRenderer.Option> /// The number of available texture formats. public let formats: [SDLPixelFormat.Format] /// The maximimum texture size. public let maximumSize: (width: Int, height: Int) public init(driver: Driver) throws { // get driver info from SDL var info = SDL_RendererInfo() try SDL_GetRenderDriverInfo(Int32(driver.rawValue), &info).sdlThrow(type: type(of: self)) self.init(info) } internal init(_ info: SDL_RendererInfo) { self.name = String(cString: info.name) self.options = BitMaskOptionSet<SDLRenderer.Option>(rawValue: info.flags) self.maximumSize = (Int(info.max_texture_width), Int(info.max_texture_height)) // copy formats array let formatsCount = Int(info.num_texture_formats) let formats = [info.texture_formats.0, info.texture_formats.1, info.texture_formats.2, info.texture_formats.3, info.texture_formats.4, info.texture_formats.5, info.texture_formats.6, info.texture_formats.7, info.texture_formats.8, info.texture_formats.9, info.texture_formats.10, info.texture_formats.11, info.texture_formats.12, info.texture_formats.13, info.texture_formats.14, info.texture_formats.15] self.formats = formats.prefix(formatsCount).map { SDLPixelFormat.Format(rawValue: $0) } } } } public extension SDLRenderer { struct Driver: IndexRepresentable { public static var all: CountableSet<Driver> { let count = Int(SDL_GetNumRenderDrivers()) return CountableSet<Driver>(count: count) } public static let `default` = Driver(rawValue: -1) public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } } }
25bf0b94e2f7d7246e95cc1ba666aaae
35.179592
120
0.602211
false
false
false
false
IngmarStein/swift
refs/heads/master
validation-test/compiler_crashers_fixed/00104-swift-constraints-constraintsystem-finalize.swift
apache-2.0
11
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func k<q>() -> [n<q>] { r [] } func k(l: Int = 0) { } n n = k n() func n<q { l n { func o o _ = o } } func ^(k: m, q) -> q { r !(k) } protocol k { j q j o = q j f = q } class l<r : n, l : n p r.q == l> : k { } class l<r, l> { } protocol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l>
415929c1647d0adf148c1cf13b368c97
16.422222
78
0.561224
false
false
false
false
urbanthings/urbanthings-sdk-apple
refs/heads/master
UrbanThingsAPI/Public/Response/PlacePointType.swift
apache-2.0
1
// // PlacePointType.swift // UrbanThingsAPI // // Created by Mark Woollard on 26/04/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import Foundation /// The PlacePointType enum defines the possible place points that can be returned in by the API. The following are supported: /// /// - Place - A place that doesn't fall into any of the other types /// - Road /// - TransitStop - A transit stop where there isn't more specific information about type of transit /// - Postcode - Place defined by a postcode (zipcode) /// - LatLng - A general location with a lat/lng position /// - Locality - A locality /// - POI - A Point of interest /// - TransitStopTram - A tram transit stop /// - TransitStopSubway - A subway transit stop /// - TransitStopRail - A rail transit stop (station) /// - TransitStopBus - A bus stop /// - TransitStopFerry - A ferry terminal /// - TransitStopCableCar - A cable car transit stop /// - TransitStopGondola - A gondola transit stop /// - TransitStopFunicular - A funicular transit stop /// - TransitStopAir - An air transit stop, airport or heliport /// - CycleHireDock - Cycle hire dock location /// - CarParkingSpace - Car park /// `PlacePointType` lists all valid types of place point. @objc public enum PlacePointType : Int { /// A place that doesn't fall into any of the other PlacePointType options, raw value 0 case Place = 0 /// A road, raw value 1 case Road = 1 /// A transit stop that doesn't fall into any of the more specific PlacePointType options, raw value 2 case TransitStop = 2 /// A place defined by postcode (zipcode), raw value 3 case Postcode = 3 /// A place for a given lat/lng coordinate, raw value 4 case LatLng = 4 /// A place defining a locality, raw value 5 case Locality = 5 /// A point of interest, raw value 6 case POI = 6 /// A transit stop for trams, raw value 100 case TransitStopTram = 100 /// A subway transit stop, raw value 101 case TransitStopSubway = 101 /// A transit stop for rail (railway station), raw value 102 case TransitStopRail = 102 /// A bus transit stop, raw value 103 case TransitStopBus = 103 /// A ferry dock/port/terminal, raw value 104 case TransitStopFerry = 104 /// A place to start/end a cable car journey, raw value 105 case TransitStopCableCar = 105 /// A place to start/end a gondoal ride, raw value 106 case TransitStopGondola = 106 /// A place to start/end a funicular ride, raw value 107 case TransitStopFunicular = 107 /// A place to start an air journey, airport/heliport etc, raw value 108 case TransitStopAir = 108 /// A place to dock/undock a hire cycle, raw value 111 case CycleHireDock = 111 /// A place with parkings spaces, raw value 112 case CarParkingSpace = 112 }
962f7f94f6feaf094f377c838ad1b007
39.5
126
0.691711
false
false
false
false
yangyu2010/DouYuZhiBo
refs/heads/master
DouYuZhiBo/DouYuZhiBo/Class/Tools/UIView/YYTitleView.swift
mit
1
// // YYTitleView.swift // DouYuZhiBo // // Created by Young on 2017/2/15. // Copyright © 2017年 YuYang. All rights reserved. // import UIKit protocol YYTitleViewDelegate : NSObjectProtocol { func yyTitleViewScrollToIndex(index: Int) } // 滑动底线的高度 fileprivate let kScrollLineViewH: CGFloat = 3 // 普通状态的颜色 fileprivate let kNomalColor: (CGFloat, CGFloat ,CGFloat) = (85, 85, 85) // 被选中的颜色 fileprivate let kSelectedColor: (CGFloat, CGFloat ,CGFloat) = (255, 128, 0) class YYTitleView: UIView { // MARK: -自定义属性 fileprivate var titles : [String] = [String]() fileprivate var originalIndex: Int = 0 weak var delegate: YYTitleViewDelegate? // MARK: -懒加载 fileprivate lazy var scrollView: UIScrollView = { let scroll = UIScrollView() scroll.backgroundColor = UIColor.white return scroll }() fileprivate lazy var segmentView: UIView = { let vi = UIView() vi.backgroundColor = UIColor.darkGray return vi }() fileprivate lazy var lineView: UIView = { let vi = UIView() vi.backgroundColor = UIColor.orange return vi }() fileprivate lazy var labelArr: [UILabel] = [UILabel]() // MARK: -构造函数 init(frame: CGRect, titles: [String]) { super.init(frame: frame) self.titles = titles setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: -设置UI extension YYTitleView { fileprivate func setupUI() { // 1.添加scroll scrollView.frame = bounds addSubview(scrollView) let labY: CGFloat = 0 let labW: CGFloat = scrollView.frame.width / CGFloat(titles.count) let labH: CGFloat = scrollView.frame.height // 2.添加底部分割线 segmentView.frame = CGRect(x: 0, y: bounds.height - kSingleLineW, width: bounds.width, height: kSingleLineW) addSubview(segmentView) // 3.添加滑动的View lineView.frame = CGRect(x: 0, y: bounds.height - kScrollLineViewH, width: labW, height: kScrollLineViewH) addSubview(lineView) for (index,title) in titles.enumerated() { let lab = UILabel() lab.frame = CGRect(x: CGFloat(index) * labW, y: labY, width: labW, height: labH) lab.text = title lab.textAlignment = .center lab.font = UIFont.systemFont(ofSize: 16.0) lab.tag = index if index == 0 { lab.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) }else { lab.textColor = UIColor(r: kNomalColor.0, g: kNomalColor.1, b: kNomalColor.2) } scrollView.addSubview(lab) labelArr.append(lab) // 添加手势 lab.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tap:))) lab.addGestureRecognizer(tap) } } } // MARK: -title点击事件 extension YYTitleView { @objc fileprivate func titleLabelClick(tap: UITapGestureRecognizer) { let currentLab = tap.view as? UILabel if currentLab?.tag == originalIndex { return } // 1.设置文字颜色 let originalLab = labelArr[originalIndex] originalLab.textColor = UIColor(r: kNomalColor.0, g: kNomalColor.1, b: kNomalColor.2) currentLab?.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) // 2.取出当前是第几个 if let currentIndex = currentLab?.tag, let currentLab = currentLab { originalIndex = currentIndex // 3.设置线滑动 UIView.animate(withDuration: 0.3, animations: { self.lineView.frame.origin.x = CGFloat(currentIndex) * currentLab.frame.width }) // 4.通知代理点击了第几个 delegate?.yyTitleViewScrollToIndex(index: currentIndex) } } } // MARK: -设置滑动效果 extension YYTitleView { func setTitleView(progress: CGFloat, sourceIndex: Int, targetIndex: Int) { // 1.取出label let sourceLab = labelArr[sourceIndex] let targetLab = labelArr[targetIndex] // 2.处理滑块 let moveTotalX = targetLab.frame.origin.x - sourceLab.frame.origin.x let moveX = moveTotalX * progress lineView.frame.origin.x = sourceLab.frame.origin.x + moveX // 3.处理字体颜色 let colorDelta = (kSelectedColor.0 - kNomalColor.0, kSelectedColor.1 - kNomalColor.1, kSelectedColor.2 - kNomalColor.2) //print(colorDelta) sourceLab.textColor = UIColor(r: kSelectedColor.0 - colorDelta.0 * progress, g: kSelectedColor.1 - colorDelta.1 * progress, b: kSelectedColor.1 - colorDelta.1 * progress) targetLab.textColor = UIColor(r: kNomalColor.0 + colorDelta.0 * progress, g: kNomalColor.1 + colorDelta.1 * progress, b: kNomalColor.2 + colorDelta.2 * progress) originalIndex = targetIndex } }
aa633a18653125a2c68b59f8bcbe8c13
29.123596
127
0.581499
false
false
false
false
omochi/numsw
refs/heads/master
Sources/numsw/NDArray/NDArrayCompoundAssignment.swift
mit
1
// Scalar public func +=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs + rhs } public func -=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs - rhs } public func *=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs * rhs } public func /=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs / rhs } public func %=<T: Moduloable>(lhs: inout NDArray<T>, rhs: T) { lhs = lhs % rhs } // NDArray public func +=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs + rhs } public func -=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs - rhs } public func *=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs * rhs } public func /=<T: Arithmetic>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs / rhs } public func %=<T: Moduloable>(lhs: inout NDArray<T>, rhs: NDArray<T>) { lhs = lhs % rhs }
1942de941d628616d4b7dceda70ebce1
21.047619
71
0.591793
false
false
false
false
Benolds/reaxn-ios
refs/heads/master
ReaXn/ReaXn/MainViewController.swift
mit
3
// // MainViewController.swift // ReaXn // // Created by Benjamin Reynolds on 7/11/15. // Copyright (c) 2015 ReaXn. All rights reserved. // import UIKit class MainViewController: UIViewController { enum ActionType { case Message case Call case VoiceMemo case AddMore } enum ActionState { case Waiting case Done } @IBOutlet var settingsButton: UIButton! @IBOutlet var actionButton: UIButton! @IBOutlet var previousTypeButton: UIButton! @IBOutlet var nextTypeButton: UIButton! @IBOutlet var sentSuccessfullyLabel: UILabel! @IBOutlet var actionTypeLabel: UILabel! var currentActionState : ActionState = ActionState.Waiting var currentActionType : ActionType = ActionType.Message var rightSwipe : UISwipeGestureRecognizer? var leftSwipe : UISwipeGestureRecognizer? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { navigationController?.setNavigationBarHidden(navigationController?.navigationBarHidden == false, animated: true) //or animated: false self.refreshViewForActionType(self.currentActionType, newActionState: self.currentActionState) rightSwipe = UISwipeGestureRecognizer(target: self, action: "swipeRight") rightSwipe!.direction = UISwipeGestureRecognizerDirection.Right view.addGestureRecognizer(rightSwipe!) leftSwipe = UISwipeGestureRecognizer(target: self, action: "swipeLeft") leftSwipe!.direction = UISwipeGestureRecognizerDirection.Left view.addGestureRecognizer(leftSwipe!) } override func viewDidAppear(animated: Bool) { self.refreshViewForActionType(self.currentActionType, newActionState: ActionState.Waiting) } override func viewWillDisappear(animated: Bool) { if let gesture = rightSwipe { view.removeGestureRecognizer(gesture) } if let gesture = leftSwipe { view.removeGestureRecognizer(gesture) } } func swipeRight() { println("swipe right") switchPrevAction(nil) } func swipeLeft() { println("swipe left") switchNextAction(nil) } override func prefersStatusBarHidden() -> Bool { return navigationController?.navigationBarHidden == true } override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return UIStatusBarAnimation.Fade } func refreshViewForActionType(newActionType : ActionType, newActionState : ActionState) { self.currentActionType = newActionType self.currentActionState = newActionState if newActionState == ActionState.Waiting { switch newActionType { case ActionType.Message: self.view.backgroundColor = UIColor(red:0.47, green:0.80, blue:0.83, alpha:1.0) actionButton.setImage(UIImage(named: "MessageBig"), forState: UIControlState.Normal) case ActionType.Call: self.view.backgroundColor = UIColor(red:0.94, green:0.47, blue:0.54, alpha:1.0) actionButton.setImage(UIImage(named: "PhoneBig"), forState: UIControlState.Normal) case ActionType.VoiceMemo: self.view.backgroundColor = UIColor(red:0.98, green:0.73, blue:0.29, alpha:1.0) actionButton.setImage(UIImage(named: "VoiceBig"), forState: UIControlState.Normal) case ActionType.AddMore: self.view.backgroundColor = UIColor(red:0.15, green:0.18, blue:0.33, alpha:1.0) actionButton.setImage(UIImage(named: "PlusBig"), forState: UIControlState.Normal) } actionButton.enabled = true sentSuccessfullyLabel.hidden = true } else { switch currentActionType { case ActionType.Message: self.view.backgroundColor = UIColor(red:0.33, green:0.80, blue:0.82, alpha:1.0) actionButton.setImage(UIImage(named: "MessageBigDone"), forState: UIControlState.Normal) case ActionType.Call: self.view.backgroundColor = UIColor(red:0.94, green:0.38, blue:0.45, alpha:1.0) actionButton.setImage(UIImage(named: "PhoneBigDone"), forState: UIControlState.Normal) case ActionType.VoiceMemo: self.view.backgroundColor = UIColor(red:0.98, green:0.69, blue:0.20, alpha:1.0) actionButton.setImage(UIImage(named: "VoiceBigDone"), forState: UIControlState.Normal) case ActionType.AddMore: self.view.backgroundColor = UIColor(red:0.15, green:0.18, blue:0.33, alpha:1.0) actionButton.setImage(UIImage(named: "PlusBig"), forState: UIControlState.Normal) } actionButton.enabled = false sentSuccessfullyLabel.hidden = false } updateAppForActionType(newActionType) } func updateAppForActionType(actionType : ActionType) { switch actionType { case ActionType.Message: actionTypeLabel.text = "MESSAGES" sentSuccessfullyLabel.text = "Sent Successfully" previousTypeButton.setImage(UIImage(named: "PlusSmall"), forState: UIControlState.Normal) nextTypeButton.setImage(UIImage(named: "PhoneSmall"), forState: UIControlState.Normal) NSUserDefaults.standardUserDefaults().setObject(Constants.DefaultsMessagesString(), forKey: Constants.DefaultsKey_ActionType()) settingsButton.hidden = false case ActionType.Call: actionTypeLabel.text = "PHONE" sentSuccessfullyLabel.text = "Calling..." previousTypeButton.setImage(UIImage(named: "MessageSmall"), forState: UIControlState.Normal) nextTypeButton.setImage(UIImage(named: "VoiceSmall"), forState: UIControlState.Normal) NSUserDefaults.standardUserDefaults().setObject(Constants.DefaultsPhoneString(), forKey: Constants.DefaultsKey_ActionType()) settingsButton.hidden = false case ActionType.VoiceMemo: actionTypeLabel.text = "VOICE MEMOS" sentSuccessfullyLabel.text = "00:00:24" previousTypeButton.setImage(UIImage(named: "PhoneSmall"), forState: UIControlState.Normal) nextTypeButton.setImage(UIImage(named: "PlusSmall"), forState: UIControlState.Normal) NSUserDefaults.standardUserDefaults().setObject(Constants.DefaultsVoiceMemosString(), forKey: Constants.DefaultsKey_ActionType()) settingsButton.hidden = false case ActionType.AddMore: actionTypeLabel.text = "ADD MORE" previousTypeButton.setImage(UIImage(named: "VoiceSmall"), forState: UIControlState.Normal) nextTypeButton.setImage(UIImage(named: "MessageSmall"), forState: UIControlState.Normal) settingsButton.hidden = true } NSUserDefaults.standardUserDefaults().synchronize() } @IBAction func triggerAction(sender: UIButton) { if self.currentActionState == ActionState.Waiting { self.refreshViewForActionType(self.currentActionType, newActionState: ActionState.Done) if self.currentActionType == ActionType.Message { if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { appDelegate.sendSMS() } } else if self.currentActionType == ActionType.AddMore { self.performSegueWithIdentifier("addMoreSegue", sender: self) return } delay(5.0) { self.refreshViewForActionType(self.currentActionType, newActionState: ActionState.Waiting) } } /*else { self.refreshViewForActionType(self.currentActionType, newActionState: ActionState.Waiting) }*/ } func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } @IBAction func switchNextAction(sender: UIButton?) { switch self.currentActionType { case ActionType.Message: refreshViewForActionType(ActionType.Call, newActionState: ActionState.Waiting) case ActionType.Call: refreshViewForActionType(ActionType.VoiceMemo, newActionState: ActionState.Waiting) case ActionType.VoiceMemo: refreshViewForActionType(ActionType.AddMore, newActionState: ActionState.Waiting) case ActionType.AddMore: refreshViewForActionType(ActionType.Message, newActionState: ActionState.Waiting) } } @IBAction func switchPrevAction(sender: UIButton?) { switch self.currentActionType { case ActionType.Message: refreshViewForActionType(ActionType.AddMore, newActionState: ActionState.Waiting) case ActionType.Call: refreshViewForActionType(ActionType.Message, newActionState: ActionState.Waiting) case ActionType.VoiceMemo: refreshViewForActionType(ActionType.Call, newActionState: ActionState.Waiting) case ActionType.AddMore: refreshViewForActionType(ActionType.VoiceMemo, newActionState: ActionState.Waiting) } } // 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. if let settingsViewController = segue.destinationViewController as? SettingsViewController { settingsViewController.currentActionType = self.currentActionType } if let addMoreViewController = segue.destinationViewController as? AddMoreViewController { addMoreViewController.currentActionType = self.currentActionType } } }
6c3d7428e62311c325ead98dd9a0ebf6
38.046763
141
0.641456
false
false
false
false
Pradeepkn/Mysore_App
refs/heads/master
MysoreApp/Network/TTNetwork/Managers/APIManager/APIKeys.swift
mit
1
// // APIKeys.swift // APIManager-Alamofire // // Created by Pradeep on 2/8/16. // Copyright © 2016 Pradeep. All rights reserved. // import Foundation struct APIConfig { // Config static var isProduction: Bool = false static var ProductionURL: String = "http://mapunity.com/api/usn/" static var StagingURL: String = "http://mapunity.com/api/usn/" static var ImageProductionURL: String = "http://mapunity.com" static var ImageStagingURL: String = "http://mapunity.com" static var BaseURL: String { if isProduction { return ProductionURL } else { return StagingURL } } static var ImageBaseURL: String { if isProduction { return ImageProductionURL } else { return ImageStagingURL } } static let timeoutInterval = 30.0 // In Seconds }
6cd24b222627084a99a2ea364fd6fe62
21.243902
69
0.598684
false
false
false
false
OlegNovosad/Sample
refs/heads/master
iOS/Severenity/Views/Chat/ChatViewController.swift
apache-2.0
2
// // Tab4ViewController.swift // severenityProject // // Created by Yura Yasinskyy on 12.09.16. // Copyright © 2016 severenity. All rights reserved. // import UIKit class ChatViewController: UIViewController { internal var presenter: ChatPresenter? internal var messages = [Dictionary<String,Any>]() @IBOutlet weak var messagesTableView: UITableView! @IBOutlet weak var newMessageTextField: UITextField! @IBOutlet weak var sendMessageButton: UIButton! // MARK: Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) presenter = ChatPresenter() presenter?.delegate = self Log.info(message: "Chat VIPER module init did complete", sender: self) } // MARK: Loading view override func viewDidLoad() { super.viewDidLoad() messagesTableView.delegate = self messagesTableView.dataSource = self messagesTableView.register(UINib(nibName: "MessageOutView", bundle: nil), forCellReuseIdentifier: "MessageOutView") messagesTableView.register(UINib(nibName: "MessageInView", bundle: nil), forCellReuseIdentifier: "MessageInView") messagesTableView.backgroundColor = UIColor.black messagesTableView.separatorColor = UIColor.clear newMessageTextField.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) Log.info(message: "Chat tab did load", sender: self); } @IBAction func sendMessageButtonTap(_ sender: AnyObject) { sendMessage() } func sendMessage() { if newMessageTextField.text != "" { presenter?.userWantsToSendMessage(with: newMessageTextField.text!) newMessageTextField.resignFirstResponder() newMessageTextField.text = "" if messages.count > 0 { messagesTableView.scrollToRow(at: NSIndexPath.init(row: messages.count-1, section: 0) as IndexPath, at: .bottom, animated: true) } } } // MARK: Managing view layout on keyboard appear/disappear func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { newMessageTextField.frame.origin.y -= keyboardSize.height - 50 // magical number sendMessageButton.frame.origin.y -= keyboardSize.height - 50 if messages.count > 3 { messagesTableView.frame.origin.y -= keyboardSize.height - 50 } } } func keyboardWillHide(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { newMessageTextField.frame.origin.y += keyboardSize.height - 50 sendMessageButton.frame.origin.y += keyboardSize.height - 50 if messages.count > 3 { messagesTableView.frame.origin.y += keyboardSize.height - 50 } } } } // MARK: ChatPresenter delegate extension ChatViewController: ChatPresenterDelegate { func displayNewMessage(with dictionary: Dictionary<String,String>) { Log.info(message: "ChatViewController is called from ChatPresenter with message: \(dictionary)", sender: self) messages.append(dictionary) messagesTableView.reloadData() } } extension ChatViewController: UITableViewDelegate, UITableViewDataSource { // MARK: UITableView delegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 105.0 // size of the cell xib } // MARK: UITableView data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell let message = messages[(indexPath as NSIndexPath).row] guard let senderName = message["senderName"] as? String, let timestamp = message["timestamp"] as? String, let messageText = message["text"] as? String, let senderFbId = message["senderId"] as? String, let currentUserFbID = FacebookService.sharedInstance.accessTokenUserID else { Log.error(message: "Cannot create chat message cell", sender: self) cell = UITableViewCell() return cell } if senderFbId != currentUserFbID { if let c = tableView.dequeueReusableCell(withIdentifier: "MessageInView", for: indexPath) as? MessageInView { c.infoLabel.text = "\(senderName), \(timestamp)" c.messageText.text = messageText FacebookService.sharedInstance.getFBProfilePicture(for: senderFbId, size: .normal, completion: { (image) in c.profilePicture.image = image }) cell = c } else { cell = tableView.dequeueReusableCell(withIdentifier: "MessageInView", for: indexPath) } } else { if let c = tableView.dequeueReusableCell(withIdentifier: "MessageOutView", for: indexPath) as? MessageOutView { c.infoLabel.text = "\(senderName), \(timestamp)" c.messageText.text = messageText FacebookService.sharedInstance.getFBProfilePicture(for: senderFbId, size: .normal, completion: { (image) in c.profilePicture.image = image }) cell = c } else { cell = tableView.dequeueReusableCell(withIdentifier: "MessageOutView", for: indexPath) } } cell.backgroundColor = UIColor.clear return cell } } // MARK: UITextField delegate extension ChatViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { sendMessage() return true } }
9e4c86d4f019e73157a2f57b45230369
37.706587
150
0.644957
false
false
false
false
corinnekrych/aerogear-ios-http-1
refs/heads/master
AeroGearHttp/JsonResponseSerializer.swift
apache-2.0
1
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * 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 /** A response deserializer to JSON objects. */ public class JsonResponseSerializer : ResponseSerializer { /** Deserialize the response received. :returns: the serialized response */ public func response(data: NSData) -> (AnyObject?) { return NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil) } /** Validate the response received. :returns: either true or false if the response is valid for this particular serializer. */ public func validateResponse(response: NSURLResponse!, data: NSData, error: NSErrorPointer) -> Bool { let httpResponse = response as! NSHTTPURLResponse if !(httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) { var userInfo = [ NSLocalizedDescriptionKey: NSHTTPURLResponse.localizedStringForStatusCode(httpResponse.statusCode), NetworkingOperationFailingURLResponseErrorKey: response] if (error != nil) { error.memory = NSError(domain: HttpResponseSerializationErrorDomain, code: httpResponse.statusCode, userInfo: userInfo) } return false } // validate JSON if (nil == NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: nil)) { let userInfo = [ NSLocalizedDescriptionKey: "Invalid response received, can't parse JSON" as NSString, NetworkingOperationFailingURLResponseErrorKey: response] if (error != nil) { error.memory = NSError(domain: HttpResponseSerializationErrorDomain, code: NSURLErrorBadServerResponse, userInfo: userInfo) } return false; } return true } public init() { } }
53b537578dbd07108d27562abf37bd43
35.140845
139
0.662378
false
false
false
false
CodaFi/swift
refs/heads/main
test/PCMacro/didset.swift
apache-2.0
21
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -whole-module-optimization -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/PCMacroRuntime.swift %S/Inputs/SilentPlaygroundsRuntime.swift // RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift // RUN: %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu import PlaygroundSupport #sourceLocation(file: "main.swift", line: 10) struct S { var a : [Int] = [] { didSet(oldValue) { print("Set") } } } var s = S() s.a = [3,2] s.a.append(300) // CHECK: [18:1-18:12] pc before // CHECK-NEXT: [18:1-18:12] pc after // CHECK-NEXT: [19:1-19:12] pc before // CHECK-NEXT: [12:9-12:25] pc before // CHECK-NEXT: [12:9-12:25] pc after // CHECK-NEXT: [13:13-13:25] pc before // CHECK-NEXT: Set // CHECK-NEXT: [13:13-13:25] pc after // CHECK-NEXT: [19:1-19:12] pc after // CHECK-NEXT: [20:1-20:16] pc before // CHECK-NEXT: [12:9-12:25] pc before // CHECK-NEXT: [12:9-12:25] pc after // CHECK-NEXT: [13:13-13:25] pc before // CHECK-NEXT: Set // CHECK-NEXT: [13:13-13:25] pc after // CHECK-NEXT: [20:1-20:16] pc after
80f3fc138a93bbe67af92dfd7f8087c2
34.913043
255
0.666465
false
false
false
false
JojoSc/OverTheEther
refs/heads/master
OverTheEther/Classes/Helpers.swift
mit
1
// // WifiServerDelegate.swift // OverTheEther // // Created by Johannes Schreiber on 17/02/16. // Copyright © 2016 Johannes Schreiber. All rights reserved. // import Foundation import SystemConfiguration /* Swift doesn't yet have an array.removeObject() method, so here is one. Removes the first occurence only. (from http://stackoverflow.com/questions/24938948/array-extension-to-remove-object-by-value ) */ extension RangeReplaceableCollectionType where Generator.Element : Equatable { mutating func removeObject(object : Generator.Element) { if let index = self.indexOf(object) { self.removeAtIndex(index) } } } /* http://stackoverflow.com/questions/26086488/detecting-if-the-wifi-is-enabled-in-swift by Sam */ public func isInternetConnected() -> Bool { let rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com") var flags : SCNetworkReachabilityFlags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(rechability!, &flags) == false { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } public func isWifiConnected() -> Bool { let r = Reach() return r.connectionStatus().description == ReachabilityStatus.Online(ReachabilityType.WiFi).description } /* func DDLogError(string:String) {print("E: "+string)} func DDLogWarn(string:String) {print("W: "+string)} func DDLogDebug(string:String) {print("D: "+string)} func DDLogInfo(string:String) {print("I: "+string)} func DDLogVerbose(string:String) {print("V: "+string)} */
5df1d746e84e096e60efc39ac8bf0323
30.545455
107
0.731257
false
false
false
false
Allow2CEO/browser-ios
refs/heads/master
Client/Application/AppDelegate.swift
mpl-2.0
1
/* 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 Shared import Storage import AVFoundation import XCGLogger import MessageUI import WebImage import SwiftKeychainWrapper import LocalAuthentication private let log = Logger.browserLogger let LatestAppVersionProfileKey = "latestAppVersion" let AllowThirdPartyKeyboardsKey = "settings.allowThirdPartyKeyboards" class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestoration { public static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { return nil } // TODO: Having all of these global opens up lots of abuse potential (open via getApp()) private var launchTimer: Timer? var window: UIWindow? var securityWindow: UIWindow? var securityViewController: PinProtectOverlayViewController? var browserViewController: BrowserViewController! var rootViewController: UINavigationController! weak var profile: BrowserProfile? var tabManager: TabManager! var braveTopViewController: BraveTopViewController! weak var application: UIApplication? var launchOptions: [AnyHashable: Any]? let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String var openInBraveParams: LaunchParams? = nil func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { BraveApp.willFinishLaunching_begin() // Hold references to willFinishLaunching parameters for delayed app launch self.application = application self.launchOptions = launchOptions log.debug("Configuring window…") self.window = BraveMainWindow(frame: UIScreen.main.bounds) self.window!.backgroundColor = UIConstants.AppBackgroundColor // Short circuit the app if we want to email logs from the debug menu if DebugSettingsBundleOptions.launchIntoEmailComposer { self.window?.rootViewController = UIViewController() presentEmailComposerWithLogs() return true } else { return startApplication(application, withLaunchOptions: launchOptions) } } // Swift Selectors hate class method on extensions, this just wraps the behavior // Also, must be public func updateDauStatWrapper() { guard let prefs = profile?.prefs else { log.warning("Couldn't find profile, unable to send dau stats!") return } let dau = DAU(prefs: prefs) dau.sendPingToServer() } fileprivate func startApplication(_ application: UIApplication, withLaunchOptions launchOptions: [AnyHashable: Any]?) -> Bool { log.debug("Setting UA…") // Ping server for stats // Sets up X second timer to represent an active user self.launchTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateDauStatWrapper), userInfo: nil, repeats: false) setUserAgents() log.debug("Starting keyboard helper…") // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() log.debug("Starting dynamic font helper…") // Start the keyboard helper to monitor and cache keyboard state. DynamicFontHelper.defaultHelper.startObserving() log.debug("Setting custom menu items…") MenuHelper.defaultHelper.setItems() log.debug("Creating Sync log file…") let logDate = Date() // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(logDate) log.debug("Creating corrupt DB logger…") Logger.corruptLogger.newLogWithDate(logDate) log.debug("Creating Browser log file…") Logger.browserLogger.newLogWithDate(logDate) log.debug("Getting profile…") let profile = getProfile(application) if !DebugSettingsBundleOptions.disableLocalWebServer { log.debug("Starting web server…") // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) } log.debug("Setting AVAudioSession category…") do { // for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers) } catch _ { log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar") } var defaultRequest = URLRequest(url: UIConstants.DefaultHomePage as URL) defaultRequest.addValue(WebServer.uniqueBytes, forHTTPHeaderField: WebServer.headerAuthKey) let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality) log.debug("Configuring tabManager…") self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, prefs: profile.prefs, imageStore: imageStore) self.tabManager.stateDelegate = self browserViewController = BraveBrowserViewController(profile: profile, tabManager: self.tabManager) browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self browserViewController.automaticallyAdjustsScrollViewInsets = false braveTopViewController = BraveTopViewController(browserViewController: browserViewController as! BraveBrowserViewController) rootViewController = UINavigationController(rootViewController: braveTopViewController) rootViewController.automaticallyAdjustsScrollViewInsets = false rootViewController.delegate = self rootViewController.isNavigationBarHidden = true self.window!.rootViewController = rootViewController // TODO: Show activity indicator instead of launching app. _ = MigrateData(completed: { (success) in if success { // TODO: Remove activity indicator. } }) let favoritesInit = profile.prefs.boolForKey(FavoritesHelper.initPrefsKey) ?? false if !favoritesInit { let isFirstLaunch = profile.prefs.arrayForKey(DAU.preferencesKey) == nil if isFirstLaunch { log.info("Favorites initialization, new user.") FavoritesHelper.addDefaultFavorites() } else { // existing user, using Brave before the topsites to favorites change. log.info("Favorites initialization, existing user.") postAsyncToMain(1.5) { self.browserViewController.tabManager.addAdjacentTabAndSelect() self.browserViewController.presentTopSitesToFavoritesChange() } } profile.prefs.setBool(true, forKey: FavoritesHelper.initPrefsKey) } // MARK: User referral program if let urp = UserReferralProgram() { let isFirstLaunch = self.getProfile(application).prefs.arrayForKey(DAU.preferencesKey) == nil if isFirstLaunch { urp.referralLookup { url in guard let url = url else { return } postAsyncToMain(1) { try? self.browserViewController.openURLInNewTab(url.asURL()) } } } else { urp.getCustomHeaders() urp.pingIfEnoughTimePassed() } } else { log.error("Failed to initialize user referral program") UrpLog.log("Failed to initialize user referral program") } log.debug("Adding observers…") NotificationCenter.default.addObserver(forName: NSNotification.Name.FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL { let title = (userInfo["Title"] as? String) ?? "" profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name) } } // check to see if we started 'cos someone tapped on a notification. if let localNotification = launchOptions?[UIApplicationLaunchOptionsKey.localNotification] as? UILocalNotification { viewURLInNewTab(localNotification) } // We need to check if the app is a clean install to use for // preventing the What's New URL from appearing. if getProfile(application).prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { getProfile(application).prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } log.debug("Updating authentication keychain state to reflect system state") self.updateAuthenticationInfo() SystemUtils.onFirstRun() log.debug("Done with setting up the application.") BraveApp.willFinishLaunching_end() return true } func applicationWillTerminate(_ application: UIApplication) { log.debug("Application will terminate.") var task: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier() task = UIApplication.shared.beginBackgroundTask(withName: "deactivateQueue", expirationHandler: { () -> Void in UIApplication.shared.endBackgroundTask(task) task = UIBackgroundTaskInvalid }) DispatchQueue.global(qos: .background).async { TabMO.clearAllPrivate() self.shutdownProfileWhenNotActive() BraveGlobalShieldStats.singleton.save() // Allow deinitializers to close our database connections. self.profile = nil self.tabManager = nil self.browserViewController = nil self.rootViewController = nil log.debug("Background cleanup completed.") task = UIBackgroundTaskInvalid } } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(_ application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", app: application) self.profile = p return p } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { var shouldPerformAdditionalDelegateHandling = true log.debug("Did finish launching.") log.debug("Making window key and visible…") self.window!.makeKeyAndVisible() // Now roll logs. log.debug("Triggering log roll.") DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background).async { Logger.syncLogger.deleteOldLogsDownToSizeLimit() Logger.browserLogger.deleteOldLogsDownToSizeLimit() } // If a shortcut was launched, display its information and take the appropriate action if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem { QuickActions.sharedInstance.launchedShortcutItem = shortcutItem // This will block "performActionForShortcutItem:completionHandler" from being called. shouldPerformAdditionalDelegateHandling = false } log.debug("Done with applicationDidFinishLaunching.") BraveApp.didFinishLaunching() let appProfile = getProfile(application) requirePinIfNeeded(profile: appProfile) return shouldPerformAdditionalDelegateHandling } // Note: annotation is explicitly marked as Any? instead of Any because of an issue leading to a crash in some versions of Xcode. // For context, see here https://bit.ly/2H04dOw (Swift contributor commenting on source of mysterious crash) and here https://bit.ly/2HDSAhz (workaround) // This'll trigger a benign warning until this version of openURL is no longer needed (newer method was added in iOS 10). func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any?) -> Bool { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } if !BraveApp.shouldHandleOpenURL(components) { return false } var url: String? var isPrivate: Bool = false for item in (components.queryItems ?? []) as [URLQueryItem] { switch item.name { case "url": url = item.value case "private": isPrivate = NSString(string: item.value ?? "false").boolValue default: () } } let params: LaunchParams if let url = url, let newURL = URL(string: url.unescape()) { params = LaunchParams(url: newURL, isPrivate: isPrivate) } else { params = LaunchParams(url: nil, isPrivate: isPrivate) } if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. launchFromURL(params) } else { openInBraveParams = params } return true } func launchFromURL(_ params: LaunchParams) { let isPrivate = params.isPrivate ?? false if let newURL = params.url { self.browserViewController.switchToTabForURLOrOpen(newURL, isPrivate: isPrivate) } else { self.browserViewController.openBlankNewTabAndFocus(isPrivate: isPrivate) } } func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplicationExtensionPointIdentifier) -> Bool { if let thirdPartyKeyboardSettingBool = getProfile(application).prefs.boolForKey(AllowThirdPartyKeyboardsKey), extensionPointIdentifier == UIApplicationExtensionPointIdentifier.keyboard { return thirdPartyKeyboardSettingBool } return true } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(_ application: UIApplication) { guard !DebugSettingsBundleOptions.launchIntoEmailComposer else { return } blurOverlayBehavior(.show) // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. self.browserViewController.loadQueuedTabs() // handle quick actions is available let quickActions = QuickActions.sharedInstance if let shortcut = quickActions.launchedShortcutItem { // dispatch asynchronously so that BVC is all set up for handling new tabs // when we try and open them quickActions.handleShortCutItem(shortcut, withBrowserViewController: browserViewController) quickActions.launchedShortcutItem = nil } // we've removed the Last Tab option, so we should remove any quick actions that we already have that are last tabs // we do this after we've handled any quick actions that have been used to open the app so that we don't b0rk if // the user has opened the app for the first time after upgrade with a Last Tab quick action QuickActions.sharedInstance.removeDynamicApplicationShortcutItemOfType(ShortcutType.OpenLastTab, fromApplication: application) // Check if we have a URL from an external app or extension waiting to launch, // then launch it on the main thread. if let params = openInBraveParams { openInBraveParams = nil DispatchQueue.main.async { self.launchFromURL(params) } } let profile = getProfile(application) if profile.prefs.boolForKey(kPrefKeyBrowserLock) == true && securityWindow?.isHidden == false { securityViewController?.auth() } } func applicationDidEnterBackground(_ application: UIApplication) { print("Close database") shutdownProfileWhenNotActive() BraveGlobalShieldStats.singleton.save() } func applicationWillResignActive(_ application: UIApplication) { BraveGlobalShieldStats.singleton.save() self.launchTimer?.invalidate() self.launchTimer = nil blurOverlayBehavior(.hide) } func applicationWillEnterForeground(_ application: UIApplication) { // The reason we need to call this method here instead of `applicationDidBecomeActive` // is that this method is only invoked whenever the application is entering the foreground where as // `applicationDidBecomeActive` will get called whenever the Touch ID authentication overlay disappears. self.updateAuthenticationInfo() profile?.reopen() let appProfile = getProfile(application) requirePinIfNeeded(profile: appProfile) } private enum BlurLayoutBehavior { case show, hide } /// Toggles blurry overview when app is not active. /// If browser lock is enabled app switcher screenshot is not leaked. private func blurOverlayBehavior(_ behavior: BlurLayoutBehavior) { guard let profile = profile, profile.prefs.boolForKey(kPrefKeyBrowserLock) == true else { return } switch behavior { case .show: UIView.animate(withDuration: 0.1, animations: { _ in self.blurryLayout.alpha = 0 }, completion: { _ in self.blurryLayout.removeFromSuperview() }) case .hide: window?.addSubview(blurryLayout) UIView.animate(withDuration: 0.1, animations: { _ in self.blurryLayout.alpha = 1 }) } } private lazy var blurryLayout: UIView = { let view = UIView(frame: UIScreen.main.bounds) let blur: UIVisualEffectView blur = UIVisualEffectView(effect: UIBlurEffect(style: .light)) blur.frame = view.frame view.addSubview(blur) view.alpha = 0 return view }() func requirePinIfNeeded(profile: Profile) { // Check for browserLock settings if profile.prefs.boolForKey(kPrefKeyBrowserLock) == true { if securityWindow != nil { securityViewController?.start() // This could have been changed elsewhere, not the best approach. securityViewController?.successCallback = hideSecurityWindowIfCorrectPin(_:) securityWindow?.isHidden = false return } let vc = PinProtectOverlayViewController() securityViewController = vc let pinOverlay = UIWindow(frame: UIScreen.main.bounds) pinOverlay.backgroundColor = UIColor(white: 0.9, alpha: 0.7) pinOverlay.windowLevel = UIWindowLevelAlert pinOverlay.rootViewController = vc securityWindow = pinOverlay pinOverlay.makeKeyAndVisible() vc.successCallback = hideSecurityWindowIfCorrectPin(_:) } } fileprivate func hideSecurityWindowIfCorrectPin(_ success: Bool) { if success { postAsyncToMain { self.securityWindow?.isHidden = true } } } fileprivate func updateAuthenticationInfo() { if let authInfo = KeychainWrapper.standard.authenticationInfo() { if !LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { authInfo.useTouchID = false KeychainWrapper.standard.setAuthenticationInfo(authInfo) } } } fileprivate func setUpWebServer(_ profile: Profile) { let server = WebServer.sharedInstance ReaderModeHandlers.register(server, profile: profile) ErrorPageHelper.register(server, certStore: profile.certStore) AboutHomeHandler.register(server) SessionRestoreHandler.register(server) // Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task // catching and handling the error seemed to fix things, but we're not sure why. // Either way, not implicitly unwrapping a try is not a great way of doing things // so this is better anyway. do { try server.start() } catch let err as NSError { log.error("Unable to start WebServer \(err)") } } fileprivate func setUserAgents() { let firefoxUA = UserAgent.defaultUserAgent() // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. Note that we use defaults here that are // readable from extensions, so they can just use the cached identifier. let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! defaults.register(defaults: ["UserAgent": firefoxUA]) SDWebImageDownloader.shared().setValue(firefoxUA, forHTTPHeaderField: "User-Agent") // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA // Some sites will only serve HTML that points to .ico files. // The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent. FaviconFetcher.userAgent = UserAgent.desktopUserAgent() } func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) { if let actionId = identifier { if let action = SentTabAction(rawValue: actionId) { viewURLInNewTab(notification) switch(action) { case .Bookmark: //addBookmark(notification) break case .ReadingList: addToReadingList(notification) break default: break } } else { print("ERROR: Unknown notification action received") } } else { print("ERROR: Unknown notification received") } } func application(_ application: UIApplication, didReceive notification: UILocalNotification) { viewURLInNewTab(notification) } fileprivate func presentEmailComposerWithLogs() { if let buildNumber = Bundle.main.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as? NSString { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setSubject("Debug Info for iOS client version v\(appVersion) (\(buildNumber))") if DebugSettingsBundleOptions.attachLogsToDebugEmail { do { let logNamesAndData = try Logger.diskLogFilenamesAndData() logNamesAndData.forEach { nameAndData in if let data = nameAndData.1 { mailComposeViewController.addAttachmentData(data, mimeType: "text/plain", fileName: nameAndData.0) } } } catch _ { print("Failed to retrieve logs from device") } } self.window?.rootViewController?.present(mailComposeViewController, animated: true, completion: nil) } } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { if let url = userActivity.webpageURL { browserViewController.switchToTabForURLOrOpen(url) return true } return false } fileprivate func viewURLInNewTab(_ notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String { if let urlToOpen = URL(string: alertURL) { browserViewController.openURLInNewTab(urlToOpen) } } } fileprivate func addToReadingList(_ notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { if let urlToOpen = URL(string: alertURL) { NotificationCenter.default.post(name: NSNotification.Name.FSReadingListAddReadingListItem, object: self, userInfo: ["URL": urlToOpen, "Title": title]) } } } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: browserViewController) completionHandler(handledShortCutItem) } #if !BRAVE var activeCrashReporter: CrashReporter? func configureActiveCrashReporter(_ optedIn: Bool?) { if let reporter = activeCrashReporter { configureCrashReporter(reporter, optedIn: optedIn) } } #endif fileprivate func shutdownProfileWhenNotActive() { // Only shutdown the profile if we are not in the foreground guard UIApplication.shared.applicationState != UIApplicationState.active else { return } profile?.shutdown() } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { #if !BRAVE func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.push { return BrowserToTrayAnimator() } else if operation == UINavigationControllerOperation.pop { return TrayToBrowserAnimator() } else { return nil } } #endif } extension AppDelegate: TabManagerStateDelegate { func tabManagerWillStoreTabs(_ tabs: [Browser]) { // It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL. let storedTabs: [RemoteTab] = tabs.flatMap( Browser.toTab ) // Don't insert into the DB immediately. We tend to contend with more important // work like querying for top sites. let queue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background) queue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(ProfileRemoteTabsSyncDelay * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)) { self.profile?.storeTabs(storedTabs) } } } extension AppDelegate: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { // Dismiss the view controller and start the app up controller.dismiss(animated: true, completion: nil) startApplication(application!, withLaunchOptions: self.launchOptions) } } struct LaunchParams { let url: URL? let isPrivate: Bool? }
9840ad64fe20d08189f104fdc420f57c
41.273529
194
0.663884
false
false
false
false
jakubknejzlik/ChipmunkSwiftWrapper
refs/heads/master
Pod/Classes/Chipmunk.swift
mit
1
// // Chipmunk.swift // Pods // // Created by Jakub Knejzlik on 15/11/15. // // import Foundation extension Bool { init(_ integer: Int32){ self.init(integer > 0) } func cpBool() -> Int32 { return self ? 1 : 0 } } extension UnsafePointer { func getUIntValue() -> UInt { let string = "\(self)"//.stringByReplacingOccurrencesOfString("0xb", withString: "").stringByReplacingOccurrencesOfString("0x", withString: "") let scanner = NSScanner(string: string) var result : UInt64 = 0 scanner.scanHexLongLong(&result) return UInt(result) } } extension UInt { init?(_ pointer: UnsafePointer<Void>) { let string = "\(pointer)"//.stringByReplacingOccurrencesOfString("0xb", withString: "").stringByReplacingOccurrencesOfString("0x", withString: "") let scanner = NSScanner(string: string) var result : UInt64 = 0 if scanner.scanHexLongLong(&result) { print(result) // 37331519 } self = UInt(result) } }
c123571440fcd9e01162ec1808dcdbe9
25.175
154
0.613767
false
false
false
false
AppLovin/iOS-SDK-Demo
refs/heads/master
Swift Demo App/iOS-SDK-Demo/ALDemoRewardedVideosViewController.swift
mit
1
// // ALDemoRewardedVideosViewController.swift // iOS-SDK-Demo // // Created by Thomas So on 9/25/15. // Copyright © 2015 AppLovin. All rights reserved. // import UIKit class ALDemoRewardedVideosViewController : ALDemoBaseViewController { @IBAction func showRewardedVideo() { // You need to preload each rewarded video before it can be displayed if ALIncentivizedInterstitialAd.shared().isReadyForDisplay { // Optional: Assign delegates ALIncentivizedInterstitialAd.shared().adDisplayDelegate = self ALIncentivizedInterstitialAd.shared().adVideoPlaybackDelegate = self ALIncentivizedInterstitialAd.showAndNotify(self) } else { preloadRewardedVideo() } } // You need to preload each rewarded video before it can be displayed @IBAction func preloadRewardedVideo() { log("Preloading...") ALIncentivizedInterstitialAd.shared().preloadAndNotify(self) } } extension ALDemoRewardedVideosViewController : ALAdLoadDelegate { func adService(_ adService: ALAdService, didLoad ad: ALAd) { log("Rewarded Video Loaded") } func adService(_ adService: ALAdService, didFailToLoadAdWithError code: Int32) { // Look at ALErrorCodes.h for list of error codes log("Rewarded video failed to load with error code \(code)") } } extension ALDemoRewardedVideosViewController : ALAdRewardDelegate { func rewardValidationRequest(for ad: ALAd, didSucceedWithResponse response: [AnyHashable: Any]) { /** * AppLovin servers validated the reward. Refresh user balance from your server. We will also pass the number of coins * awarded and the name of the currency. However, ideally, you should verify this with your server before granting it. */ // "current" - "Coins", "Gold", whatever you set in the dashboard. // "amount" - "5" or "5.00" if you've specified an amount in the UI. if let amount = response["amount"] as? NSString, let currencyName = response["currency"] as? NSString { log("Rewarded \(amount.floatValue) \(currencyName)") } } func rewardValidationRequest(for ad: ALAd, didFailWithError responseCode: Int) { if responseCode == kALErrorCodeIncentivizedUserClosedVideo { // Your user exited the video prematurely. It's up to you if you'd still like to grant // a reward in this case. Most developers choose not to. Note that this case can occur // after a reward was initially granted (since reward validation happens as soon as a // video is launched). } else if responseCode == kALErrorCodeIncentivizedValidationNetworkTimeout || responseCode == kALErrorCodeIncentivizedUnknownServerError { // Some server issue happened here. Don't grant a reward. By default we'll show the user // a UIAlertView telling them to try again later, but you can change this in the // Manage Apps UI. } else if responseCode == kALErrorCodeIncentiviziedAdNotPreloaded { // Indicates that you called for a rewarded video before one was available. } log("Reward validation request failed with error code \(responseCode)") } func rewardValidationRequest(for ad: ALAd, didExceedQuotaWithResponse response: [AnyHashable: Any]) { // Your user has already earned the max amount you allowed for the day at this point, so // don't give them any more money. By default we'll show them a UIAlertView explaining this, // though you can change that from the Manage Apps UI. log("Reward validation request did exceed quota with response: \(response)") } func rewardValidationRequest(for ad: ALAd, wasRejectedWithResponse response: [AnyHashable: Any]) { // Your user couldn't be granted a reward for this view. This could happen if you've blacklisted // them, for example. Don't grant them any currency. By default we'll show them a UIAlertView explaining this, // though you can change that from the Manage Apps UI. log("Reward validation request was rejected with response: \(response)") } } extension ALDemoRewardedVideosViewController : ALAdDisplayDelegate { func ad(_ ad: ALAd, wasDisplayedIn view: UIView) { log("Ad Displayed") } func ad(_ ad: ALAd, wasHiddenIn view: UIView) { log("Ad Dismissed") } func ad(_ ad: ALAd, wasClickedIn view: UIView) { log("Ad Clicked") } } extension ALDemoRewardedVideosViewController : ALAdVideoPlaybackDelegate { func videoPlaybackBegan(in ad: ALAd) { log("Video Started") } func videoPlaybackEnded(in ad: ALAd, atPlaybackPercent percentPlayed: NSNumber, fullyWatched wasFullyWatched: Bool) { log("Video Ended") } }
9cecd7890a6e95783f88a8bd2e628473
35.717391
142
0.661733
false
false
false
false
mark644873613/Doctor-lives
refs/heads/master
Doctor lives/Doctor lives/classes/Home首页/main(主要的)/view/ListCell.swift
mit
1
// // ListCell.swift // Doctor lives // // Created by qianfeng on 16/11/8. // Copyright © 2016年 zhb. All rights reserved. // import UIKit class ListCell: UITableViewCell { //点击按钮 点击方法。tag=400~404 @IBAction func btnClick(sender: AnyObject) { } @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var adressLabel: UILabel! @IBOutlet weak var imageV: UIImageView! @IBOutlet weak var favoLabel: UILabel! @IBOutlet weak var commentLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! //显示数据 var cellModel:HomeDetailImage?{ didSet{ if cellModel != nil { showData() } } } //显示数据 func showData(){ //人头像图 let url=NSURL(string: (cellModel?.avatar?.avatar_url)!) imageV.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil) imageV.layer.cornerRadius=25 imageV.layer.masksToBounds=true //名字 let authorData=cellModel?.author nameLabel.text=authorData //医院 let hospitalData=cellModel?.hospital adressLabel.text=hospitalData //title let docotorTitle=cellModel?.title titleLabel.text=docotorTitle //收藏 let certData=cellModel?.cert_status favoLabel.text=String(certData!) //评论 let commentData=cellModel?.comment_count commentLabel.text=String(commentData!) let g=UITapGestureRecognizer(target: self, action: #selector(imagAction(_:))) addGestureRecognizer(g) } //点击事件 func imagAction(g:UITapGestureRecognizer){ } //创建cell的方法 class func createDetailCellFor(tableView:UITableView, atIndexPath indexPath: NSIndexPath, cellModel:HomeDetailImage?) -> ListCell { let cellId="listCellId" var cell=tableView.dequeueReusableCellWithIdentifier(cellId) as? ListCell if nil == cell { //IngreLikeCell.xib cell = NSBundle.mainBundle().loadNibNamed("ListCell", owner: nil, options: nil).last as? ListCell } //显示数据 cell?.cellModel=cellModel return cell! } @IBOutlet weak var hemeLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
b6dbec2d3d4374e4964da30a65edbad3
25.949495
135
0.603448
false
false
false
false
HackerEdu/TangZhifeng
refs/heads/master
day3/day3.playground/section-1.swift
mit
1
class Stack<Int> { var items: [Int]? = [] //这个函数用于在栈中增加一个元素,简单的调用数组append函数就能实现 func push(value: Int) { items?.append(value) } //为什么Int后要用“?” //如果申明为Int变量,那么它的返回值只能为数字而不能是nil //这个函数栈中的一个元素 func pop() -> Int?{ if let value = self.top(){ //判断是否为空??? items?.removeLast() return value } return nil } func top() -> Int?{ if let value = items?.last{ // 取出最后一个值 return value } return nil } } var stack = Stack<Int>() stack.push(0) stack.push(1) stack.push(2) stack.top() stack.pop()! stack.top() println("**********************") println() class Queue<Int> { var items:[Int]? = [] func enqeue(value:Int){ items?.append(value) } func dequeue() -> Int?{ //从队列中取出一个值,先进先出,后进后出 if items?.count > 0 { //同样判断这个队列不为空,这个栈的判断有什么区别? let obj = items?.removeAtIndex(0) //为什么运行了3次? return obj }else{ return nil } } var isEmpty: Bool{ if let items = self.items { //调用数组中“isEmpty”的函数 return items.isEmpty }else{ return true } } var description:String { var description:String = "" if let tempItems = self.items{ //把数组备份 while !(self.isEmpty){ description += "\(self.dequeue()!) " // 把数组中的元素全部拿出来 } self.items = tempItems } return description } } var queue = Queue<Int>() queue.description println("***************") class Node<T: Equatable> { //Equatable是什么? 表示类型T遵循Equatable协议(可相等) var value: T var next: Node? = nil init(_ value: T) { //这段代码的意义? self.value = value } } class LinkedList<T: Equatable>{ var head: Node<T>? = nil func insertTail(value: T){ if head == nil { head = Node(value) }else{ var lastValue = head while lastValue?.next != nil{ lastValue = lastValue?.next } let newNode = Node(value) lastValue?.next = newNode } } func insertHead(value: T) { if head == nil { self.head = Node(value) }else{ let newNode = Node(value) newNode.next = head self.head = newNode } } func remove(value: T){ if head != nil { var node = head var preNode: Node<T>? = nil while node?.value != value && node?.next != nil { preNode = node node = node?.next } if node?.value == value { if node?.next != nil{ preNode?.next = node?.next }else{ preNode?.next = nil } } } } var description: String { var node = head var description = "\(node!.value)" while node?.next != nil{ node = node?.next description += " \(node!.value)" } return description } } var linkedList = LinkedList<String>() linkedList.insertHead("Apple") linkedList.insertTail("is") linkedList.insertHead("an") linkedList.insertTail("gift") linkedList.remove("is") linkedList.description println("**************")
f4fa71e4e87563765da01f7ef59616c2
17.520619
69
0.458391
false
false
false
false
timestocome/SoundFFT
refs/heads/master
Sounds/GraphView.swift
mit
1
// // GraphView.swift // Sensors // // Created by Linda Cobb on 9/22/14. // Copyright (c) 2014 TimesToCome Mobile. All rights reserved. // import Foundation import UIKit class GraphView: UIView { // graph dimensions var area: CGRect! var maxPoints: Int! var height: CGFloat! // incoming data to graph var dataArrayX:[CGFloat]! // graph data points var x: CGFloat = 0.0 var previousX:CGFloat = 0.0 var mark:CGFloat = 0.0 required init( coder aDecoder: NSCoder ){ super.init(coder: aDecoder) } override init(frame:CGRect){ super.init(frame:frame) } func setupGraphView() { area = frame maxPoints = Int(area.size.width) height = CGFloat(area.size.height) dataArrayX = [CGFloat](count:maxPoints, repeatedValue: 0.0) } func addX(x: UInt8){ // scale incoming data and insert it into data array let xScaled = height - CGFloat(x) * 0.4 dataArrayX.insert(xScaled, atIndex: 0) dataArrayX.removeLast() setNeedsDisplay() } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColor(context, [1.0, 0.0, 0.0, 1.0]) for i in 1..<maxPoints { mark = CGFloat(i) // plot x CGContextMoveToPoint(context, mark-1, self.dataArrayX[i-1]) CGContextAddLineToPoint(context, mark, self.dataArrayX[i]) CGContextStrokePath(context) } } }
7cb7767bc83ab60e5730b24debd914ab
17.032258
75
0.556351
false
false
false
false
natecook1000/swift
refs/heads/master
test/SILOptimizer/access_wmo.swift
apache-2.0
1
// RUN: %target-swift-frontend -parse-as-library -emit-sil -enforce-exclusivity=checked -O -primary-file %s %S/Inputs/access_wmo_def.swift | %FileCheck %s --check-prefix=PRIMARY // RUN: %target-swift-frontend -parse-as-library -emit-sil -enforce-exclusivity=checked -O %s %S/Inputs/access_wmo_def.swift | %FileCheck %s --check-prefix=WMO // ===---------------------------------------------------------------------===// // testAccessGlobal: Access a global defined in another file. // // In -primary-file mode, all begin_access markers remain dynamic. // // With WMO, only the begin_access markers for the internal global should be // promoted to static. // ===---------------------------------------------------------------------===// // readGlobal(): // PRIMARY-LABEL: sil @$S10access_wmo10readGlobalSiyF : $@convention(thin) () -> Int { // function_ref internalGlobal.unsafeMutableAddressor // PRIMARY: [[F1:%.*]] = function_ref @$S10access_wmo14internalGlobalSivau : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[G1:%.*]] = apply [[F1]]() : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[P1:%.*]] = pointer_to_address [[G1]] : $Builtin.RawPointer to [strict] $*Int // PRIMARY: [[A1:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[P1]] : $*Int // PRIMARY: end_access [[A1]] : $*Int // function_ref publicGlobal.unsafeMutableAddressor // PRIMARY: [[F2:%.*]] = function_ref @$S10access_wmo12publicGlobalSivau : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[G2:%.*]] = apply [[F2]]() : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[P2:%.*]] = pointer_to_address [[G2]] : $Builtin.RawPointer to [strict] $*Int // PRIMARY: [[A2:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[P2]] : $*Int // PRIMARY: end_access [[A2]] : $*Int // PRIMARY-LABEL: } // end sil function '$S10access_wmo10readGlobalSiyF' // // WMO-LABEL: sil @$S10access_wmo10readGlobalSiyF : $@convention(thin) () -> Int { // WMO: [[G1:%.*]] = global_addr @$S10access_wmo14internalGlobalSivp : $*Int // WMO: [[A1:%.*]] = begin_access [read] [static] [no_nested_conflict] [[G1]] : $*Int // WMO: end_access [[A1]] : $*Int // WMO: [[G2:%.*]] = global_addr @$S10access_wmo12publicGlobalSivp : $*Int // WMO: [[A2:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[G2]] : $*Int // WMO: end_access [[A2]] : $*Int // WMO-LABEL: } // end sil function '$S10access_wmo10readGlobalSiyF' public func readGlobal() -> Int { return internalGlobal + publicGlobal } @inline(never) func setInt(_ i: inout Int, _ v: Int) { i = v } func inlinedSetInt(_ i: inout Int, _ v: Int) { i = v } // testAccessGlobal(v:) // PRIMARY-LABEL: sil @$S10access_wmo16testAccessGlobal1vySi_tF : $@convention(thin) (Int) -> () { // PRIMARY: bb0(%0 : $Int): // // function_ref internalGlobal.unsafeMutableAddressor // PRIMARY: [[F1:%.*]] = function_ref @$S10access_wmo14internalGlobalSivau : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[G1:%.*]] = apply [[F1]]() : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[P1:%.*]] = pointer_to_address [[G1]] : $Builtin.RawPointer to [strict] $*Int // PRIMARY: [[A1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[P1]] : $*Int // function_ref setInt(_:_:) // PRIMARY: [[F2:%.*]] = function_ref @$S10access_wmo6setIntyySiz_SitF : $@convention(thin) (@inout Int, Int) -> () // PRIMARY: apply [[F2]]([[A1]], %0) : $@convention(thin) (@inout Int, Int) -> () // PRIMARY: end_access [[A1]] : $*Int // // function_ref publicGlobal.unsafeMutableAddressor // PRIMARY: [[F3:%.*]] = function_ref @$S10access_wmo12publicGlobalSivau : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[G2:%.*]] = apply [[F3]]() : $@convention(thin) () -> Builtin.RawPointer // PRIMARY: [[P2:%.*]] = pointer_to_address [[G2]] : $Builtin.RawPointer to [strict] $*Int // PRIMARY: [[A2:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[P2]] : $*Int // PRIMARY: apply [[F2]]([[A2]], %0) : $@convention(thin) (@inout Int, Int) -> () // PRIMARY: end_access [[A2]] : $*Int // PRIMARY-LABEL: } // end sil function '$S10access_wmo16testAccessGlobal1vySi_tF' // // WMO-LABEL: sil @$S10access_wmo16testAccessGlobal1vySi_tF : $@convention(thin) (Int) -> () { // WMO: bb0(%0 : $Int): // WMO: [[G1:%.*]] = global_addr @$S10access_wmo14internalGlobalSivp : $*Int // WMO: [[A1:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[G1]] : $*Int // function_ref setInt(_:_:) // WMO: [[F:%.*]] = function_ref @$S10access_wmo6setIntyySiz_SitF : $@convention(thin) (@inout Int, Int) -> () // WMO: apply [[F]]([[A1]], %0) : $@convention(thin) (@inout Int, Int) -> () // WMO: end_access [[A1]] : $*Int // // WMO: [[G2:%.*]] = global_addr @$S10access_wmo12publicGlobalSivp : $*Int // WMO: [[A2:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[G2]] : $*Int // function_ref setInt(_:_:) // WMO: apply [[F]]([[A2]], %0) : $@convention(thin) (@inout Int, Int) -> () // WMO: end_access [[A2]] : $*Int // WMO-LABEL: } // end sil function '$S10access_wmo16testAccessGlobal1vySi_tF' public func testAccessGlobal(v: Int) { setInt(&internalGlobal, v) setInt(&publicGlobal, v) } @inline(never) func setKeyPath(_ c: C, _ kp: ReferenceWritableKeyPath<C, Int>, _ v: Int) { c[keyPath: kp] = v } // ===---------------------------------------------------------------------===// // testAccessProp: Access a class property defined in another file. // // In -primary-file mode, all nonfinal access is behind // getter, setter, or materializeForSet calls. The final access remains // dynamic because the property is "visibleExternally". i.e. the compiler can't // see how other files are using it. // // With WMO... // // access to setterProp and finalProp are promoted to static. // setterProp is a setter call, and finalProp is non-polymorphic. // // inlinedProp and internalProp could be also be promoted to static, but are // accessed via begin_unpaired_access in materializeForSet. (When the class // definition is in another file, the compiler unfortunately and unnecessarilly // generates materializeForSet calls even in "wmo" mode). These unpaired access // cannot (easily) be marked [no_nested_conflict]. Failing to mark the modify // as [no_nested_access] in turn inhibits optimization of the property reads. // Rather than teach the WMO to handle unpaired access, better solutions would // be either: // // - The inlinedProp case could be handled with a separate pass that promotes // obvious unpaired access patterns to regular scoped access. // // - To handle internalProp SILGen could stop using materializeForSet for // stored properties: // // See <rdar://problem/41302183> [exclusivity] Optimize formal access from // inlined materializeForSet. // // keyPathProp is promoted to static enforcement because a settable_property // keypath can only be formally accessed within the getter and setter, which // the compiler can already see. // // Perversely, finalKeyPathProp *cannot* be promoted to static enforcement // because a storedProperty keypath is formed. The compiler does not currently // attempt to track down all uses of a storedProperty keypath. The actual // access occurs via a Builtin that takes a RawPointer. The formation of a // stored_property keypath is always conservatively considered a possible // nested access. // ===---------------------------------------------------------------------===// public func readProp(c: C) -> Int { return c.setterProp + c.finalProp + c.inlinedProp + c.internalProp + c.keyPathProp + c.finalKeyPathProp + c.publicProp } public func testAccessProp(c: C, v: Int) { c.setterProp = v setInt(&c.finalProp, v) inlinedSetInt(&c.inlinedProp, v) setInt(&c.internalProp, v) setKeyPath(c, \C.keyPathProp, v) setKeyPath(c, \C.finalKeyPathProp, v) setInt(&c.publicProp, v) } // PRIMARY-LABEL: sil @$S10access_wmo8readProp1cSiAA1CC_tF : $@convention(thin) (@guaranteed C) -> Int { // PRIMARY-NOT: begin_{{.*}}access // PRIMARY: [[E1:%.*]] = ref_element_addr %0 : $C, #C.finalProp // PRIMARY: [[A1:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[E1]] : $*Int // PRIMARY: end_access [[A1]] : $*Int // PRIMARY-NOT: begin_{{.*}}access // PRIMARY: [[E2:%.*]] = ref_element_addr %0 : $C, #C.finalKeyPathProp // PRIMARY: [[A2:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[E2]] : $*Int // PRIMARY: end_access [[A2]] : $*Int // PRIMARY-NOT: begin_{{.*}}access // PRIMARY-LABEL: } // end sil function '$S10access_wmo8readProp1cSiAA1CC_tF' // // WMO-LABEL: sil @$S10access_wmo8readProp1cSiAA1CC_tF : $@convention(thin) (@guaranteed C) -> Int { // WMO: [[E1:%.*]] = ref_element_addr %0 : $C, #C.setterProp // WMO: [[A1:%.*]] = begin_access [read] [static] [no_nested_conflict] [[E1]] : $*Int // WMO: end_access [[A1]] : $*Int // // WMO: [[E2:%.*]] = ref_element_addr %0 : $C, #C.finalProp // WMO: [[A2:%.*]] = begin_access [read] [static] [no_nested_conflict] [[E2]] : $*Int // WMO: end_access [[A2]] : $*Int // // WMO: [[E3:%.*]] = ref_element_addr %0 : $C, #C.inlinedProp // WMO: [[A3:%.*]] = begin_access [read] [static] [no_nested_conflict] [[E3]] : $*Int // WMO: end_access [[A3]] : $*Int // // WMO: [[E4:%.*]] = ref_element_addr %0 : $C, #C.internalProp // WMO: [[A4:%.*]] = begin_access [read] [static] [no_nested_conflict] [[E4]] : $*Int // WMO: end_access [[A4]] : $*Int // // WMO: [[E5:%.*]] = ref_element_addr %0 : $C, #C.keyPathProp // WMO: [[A5:%.*]] = begin_access [read] [static] [no_nested_conflict] [[E5]] : $*Int // WMO: end_access [[A5]] : $*Int // // WMO: [[E6:%.*]] = ref_element_addr %0 : $C, #C.finalKeyPathProp // WMO: [[A6:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[E6]] : $*Int // WMO: end_access [[A6]] : $*Int // // WMO: [[E7:%.*]] = ref_element_addr %0 : $C, #C.publicProp // WMO: [[A7:%.*]] = begin_access [read] [dynamic] [no_nested_conflict] [[E7]] : $*Int // WMO: end_access [[A7]] : $*Int // WMO-LABEL: } // end sil function '$S10access_wmo8readProp1cSiAA1CC_tF' // PRIMARY-LABEL: sil @$S10access_wmo14testAccessProp1c1vyAA1CC_SitF : $@convention(thin) (@guaranteed C, Int) -> () { // PRIMARY-NOT: begin_{{.*}}access // PRIMARY: [[E1:%.*]] = ref_element_addr %0 : $C, #C.finalProp // PRIMARY: [[A1:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[E1]] : $*Int // function_ref setInt(_:_:) // PRIMARY: [[F1:%.*]] = function_ref @$S10access_wmo6setIntyySiz_SitF : $@convention(thin) (@inout Int, Int) -> () // PRIMARY: apply [[F1]]([[A1]], %1) : $@convention(thin) (@inout Int, Int) -> () // PRIMARY: end_access [[A1]] : $*Int // PRIMARY-NOT: begin_{{.*}}access // PRIMARY-LABEL: } // end sil function '$S10access_wmo14testAccessProp1c1vyAA1CC_SitF' // WMO-LABEL: sil @$S10access_wmo14testAccessProp1c1vyAA1CC_SitF : $@convention(thin) (@guaranteed C, Int) -> () { // WMO: [[E1:%.*]] = ref_element_addr %0 : $C, #C.setterProp // WMO: [[A1:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[E1]] : $*Int // WMO: end_access [[A1]] : $*Int // // WMO: [[E2:%.*]] = ref_element_addr %0 : $C, #C.finalProp // WMO: [[A2:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[E2]] : $*Int // function_ref setInt(_:_:) // WMO: [[F1:%.*]] = function_ref @$S10access_wmo6setIntyySiz_SitF : $@convention(thin) (@inout Int, Int) -> () // WMO: apply [[F1]]([[A2]], %1) : $@convention(thin) (@inout Int, Int) -> () // WMO: end_access [[A2]] : $*Int // // WMO: [[E3:%.*]] = ref_element_addr %0 : $C, #C.inlinedProp // WMO: [[A3:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[E3]] : $*Int // WMO: end_access [[A3]] : $*Int // // WMO: [[E4:%.*]] = ref_element_addr %0 : $C, #C.internalProp // WMO: [[A4:%.*]] = begin_access [modify] [static] [no_nested_conflict] [[E4]] : $*Int // WMO: apply [[F1]]([[A4]], %1) : $@convention(thin) (@inout Int, Int) -> () // WMO: end_access [[A4]] // // WMO: [[KP:%.*]] = keypath $ReferenceWritableKeyPath<C, Int>, (root $C; settable_property $Int, id #C.keyPathProp!getter.1 : (C) -> () -> Int, getter @$S10access_wmo1CC11keyPathPropSivpACTK : $@convention(thin) (@in_guaranteed C) -> @out Int, setter @$S10access_wmo1CC11keyPathPropSivpACTk : $@convention(thin) (@in_guaranteed Int, @in_guaranteed C) -> ()) // function_ref setKeyPath(_:_:_:) // WMO: [[F2:%.*]] = function_ref @$S10access_wmo10setKeyPathyyAA1CC_s017ReferenceWritabledE0CyADSiGSitF : $@convention(thin) (@guaranteed C, @guaranteed ReferenceWritableKeyPath<C, Int>, Int) -> () // WMO: apply [[F2]](%0, [[KP]], %1) : $@convention(thin) (@guaranteed C, @guaranteed ReferenceWritableKeyPath<C, Int>, Int) -> () // // WMO: [[FKP:%.*]] = keypath $ReferenceWritableKeyPath<C, Int>, (root $C; stored_property #C.finalKeyPathProp : $Int) // WMO: apply [[F2]](%0, [[FKP]], %1) : $@convention(thin) (@guaranteed C, @guaranteed ReferenceWritableKeyPath<C, Int>, Int) -> () // // WMO: [[E4:%.*]] = ref_element_addr %0 : $C, #C.publicProp // WMO: [[A4:%.*]] = begin_access [modify] [dynamic] [no_nested_conflict] [[E4]] : $*Int // WMO: apply [[F1]]([[A4]], %1) : $@convention(thin) (@inout Int, Int) -> () // WMO: end_access [[A4]] // WMO-LABEL: } // end sil function '$S10access_wmo14testAccessProp1c1vyAA1CC_SitF'
a8613b76157a9423d50f0cd9c86a05ba
53.783333
359
0.624506
false
true
false
false
adrfer/swift
refs/heads/master
validation-test/Evolution/test_struct_fixed_layout_add_conformance.swift
apache-2.0
1
// RUN: rm -rf %t && mkdir -p %t/before && mkdir -p %t/after // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/struct_fixed_layout_add_conformance.swift -o %t/before/struct_fixed_layout_add_conformance.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/struct_fixed_layout_add_conformance.swift -o %t/before/struct_fixed_layout_add_conformance.o // RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/struct_fixed_layout_add_conformance.swift -o %t/after/struct_fixed_layout_add_conformance.o // RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/struct_fixed_layout_add_conformance.swift -o %t/after/struct_fixed_layout_add_conformance.o // RUN: %target-build-swift -D BEFORE -c %s -I %t/before -o %t/before/main.o // RUN: %target-build-swift -D AFTER -c %s -I %t/after -o %t/after/main.o // RUN: %target-build-swift %t/before/struct_fixed_layout_add_conformance.o %t/before/main.o -o %t/before_before // RUN: %target-build-swift %t/before/struct_fixed_layout_add_conformance.o %t/after/main.o -o %t/before_after // RUN: %target-build-swift %t/after/struct_fixed_layout_add_conformance.o %t/before/main.o -o %t/after_before // RUN: %target-build-swift %t/after/struct_fixed_layout_add_conformance.o %t/after/main.o -o %t/after_after // RUN: %target-run %t/before_before // RUN: %target-run %t/before_after // RUN: %target-run %t/after_before // RUN: %target-run %t/after_after import StdlibUnittest import struct_fixed_layout_add_conformance var StructFixedLayoutAddConformanceTest = TestSuite("StructFixedLayoutAddConformance") // FIXME: Once we have availability information for conformances, we can // make this non-generic as long as we're careful to never directly // reference an unavailable conformance table symbol @inline(never) func workWithPointLike<T>(t: T) { if getVersion() > 0 { var p = t as! PointLike p.x = 30 p.y = 40 expectEqual(p.x, 30) expectEqual(p.y, 40) } else { expectEqual(t is PointLike, false) } } StructFixedLayoutAddConformanceTest.test("AddConformance") { var t = AddConformance() do { t.x = 10 t.y = 20 expectEqual(t.x, 10) expectEqual(t.y, 20) } workWithPointLike(t) } #if AFTER protocol MyPointLike { var x: Int { get set } var y: Int { get set } } protocol MyPoint3DLike { var z: Int { get set } } extension AddConformance : MyPointLike {} extension AddConformance : MyPoint3DLike {} StructFixedLayoutAddConformanceTest.test("MyPointLike") { var p: MyPointLike = AddConformance() do { p.x = 50 p.y = 60 expectEqual(p.x, 50) expectEqual(p.y, 60) } } #endif runAllTests()
9317db0fef23208ef9f6dc432d26e41b
33.246914
187
0.711247
false
true
false
false
SanctionCo/pilot-ios
refs/heads/master
Pods/Gallery/Sources/Utils/Extensions/UIImageView+Extensions.swift
mit
1
import UIKit import Photos extension UIImageView { func g_loadImage(_ asset: PHAsset) { guard frame.size != CGSize.zero else { image = GalleryBundle.image("gallery_placeholder") return } if tag == 0 { image = GalleryBundle.image("gallery_placeholder") } else { PHImageManager.default().cancelImageRequest(PHImageRequestID(tag)) } let options = PHImageRequestOptions() let id = PHImageManager.default().requestImage(for: asset, targetSize: frame.size, contentMode: .aspectFill, options: options) { [weak self] image, _ in self?.image = image } tag = Int(id) } }
8d9afd355b40432834eac6c2cd4e279b
23.066667
109
0.583102
false
false
false
false
alexanderedge/European-Sports
refs/heads/master
EurosportKit/Protocols/NumberIdentifiable.swift
mit
1
// // NumberIdentifiable.swift // EurosportPlayer // // Created by Alexander Edge on 28/05/2016. import Foundation import CoreData @objc public protocol Int32Identifiable { var identifier: Int32 { get set } } extension Fetchable where Self: NSManagedObject, Self: Int32Identifiable, FetchableType == Self { public static func existingObject(_ identifier: Int32, inContext context: NSManagedObjectContext) throws -> FetchableType? { let predicate = NSPredicate(format: "identifier == %d", identifier) return try singleObject(in: context, predicate: predicate, sortedBy: nil, ascending: true) } public static func newOrExistingObject(_ identifier: Int32, inContext context: NSManagedObjectContext) throws -> FetchableType { if let existingObject = try existingObject(identifier, inContext: context) { return existingObject } let newObject = Self(context: context) newObject.identifier = identifier return newObject } }
df53bf46171fc993eb4a16b5597645aa
30.75
132
0.714567
false
false
false
false
noppefoxwolf/TVUploader-iOS
refs/heads/master
TVUploader/STTwitter/Classes/APIExtensions.swift
mit
1
// // APIExtensions.swift // Pods // // Created by Tomoya Hirano on 2016/08/30. // // import Foundation import STTwitter import Unbox extension STTwitterAPI { func postMediaUploadAsyncINITWithVideoURL(videoMediaURL: NSURL, successBlock: ((AsyncInitResponce) -> Void), errorBlock: ((ErrorType) -> Void)) -> STTwitterRequestProtocol? { let kBaseURLStringUpload_1_1 = "https://upload.twitter.com/1.1" let STTwitterAPIMediaDataIsEmpty = 1 let data = NSData(contentsOfURL: videoMediaURL) if (data == nil) { let error = NSError(domain: NSStringFromClass(self.dynamicType), code: STTwitterAPIMediaDataIsEmpty, userInfo: [NSLocalizedDescriptionKey: "data is nil"]) errorBlock(error) return nil } var md = [String: String]() md["command"] = "INIT" md["media_type"] = "video/mp4" md["total_bytes"] = "\(data?.length ?? 0)" md["media_category"] = "tweet_video" return self.postResource("media/upload.json", baseURLString: kBaseURLStringUpload_1_1, parameters: md, uploadProgressBlock: nil, downloadProgressBlock: nil, successBlock: { (rateLimit, response) in do { let responseObject: AsyncInitResponce = try Unbox(response as! UnboxableDictionary) successBlock(responseObject) } catch let error { errorBlock(error) } }, errorBlock: { (error) in errorBlock(error) }) } func postMediaUploadAsyncFINALIZEWithMediaID(mediaId: String, successBlock: ((AsyncFinalizeResponce) -> Void), errorBlock: ((ErrorType) -> Void)) -> STTwitterRequestProtocol { let kBaseURLStringUpload_1_1 = "https://upload.twitter.com/1.1" var md = [String: String]() md["command"] = "FINALIZE" md["media_id"] = mediaId return self.postResource("media/upload.json", baseURLString: kBaseURLStringUpload_1_1, parameters: md, uploadProgressBlock: nil, downloadProgressBlock: nil, successBlock: { (rateLimit, response) in do { let responseObject: AsyncFinalizeResponce = try Unbox(response as! UnboxableDictionary) successBlock(responseObject) } catch let error { errorBlock(error) } }, errorBlock: { (error) in errorBlock(error) }) } func postMediaUploadAsyncSTATUSWithMediaID(mediaId: String, successBlock: ((AsyncSTATUSResponce) -> Void), errorBlock: ((ErrorType) -> Void)) -> STTwitterRequestProtocol { let kBaseURLStringUpload_1_1 = "https://upload.twitter.com/1.1" var md = [String: String]() md["command"] = "STATUS" md["media_id"] = mediaId self.getResource("media/upload.json", baseURLString: kBaseURLStringUpload_1_1, parameters: md, downloadProgressBlock: nil, successBlock: { (rateLimit, response) in }) { (error) in } return self.getResource("media/upload.json", baseURLString: kBaseURLStringUpload_1_1, parameters: md, downloadProgressBlock: nil, successBlock: { (rateLimit, response) in do { let responseObject: AsyncSTATUSResponce = try Unbox(response as! UnboxableDictionary) successBlock(responseObject) } catch let error { errorBlock(error) } }, errorBlock: { (error) in errorBlock(error) }) } }
dd419c31323205efbe19b7486a03bbb0
39.304762
177
0.515717
false
false
false
false
TrustWallet/trust-wallet-ios
refs/heads/master
Trust/Settings/Types/Config.swift
gpl-3.0
1
// Copyright DApps Platform Inc. All rights reserved. import Foundation import TrustCore struct Config { private struct Keys { static let currencyID = "currencyID" } static let dbMigrationSchemaVersion: UInt64 = 77 static let current: Config = Config() let defaults: UserDefaults init( defaults: UserDefaults = UserDefaults.standard ) { self.defaults = defaults } var currency: Currency { get { //If it is saved currency if let currency = defaults.string(forKey: Keys.currencyID) { return Currency(rawValue: currency)! } //If ther is not saved currency try to use user local currency if it is supported. let avaliableCurrency = Currency.allValues.first { currency in return currency.rawValue == Locale.current.currencySymbol } if let isAvaliableCurrency = avaliableCurrency { return isAvaliableCurrency } //If non of the previous is not working return USD. return Currency.USD } set { defaults.set(newValue.rawValue, forKey: Keys.currencyID) } } var servers: [Coin] { return [ Coin.ethereum, Coin.ethereumClassic, Coin.poa, Coin.callisto, Coin.gochain, ] } }
7ed053df6a71d67c71b7f055eac35726
26.076923
94
0.584517
false
true
false
false
huonw/swift
refs/heads/master
stdlib/public/SDK/Foundation/NSStringAPI.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Exposing the API of NSString on Swift's String // //===----------------------------------------------------------------------===// // Important Note // ============== // // This file is shared between two projects: // // 1. https://github.com/apple/swift/tree/master/stdlib/public/SDK/Foundation // 2. https://github.com/apple/swift-corelibs-foundation/tree/master/Foundation // // If you change this file, you must update it in both places. #if !DEPLOYMENT_RUNTIME_SWIFT @_exported import Foundation // Clang module #endif // Open Issues // =========== // // Property Lists need to be properly bridged // func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray { let result = NSMutableArray(capacity: a.count) for s in a { result.add(f(s)) } return result } #if !DEPLOYMENT_RUNTIME_SWIFT // We only need this for UnsafeMutablePointer, but there's not currently a way // to write that constraint. extension Optional { /// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the /// address of `object` to `body`. /// /// This is intended for use with Foundation APIs that return an Objective-C /// type via out-parameter where it is important to be able to *ignore* that /// parameter by passing `nil`. (For some APIs, this may allow the /// implementation to avoid some work.) /// /// In most cases it would be simpler to just write this code inline, but if /// `body` is complicated than that results in unnecessarily repeated code. internal func _withNilOrAddress<NSType : AnyObject, ResultType>( of object: inout NSType?, _ body: (AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType ) -> ResultType { return self == nil ? body(nil) : body(&object) } } #endif extension String { //===--- Class Methods --------------------------------------------------===// //===--------------------------------------------------------------------===// // @property (class) const NSStringEncoding *availableStringEncodings; /// An array of the encodings that strings support in the application's /// environment. public static var availableStringEncodings: [Encoding] { var result = [Encoding]() var p = NSString.availableStringEncodings while p.pointee != 0 { result.append(Encoding(rawValue: p.pointee)) p += 1 } return result } // @property (class) NSStringEncoding defaultCStringEncoding; /// The C-string encoding assumed for any method accepting a C string as an /// argument. public static var defaultCStringEncoding: Encoding { return Encoding(rawValue: NSString.defaultCStringEncoding) } // + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding /// Returns a human-readable string giving the name of the specified encoding. /// /// - Parameter encoding: A string encoding. For possible values, see /// `String.Encoding`. /// - Returns: A human-readable string giving the name of `encoding` in the /// current locale. public static func localizedName( of encoding: Encoding ) -> String { return NSString.localizedName(of: encoding.rawValue) } // + (instancetype)localizedStringWithFormat:(NSString *)format, ... /// Returns a string created by using a given format string as a /// template into which the remaining argument values are substituted /// according to the user's default locale. public static func localizedStringWithFormat( _ format: String, _ arguments: CVarArg... ) -> String { return String(format: format, locale: Locale.current, arguments: arguments) } //===--------------------------------------------------------------------===// // NSString factory functions that have a corresponding constructor // are omitted. // // + (instancetype)string // // + (instancetype) // stringWithCharacters:(const unichar *)chars length:(NSUInteger)length // // + (instancetype)stringWithFormat:(NSString *)format, ... // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError **)error // // + (instancetype) // stringWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error // // + (instancetype) // stringWithCString:(const char *)cString // encoding:(NSStringEncoding)enc //===--------------------------------------------------------------------===// //===--- Adds nothing for String beyond what String(s) does -------------===// // + (instancetype)stringWithString:(NSString *)aString //===--------------------------------------------------------------------===// // + (instancetype)stringWithUTF8String:(const char *)bytes /// Creates a string by copying the data from a given /// C array of UTF8-encoded bytes. public init?(utf8String bytes: UnsafePointer<CChar>) { if let ns = NSString(utf8String: bytes) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } } extension String { //===--- Already provided by String's core ------------------------------===// // - (instancetype)init //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithBytes:(const void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding /// Creates a new string equivalent to the given bytes interpreted in the /// specified encoding. /// /// - Parameters: /// - bytes: A sequence of bytes to interpret using `encoding`. /// - encoding: The ecoding to use to interpret `bytes`. public init? <S: Sequence>(bytes: S, encoding: Encoding) where S.Iterator.Element == UInt8 { let byteArray = Array(bytes) if let ns = NSString( bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithBytesNoCopy:(void *)bytes // length:(NSUInteger)length // encoding:(NSStringEncoding)encoding // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of bytes from the /// given buffer, interpreted in the specified encoding, and optionally /// frees the buffer. /// /// - Warning: This initializer is not memory-safe! public init?( bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, encoding: Encoding, freeWhenDone flag: Bool ) { if let ns = NSString( bytesNoCopy: bytes, length: length, encoding: encoding.rawValue, freeWhenDone: flag) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // - (instancetype) // initWithCharacters:(const unichar *)characters // length:(NSUInteger)length /// Creates a new string that contains the specified number of characters /// from the given C array of Unicode characters. public init( utf16CodeUnits: UnsafePointer<unichar>, count: Int ) { self = String._unconditionallyBridgeFromObjectiveC(NSString(characters: utf16CodeUnits, length: count)) } // - (instancetype) // initWithCharactersNoCopy:(unichar *)characters // length:(NSUInteger)length // freeWhenDone:(BOOL)flag /// Creates a new string that contains the specified number of characters /// from the given C array of UTF-16 code units. public init( utf16CodeUnitsNoCopy: UnsafePointer<unichar>, count: Int, freeWhenDone flag: Bool ) { self = String._unconditionallyBridgeFromObjectiveC(NSString( charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy), length: count, freeWhenDone: flag)) } //===--- Initializers that can fail -------------------------------------===// // - (instancetype) // initWithContentsOfFile:(NSString *)path // encoding:(NSStringEncoding)enc // error:(NSError **)error // /// Produces a string created by reading data from the file at a /// given path interpreted using a given encoding. public init( contentsOfFile path: String, encoding enc: Encoding ) throws { let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfFile:(NSString *)path // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from the file at /// a given path and returns by reference the encoding used to /// interpret the file. public init( contentsOfFile path: String, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOfFile: path, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOfFile path: String ) throws { let ns = try NSString(contentsOfFile: path, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // encoding:(NSStringEncoding)enc // error:(NSError**)error /// Produces a string created by reading data from a given URL /// interpreted using a given encoding. Errors are written into the /// inout `error` argument. public init( contentsOf url: URL, encoding enc: Encoding ) throws { let ns = try NSString(contentsOf: url, encoding: enc.rawValue) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithContentsOfURL:(NSURL *)url // usedEncoding:(NSStringEncoding *)enc // error:(NSError **)error /// Produces a string created by reading data from a given URL /// and returns by reference the encoding used to interpret the /// data. Errors are written into the inout `error` argument. public init( contentsOf url: URL, usedEncoding: inout Encoding ) throws { var enc: UInt = 0 let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc) usedEncoding = Encoding(rawValue: enc) self = String._unconditionallyBridgeFromObjectiveC(ns) } public init( contentsOf url: URL ) throws { let ns = try NSString(contentsOf: url, usedEncoding: nil) self = String._unconditionallyBridgeFromObjectiveC(ns) } // - (instancetype) // initWithCString:(const char *)nullTerminatedCString // encoding:(NSStringEncoding)encoding /// Produces a string containing the bytes in a given C array, /// interpreted according to a given encoding. public init?( cString: UnsafePointer<CChar>, encoding enc: Encoding ) { if let ns = NSString(cString: cString, encoding: enc.rawValue) { self = String._unconditionallyBridgeFromObjectiveC(ns) } else { return nil } } // FIXME: handle optional locale with default arguments // - (instancetype) // initWithData:(NSData *)data // encoding:(NSStringEncoding)encoding /// Returns a `String` initialized by converting given `data` into /// Unicode characters using a given `encoding`. public init?(data: Data, encoding: Encoding) { guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil } self = String._unconditionallyBridgeFromObjectiveC(s) } // - (instancetype)initWithFormat:(NSString *)format, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted. public init(format: String, _ arguments: CVarArg...) { self = String(format: format, arguments: arguments) } // - (instancetype) // initWithFormat:(NSString *)format // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to the user's default locale. public init(format: String, arguments: [CVarArg]) { self = String(format: format, locale: nil, arguments: arguments) } // - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ... /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: String, locale: Locale?, _ args: CVarArg...) { self = String(format: format, locale: locale, arguments: args) } // - (instancetype) // initWithFormat:(NSString *)format // locale:(id)locale // arguments:(va_list)argList /// Returns a `String` object initialized by using a given /// format string as a template into which the remaining argument /// values are substituted according to given locale information. public init(format: String, locale: Locale?, arguments: [CVarArg]) { #if DEPLOYMENT_RUNTIME_SWIFT self = withVaList(arguments) { String._unconditionallyBridgeFromObjectiveC( NSString(format: format, locale: locale?._bridgeToObjectiveC(), arguments: $0) ) } #else self = withVaList(arguments) { NSString(format: format, locale: locale, arguments: $0) as String } #endif } } extension StringProtocol where Index == String.Index { //===--- Bridging Helpers -----------------------------------------------===// //===--------------------------------------------------------------------===// /// The corresponding `NSString` - a convenience for bridging code. // FIXME(strings): There is probably a better way to bridge Self to NSString var _ns: NSString { return self._ephemeralString._bridgeToObjectiveC() } // self can be a Substring so we need to subtract/add this offset when // passing _ns to the Foundation APIs. Will be 0 if self is String. @inlinable internal var _substringOffset: Int { return self.startIndex.encodedOffset } /// Return an `Index` corresponding to the given offset in our UTF-16 /// representation. func _index(_ utf16Index: Int) -> Index { return Index(encodedOffset: utf16Index + _substringOffset) } @inlinable internal func _toRelativeNSRange(_ r: Range<String.Index>) -> NSRange { return NSRange( location: r.lowerBound.encodedOffset - _substringOffset, length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset) } /// Return a `Range<Index>` corresponding to the given `NSRange` of /// our UTF-16 representation. func _range(_ r: NSRange) -> Range<Index> { return _index(r.location)..<_index(r.location + r.length) } /// Return a `Range<Index>?` corresponding to the given `NSRange` of /// our UTF-16 representation. func _optionalRange(_ r: NSRange) -> Range<Index>? { if r.location == NSNotFound { return nil } return _range(r) } /// Invoke `body` on an `Int` buffer. If `index` was converted from /// non-`nil`, convert the buffer to an `Index` and write it into the /// memory referred to by `index` func _withOptionalOutParameter<Result>( _ index: UnsafeMutablePointer<Index>?, _ body: (UnsafeMutablePointer<Int>?) -> Result ) -> Result { var utf16Index: Int = 0 let result = (index != nil ? body(&utf16Index) : body(nil)) index?.pointee = _index(utf16Index) return result } /// Invoke `body` on an `NSRange` buffer. If `range` was converted /// from non-`nil`, convert the buffer to a `Range<Index>` and write /// it into the memory referred to by `range` func _withOptionalOutParameter<Result>( _ range: UnsafeMutablePointer<Range<Index>>?, _ body: (UnsafeMutablePointer<NSRange>?) -> Result ) -> Result { var nsRange = NSRange(location: 0, length: 0) let result = (range != nil ? body(&nsRange) : body(nil)) range?.pointee = self._range(nsRange) return result } //===--- Instance Methods/Properties-------------------------------------===// //===--------------------------------------------------------------------===// //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // @property BOOL boolValue; // - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding /// Returns a Boolean value that indicates whether the string can be /// converted to the specified encoding without loss of information. /// /// - Parameter encoding: A string encoding. /// - Returns: `true` if the string can be encoded in `encoding` without loss /// of information; otherwise, `false`. public func canBeConverted(to encoding: String.Encoding) -> Bool { return _ns.canBeConverted(to: encoding.rawValue) } // @property NSString* capitalizedString /// A copy of the string with each word changed to its corresponding /// capitalized spelling. /// /// This property performs the canonical (non-localized) mapping. It is /// suitable for programming operations that require stable results not /// depending on the current locale. /// /// A capitalized string is a string with the first character in each word /// changed to its corresponding uppercase value, and all remaining /// characters set to their corresponding lowercase values. A "word" is any /// sequence of characters delimited by spaces, tabs, or line terminators. /// Some common word delimiting punctuation isn't considered, so this /// property may not generally produce the desired results for multiword /// strings. See the `getLineStart(_:end:contentsEnd:for:)` method for /// additional information. /// /// Case transformations aren’t guaranteed to be symmetrical or to produce /// strings of the same lengths as the originals. public var capitalized: String { return _ns.capitalized as String } // @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0); /// A capitalized representation of the string that is produced /// using the current locale. @available(macOS 10.11, iOS 9.0, *) public var localizedCapitalized: String { return _ns.localizedCapitalized } // - (NSString *)capitalizedStringWithLocale:(Locale *)locale /// Returns a capitalized representation of the string /// using the specified locale. public func capitalized(with locale: Locale?) -> String { return _ns.capitalized(with: locale) as String } // - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString /// Returns the result of invoking `compare:options:` with /// `NSCaseInsensitiveSearch` as the only option. public func caseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.caseInsensitiveCompare(aString._ephemeralString) } //===--- Omitted by agreement during API review 5/20/2014 ---------------===// // - (unichar)characterAtIndex:(NSUInteger)index // // We have a different meaning for "Character" in Swift, and we are // trying not to expose error-prone UTF-16 integer indexes // - (NSString *) // commonPrefixWithString:(NSString *)aString // options:(StringCompareOptions)mask /// Returns a string containing characters this string and the /// given string have in common, starting from the beginning of each /// up to the first characters that aren't equivalent. public func commonPrefix< T : StringProtocol >(with aString: T, options: String.CompareOptions = []) -> String { return _ns.commonPrefix(with: aString._ephemeralString, options: options) } // - (NSComparisonResult) // compare:(NSString *)aString // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range // // - (NSComparisonResult) // compare:(NSString *)aString options:(StringCompareOptions)mask // range:(NSRange)range locale:(id)locale /// Compares the string using the specified options and /// returns the lexical ordering for the range. public func compare<T : StringProtocol>( _ aString: T, options mask: String.CompareOptions = [], range: Range<Index>? = nil, locale: Locale? = nil ) -> ComparisonResult { // According to Ali Ozer, there may be some real advantage to // dispatching to the minimal selector for the supplied options. // So let's do that; the switch should compile away anyhow. let aString = aString._ephemeralString return locale != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange( range ?? startIndex..<endIndex ), locale: locale?._bridgeToObjectiveC() ) : range != nil ? _ns.compare( aString, options: mask, range: _toRelativeNSRange(range!) ) : !mask.isEmpty ? _ns.compare(aString, options: mask) : _ns.compare(aString) } // - (NSUInteger) // completePathIntoString:(NSString **)outputName // caseSensitive:(BOOL)flag // matchesIntoArray:(NSArray **)outputArray // filterTypes:(NSArray *)filterTypes /// Interprets the string as a path in the file system and /// attempts to perform filename completion, returning a numeric /// value that indicates whether a match was possible, and by /// reference the longest path that matches the string. /// /// - Returns: The actual number of matching paths. public func completePath( into outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { #if DEPLOYMENT_RUNTIME_SWIFT var outputNamePlaceholder: String? var outputArrayPlaceholder = [String]() let res = self._ns.completePath( into: &outputNamePlaceholder, caseSensitive: caseSensitive, matchesInto: &outputArrayPlaceholder, filterTypes: filterTypes ) if let n = outputNamePlaceholder { outputName?.pointee = n } else { outputName?.pointee = "" } outputArray?.pointee = outputArrayPlaceholder return res #else // DEPLOYMENT_RUNTIME_SWIFT var nsMatches: NSArray? var nsOutputName: NSString? let result: Int = outputName._withNilOrAddress(of: &nsOutputName) { outputName in outputArray._withNilOrAddress(of: &nsMatches) { outputArray in // FIXME: completePath(...) is incorrectly annotated as requiring // non-optional output parameters. rdar://problem/25494184 let outputNonOptionalName = unsafeBitCast( outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self) let outputNonOptionalArray = unsafeBitCast( outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self) return self._ns.completePath( into: outputNonOptionalName, caseSensitive: caseSensitive, matchesInto: outputNonOptionalArray, filterTypes: filterTypes ) } } if let matches = nsMatches { // Since this function is effectively a bridge thunk, use the // bridge thunk semantics for the NSArray conversion outputArray?.pointee = matches as! [String] } if let n = nsOutputName { outputName?.pointee = n as String } return result #endif // DEPLOYMENT_RUNTIME_SWIFT } // - (NSArray *) // componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator /// Returns an array containing substrings from the string /// that have been divided by characters in the given set. public func components(separatedBy separator: CharacterSet) -> [String] { return _ns.components(separatedBy: separator) } // - (NSArray *)componentsSeparatedByString:(NSString *)separator /// Returns an array containing substrings from the string that have been /// divided by the given separator. /// /// The substrings in the resulting array appear in the same order as the /// original string. Adjacent occurrences of the separator string produce /// empty strings in the result. Similarly, if the string begins or ends /// with the separator, the first or last substring, respectively, is empty. /// The following example shows this behavior: /// /// let list1 = "Karin, Carrie, David" /// let items1 = list1.components(separatedBy: ", ") /// // ["Karin", "Carrie", "David"] /// /// // Beginning with the separator: /// let list2 = ", Norman, Stanley, Fletcher" /// let items2 = list2.components(separatedBy: ", ") /// // ["", "Norman", "Stanley", "Fletcher" /// /// If the list has no separators, the array contains only the original /// string itself. /// /// let name = "Karin" /// let list = name.components(separatedBy: ", ") /// // ["Karin"] /// /// - Parameter separator: The separator string. /// - Returns: An array containing substrings that have been divided from the /// string using `separator`. // FIXME(strings): now when String conforms to Collection, this can be // replaced by split(separator:maxSplits:omittingEmptySubsequences:) public func components< T : StringProtocol >(separatedBy separator: T) -> [String] { return _ns.components(separatedBy: separator._ephemeralString) } // - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the string as a C string /// using a given encoding. public func cString(using encoding: String.Encoding) -> [CChar]? { return withExtendedLifetime(_ns) { (s: NSString) -> [CChar]? in _persistCString(s.cString(using: encoding.rawValue)) } } // - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding // // - (NSData *) // dataUsingEncoding:(NSStringEncoding)encoding // allowLossyConversion:(BOOL)flag /// Returns a `Data` containing a representation of /// the `String` encoded using a given encoding. public func data( using encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { return _ns.data( using: encoding.rawValue, allowLossyConversion: allowLossyConversion) } // @property NSString* decomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form D. public var decomposedStringWithCanonicalMapping: String { return _ns.decomposedStringWithCanonicalMapping } // @property NSString* decomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KD. public var decomposedStringWithCompatibilityMapping: String { return _ns.decomposedStringWithCompatibilityMapping } //===--- Importing Foundation should not affect String printing ---------===// // Therefore, we're not exposing this: // // @property NSString* description //===--- Omitted for consistency with API review results 5/20/2014 -----===// // @property double doubleValue; // - (void) // enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block /// Enumerates all the lines in a string. public func enumerateLines( invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void ) { _ns.enumerateLines { (line: String, stop: UnsafeMutablePointer<ObjCBool>) in var stop_ = false body(line, &stop_) if stop_ { stop.pointee = true } } } // @property NSStringEncoding fastestEncoding; /// The fastest encoding to which the string can be converted without loss /// of information. public var fastestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.fastestEncoding) } // - (BOOL) // getCString:(char *)buffer // maxLength:(NSUInteger)maxBufferCount // encoding:(NSStringEncoding)encoding /// Converts the `String`'s content to a given encoding and /// stores them in a buffer. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. public func getCString( _ buffer: inout [CChar], maxLength: Int, encoding: String.Encoding ) -> Bool { return _ns.getCString(&buffer, maxLength: Swift.min(buffer.count, maxLength), encoding: encoding.rawValue) } // - (NSUInteger)hash /// An unsigned integer that can be used as a hash table address. public var hash: Int { return _ns.hash } // - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the number of bytes required to store the /// `String` in a given encoding. public func lengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.lengthOfBytes(using: encoding.rawValue) } // - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString /// Compares the string and the given string using a case-insensitive, /// localized, comparison. public func localizedCaseInsensitiveCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCaseInsensitiveCompare(aString._ephemeralString) } // - (NSComparisonResult)localizedCompare:(NSString *)aString /// Compares the string and the given string using a localized comparison. public func localizedCompare< T : StringProtocol >(_ aString: T) -> ComparisonResult { return _ns.localizedCompare(aString._ephemeralString) } /// Compares the string and the given string as sorted by the Finder. public func localizedStandardCompare< T : StringProtocol >(_ string: T) -> ComparisonResult { return _ns.localizedStandardCompare(string._ephemeralString) } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property long long longLongValue // @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0); /// A lowercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedLowercase: String { return _ns.localizedLowercase } // - (NSString *)lowercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to lowercase, taking into account the specified /// locale. public func lowercased(with locale: Locale?) -> String { return _ns.lowercased(with: locale) } // - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc /// Returns the maximum number of bytes needed to store the /// `String` in a given encoding. public func maximumLengthOfBytes(using encoding: String.Encoding) -> Int { return _ns.maximumLengthOfBytes(using: encoding.rawValue) } // @property NSString* precomposedStringWithCanonicalMapping; /// A string created by normalizing the string's contents using Form C. public var precomposedStringWithCanonicalMapping: String { return _ns.precomposedStringWithCanonicalMapping } // @property NSString * precomposedStringWithCompatibilityMapping; /// A string created by normalizing the string's contents using Form KC. public var precomposedStringWithCompatibilityMapping: String { return _ns.precomposedStringWithCompatibilityMapping } #if !DEPLOYMENT_RUNTIME_SWIFT // - (id)propertyList /// Parses the `String` as a text representation of a /// property list, returning an NSString, NSData, NSArray, or /// NSDictionary object, according to the topmost element. public func propertyList() -> Any { return _ns.propertyList() } // - (NSDictionary *)propertyListFromStringsFileFormat /// Returns a dictionary object initialized with the keys and /// values found in the `String`. public func propertyListFromStringsFileFormat() -> [String : String] { return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:] } #endif // - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Returns a Boolean value indicating whether the string contains the given /// string, taking the current locale into account. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardContains< T : StringProtocol >(_ string: T) -> Bool { return _ns.localizedStandardContains(string._ephemeralString) } // @property NSStringEncoding smallestEncoding; /// The smallest encoding to which the string can be converted without /// loss of information. public var smallestEncoding: String.Encoding { return String.Encoding(rawValue: _ns.smallestEncoding) } // - (NSString *) // stringByAddingPercentEncodingWithAllowedCharacters: // (NSCharacterSet *)allowedCharacters /// Returns a new string created by replacing all characters in the string /// not in the specified set with percent encoded characters. public func addingPercentEncoding( withAllowedCharacters allowedCharacters: CharacterSet ) -> String? { // FIXME: the documentation states that this method can return nil if the // transformation is not possible, without going into further details. The // implementation can only return nil if malloc() returns nil, so in // practice this is not possible. Still, to be consistent with // documentation, we declare the method as returning an optional String. // // <rdar://problem/17901698> Docs for -[NSString // stringByAddingPercentEncodingWithAllowedCharacters] don't precisely // describe when return value is nil return _ns.addingPercentEncoding(withAllowedCharacters: allowedCharacters ) } // - (NSString *)stringByAppendingFormat:(NSString *)format, ... /// Returns a string created by appending a string constructed from a given /// format string and the following arguments. public func appendingFormat< T : StringProtocol >( _ format: T, _ arguments: CVarArg... ) -> String { return _ns.appending( String(format: format._ephemeralString, arguments: arguments)) } // - (NSString *)stringByAppendingString:(NSString *)aString /// Returns a new string created by appending the given string. // FIXME(strings): shouldn't it be deprecated in favor of `+`? public func appending< T : StringProtocol >(_ aString: T) -> String { return _ns.appending(aString._ephemeralString) } /// Returns a string with the given character folding options /// applied. public func folding( options: String.CompareOptions = [], locale: Locale? ) -> String { return _ns.folding(options: options, locale: locale) } // - (NSString *)stringByPaddingToLength:(NSUInteger)newLength // withString:(NSString *)padString // startingAtIndex:(NSUInteger)padIndex /// Returns a new string formed from the `String` by either /// removing characters from the end, or by appending as many /// occurrences as necessary of a given pad string. public func padding< T : StringProtocol >( toLength newLength: Int, withPad padString: T, startingAt padIndex: Int ) -> String { return _ns.padding( toLength: newLength, withPad: padString._ephemeralString, startingAt: padIndex) } // @property NSString* stringByRemovingPercentEncoding; /// A new string made from the string by replacing all percent encoded /// sequences with the matching UTF-8 characters. public var removingPercentEncoding: String? { return _ns.removingPercentEncoding } // - (NSString *) // stringByReplacingCharactersInRange:(NSRange)range // withString:(NSString *)replacement /// Returns a new string in which the characters in a /// specified range of the `String` are replaced by a given string. public func replacingCharacters< T : StringProtocol, R : RangeExpression >(in range: R, with replacement: T) -> String where R.Bound == Index { return _ns.replacingCharacters( in: _toRelativeNSRange(range.relative(to: self)), with: replacement._ephemeralString) } // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // // - (NSString *) // stringByReplacingOccurrencesOfString:(NSString *)target // withString:(NSString *)replacement // options:(StringCompareOptions)options // range:(NSRange)searchRange /// Returns a new string in which all occurrences of a target /// string in a specified range of the string are replaced by /// another given string. public func replacingOccurrences< Target : StringProtocol, Replacement : StringProtocol >( of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { let target = target._ephemeralString let replacement = replacement._ephemeralString return (searchRange != nil) || (!options.isEmpty) ? _ns.replacingOccurrences( of: target, with: replacement, options: options, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ) ) : _ns.replacingOccurrences(of: target, with: replacement) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a new string made by replacing in the `String` /// all percent escapes with the matching characters as determined /// by a given encoding. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.") public func replacingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.replacingPercentEscapes(using: encoding.rawValue) } #endif // - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set /// Returns a new string made by removing from both ends of /// the `String` characters contained in a given character set. public func trimmingCharacters(in set: CharacterSet) -> String { return _ns.trimmingCharacters(in: set) } // @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0); /// An uppercase version of the string that is produced using the current /// locale. @available(macOS 10.11, iOS 9.0, *) public var localizedUppercase: String { return _ns.localizedUppercase as String } // - (NSString *)uppercaseStringWithLocale:(Locale *)locale /// Returns a version of the string with all letters /// converted to uppercase, taking into account the specified /// locale. public func uppercased(with locale: Locale?) -> String { return _ns.uppercased(with: locale) } //===--- Omitted due to redundancy with "utf8" property -----------------===// // - (const char *)UTF8String // - (BOOL) // writeToFile:(NSString *)path // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to a file at a given /// path using a given encoding. public func write< T : StringProtocol >( toFile path: T, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( toFile: path._ephemeralString, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (BOOL) // writeToURL:(NSURL *)url // atomically:(BOOL)useAuxiliaryFile // encoding:(NSStringEncoding)enc // error:(NSError **)error /// Writes the contents of the `String` to the URL specified /// by url using the specified encoding. public func write( to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { try _ns.write( to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue) } // - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0); #if !DEPLOYMENT_RUNTIME_SWIFT /// Perform string transliteration. @available(macOS 10.11, iOS 9.0, *) public func applyingTransform( _ transform: StringTransform, reverse: Bool ) -> String? { return _ns.applyingTransform(transform, reverse: reverse) } // - (void) // enumerateLinguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // usingBlock:( // void (^)( // NSString *tag, NSRange tokenRange, // NSRange sentenceRange, BOOL *stop) // )block /// Performs linguistic analysis on the specified string by /// enumerating the specific range of the string, providing the /// Block with the located tags. public func enumerateLinguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, invoking body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) where R.Bound == Index { let range = range.relative(to: self) _ns.enumerateLinguisticTags( in: _toRelativeNSRange(range), scheme: tagScheme._ephemeralString, options: opts, orthography: orthography != nil ? orthography! : nil ) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { $3.pointee = true } } } #endif // - (void) // enumerateSubstringsInRange:(NSRange)range // options:(NSStringEnumerationOptions)opts // usingBlock:( // void (^)( // NSString *substring, // NSRange substringRange, // NSRange enclosingRange, // BOOL *stop) // )block /// Enumerates the substrings of the specified type in the specified range of /// the string. /// /// Mutation of a string value while enumerating its substrings is not /// supported. If you need to mutate a string from within `body`, convert /// your string to an `NSMutableString` instance and then call the /// `enumerateSubstrings(in:options:using:)` method. /// /// - Parameters: /// - range: The range within the string to enumerate substrings. /// - opts: Options specifying types of substrings and enumeration styles. /// If `opts` is omitted or empty, `body` is called a single time with /// the range of the string specified by `range`. /// - body: The closure executed for each substring in the enumeration. The /// closure takes four arguments: /// - The enumerated substring. If `substringNotRequired` is included in /// `opts`, this parameter is `nil` for every execution of the /// closure. /// - The range of the enumerated substring in the string that /// `enumerate(in:options:_:)` was called on. /// - The range that includes the substring as well as any separator or /// filler characters that follow. For instance, for lines, /// `enclosingRange` contains the line terminators. The enclosing /// range for the first string enumerated also contains any characters /// that occur before the string. Consecutive enclosing ranges are /// guaranteed not to overlap, and every single character in the /// enumerated range is included in one and only one enclosing range. /// - An `inout` Boolean value that the closure can use to stop the /// enumeration by setting `stop = true`. public func enumerateSubstrings< R : RangeExpression >( in range: R, options opts: String.EnumerationOptions = [], _ body: @escaping ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) where R.Bound == Index { _ns.enumerateSubstrings( in: _toRelativeNSRange(range.relative(to: self)), options: opts) { var stop_ = false body($0, self._range($1), self._range($2), &stop_) if stop_ { UnsafeMutablePointer($3).pointee = true } } } //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property float floatValue; // - (BOOL) // getBytes:(void *)buffer // maxLength:(NSUInteger)maxBufferCount // usedLength:(NSUInteger*)usedBufferCount // encoding:(NSStringEncoding)encoding // options:(StringEncodingConversionOptions)options // range:(NSRange)range // remainingRange:(NSRangePointer)leftover /// Writes the given `range` of characters into `buffer` in a given /// `encoding`, without any allocations. Does not NULL-terminate. /// /// - Parameter buffer: A buffer into which to store the bytes from /// the receiver. The returned bytes are not NUL-terminated. /// /// - Parameter maxBufferCount: The maximum number of bytes to write /// to buffer. /// /// - Parameter usedBufferCount: The number of bytes used from /// buffer. Pass `nil` if you do not need this value. /// /// - Parameter encoding: The encoding to use for the returned bytes. /// /// - Parameter options: A mask to specify options to use for /// converting the receiver's contents to `encoding` (if conversion /// is necessary). /// /// - Parameter range: The range of characters in the receiver to get. /// /// - Parameter leftover: The remaining range. Pass `nil` If you do /// not need this value. /// /// - Returns: `true` iff some characters were converted. /// /// - Note: Conversion stops when the buffer fills or when the /// conversion isn't possible due to the chosen encoding. /// /// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes. public func getBytes< R : RangeExpression >( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: R, remaining leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool where R.Bound == Index { return _withOptionalOutParameter(leftover) { self._ns.getBytes( &buffer, maxLength: Swift.min(buffer.count, maxBufferCount), usedLength: usedBufferCount, encoding: encoding.rawValue, options: options, range: _toRelativeNSRange(range.relative(to: self)), remaining: $0) } } // - (void) // getLineStart:(NSUInteger *)startIndex // end:(NSUInteger *)lineEndIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first line and /// the end of the last line touched by the given range. public func getLineStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getLineStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } // - (void) // getParagraphStart:(NSUInteger *)startIndex // end:(NSUInteger *)endIndex // contentsEnd:(NSUInteger *)contentsEndIndex // forRange:(NSRange)aRange /// Returns by reference the beginning of the first paragraph /// and the end of the last paragraph touched by the given range. public func getParagraphStart< R : RangeExpression >( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, for range: R ) where R.Bound == Index { _withOptionalOutParameter(start) { start in self._withOptionalOutParameter(end) { end in self._withOptionalOutParameter(contentsEnd) { contentsEnd in self._ns.getParagraphStart( start, end: end, contentsEnd: contentsEnd, for: _toRelativeNSRange(range.relative(to: self))) } } } } //===--- Already provided by core Swift ---------------------------------===// // - (instancetype)initWithString:(NSString *)aString //===--- Initializers that can fail dropped for factory functions -------===// // - (instancetype)initWithUTF8String:(const char *)bytes //===--- Omitted for consistency with API review results 5/20/2014 ------===// // @property NSInteger integerValue; // @property Int intValue; //===--- Omitted by apparent agreement during API review 5/20/2014 ------===// // @property BOOL absolutePath; // - (BOOL)isEqualToString:(NSString *)aString // - (NSRange)lineRangeForRange:(NSRange)aRange /// Returns the range of characters representing the line or lines /// containing a given range. public func lineRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _range(_ns.lineRange( for: _toRelativeNSRange(aRange.relative(to: self)))) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSArray *) // linguisticTagsInRange:(NSRange)range // scheme:(NSString *)tagScheme // options:(LinguisticTaggerOptions)opts // orthography:(Orthography *)orthography // tokenRanges:(NSArray**)tokenRanges /// Returns an array of linguistic tags for the specified /// range and requested tags within the receiving string. public func linguisticTags< T : StringProtocol, R : RangeExpression >( in range: R, scheme tagScheme: T, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil? ) -> [String] where R.Bound == Index { var nsTokenRanges: NSArray? let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) { self._ns.linguisticTags( in: _toRelativeNSRange(range.relative(to: self)), scheme: tagScheme._ephemeralString, options: opts, orthography: orthography, tokenRanges: $0) as NSArray } if let nsTokenRanges = nsTokenRanges { tokenRanges?.pointee = (nsTokenRanges as [AnyObject]).map { self._range($0.rangeValue) } } return result as! [String] } // - (NSRange)paragraphRangeForRange:(NSRange)aRange /// Returns the range of characters representing the /// paragraph or paragraphs containing a given range. public func paragraphRange< R : RangeExpression >(for aRange: R) -> Range<Index> where R.Bound == Index { return _range( _ns.paragraphRange(for: _toRelativeNSRange(aRange.relative(to: self)))) } #endif // - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // // - (NSRange) // rangeOfCharacterFromSet:(NSCharacterSet *)aSet // options:(StringCompareOptions)mask // range:(NSRange)aRange /// Finds and returns the range in the `String` of the first /// character from a given character set found in a given range with /// given options. public func rangeOfCharacter( from aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { return _optionalRange( _ns.rangeOfCharacter( from: aSet, options: mask, range: _toRelativeNSRange( aRange ?? startIndex..<endIndex ) ) ) } // - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex /// Returns the range in the `String` of the composed /// character sequence located at a given index. public func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> { return _range( _ns.rangeOfComposedCharacterSequence(at: anIndex.encodedOffset)) } // - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range /// Returns the range in the string of the composed character /// sequences for a given range. public func rangeOfComposedCharacterSequences< R : RangeExpression >( for range: R ) -> Range<Index> where R.Bound == Index { // Theoretically, this will be the identity function. In practice // I think users will be able to observe differences in the input // and output ranges due (if nothing else) to locale changes return _range( _ns.rangeOfComposedCharacterSequences( for: _toRelativeNSRange(range.relative(to: self)))) } // - (NSRange)rangeOfString:(NSString *)aString // // - (NSRange) // rangeOfString:(NSString *)aString options:(StringCompareOptions)mask // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)aRange // // - (NSRange) // rangeOfString:(NSString *)aString // options:(StringCompareOptions)mask // range:(NSRange)searchRange // locale:(Locale *)locale /// Finds and returns the range of the first occurrence of a /// given string within a given range of the `String`, subject to /// given options, using the specified locale, if any. public func range< T : StringProtocol >( of aString: T, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { let aString = aString._ephemeralString return _optionalRange( locale != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange( searchRange ?? startIndex..<endIndex ), locale: locale ) : searchRange != nil ? _ns.range( of: aString, options: mask, range: _toRelativeNSRange(searchRange!) ) : !mask.isEmpty ? _ns.range(of: aString, options: mask) : _ns.range(of: aString) ) } // - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0); /// Finds and returns the range of the first occurrence of a given string, /// taking the current locale into account. Returns `nil` if the string was /// not found. /// /// This is the most appropriate method for doing user-level string searches, /// similar to how searches are done generally in the system. The search is /// locale-aware, case and diacritic insensitive. The exact list of search /// options applied may change over time. @available(macOS 10.11, iOS 9.0, *) public func localizedStandardRange< T : StringProtocol >(of string: T) -> Range<Index>? { return _optionalRange( _ns.localizedStandardRange(of: string._ephemeralString)) } #if !DEPLOYMENT_RUNTIME_SWIFT // - (NSString *) // stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding /// Returns a representation of the `String` using a given /// encoding to determine the percent escapes necessary to convert /// the `String` into a legal URL string. @available(swift, deprecated: 3.0, obsoleted: 4.0, message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.") public func addingPercentEscapes( using encoding: String.Encoding ) -> String? { return _ns.addingPercentEscapes(using: encoding.rawValue) } #endif //===--- From the 10.10 release notes; not in public documentation ------===// // No need to make these unavailable on earlier OSes, since they can // forward trivially to rangeOfString. /// Returns `true` iff `other` is non-empty and contained within /// `self` by case-sensitive, non-literal search. /// /// Equivalent to `self.rangeOfString(other) != nil` public func contains<T : StringProtocol>(_ other: T) -> Bool { let r = self.range(of: other) != nil if #available(macOS 10.10, iOS 8.0, *) { _sanityCheck(r == _ns.contains(other._ephemeralString)) } return r } /// Returns a Boolean value indicating whether the given string is non-empty /// and contained within this string by case-insensitive, non-literal /// search, taking into account the current locale. /// /// Locale-independent case-insensitive operation, and other needs, can be /// achieved by calling `range(of:options:range:locale:)`. /// /// Equivalent to: /// /// range(of: other, options: .caseInsensitiveSearch, /// locale: Locale.current) != nil public func localizedCaseInsensitiveContains< T : StringProtocol >(_ other: T) -> Bool { let r = self.range( of: other, options: .caseInsensitive, locale: Locale.current ) != nil if #available(macOS 10.10, iOS 8.0, *) { _sanityCheck(r == _ns.localizedCaseInsensitiveContains(other._ephemeralString)) } return r } } // Deprecated slicing extension StringProtocol where Index == String.Index { // - (NSString *)substringFromIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` from the one at a given index to the end. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range from' operator.") public func substring(from index: Index) -> String { return _ns.substring(from: index.encodedOffset) } // - (NSString *)substringToIndex:(NSUInteger)anIndex /// Returns a new string containing the characters of the /// `String` up to, but not including, the one at a given index. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript with a 'partial range upto' operator.") public func substring(to index: Index) -> String { return _ns.substring(to: index.encodedOffset) } // - (NSString *)substringWithRange:(NSRange)aRange /// Returns a string object containing the characters of the /// `String` that lie within a given range. @available(swift, deprecated: 4.0, message: "Please use String slicing subscript.") public func substring(with aRange: Range<Index>) -> String { return _ns.substring(with: _toRelativeNSRange(aRange)) } } extension StringProtocol { // - (const char *)fileSystemRepresentation /// Returns a file system-specific representation of the `String`. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public var fileSystemRepresentation: [CChar] { fatalError("unavailable function can't be called") } // - (BOOL) // getFileSystemRepresentation:(char *)buffer // maxLength:(NSUInteger)maxLength /// Interprets the `String` as a system-independent path and /// fills a buffer with a C-string in a format and encoding suitable /// for use with file-system calls. /// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes. @available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.") public func getFileSystemRepresentation( _ buffer: inout [CChar], maxLength: Int) -> Bool { fatalError("unavailable function can't be called") } //===--- Kept for consistency with API review results 5/20/2014 ---------===// // We decided to keep pathWithComponents, so keeping this too // @property NSString lastPathComponent; /// Returns the last path component of the `String`. @available(*, unavailable, message: "Use lastPathComponent on URL instead.") public var lastPathComponent: String { fatalError("unavailable function can't be called") } //===--- Renamed by agreement during API review 5/20/2014 ---------------===// // @property NSUInteger length; /// Returns the number of Unicode characters in the `String`. @available(*, unavailable, message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count") public var utf16Count: Int { fatalError("unavailable function can't be called") } // @property NSArray* pathComponents /// Returns an array of NSString objects containing, in /// order, each path component of the `String`. @available(*, unavailable, message: "Use pathComponents on URL instead.") public var pathComponents: [String] { fatalError("unavailable function can't be called") } // @property NSString* pathExtension; /// Interprets the `String` as a path and returns the /// `String`'s extension, if any. @available(*, unavailable, message: "Use pathExtension on URL instead.") public var pathExtension: String { fatalError("unavailable function can't be called") } // @property NSString *stringByAbbreviatingWithTildeInPath; /// Returns a new string that replaces the current home /// directory portion of the current path with a tilde (`~`) /// character. @available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.") public var abbreviatingWithTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathComponent:(NSString *)aString /// Returns a new string made by appending to the `String` a given string. @available(*, unavailable, message: "Use appendingPathComponent on URL instead.") public func appendingPathComponent(_ aString: String) -> String { fatalError("unavailable function can't be called") } // - (NSString *)stringByAppendingPathExtension:(NSString *)ext /// Returns a new string made by appending to the `String` an /// extension separator followed by a given extension. @available(*, unavailable, message: "Use appendingPathExtension on URL instead.") public func appendingPathExtension(_ ext: String) -> String? { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingLastPathComponent; /// Returns a new string made by deleting the last path /// component from the `String`, along with any final path /// separator. @available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.") public var deletingLastPathComponent: String { fatalError("unavailable function can't be called") } // @property NSString* stringByDeletingPathExtension; /// Returns a new string made by deleting the extension (if /// any, and only the last) from the `String`. @available(*, unavailable, message: "Use deletingPathExtension on URL instead.") public var deletingPathExtension: String { fatalError("unavailable function can't be called") } // @property NSString* stringByExpandingTildeInPath; /// Returns a new string made by expanding the initial /// component of the `String` to its full path value. @available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.") public var expandingTildeInPath: String { fatalError("unavailable function can't be called") } // - (NSString *) // stringByFoldingWithOptions:(StringCompareOptions)options // locale:(Locale *)locale @available(*, unavailable, renamed: "folding(options:locale:)") public func folding( _ options: String.CompareOptions = [], locale: Locale? ) -> String { fatalError("unavailable function can't be called") } // @property NSString* stringByResolvingSymlinksInPath; /// Returns a new string made from the `String` by resolving /// all symbolic links and standardizing path. @available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.") public var resolvingSymlinksInPath: String { fatalError("unavailable property") } // @property NSString* stringByStandardizingPath; /// Returns a new string made by removing extraneous path /// components from the `String`. @available(*, unavailable, message: "Use standardizingPath on URL instead.") public var standardizingPath: String { fatalError("unavailable function can't be called") } // - (NSArray *)stringsByAppendingPaths:(NSArray *)paths /// Returns an array of strings made by separately appending /// to the `String` each string in a given array. @available(*, unavailable, message: "Map over paths with appendingPathComponent instead.") public func strings(byAppendingPaths paths: [String]) -> [String] { fatalError("unavailable function can't be called") } } // Pre-Swift-3 method names extension String { @available(*, unavailable, renamed: "localizedName(of:)") public static func localizedNameOfStringEncoding( _ encoding: String.Encoding ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func pathWithComponents(_ components: [String]) -> String { fatalError("unavailable function can't be called") } // + (NSString *)pathWithComponents:(NSArray *)components /// Returns a string built from the strings in a given array /// by concatenating them with a path separator between each pair. @available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.") public static func path(withComponents components: [String]) -> String { fatalError("unavailable function can't be called") } } extension StringProtocol { @available(*, unavailable, renamed: "canBeConverted(to:)") public func canBeConvertedToEncoding(_ encoding: String.Encoding) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "capitalizedString(with:)") public func capitalizedStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "commonPrefix(with:options:)") public func commonPrefixWith( _ aString: String, options: String.CompareOptions) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)") public func completePathInto( _ outputName: UnsafeMutablePointer<String>? = nil, caseSensitive: Bool, matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil, filterTypes: [String]? = nil ) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedByCharactersIn( _ separator: CharacterSet ) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "components(separatedBy:)") public func componentsSeparatedBy(_ separator: String) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "cString(usingEncoding:)") public func cStringUsingEncoding(_ encoding: String.Encoding) -> [CChar]? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)") public func dataUsingEncoding( _ encoding: String.Encoding, allowLossyConversion: Bool = false ) -> Data? { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)") public func enumerateLinguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options, orthography: NSOrthography?, _ body: (String, Range<Index>, Range<Index>, inout Bool) -> Void ) { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)") public func enumerateSubstringsIn( _ range: Range<Index>, options opts: String.EnumerationOptions = [], _ body: ( _ substring: String?, _ substringRange: Range<Index>, _ enclosingRange: Range<Index>, inout Bool ) -> Void ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") public func getBytes( _ buffer: inout [UInt8], maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>, encoding: String.Encoding, options: String.EncodingConversionOptions = [], range: Range<Index>, remainingRange leftover: UnsafeMutablePointer<Range<Index>> ) -> Bool { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)") public func getLineStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)") public func getParagraphStart( _ start: UnsafeMutablePointer<Index>, end: UnsafeMutablePointer<Index>, contentsEnd: UnsafeMutablePointer<Index>, forRange: Range<Index> ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lengthOfBytes(using:)") public func lengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "lineRange(for:)") public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } #if !DEPLOYMENT_RUNTIME_SWIFT @available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)") public func linguisticTagsIn( _ range: Range<Index>, scheme tagScheme: String, options opts: NSLinguisticTagger.Options = [], orthography: NSOrthography? = nil, tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil ) -> [String] { fatalError("unavailable function can't be called") } #endif @available(*, unavailable, renamed: "lowercased(with:)") public func lowercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "maximumLengthOfBytes(using:)") public func maximumLengthOfBytesUsingEncoding(_ encoding: String.Encoding) -> Int { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "paragraphRange(for:)") public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)") public func rangeOfCharacterFrom( _ aSet: CharacterSet, options mask: String.CompareOptions = [], range aRange: Range<Index>? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)") public func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)") public func rangeOfComposedCharacterSequencesFor( _ range: Range<Index> ) -> Range<Index> { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "range(of:options:range:locale:)") public func rangeOf( _ aString: String, options mask: String.CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil ) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "localizedStandardRange(of:)") public func localizedStandardRangeOf(_ string: String) -> Range<Index>? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)") public func addingPercentEncodingWithAllowedCharacters( _ allowedCharacters: CharacterSet ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "addingPercentEscapes(using:)") public func addingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "appendingFormat") public func stringByAppendingFormat( _ format: String, _ arguments: CVarArg... ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "padding(toLength:with:startingAt:)") public func byPaddingToLength( _ newLength: Int, withString padString: String, startingAt padIndex: Int ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingCharacters(in:with:)") public func replacingCharactersIn( _ range: Range<Index>, withString replacement: String ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)") public func replacingOccurrencesOf( _ target: String, withString replacement: String, options: String.CompareOptions = [], range searchRange: Range<Index>? = nil ) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)") public func replacingPercentEscapesUsingEncoding( _ encoding: String.Encoding ) -> String? { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "trimmingCharacters(in:)") public func byTrimmingCharactersIn(_ set: CharacterSet) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "strings(byAppendingPaths:)") public func stringsByAppendingPaths(_ paths: [String]) -> [String] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(from:)") public func substringFrom(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(to:)") public func substringTo(_ index: Index) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "substring(with:)") public func substringWith(_ aRange: Range<Index>) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "uppercased(with:)") public func uppercaseStringWith(_ locale: Locale?) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(toFile:atomically:encoding:)") public func writeToFile( _ path: String, atomically useAuxiliaryFile:Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed: "write(to:atomically:encoding:)") public func writeToURL( _ url: URL, atomically useAuxiliaryFile: Bool, encoding enc: String.Encoding ) throws { fatalError("unavailable function can't be called") } }
88b4ed54b0396ccb9c315ca07d2daa9d
34.447878
279
0.677102
false
false
false
false
sopinetchat/SopinetChat-iOS
refs/heads/master
Pod/Views/SChatComposerTextView.swift
gpl-3.0
1
// // SChatComposerTextView.swift // Pods // // Created by David Moreno Lora on 2/5/16. // // import UIKit import Foundation class SChatComposerTextView: UITextView { var placeHolder: String = NSBundle.sChatLocalizedStringForKey("schat_new_message") var placeHolderTextColor: UIColor = UIColor.lightGrayColor() // MARK: Initialization func sChatConfigureTextView() { self.translatesAutoresizingMaskIntoConstraints = false let cornerRadius: CGFloat = 6.0 self.backgroundColor = UIColor.whiteColor() self.layer.borderWidth = 0.5 self.layer.borderColor = UIColor.lightGrayColor().CGColor self.layer.cornerRadius = cornerRadius self.scrollIndicatorInsets = UIEdgeInsetsMake(cornerRadius, 0.0, cornerRadius, 0.0) self.textContainerInset = UIEdgeInsetsMake(4.0, 2.0, 4.0, 2.0) self.contentInset = UIEdgeInsetsMake(1.0, 0.0, 1.0, 0.0) self.scrollEnabled = true self.scrollsToTop = false self.userInteractionEnabled = true self.font = UIFont.systemFontOfSize(16.0) self.textColor = UIColor.blackColor() self.textAlignment = .Natural self.contentMode = .Redraw self.dataDetectorTypes = .None self.keyboardAppearance = .Default self.keyboardType = .Default self.returnKeyType = .Default self.text = "" self.sChatAddTextViewNotificationObservers() } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) self.sChatConfigureTextView() } required public init?(coder: NSCoder) { super.init(coder: coder) self.sChatConfigureTextView() } // MARK: Composer TextView override func hasText() -> Bool { return self.text.sChatStringByTrimingWhitespace().characters.count > 0 } func setComposerText(text: String) { self.text = text self.setNeedsDisplay() } func setComposerFont(font: UIFont) { self.font = font self.setNeedsDisplay() } func setComposerTextAlignment(textAlignment: NSTextAlignment) { self.textAlignment = textAlignment self.setNeedsDisplay() } // MARK: Setters func setComposerPlaceHolder(placeHolder: String) { if placeHolder == self.placeHolder { return } self.placeHolder = placeHolder self.setNeedsDisplay() } func setComposerPlaceHolderTextColor(placeHolderTextColor: UIColor) { if placeHolderTextColor == self.placeHolderTextColor { return } self.placeHolderTextColor = placeHolderTextColor self.setNeedsDisplay() } // MARK: Drawing override func drawRect(rect: CGRect) { super.drawRect(rect) if self.text.characters.count == 0 { self.placeHolderTextColor.set() self.placeHolder.drawInRect(CGRectInset(rect, 7.0, 4.0), withAttributes: self.sChatPlaceHolderTextAttributes() as! [String : AnyObject]) } } // MARK: Utils func sChatPlaceHolderTextAttributes() -> NSDictionary { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = .ByTruncatingTail paragraphStyle.alignment = self.textAlignment return [NSFontAttributeName : self.font!, NSForegroundColorAttributeName: self.placeHolderTextColor, NSParagraphStyleAttributeName: paragraphStyle] } // MARK: Notifications func sChatAddTextViewNotificationObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sChatDidReceiveTextViewNotification(_:)), name: UITextViewTextDidChangeNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sChatDidReceiveTextViewNotification(_:)), name: UITextViewTextDidBeginEditingNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.sChatDidReceiveTextViewNotification(_:)), name: UITextViewTextDidEndEditingNotification, object: self) } func sChatRemoveTextViewNotificationObservers() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidBeginEditingNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidEndEditingNotification, object: nil) } func sChatDidReceiveTextViewNotification(notification: NSNotification) { self.setNeedsDisplay() } }
8ecb04fc9e853d6c78b19c0b0a2eea6c
29.789157
192
0.647036
false
false
false
false
ahmetkgunay/DrawPathView
refs/heads/master
DrawPathViewSwiftDemo/DrawPathViewSwiftDemo/ViewController.swift
mit
1
// // ViewController.swift // DrawPathViewSwiftDemo // // Created by Ahmet Kazim Günay on 15/12/15. // Copyright © 2015 Ahmet Kazim Günay. All rights reserved. // import UIKit class ViewController: UIViewController, DrawPathViewDelegate { lazy var drawView : DrawPathView = { let dv = DrawPathView(frame: self.view.bounds) dv.lineWidth = 10.0 dv.delegate = self return dv }() final let selectedBorderWidth = CGFloat(3) final let bottomViewHeight = CGFloat(44) final let buttonHeight = CGFloat(40) final let colors = [UIColor.red, .green, .orange, .yellow, .purple] // MARK: - View lifecycle - override func viewDidLoad() { super.viewDidLoad() view.addSubview(drawView) addBottomButtons() addTopButtons() } // MARK: - Private - private func addBottomButtons() { for i in 0..<colors.count { let btn = UIButton(type: UIButtonType.system) let buttonContainerWidth = view.frame.size.width let xPos = CGFloat(i) * (buttonContainerWidth / 5) + 10 let yPos = view.frame.size.height - bottomViewHeight - 22 btn.tag = i btn.backgroundColor = colors[i] btn.frame = CGRect(x:xPos, y:yPos, width:buttonHeight, height:buttonHeight) btn.layer.cornerRadius = buttonHeight / 2 btn.layer.borderColor = UIColor.darkGray.cgColor btn.layer.borderWidth = i == 0 ? selectedBorderWidth : 0 btn.layer.masksToBounds = true btn.addTarget(self, action:#selector(btnColorTapped(sender:)), for: .touchUpInside) view.addSubview(btn) } } private func addTopButtons() { for i in 0..<2 { let btn = UIButton(type: UIButtonType.system) let buttonContainerWidth = view.frame.size.width let xPos = CGFloat(i) * (buttonContainerWidth / 2) + 10 let yPos = CGFloat(44) btn.tag = i btn.frame = CGRect(x:xPos, y:yPos, width:buttonContainerWidth / 2 - 30, height:buttonHeight) btn.setTitle(i == 0 ? "Erase Last" : "Erase All", for: .normal) btn.setTitleColor(UIColor.blue, for: .normal) btn.addTarget(self, action:#selector(btnEraseTapped(sender:)), for: .touchUpInside) view.addSubview(btn) } } // MARK: - Button Actions - @objc internal func btnColorTapped(sender : UIButton) { let index = sender.tag let selectedColor = colors[index] drawView.changeStrokeColor(selectedColor) clearButtons() sender.layer.borderWidth = selectedBorderWidth } private func clearButtons () { for subview in view.subviews { if subview is UIButton { subview.layer.borderWidth = 0 } } } @objc internal func btnEraseTapped(sender : UIButton) { let index = sender.tag; switch index { case 0: drawView.clearLast() case 1: drawView.clearAll() default:break } } // MARK: - DrawPathView Delegate - func viewDrawStartedDrawing() { print("Started Drawing") } func viewDrawEndedDrawing() { print("Ended Drawing") } // MARK: - Memory Management - override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
7c0f72006f789d904237e351d189aa88
29.025424
104
0.583122
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Platform/Sources/PlatformUIKit/QRCode/QRCode.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import PlatformKit import UIKit public protocol QRCodeAPI { var image: UIImage? { get } init?(string: String) init(data: Data) } extension QRCodeAPI { public init?(string: String) { guard let data = string.data(using: .utf8) else { return nil } self.init(data: data) } } /// Generates a `QRCode` image from a given String or Data object. public struct QRCode: QRCodeAPI { private let data: Data public init(data: Data) { self.data = data } public var image: UIImage? { guard let ciImage = ciImage else { return nil } let scaleXY = UIScreen.main.bounds.width / ciImage.extent.size.width let scale = CGAffineTransform(scaleX: scaleXY, y: scaleXY) return UIImage(ciImage: ciImage.transformed(by: scale)) } private var ciImage: CIImage? { guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil } filter.setDefaults() filter.setValue(data, forKey: "inputMessage") filter.setValue("M", forKey: "inputCorrectionLevel") return filter.outputImage } }
8711ba37717564088050b84e3121c222
25.391304
82
0.645799
false
false
false
false
xjmeplws/AGDropdown
refs/heads/master
AGDropdown/AGButton.swift
mit
1
// // AGButton.swift // AGDropdown // // Created by huangyawei on 16/3/22. // Copyright © 2016年 xjmeplws. All rights reserved. // import Foundation import UIKit class AGButton: UIButton { private var isRotate = false ///button's image var image: UIImage? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func drawRect(rect: CGRect) { super.drawRect(rect) if self.image == nil { self.image = renderImage() } self.setImage(self.image, forState: .Normal) self.imageEdgeInsets = UIEdgeInsetsMake(0, (self.frame.size.width - 30), 0, 0) self.removeTarget(self, action: "rotateSelf", forControlEvents: .TouchUpInside) self.addTarget(self, action: "rotateSelf", forControlEvents: .TouchUpInside) } func rotateSelf() { guard let rotateImageView = self.imageView else { return } let transform = CGAffineTransformMakeRotation(!isRotate ? CGFloat(M_PI) : 0) isRotate = !isRotate UIView.animateWithDuration(0.1, animations: { rotateImageView.transform = transform }) } private func renderImage() -> UIImage? { let renderRect = CGRectMake(0.0, 0.0, 14.0, 10.0) UIGraphicsBeginImageContext(renderRect.size) let context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, AGDataSource.hexColor(0xAAAAAA).CGColor) CGContextMoveToPoint(context, 0.0, 0.0) CGContextAddLineToPoint(context, 14.0, 0.0) CGContextAddLineToPoint(context, 7.0, 10.0) CGContextFillPath(context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } }
354ad7990b1a3c59bbd748374d94579d
29.516129
88
0.640402
false
false
false
false
simonnarang/Fandom-IOS
refs/heads/master
Fandomm/ShareLinkViewController.swift
unlicense
1
// // ShareLinkViewController.swift // Fandomm // // Created by Simon Narang on 11/29/15. // Copyright © 2015 Simon Narang. All rights reserved. // import UIKit class ShareLinkViewController: UIViewController { //vars var shareLinkk = String() var fandommcount = 0 var usernameThreeTextOne = String() var userFandoms = [AnyObject]() //IBOUTLETS @IBOutlet weak var shareLink: UITextField! //after text is typed in... share it! func next() -> Void { if self.shareLink.text != "" && self.shareLink.text != " " { //make user inputted text the text to share self.shareLinkk = self.shareLink.text! print("Text to be shared typed in by user @\(self.usernameThreeTextOne)") performSegueWithIdentifier("segueThree", sender: nil) }else{ print("user didnt type anything in for sharing text") } } @IBAction func shareLinkButton(sender: AnyObject) { self.next() } //startup junk override func viewDidLoad() { super.viewDidLoad() //tap screen to close keyboard in case it doesnt close some other way let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ShareLinkViewController.dismissKeyboard)) view.addGestureRecognizer(tap) fandommcount = 0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueThree" { let destViewContOne: ShareToFandomNavigationViewController = segue.destinationViewController as! ShareToFandomNavigationViewController destViewContOne.usernameThreeTextOne = self.usernameThreeTextOne destViewContOne.shareLinky = self.shareLinkk destViewContOne.userFandoms = self.userFandoms }else { print("there is an undocumented segue form the sharelink tab") } } //dissmiss keyboard on tap func dismissKeyboard() { view.endEditing(true) } //perform posting with return key func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) self.next() return false } }
034b2d57acdedb48f7d5ae0826265dc5
28.232558
146
0.609387
false
false
false
false
gaolichuang/actor-platform
refs/heads/master
actor-apps/app-ios/ActorCore/Providers/iOSNotificationProvider.swift
mit
2
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation import AVFoundation import AudioToolbox.AudioServices @objc class iOSNotificationProvider: NSObject, ACNotificationProvider { var internalMessage:SystemSoundID = 0 var sounds: [String: SystemSoundID] = [:] var lastSoundPlay: Double = 0 override init() { super.init() let path = NSBundle.mainBundle().URLForResource("notification", withExtension: "caf"); AudioServicesCreateSystemSoundID(path!, &internalMessage) } func onMessageArriveInAppWithMessenger(messenger: ACMessenger!) { let currentTime = NSDate().timeIntervalSinceReferenceDate if (currentTime - lastSoundPlay > 0.2) { AudioServicesPlaySystemSound(internalMessage) lastSoundPlay = currentTime } } func onNotificationWithMessenger(messenger: ACMessenger!, withTopNotifications topNotifications: JavaUtilList!, withMessagesCount messagesCount: jint, withConversationsCount conversationsCount: jint) { let n = topNotifications.getWithInt(0) as! ACNotification messenger.getFormatter().formatNotificationText(n) var message = messenger.getFormatter().formatNotificationText(n) if (!messenger.isShowNotificationsText()) { message = NSLocalizedString("NotificationSecretMessage", comment: "New Message") } let senderUser = messenger.getUserWithUid(n.sender) var sender = senderUser.getNameModel().get() let peer = n.peer if (peer.isGroup) { let group = messenger.getGroupWithGid(n.peer.peerId) sender = "\(sender)@\(group.getNameModel().get())" } dispatchOnUi { () -> Void in let localNotification = UILocalNotification () localNotification.alertBody = "\(sender): \(message)" if (messenger.isNotificationSoundEnabled()) { localNotification.soundName = "\(self.getNotificationSound(messenger)).caf" } localNotification.applicationIconBadgeNumber = Actor.getAppState().globalCounter.get().integerValue UIApplication.sharedApplication().presentLocalNotificationNow(localNotification) } } func onUpdateNotificationWithMessenger(messenger: ACMessenger!, withTopNotifications topNotifications: JavaUtilList!, withMessagesCount messagesCount: jint, withConversationsCount conversationsCount: jint) { // Not Supported } func hideAllNotifications() { dispatchOnUi { () -> Void in // Clearing notifications let number = Actor.getAppState().globalCounter.get().integerValue UIApplication.sharedApplication().applicationIconBadgeNumber = 0 // If current value will equals to number + 1 UIApplication.sharedApplication().applicationIconBadgeNumber = number + 1 UIApplication.sharedApplication().applicationIconBadgeNumber = number // Clearing local notifications UIApplication.sharedApplication().cancelAllLocalNotifications() } } func getNotificationSound(messenger: ACMessenger!) -> String { if (messenger.getNotificationSound() != nil) { let path = NSBundle.mainBundle().pathForResource(messenger.getNotificationSound(), ofType: "caf") if (NSFileManager.defaultManager().fileExistsAtPath(path!)) { return messenger.getNotificationSound() } } return "iapetus" } }
0f4b6cb672f0289506fc3a917cc1ff76
41.564706
211
0.666667
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Playgrounds/Playback.playground/Pages/Recording Nodes.xcplaygroundpage/Contents.swift
mit
1
//: ## Recording Nodes //: ### AKNodeRecorder allows you to record the output of a specific node. //: ### Let's record a sawtooth solo. import XCPlayground import AudioKit //: Set up a source to be recorded var oscillator = AKOscillator(waveform: AKTable(.Sawtooth)) var currentAmplitude = 0.1 var currentRampTime = 0.2 //: Pass our Oscillator thru a mixer. It fixes a problem with raw oscillator //: nodes that can only be recorded once they passed thru an AKMixer. let oscMixer = AKMixer(oscillator) //: Let's add some space to our oscillator let reverb = AKReverb(oscMixer) reverb.loadFactoryPreset(.LargeHall) reverb.dryWetMix = 0.5 //: Create an AKAudioFile to record to: let tape = try? AKAudioFile() //: We set a player to playback our "tape" let player = try? AKAudioPlayer(file: tape!) //: Mix our reverberated oscillator with our player, so we can listen to both. let mixer = AKMixer(player!, reverb) AudioKit.output = mixer AudioKit.start() //: Now we set an AKNodeRecorder to our oscillator. You can change the recorded //: node to "reverb" if you prefer to record a "wet" oscillator... let recorder = try? AKNodeRecorder(node: oscMixer, file: tape!) //: Build our User interface class PlaygroundView: AKPlaygroundView, AKKeyboardDelegate { var recordLabel: Label? var playLabel: Label? override func setup() { addTitle("Recording Nodes") recordLabel = addLabel("Press Record to Record...") addSubview(AKButton(title: "Record", color: AKColor.redColor()) { if recorder!.isRecording { let dur = String(format: "%0.3f seconds", recorder!.recordedDuration) self.recordLabel!.text = "Stopped. (\(dur) recorded)" recorder?.stop() return "Record" } else { self.recordLabel!.text = "Recording..." try? recorder?.record() return "Stop" }}) addSubview(AKButton(title: "Reset Recording", color: AKColor.redColor()) { self.recordLabel!.text = "Tape Cleared!" try? recorder?.reset() return "Reset Recording" }) playLabel = addLabel("Press Play to playback...") addSubview(AKButton(title: "Play") { if player!.isPlaying { self.playLabel!.text = "Stopped playback!" player?.stop() return "Play" } else { try? player?.reloadFile() // If the tape is not empty, we can play it !... if player?.audioFile.duration > 0 { self.playLabel!.text = "Playing..." player?.completionHandler = self.callback player?.play() } else { self.playLabel!.text = "Tape is empty!..." } return "Stop" }}) let keyboard = AKKeyboardView(width: 440, height: 100) keyboard.delegate = self self.addSubview(keyboard) } func callback() { // We use Dispatch_async to refresh UI as callback is invoked from a background thread dispatch_async(dispatch_get_main_queue()) { self.playLabel!.text = "Finished playing!" } } // Synth UI func noteOn(note: MIDINoteNumber) { // start from the correct note if amplitude is zero if oscillator.amplitude == 0 { oscillator.rampTime = 0 } oscillator.frequency = note.midiNoteToFrequency() // Still use rampTime for volume oscillator.rampTime = currentRampTime oscillator.amplitude = currentAmplitude oscillator.play() } func noteOff(note: MIDINoteNumber) { oscillator.amplitude = 0 } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
a78244ffe7ac791cefc19d4efcae416f
31.147541
94
0.609383
false
false
false
false
niekang/WeiBo
refs/heads/master
WeiBo/Class/View/Home/WBHomeViewController.swift
apache-2.0
1
// // HomeViewController.swift // WeiBo // // Created by 聂康 on 2017/6/19. // Copyright © 2017年 com.nk. All rights reserved. // import UIKit import RxSwift private let normalCellId = "WBStatusNormalCell" private let retweetedCellId = "WBStatusRetweetedCell" class WBHomeViewController: WBBaseTabViewController { lazy var statusListViewModel = WBStatusListViewModel() // ViewModel 处理微博数据 let refreshControl = NKRefreshControl() /// 下拉刷新控件 let adapter = TableViewDataSource<WBStatusViewModel>() override func viewDidLoad() { //在判断登录状态之前 注册table 接收到登录通知之后 显示数据 setupUI() self.configTable() super.viewDidLoad() } override func loginSuccess() { super.loginSuccess() self.loadData() } @objc func loadData() { /// 如果是下拉,显示下拉动画 refreshControl.beginRefresh() statusListViewModel.loadWBStatusListData(isHeader: true) {[weak self] (isSuccess) in guard let weakSelf = self else { return } weakSelf.refreshControl.endRefresh() weakSelf.adapter.dataSource = weakSelf.statusListViewModel.statusList weakSelf.tableView.reloadData() } } func loadMoreData() { statusListViewModel.loadWBStatusListData(isHeader: false) {[weak self] (isSuccess) in guard let weakSelf = self else { return } weakSelf.adapter.dataSource = weakSelf.statusListViewModel.statusList weakSelf.tableView.reloadData() weakSelf.refreshControl.endRefresh() } } } extension WBHomeViewController { func configTable() { tableView.delegate = adapter tableView.dataSource = adapter adapter.configCell = {[unowned self](indexPath, statusViewModel, _, _) in let cellId = (statusViewModel.status.retweeted_status != nil) ? retweetedCellId : normalCellId let cell = self.tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! WBStatusCell cell.statusViewModel = statusViewModel return cell } adapter.willDisplayCell = {[unowned self](indexPath, statusViewModel, _ , _ ) in let row = indexPath.row /// 当滑到底部的时候加载数据 if row == (self.adapter.dataSource.count - 1){ self.loadMoreData() } } } } extension WBHomeViewController { func setupUI() { if navigationItem.titleView == nil{ tableView.register(UINib(nibName: normalCellId, bundle: nil), forCellReuseIdentifier: normalCellId) tableView.register(UINib(nibName: retweetedCellId, bundle: nil), forCellReuseIdentifier: retweetedCellId) tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 300 tableView.addSubview(refreshControl) refreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged) setupBarButtonItems() } NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: NSNotification.Name.init(rawValue: WBHomeVCShouldRefresh), object: nil) } func setupBarButtonItems() { navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(leftButtonClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightButtonClick)) let name = WBUserAccont.shared.screen_name let btn = WBTitleButton(title: name) navigationItem.titleView = btn btn.addTarget(self, action: #selector(titleButtonClick(btn:)), for: .touchUpInside) } @objc func leftButtonClick() { } @objc func rightButtonClick() { let QRCodeVC = WBQRCodeViewController() navigationController?.pushViewController(QRCodeVC, animated: true) } @objc func titleButtonClick(btn:UIButton) { btn.isSelected = !btn.isSelected } }
2ffae82717030d163f3f228d8eb96e0b
30.522059
161
0.631211
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
refs/heads/master
ResearchUXFactory/NSDate+Utilities.swift
bsd-3-clause
1
// // NSDate+Utilities.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import UIKit extension Date { public func startOfDay() -> Date { let calendar = Calendar.current let unitFlags: NSCalendar.Unit = [.day, .month, .year] let components = (calendar as NSCalendar).components(unitFlags, from: self) return calendar.date(from: components) ?? self } public var isToday: Bool { return self.startOfDay() == Date().startOfDay() } public var isTomorrow: Bool { return self.startOfDay() == Date().startOfDay().addingNumberOfDays(1) } public func addingNumberOfDays(_ days: Int) -> Date { let calendar = Calendar.current return calendar.date(byAdding: .day, value: days, to: self, wrappingComponents: false)! } }
3971ee1741d220691ff0da98e683952f
41.982759
95
0.72844
false
false
false
false
justindarc/focus
refs/heads/master
Blockzilla/SettingsViewController.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import SnapKit import UIKit import Telemetry import LocalAuthentication import Intents import IntentsUI class SettingsTableViewCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) let backgroundColorView = UIView() backgroundColorView.backgroundColor = UIConstants.colors.cellSelected selectedBackgroundView = backgroundColorView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func setupDynamicFont(forLabels labels: [UILabel], addObserver: Bool = false) { for label in labels { label.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.body) label.adjustsFontForContentSizeCategory = true } NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: nil, queue: nil) { _ in self.setupDynamicFont(forLabels: labels) } } } class SettingsTableViewAccessoryCell: SettingsTableViewCell { private let newLabel = SmartLabel() let accessoryLabel = SmartLabel() private let spacerView = UIView() var accessoryLabelText: String? { get { return accessoryLabel.text } set { accessoryLabel.text = newValue accessoryLabel.sizeToFit() } } var labelText: String? { get { return newLabel.text } set { newLabel.text = newValue newLabel.sizeToFit() } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupDynamicFont(forLabels: [newLabel, accessoryLabel], addObserver: true) newLabel.numberOfLines = 0 newLabel.lineBreakMode = .byWordWrapping contentView.addSubview(accessoryLabel) contentView.addSubview(newLabel) contentView.addSubview(spacerView) newLabel.textColor = UIConstants.colors.settingsTextLabel accessoryLabel.textColor = UIConstants.colors.settingsDetailLabel accessoryType = .disclosureIndicator accessoryLabel.setContentHuggingPriority(.required, for: .horizontal) accessoryLabel.setContentCompressionResistancePriority(.required, for: .horizontal) accessoryLabel.snp.makeConstraints { make in make.trailing.centerY.equalToSuperview() } newLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) newLabel.setContentCompressionResistancePriority(.required, for: .vertical) spacerView.snp.makeConstraints { make in make.top.bottom.leading.equalToSuperview() make.width.equalTo(UIConstants.layout.settingsFirstTitleOffset) } newLabel.snp.makeConstraints { make in make.leading.equalTo(spacerView.snp.trailing) make.top.equalToSuperview().offset(11) make.bottom.equalToSuperview().offset(-11) make.trailing.equalTo(accessoryLabel.snp.leading).offset(-10) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SettingsTableViewToggleCell: SettingsTableViewCell { private let newLabel = SmartLabel() private let newDetailLabel = SmartLabel() private let spacerView = UIView() var navigationController: UINavigationController? init(style: UITableViewCell.CellStyle, reuseIdentifier: String?, toggle: BlockerToggle) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupDynamicFont(forLabels: [newLabel, newDetailLabel], addObserver: true) newLabel.numberOfLines = 0 newLabel.text = toggle.label textLabel?.numberOfLines = 0 textLabel?.text = toggle.label newDetailLabel.numberOfLines = 0 detailTextLabel?.numberOfLines = 0 detailTextLabel?.text = toggle.subtitle backgroundColor = UIConstants.colors.cellBackground newLabel.textColor = UIConstants.colors.settingsTextLabel textLabel?.textColor = UIConstants.colors.settingsTextLabel layoutMargins = UIEdgeInsets.zero newDetailLabel.textColor = UIConstants.colors.settingsDetailLabel detailTextLabel?.textColor = UIConstants.colors.settingsDetailLabel accessoryView = PaddedSwitch(switchView: toggle.toggle) selectionStyle = .none // Add "Learn More" button recognition if toggle.label == UIConstants.strings.labelSendAnonymousUsageData || toggle.label == UIConstants.strings.settingsSearchSuggestions { addSubview(newLabel) addSubview(newDetailLabel) addSubview(spacerView) textLabel?.isHidden = true let selector = toggle.label == UIConstants.strings.labelSendAnonymousUsageData ? #selector(tappedLearnMoreFooter) : #selector(tappedLearnMoreSearchSuggestionsFooter) let learnMoreButton = UIButton() learnMoreButton.setTitle(UIConstants.strings.learnMore, for: .normal) learnMoreButton.setTitleColor(UIConstants.colors.settingsLink, for: .normal) if let cellFont = detailTextLabel?.font { learnMoreButton.titleLabel?.font = UIFont(name: cellFont.fontName, size: cellFont.pointSize) } let tapGesture = UITapGestureRecognizer(target: self, action: selector) learnMoreButton.addGestureRecognizer(tapGesture) addSubview(learnMoreButton) // Adjust the offsets to allow the buton to fit spacerView.snp.makeConstraints { make in make.top.bottom.leading.equalToSuperview() make.trailing.equalTo(textLabel!.snp.leading) } newLabel.snp.makeConstraints { make in make.leading.equalTo(spacerView.snp.trailing) make.top.equalToSuperview().offset(8) } learnMoreButton.snp.makeConstraints { make in make.leading.equalTo(spacerView.snp.trailing) make.bottom.equalToSuperview().offset(4) } newDetailLabel.snp.makeConstraints { make in let lineHeight = newLabel.font.lineHeight make.top.equalToSuperview().offset(10 + lineHeight) make.leading.equalTo(spacerView.snp.trailing) make.trailing.equalTo(contentView) if let learnMoreHeight = learnMoreButton.titleLabel?.font.lineHeight { make.bottom.equalToSuperview().offset(-8 - learnMoreHeight) } } newLabel.setupShrinkage() newDetailLabel.setupShrinkage() } } private func tappedFooter(topic: String) { guard let url = SupportUtils.URLForTopic(topic: topic) else { return } let contentViewController = SettingsContentViewController(url: url) navigationController?.pushViewController(contentViewController, animated: true) } @objc func tappedLearnMoreFooter(gestureRecognizer: UIGestureRecognizer) { tappedFooter(topic: UIConstants.strings.sumoTopicUsageData) } @objc func tappedLearnMoreSearchSuggestionsFooter(gestureRecognizer: UIGestureRecognizer) { tappedFooter(topic: UIConstants.strings.sumoTopicSearchSuggestion) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { enum Section: String { case privacy, search, siri, integration, mozilla var numberOfRows: Int { switch self { case .privacy: if BiometryType(context: LAContext()).hasBiometry { return 4 } return 3 case .search: return 3 case .siri: return 3 case .integration: return 1 case .mozilla: // Show tips option should not be displayed for users that do not see tips return TipManager.shared.shouldShowTips() ? 3 : 2 } } var headerText: String? { switch self { case .privacy: return UIConstants.strings.toggleSectionPrivacy case .search: return UIConstants.strings.settingsSearchTitle case .siri: return UIConstants.strings.siriShortcutsTitle case .integration: return UIConstants.strings.toggleSectionSafari case .mozilla: return UIConstants.strings.toggleSectionMozilla } } static func getSections() -> [Section] { if #available(iOS 12.0, *) { return [.privacy, .search, .siri, integration, .mozilla] } else { return [.privacy, .search, integration, .mozilla] } } } enum BiometryType { enum Status { case hasIdentities case hasNoIdentities init(_ hasIdentities: Bool) { self = hasIdentities ? .hasIdentities : .hasNoIdentities } } case faceID(Status), touchID(Status), none private static let NO_IDENTITY_ERROR = -7 var hasBiometry: Bool { switch self { case .touchID, .faceID: return true case .none: return false } } var hasIdentities: Bool { switch self { case .touchID(Status.hasIdentities), .faceID(Status.hasIdentities): return true default: return false } } init(context: LAContext) { var biometricError: NSError? guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &biometricError) else { self = .none; return } let status = Status(biometricError.map({ $0.code != BiometryType.NO_IDENTITY_ERROR }) ?? true) switch context.biometryType { case .faceID: self = .faceID(status) case .touchID: self = .touchID(status) case .none: self = .none } } } private let tableView = UITableView(frame: .zero, style: .grouped) // Hold a strong reference to the block detector so it isn't deallocated // in the middle of its detection. private let detector = BlockerEnabledDetector.makeInstance() private let biometryType = BiometryType(context: LAContext()) private var isSafariEnabled = false private let searchEngineManager: SearchEngineManager private var highlightsButton: UIBarButtonItem? private let whatsNew: WhatsNewDelegate private lazy var sections = { Section.getSections() }() private var toggles = [Int: [Int: BlockerToggle]]() private func getSectionIndex(_ section: Section) -> Int? { return Section.getSections().index(where: { $0 == section }) } private func initializeToggles() { let blockFontsToggle = BlockerToggle(label: UIConstants.strings.labelBlockFonts, setting: SettingsToggle.blockFonts) let usageDataSubtitle = String(format: UIConstants.strings.detailTextSendUsageData, AppInfo.productName) let usageDataToggle = BlockerToggle(label: UIConstants.strings.labelSendAnonymousUsageData, setting: SettingsToggle.sendAnonymousUsageData, subtitle: usageDataSubtitle) let searchSuggestionSubtitle = String(format: UIConstants.strings.detailTextSearchSuggestion, AppInfo.productName) let searchSuggestionToggle = BlockerToggle(label: UIConstants.strings.settingsSearchSuggestions, setting: SettingsToggle.enableSearchSuggestions, subtitle: searchSuggestionSubtitle) let safariToggle = BlockerToggle(label: UIConstants.strings.toggleSafari, setting: SettingsToggle.safari) let homeScreenTipsToggle = BlockerToggle(label: UIConstants.strings.toggleHomeScreenTips, setting: SettingsToggle.showHomeScreenTips) if let privacyIndex = getSectionIndex(Section.privacy) { if let biometricToggle = createBiometricLoginToggleIfAvailable() { toggles[privacyIndex] = [1: blockFontsToggle, 2: biometricToggle, 3: usageDataToggle] } else { toggles[privacyIndex] = [1: blockFontsToggle, 2: usageDataToggle] } } if let searchIndex = getSectionIndex(Section.search) { toggles[searchIndex] = [2: searchSuggestionToggle] } if let integrationIndex = getSectionIndex(Section.integration) { toggles[integrationIndex] = [0: safariToggle] } if let mozillaIndex = getSectionIndex(Section.mozilla) { toggles[mozillaIndex] = [0: homeScreenTipsToggle] } } /// Used to calculate cell heights. private lazy var dummyToggleCell: UITableViewCell = { let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell") cell.accessoryView = PaddedSwitch(switchView: UISwitch()) return cell }() private var shouldScrollToSiri: Bool init(searchEngineManager: SearchEngineManager, whatsNew: WhatsNewDelegate, shouldScrollToSiri: Bool = false) { self.searchEngineManager = searchEngineManager self.whatsNew = whatsNew self.shouldScrollToSiri = shouldScrollToSiri super.init(nibName: nil, bundle: nil) tableView.register(SettingsTableViewAccessoryCell.self, forCellReuseIdentifier: "accessoryCell") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { view.backgroundColor = UIConstants.colors.background title = UIConstants.strings.settingsTitle let navigationBar = navigationController!.navigationBar navigationBar.isTranslucent = false navigationBar.barTintColor = UIConstants.colors.settingsNavBar navigationBar.tintColor = UIConstants.colors.navigationButton navigationBar.titleTextAttributes = [.foregroundColor: UIConstants.colors.navigationTitle] let navBarBorderRect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 0.25) let imageRenderer = UIGraphicsImageRenderer(bounds: navBarBorderRect) let borderImage = imageRenderer.image(actions: { (context) in UIConstants.colors.settingsNavBorder.setFill() context.cgContext.fill(navBarBorderRect) }) navigationController?.navigationBar.shadowImage = borderImage let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSettings)) doneButton.tintColor = UIConstants.Photon.Magenta40 doneButton.accessibilityIdentifier = "SettingsViewController.doneButton" navigationItem.leftBarButtonItem = doneButton highlightsButton = UIBarButtonItem(title: UIConstants.strings.whatsNewTitle, style: .plain, target: self, action: #selector(whatsNewClicked)) highlightsButton?.image = UIImage(named: "highlight") highlightsButton?.accessibilityIdentifier = "SettingsViewController.whatsNewButton" navigationItem.rightBarButtonItem = highlightsButton if whatsNew.shouldShowWhatsNew() { highlightsButton?.tintColor = UIConstants.colors.whatsNew } view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) } tableView.dataSource = self tableView.delegate = self tableView.backgroundColor = UIConstants.colors.background tableView.layoutMargins = UIEdgeInsets.zero tableView.separatorColor = UIConstants.colors.settingsSeparator tableView.allowsSelection = true tableView.estimatedRowHeight = 44 initializeToggles() for (sectionIndex, toggleArray) in toggles { for (cellIndex, blockerToggle) in toggleArray { let toggle = blockerToggle.toggle toggle.onTintColor = UIConstants.colors.toggleOn toggle.addTarget(self, action: #selector(toggleSwitched(_:)), for: .valueChanged) toggle.isOn = Settings.getToggle(blockerToggle.setting) toggles[sectionIndex]?[cellIndex] = blockerToggle } } NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateSafariEnabledState() tableView.reloadData() if shouldScrollToSiri { guard let siriSection = getSectionIndex(Section.siri) else { shouldScrollToSiri = false return } let siriIndexPath = IndexPath(row: 0, section: siriSection) tableView.scrollToRow(at: siriIndexPath, at: .none, animated: false) shouldScrollToSiri = false } } @objc private func applicationDidBecomeActive() { // On iOS 9, we detect the blocker status by loading an invisible SafariViewController // in the current view. We can only run the detector if the view is visible; otherwise, // the detection callback won't fire and the detector won't be cleaned up. if isViewLoaded && view.window != nil { updateSafariEnabledState() } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } private func createBiometricLoginToggleIfAvailable() -> BlockerToggle? { guard biometryType.hasBiometry else { return nil } let label: String let subtitle: String switch biometryType { case .faceID: label = UIConstants.strings.labelFaceIDLogin subtitle = String(format: UIConstants.strings.labelFaceIDLoginDescription, AppInfo.productName) case .touchID: label = UIConstants.strings.labelTouchIDLogin subtitle = String(format: UIConstants.strings.labelTouchIDLoginDescription, AppInfo.productName) default: // Unknown biometric type return nil } let toggle = BlockerToggle(label: label, setting: SettingsToggle.biometricLogin, subtitle: subtitle) toggle.toggle.isEnabled = biometryType.hasIdentities return toggle } private func toggleForIndexPath(_ indexPath: IndexPath) -> BlockerToggle { guard let toggle = toggles[indexPath.section]?[indexPath.row] else { return BlockerToggle(label: "Error", setting: SettingsToggle.blockAds)} return toggle } private func setupToggleCell(indexPath: IndexPath, navigationController: UINavigationController?) -> SettingsTableViewToggleCell { let toggle = toggleForIndexPath(indexPath) let cell = SettingsTableViewToggleCell(style: .subtitle, reuseIdentifier: "toggleCell", toggle: toggle) cell.navigationController = navigationController return cell } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell switch sections[indexPath.section] { case .privacy: if indexPath.row == 0 { cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "trackingCell") cell.textLabel?.text = String(format: UIConstants.strings.trackingProtectionLabel) cell.accessibilityIdentifier = "settingsViewController.trackingCell" cell.accessoryType = .disclosureIndicator } else { cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController) } case .search: if indexPath.row < 2 { guard let searchCell = tableView.dequeueReusableCell(withIdentifier: "accessoryCell") as? SettingsTableViewAccessoryCell else { fatalError("Accessory cells do not exist") } let autocompleteLabel = Settings.getToggle(.enableDomainAutocomplete) || Settings.getToggle(.enableCustomDomainAutocomplete) ? UIConstants.strings.autocompleteCustomEnabled : UIConstants.strings.autocompleteCustomDisabled let labels : (label: String, accessoryLabel: String, identifier: String) = indexPath.row == 0 ? (UIConstants.strings.settingsSearchLabel, searchEngineManager.activeEngine.name, "SettingsViewController.searchCell") :(UIConstants.strings.settingsAutocompleteSection, autocompleteLabel, "SettingsViewController.autocompleteCell") searchCell.accessoryLabelText = labels.accessoryLabel searchCell.labelText = labels.label searchCell.accessibilityIdentifier = labels.identifier cell = searchCell } else { cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController) } case .siri: guard #available(iOS 12.0, *), let siriCell = tableView.dequeueReusableCell(withIdentifier: "accessoryCell") as? SettingsTableViewAccessoryCell else { fatalError("No accessory cells") } if indexPath.row == 0 { siriCell.labelText = UIConstants.strings.eraseSiri siriCell.accessibilityIdentifier = "settingsViewController.siriEraseCell" SiriShortcuts().hasAddedActivity(type: .erase) { (result: Bool) in siriCell.accessoryLabel.text = result ? UIConstants.strings.Edit : UIConstants.strings.addToSiri } } else if indexPath.row == 1 { siriCell.labelText = UIConstants.strings.eraseAndOpenSiri siriCell.accessibilityIdentifier = "settingsViewController.siriEraseAndOpenCell" SiriShortcuts().hasAddedActivity(type: .eraseAndOpen) { (result: Bool) in siriCell.accessoryLabel.text = result ? UIConstants.strings.Edit : UIConstants.strings.addToSiri } } else { siriCell.labelText = UIConstants.strings.openUrlSiri siriCell.accessibilityIdentifier = "settingsViewController.siriOpenURLCell" SiriShortcuts().hasAddedActivity(type: .openURL) { (result: Bool) in siriCell.accessoryLabel.text = result ? UIConstants.strings.Edit : UIConstants.strings.add } } cell = siriCell case .mozilla where TipManager.shared.shouldShowTips(): if indexPath.row == 0 { cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController) } else if indexPath.row == 1 { cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "aboutCell") cell.textLabel?.text = String(format: UIConstants.strings.aboutTitle, AppInfo.productName) cell.accessibilityIdentifier = "settingsViewController.about" } else { cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "ratingCell") cell.textLabel?.text = String(format: UIConstants.strings.ratingSetting, AppInfo.productName) cell.accessibilityIdentifier = "settingsViewController.rateFocus" } case .mozilla where !TipManager.shared.shouldShowTips(): if indexPath.row == 0 { cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "aboutCell") cell.textLabel?.text = String(format: UIConstants.strings.aboutTitle, AppInfo.productName) cell.accessibilityIdentifier = "settingsViewController.about" } else { cell = SettingsTableViewCell(style: .subtitle, reuseIdentifier: "ratingCell") cell.textLabel?.text = String(format: UIConstants.strings.ratingSetting, AppInfo.productName) cell.accessibilityIdentifier = "settingsViewController.rateFocus" } default: cell = setupToggleCell(indexPath: indexPath, navigationController: navigationController) } cell.backgroundColor = UIConstants.colors.cellBackground cell.textLabel?.textColor = UIConstants.colors.settingsTextLabel cell.layoutMargins = UIEdgeInsets.zero cell.detailTextLabel?.textColor = UIConstants.colors.settingsDetailLabel cell.textLabel?.setupShrinkage() cell.detailTextLabel?.setupShrinkage() return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].numberOfRows } func numberOfSections(in tableView: UITableView) -> Int { return sections.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // Height for the Search Engine and Learn More row. if indexPath.section == 5 || (indexPath.section == 4 && indexPath.row >= 1) { return 44 } // We have to manually calculate the cell height since UITableViewCell doesn't correctly // layout multiline detailTextLabels. let toggle = toggleForIndexPath(indexPath) let tableWidth = tableView.frame.width let accessoryWidth = dummyToggleCell.accessoryView!.frame.width let insetsWidth = 2 * tableView.separatorInset.left let width = tableWidth - accessoryWidth - insetsWidth var height = heightForLabel(dummyToggleCell.textLabel!, width: width, text: toggle.label) if let subtitle = toggle.subtitle { height += heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: subtitle) if toggle.label == UIConstants.strings.labelSendAnonymousUsageData || toggle.label == UIConstants.strings.settingsSearchSuggestions { height += 10 } } return height + 22 } private func heightForLabel(_ label: UILabel, width: CGFloat, text: String) -> CGFloat { let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let attrs: [NSAttributedString.Key: Any] = [.font: label.font] let boundingRect = NSString(string: text).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil) return boundingRect.height } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var groupingOffset = UIConstants.layout.settingsDefaultTitleOffset if sections[section] == .privacy { groupingOffset = UIConstants.layout.settingsFirstTitleOffset } // Hack: We want the header view's margin to match the cells, so we create an empty // cell with a blank space as text to layout the text label. From there, we can define // constraints for our custom label based on the cell's label. let cell = UITableViewCell() cell.textLabel?.text = " " cell.backgroundColor = UIConstants.colors.background let label = SmartLabel() label.text = sections[section].headerText label.textColor = UIConstants.colors.tableSectionHeader label.font = UIConstants.fonts.tableSectionHeader cell.contentView.addSubview(label) label.snp.makeConstraints { make in make.leading.trailing.equalTo(cell.textLabel!) make.centerY.equalTo(cell.textLabel!).offset(groupingOffset) } return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return sections[section] == .privacy ? 50 : 30 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch sections[indexPath.section] { case .privacy: if indexPath.row == 0 { let trackingProtectionVC = TrackingProtectionViewController() navigationController?.pushViewController(trackingProtectionVC, animated: true) } case .search: if indexPath.row == 0 { let searchSettingsViewController = SearchSettingsViewController(searchEngineManager: searchEngineManager) searchSettingsViewController.delegate = self navigationController?.pushViewController(searchSettingsViewController, animated: true) } else if indexPath.row == 1 { let autcompleteSettingViewController = AutocompleteSettingViewController() navigationController?.pushViewController(autcompleteSettingViewController, animated: true) } case .siri: guard #available(iOS 12.0, *) else { return } if indexPath.row == 0 { SiriShortcuts().manageSiri(for: SiriShortcuts.activityType.erase, in: self) UserDefaults.standard.set(false, forKey: TipManager.TipKey.siriEraseTip) } else if indexPath.row == 1 { SiriShortcuts().manageSiri(for: SiriShortcuts.activityType.eraseAndOpen, in: self) UserDefaults.standard.set(false, forKey: TipManager.TipKey.siriEraseTip) } else { let siriFavoriteVC = SiriFavoriteViewController() navigationController?.pushViewController(siriFavoriteVC, animated: true) } case .mozilla where TipManager.shared.shouldShowTips(): if indexPath.row == 1 { aboutClicked() } else if indexPath.row == 2 { let appId = AppInfo.config.appId if let reviewURL = URL(string: "https://itunes.apple.com/app/id\(appId)?action=write-review"), UIApplication.shared.canOpenURL(reviewURL) { UIApplication.shared.open(reviewURL, options: [:], completionHandler: nil) } } case .mozilla where !TipManager.shared.shouldShowTips(): if indexPath.row == 0 { aboutClicked() } else if indexPath.row == 1 { let appId = AppInfo.config.appId if let reviewURL = URL(string: "https://itunes.apple.com/app/id\(appId)?action=write-review"), UIApplication.shared.canOpenURL(reviewURL) { UIApplication.shared.open(reviewURL, options: [:], completionHandler: nil) } } default: break } } private func updateSafariEnabledState() { guard let index = getSectionIndex(Section.integration), let safariToggle = toggles[index]?[0]?.toggle else { return } safariToggle.isEnabled = false detector.detectEnabled(view) { [weak self] enabled in safariToggle.isOn = enabled && Settings.getToggle(.safari) safariToggle.isEnabled = true self?.isSafariEnabled = enabled } } @objc private func dismissSettings() { self.dismiss(animated: true, completion: nil) } @objc private func aboutClicked() { navigationController!.pushViewController(AboutViewController(), animated: true) } @objc private func whatsNewClicked() { highlightsButton?.tintColor = UIColor.white guard let focusURL = SupportUtils.URLForTopic(topic: UIConstants.strings.sumoTopicWhatsNew) else { return } guard let klarURL = SupportUtils.URLForTopic(topic: UIConstants.strings.klarSumoTopicWhatsNew) else { return } if AppInfo.isKlar { navigationController?.pushViewController(SettingsContentViewController(url: klarURL), animated: true) } else { navigationController?.pushViewController(SettingsContentViewController(url: focusURL), animated: true) } whatsNew.didShowWhatsNew() } @objc private func toggleSwitched(_ sender: UISwitch) { let toggle = toggles.values.filter { $0.values.filter { $0.toggle == sender } != []}[0].values.filter { $0.toggle == sender }[0] func updateSetting() { let telemetryEvent = TelemetryEvent(category: TelemetryEventCategory.action, method: TelemetryEventMethod.change, object: "setting", value: toggle.setting.rawValue) telemetryEvent.addExtra(key: "to", value: sender.isOn) Telemetry.default.recordEvent(telemetryEvent) Settings.set(sender.isOn, forToggle: toggle.setting) ContentBlockerHelper.shared.reload() Utils.reloadSafariContentBlocker() } // First check if the user changed the anonymous usage data setting and follow that choice right // here. Otherwise it will be delayed until the application restarts. if toggle.setting == .sendAnonymousUsageData { Telemetry.default.configuration.isCollectionEnabled = sender.isOn Telemetry.default.configuration.isUploadEnabled = sender.isOn } else if toggle.setting == .biometricLogin { UserDefaults.standard.set(false, forKey: TipManager.TipKey.biometricTip) } switch toggle.setting { case .safari where sender.isOn && !isSafariEnabled: let instructionsViewController = SafariInstructionsViewController() navigationController!.pushViewController(instructionsViewController, animated: true) updateSetting() case .enableSearchSuggestions: UserDefaults.standard.set(true, forKey: SearchSuggestionsPromptView.respondedToSearchSuggestionsPrompt) updateSetting() case .showHomeScreenTips: updateSetting() // This update must occur after the setting has been updated to properly take effect. if let browserViewController = presentingViewController as? BrowserViewController { browserViewController.refreshTipsDisplay() } default: updateSetting() } } } extension SettingsViewController: SearchSettingsViewControllerDelegate { func searchSettingsViewController(_ searchSettingsViewController: SearchSettingsViewController, didSelectEngine engine: SearchEngine) { (tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? SettingsTableViewAccessoryCell)?.accessoryLabelText = engine.name } } extension SettingsViewController: INUIAddVoiceShortcutViewControllerDelegate { @available(iOS 12.0, *) func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) { controller.dismiss(animated: true, completion: nil) } @available(iOS 12.0, *) func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } } @available(iOS 12.0, *) extension SettingsViewController: INUIEditVoiceShortcutViewControllerDelegate { func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didUpdate voiceShortcut: INVoiceShortcut?, error: Error?) { controller.dismiss(animated: true, completion: nil) } func editVoiceShortcutViewController(_ controller: INUIEditVoiceShortcutViewController, didDeleteVoiceShortcutWithIdentifier deletedVoiceShortcutIdentifier: UUID) { controller.dismiss(animated: true, completion: nil) } func editVoiceShortcutViewControllerDidCancel(_ controller: INUIEditVoiceShortcutViewController) { controller.dismiss(animated: true, completion: nil) } }
ae27006c772ad8f5dc1aea489984be84
44.821293
237
0.671148
false
false
false
false
ziogaschr/SwiftPasscodeLock
refs/heads/master
PasscodeLockTests/PasscodeLock/EnterPasscodeStateTests.swift
mit
1
// // EnterPasscodeStateTests.swift // PasscodeLock // // Created by Yanko Dimitrov on 8/28/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import XCTest class NotificaionObserver: NSObject { var called = false var callCounter = 0 func observe(notification: String) { let center = NotificationCenter.default center.addObserver(self, selector: #selector(NotificaionObserver.handle(notification:)), name: NSNotification.Name(rawValue: notification), object: nil) } @objc func handle(notification: NSNotification) { called = true callCounter += 1 } } class EnterPasscodeStateTests: XCTestCase { var passcodeLock: FakePasscodeLock! var passcodeState: EnterPasscodeState! var repository: FakePasscodeRepository! override func setUp() { super.setUp() repository = FakePasscodeRepository() let config = FakePasscodeLockConfiguration(repository: repository) passcodeState = EnterPasscodeState() passcodeLock = FakePasscodeLock(state: passcodeState, configuration: config) } func testAcceptCorrectPasscode() { class MockDelegate: FakePasscodeLockDelegate { var called = false override func passcodeLockDidSucceed(_ lock: PasscodeLockType) { called = true } } let delegate = MockDelegate() passcodeLock.delegate = delegate passcodeState.acceptPasscode(repository.fakePasscode, fromLock: passcodeLock) XCTAssertEqual(delegate.called, true, "Should call the delegate when the passcode is correct") } func testAcceptIncorrectPasscode() { class MockDelegate: FakePasscodeLockDelegate { var called = false override func passcodeLockDidFail(_ lock: PasscodeLockType) { called = true } } let delegate = MockDelegate() passcodeLock.delegate = delegate passcodeState.acceptPasscode(["0", "0", "0", "0"], fromLock: passcodeLock) XCTAssertEqual(delegate.called, true, "Should call the delegate when the passcode is incorrect") } func testIncorrectPasscodeNotification() { let observer = NotificaionObserver() observer.observe(notification: PasscodeLockIncorrectPasscodeNotification) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) XCTAssertEqual(observer.called, true, "Should send a notificaiton when the maximum number of incorrect attempts is reached") } func testIncorrectPasscodeSendNotificationOnce() { let observer = NotificaionObserver() observer.observe(notification: PasscodeLockIncorrectPasscodeNotification) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) passcodeState.acceptPasscode(["0"], fromLock: passcodeLock) XCTAssertEqual(observer.callCounter, 1, "Should send the notification only once") } }
876fcdae63c31f4c2f4a620bad51498f
30.87931
160
0.632504
false
true
false
false
bangslosan/SwiftOverlays
refs/heads/master
Example/Example/OverlayExampleVC.swift
mit
1
// // WaitVC.swift // Example // // Created by Peter Prokop on 17/10/14. // // import UIKit class OverlayExampleVC: UIViewController { enum ExampleType { case Wait case WaitWithText case TextOnly case ImageAndText case AnnoyingNotification } @IBOutlet var annoyingNotificationView: UIView? var type: ExampleType = .Wait override func viewDidLoad() { super.viewDidLoad() self.begin() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: begin/end func begin() { switch (type) { case .Wait: self.showWaitOverlay() // Or SwiftOverlays.showCenteredWaitOverlay(self.view) case .WaitWithText: let text = "Please wait..." self.showWaitOverlayWithText(text) // Or SwiftOverlays.showCenteredWaitOverlayWithText(self.view, text: text) case .TextOnly: let text = "This is a text-only overlay...\n...spanning several lines" self.showTextOverlay(text) // Or SwiftOverlays.showTextOverlay(self.view, text: text) return case .ImageAndText: let image = PPSwiftGifs.animatedImageWithGIFNamed("Loading") let text = "Overlay\nWith cool GIF!" self.showImageAndTextOverlay(image!, text: text) // Or SwiftOverlays.showImageAndTextOverlay(self.view, image: image!, text: text) return case .AnnoyingNotification: NSBundle.mainBundle().loadNibNamed("AnnoyingNotification", owner: self, options: nil) annoyingNotificationView!.frame.size.width = self.view.bounds.width; UIViewController.showNotificationOnTopOfStatusBar(annoyingNotificationView!, duration: 5) // Or SwiftOverlays.showAnnoyingNotificationOnTopOfStatusBar(annoyingNotificationView!, duration: 5) return } let delay = 2.0 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { [weak self] in let strongSelf = self if strongSelf != nil { strongSelf!.end() } }) } func end() { switch (type) { case .Wait, .WaitWithText, .TextOnly, .ImageAndText: SwiftOverlays.removeAllOverlaysFromView(self.view) case .AnnoyingNotification: return } let delay = 0.5 * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { [weak self] in let strongSelf = self if strongSelf != nil { self!.begin() } }) } }
8d8c86eeb4bf7c111781a42867e662b2
28.242991
112
0.558184
false
false
false
false
luowei/PaintCodeSamples
refs/heads/master
GraphicDraw/GraphicDraw/MyCollectionViewController.swift
apache-2.0
1
// // MyCollectionViewCollectionViewController.swift // GraphicDraw // // Created by luowei on 2016/10/19. // Copyright © 2016年 wodedata. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class MyCollectionViewController: UICollectionViewController { private var timer: Timer? override func viewDidLoad() { super.viewDidLoad() timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true) guard let t = timer as Timer? else { return } RunLoop.current.add(t, forMode: .commonModes) } @objc func updateTime(){ MyClockKit.hours = CGFloat(Date().hour()) MyClockKit.minutes = CGFloat(Date().minute()) MyClockKit.seconds = CGFloat(Date().second()) guard let visibleCells = self.collectionView?.visibleCells as [UICollectionViewCell]? else{ return } for v:UICollectionViewCell in visibleCells { guard let myCell = v as? MyCell as MyCell? else { break } myCell.clockView.setNeedsDisplay() } } deinit { guard let t = timer as Timer? else { return } t.invalidate() } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1000 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) // Configure the cell (cell as? MyCell)?.clockView.setNeedsDisplay() return cell } // MARK: UICollectionViewDelegate }
8a08a1b970c21e49d2f6d24d3b631749
26.643836
138
0.635282
false
false
false
false
argent-os/argent-ios
refs/heads/master
app-ios/WebPrivacyViewController.swift
mit
1
// // WebPrivacyViewController.swift // argent-ios // // Created by Sinan Ulkuatam on 3/27/16. // Copyright © 2016 Sinan Ulkuatam. All rights reserved. // import Foundation import UIKit import WebKit import CWStatusBarNotification class WebPrivacyViewController: UIViewController, WKNavigationDelegate, WKUIDelegate { @IBOutlet var containerView : UIView! = nil var webView: WKWebView? override func loadView() { super.loadView() self.navigationController?.navigationBar.tintColor = UIColor.darkGrayColor() self.webView = WKWebView() self.webView?.UIDelegate = self self.webView?.contentMode = UIViewContentMode.ScaleToFill self.view = self.webView! } override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string:"https://www.argentapp.com/privacy") let req = NSURLRequest(URL:url!) self.webView!.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } lazy var previewActions: [UIPreviewActionItem] = { func previewActionForTitle(title: String, style: UIPreviewActionStyle = .Default) -> UIPreviewAction { return UIPreviewAction(title: title, style: style) { previewAction, viewController in // guard let detailViewController = viewController as? DetailViewController, // item = detailViewController.detailItemTitle else { return } // print("\(previewAction.title) triggered from `DetailViewController` for item: \(item)") if title == "Copy Link" { showGlobalNotification("Link copied!", duration: 3.0, inStyle: CWNotificationAnimationStyle.Top, outStyle: CWNotificationAnimationStyle.Top, notificationStyle: CWNotificationStyle.StatusBarNotification, color: UIColor.skyBlue()) UIPasteboard.generalPasteboard().string = "https://www.argentapp.com/privacy" } if title == "Share" { let activityViewController = UIActivityViewController( activityItems: [APP_NAME + " Privacy Policy https://www.argentapp.com/privacy" as NSString], applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList] self.presentViewController(activityViewController, animated: true, completion: nil) } } } let action1 = previewActionForTitle("Copy Link") // return [action1] let action2 = previewActionForTitle("Share") return [action1, action2] // let action2 = previewActionForTitle("Share", style: .Destructive) // let subAction1 = previewActionForTitle("Sub Action 1") // let subAction2 = previewActionForTitle("Sub Action 2") // let groupedActions = UIPreviewActionGroup(title: "More", style: .Default, actions: [subAction1, subAction2] ) // return [action1, action2, groupedActions] }() override func previewActionItems() -> [UIPreviewActionItem] { return previewActions } }
066e548dc64dee123513acffbff77787
40.109756
248
0.62819
false
false
false
false
jgonfer/JGFLabRoom
refs/heads/master
JGFLabRoom/Controller/Information Access/OAuth/STwitterViewController.swift
mit
1
// // STwitterViewController.swift // JGFLabRoom // // Created by Josep González on 25/1/16. // Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved. // /* * MARK: IMPORTANT: For more information about Twitter API * go to https://dev.twitter.com/oauth/overview */ import UIKit class STwitterViewController: UITableViewController { var results = ["Sig in with Twitter"] var indexSelected: NSIndexPath? override func viewDidLoad() { super.viewDidLoad() setupController() } private func setupController() { Utils.registerStandardXibForTableView(tableView, name: "cell") Utils.cleanBackButtonTitle(navigationController) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let indexSelected = indexSelected else { return } switch segue.identifier! { case kSegueIdListApps: if let vcToShow = segue.destinationViewController as? ListAppsViewController { vcToShow.indexSelected = indexSelected } default: break } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 55 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return results.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let reuseIdentifier = "cell" var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) if (cell != nil) { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier) } cell!.textLabel!.text = results[indexPath.row] cell?.accessoryType = .DisclosureIndicator //cell!.detailTextLabel!.text = "some text" return cell! } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.indexSelected = indexPath performSegueWithIdentifier(kSegueIdListApps, sender: tableView) tableView.deselectRowAtIndexPath(indexPath, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bbad7bfe960dbb5cdbe84184295e8c30
31.148148
118
0.666539
false
false
false
false
madbat/SwiftMath
refs/heads/master
SwiftMathTests/ComplexMultisetMatcher.swift
mit
1
// // ComplexArrayMatcher.swift // SwiftMath // // Created by Matteo Battaglio on 10/05/15. // Copyright (c) 2015 Matteo Battaglio. All rights reserved. // import Foundation import SwiftMath import Nimble import Set // Using the same value as Nimble's default delta constant let DefaultDelta = 0.0001 public func isCloseTo<T: RealType>(actual: Complex<T>, _ expected: Complex<T>) -> Bool { return abs(actual - expected) < T(DefaultDelta) } public func beCloseTo<T: RealType>(var expectedValue: Multiset<Complex<T>>) -> MatcherFunc<Multiset<Complex<T>>> { print("Expected value is: \(expectedValue)") return MatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "be close to <\(expectedValue)>" if let value = actualExpression.evaluate() { for element in value { var containedElement: Complex<T>? = nil if expectedValue.contains(element) { containedElement = element } else { for expectedElement in expectedValue { if isCloseTo(element, expectedElement) { containedElement = expectedElement break } } } if containedElement != nil { expectedValue.remove(containedElement!) } else { return false } } print("Expected value NOW is: \(expectedValue)") return expectedValue.isEmpty } else { return false } } }
1837b7358e1e90f18b7f47ec6a09e3e5
32.26
114
0.561974
false
false
false
false
questbeat/RateLimit
refs/heads/master
RateLimit/RateLimit.swift
mit
1
// // RateLimit.swift // Riverflow // // Created by Katsuma Tanaka on 2015/03/11. // Copyright (c) 2015年 Katsuma Tanaka. All rights reserved. // import Foundation public class RateLimit: NSObject { // MARK: - Properties public let interval: NSTimeInterval public let limit: UInt public var onReset: (() -> Void)? public private(set) var numberOfCalls: UInt = 0 public var remaining: UInt { return limit - numberOfCalls } public var exceeded: Bool { return (numberOfCalls >= limit) } private var timer: NSTimer? private var startDate: NSDate? // MARK: - Initializers public init(interval: NSTimeInterval, limit: UInt) { self.interval = interval self.limit = limit super.init() } public convenience init(limitPerHour: UInt) { self.init(interval: 60.0 * 60.0, limit: limitPerHour) } public convenience init(limitPerMinutes: UInt) { self.init(interval: 60.0, limit: limitPerMinutes) } public convenience init(limitPerSecond: UInt) { self.init(interval: 1.0, limit: limitPerSecond) } // MARK: - Updating Rate Limit public func call() -> Bool { if exceeded { return false } numberOfCalls++ if startDate == nil { startDate = NSDate() startTimer() } return true } public func reset() { stopTimer() numberOfCalls = 0 startDate = nil onReset?() } // MARK: - Timer private func startTimer() { stopTimer() timer = NSTimer.scheduledTimerWithTimeInterval( interval, target: self, selector: "timerFired:", userInfo: nil, repeats: false ) } private func stopTimer() { timer?.invalidate() timer = nil } internal func timerFired(sender: AnyObject) { reset() } }
2ecb679ed8556dcd6d3b69b5aaad2479
19.371429
61
0.531557
false
false
false
false
CodaFi/Basis
refs/heads/master
Basis/Map.swift
mit
2
// // Map.swift // Basis // // Created by Robert Widmann on 9/16/14. // Copyright (c) 2014 TypeLift. All rights reserved. // Released under the MIT license. // public enum MapD<K, A> { case Empty case Destructure(UInt, K, A, Map<K, A>!, Map<K, A>!) } /// An immutable map between keys and values. public final class Map<K, A> : K2<K, A> { let size : UInt let k : K! let a : A! let l : Map<K, A>! let r : Map<K, A>! init(_ size : UInt, _ k : K!, _ a : A!, _ l : Map<K, A>!, _ r : Map<K, A>!) { self.size = size self.k = k self.a = a self.l = l self.r = r } public func match() -> MapD<K, A> { if self.size == 0 || k == nil || a == nil { return .Empty } return .Destructure(size, k, a, l, r) } } /// Produces an empty map. public func empty<K, A>() -> Map<K, A> { return Map<K, A>(0, nil, nil, nil, nil) } /// Produces a map with one key-value pair. public func singleton<K, A>(key : K) -> A -> Map<K, A> { return { val in Map<K, A>(1, key, val, nil, nil) } } /// Builds a map from an association list. /// /// This function is left-biased in that if there are multiple keys for one value, only the last is /// retained. public func fromArray<K : Comparable, A>(xs : [(K, A)]) -> Map<K, A> { return foldl({ insert(fst($1))(snd($1))($0) })(empty())(xs) } /// Builds an association list from a map. public func toArray<K, A>(m : Map<K, A>) -> [(K, A)] { return foldrWithKey({ k in return { x in return { l in return (k, x) <| l } } })([])(m) } /// Inserts a new key-value pair and returns a new map. /// /// This function is left-biased in that it will replace any old value in the map with the new given /// value if the two keys are the same. public func insert<K : Comparable, A>(key : K) -> A -> Map<K, A> -> Map<K, A> { return { val in { m in switch m.match() { case .Empty: return singleton(key)(val) case .Destructure(let sz, let ky, let y, let l, let r): if key < ky { return balance(ky)(x: y)(l: insert(key)(val)(l))(r: r) } else if key > ky { return balance(ky)(x: y)(l: l)(r: insert(key)(val)(r)) } return Map(sz, key, val, l, r) } } } } /// Inserts a new key-value pair after applying a function to the new value and old value and /// returns a new map. /// /// If a value does not exist for a given key, this function inserts a new key-value pair and /// returns a new map. If the a value does exist, the function will be called with the old and new /// values for that key, and the key-value pair of the key and the result of the function call is /// inserted. public func insertWith<K : Comparable, A>(f : A -> A -> A) -> K -> A -> Map<K, A> -> Map<K, A> { return { key in { val in { m in return insertWithKey({ _ in { x in { y in f(x)(y) } } })(key)(val)(m) } } } } /// Inserts a new key-value pair after applying a function to the key, new value, and old value and /// returns a new map. /// /// If a value does not exist for a given key, this function inserts a new key-value pair and /// returns a new map. If the a value does exist, the function will be called with the key, and the /// old and new values for that key, and the key-value pair of the key and the result of the /// function call is inserted. public func insertWithKey<K : Comparable, A>(f : K -> A -> A -> A) -> K -> A -> Map<K, A> -> Map<K, A> { return { key in { val in { m in switch m.match() { case .Empty: return singleton(key)(val) case .Destructure(let sy, let ky, let y, let l, let r): if key < ky { return balance(ky)(x: y)(l: insertWithKey(f)(key)(val)(l))(r: r) } else if key > ky { return balance(ky)(x: y)(l: l)(r: insertWithKey(f)(key)(val)(r)) } return Map(sy, key, (f(key)(val)(y)), l, r) } } } } } /// Deletes a key and its associated value from the map and returns a new map. /// /// If the key does not exist in the map, it is returned unmodified. public func delete<K : Comparable, A>(k : K) -> Map<K, A> -> Map<K, A> { return { m in switch m.match() { case .Empty: return empty() case .Destructure(_, let kx, let x, let l, let r): if k < kx { return balance(kx)(x: x)(l: delete(k)(m))(r: r) } else if k > kx { return balance(kx)(x: x)(l: l)(r: delete(k)(m)) } return glue(l, r) } } } /// Finds and deletes the minimal element in a map of ordered keys. /// /// This function is partial with respect to empty maps. public func deleteFindMin<K, A>(m : Map<K, A>) -> ((K, A), Map<K, A>) { switch m.match() { case .Empty: return error("Cannot delete the minimal element of an empty map.") case .Destructure(_, let k, let x, let l, let r): switch l.match() { case .Empty: return ((k, x), r) case .Destructure(_, _, _, _, _): let (km, l1) = deleteFindMin(l) return (km, balance(k)(x: x)(l: l1)(r: r)) } } } /// Finds and deletes the maximal element in a map of ordered keys. /// /// This function is partial with respect to empty maps. public func deleteFindMax<K, A>(m : Map<K, A>) -> ((K, A), Map<K, A>) { switch m.match() { case .Empty: return error("Cannot delete the maximal element of an empty map.") case .Destructure(_, let k, let x, let l, let r): switch l.match() { case .Empty: return ((k, x), r) case .Destructure(_, _, _, _, _): let (km, r1) = deleteFindMin(l) return (km, balance(k)(x: x)(l: l)(r: r1)) } } } /// Balancing based on unoptimized algorithm in Data.Map.Base /// http://www.haskell.org/ghc/docs/7.8.3/html/libraries/containers-0.5.5.1/src/Data-Map-Base.html#balance /// which is, in turn, based on the paper /// http://groups.csail.mit.edu/mac/users/adams/BB/ private func balance<K, A>(k : K)(x : A)(l : Map<K, A>)(r : Map<K, A>) -> Map<K, A> { if l.size + r.size <= 1 { return Map(l.size + r.size + 1, k, x, l, r) } else if r.size > l.size * 3 { return rotateL(k)(x: x)(l: l)(r: r) } else if l.size > r.size * 3 { return rotateR(k)(x: x)(l: l)(r: r) } return Map(l.size + r.size, k, x, l, r) } private func rotateL<K, A>(k : K)(x : A)(l : Map<K, A>)(r : Map<K, A>) -> Map<K, A> { switch r.match() { case .Empty: return error("") case .Destructure(_, _, _, let ly, let ry): if ly.size < 2 * ry.size { return single(k)(x1: x)(t1: l)(t2: r) } return double(k)(x1: x)(t1: l)(t2: r) } } private func rotateR<K, A>(k : K)(x : A)(l : Map<K, A>)(r : Map<K, A>) -> Map<K, A> { switch l.match() { case .Empty: return error("") case .Destructure(_, _, _, let ly, let ry): if ly.size < 2 * ry.size { return single(k)(x1: x)(t1: l)(t2: r) } return double(k)(x1: x)(t1: l)(t2: r) } } private func single<K, A>(k1 : K)(x1 : A)(t1 : Map<K, A>)(t2 : Map<K, A>) -> Map<K, A> { switch t2.match() { case .Empty: switch t1.match() { case .Empty: return error("") case .Destructure(_, let k2, let x2, let t1, let t3): return bin(k2, x2, t1, bin(k1, x1, t3, t2)) } case .Destructure(_, let k2, let x2, let t2, let t3): return bin(k2, x2, bin(k1, x1, t1, t2), t3) } } private func double<K, A>(k1 : K)(x1 : A)(t1 : Map<K, A>)(t2 : Map<K, A>) -> Map<K, A> { switch t2.match() { case .Empty: switch t1.match() { case .Empty: return error("") case .Destructure(_, let k2, let x2, let b, let t4): switch b.match() { case .Empty: return error("") case .Destructure(_, let k3, let x3, let t2, let t3): return bin(k3, x3, bin(k2, x2, t1, t2), bin(k1, x1, t3, t4)) } } case .Destructure(_, let k2, let x2, let b, let t4): switch b.match() { case .Empty: return error("") case .Destructure(_, let k3, let x3, let t2, let t3): return bin(k3, x3, bin(k1, x1, t1, t2), bin(k2, x2, t3, t4)) } } } private func glue<K, A>(l : Map<K, A>, r : Map<K, A>) -> Map<K, A> { if l.size == 0 { return r } if r.size == 0 { return l } if l.size > r.size { let ((km, m), l1) = deleteFindMax(l) return balance(km)(x: m)(l: l1)(r: r) } let ((km, m), r1) = deleteFindMin(r) return balance(km)(x: m)(l: l)(r: r1) } private func bin<K, A>(k : K, x : A, l : Map<K, A>, r : Map<K, A>) -> Map<K, A> { return Map(l.size + r.size + 1, k, x, l, r) }
1676594296b59636b06d0019276de00e
28.642336
106
0.578183
false
false
false
false
MatthewYork/DateTools
refs/heads/master
DateToolsSwift/DateTools/TimePeriod.swift
mit
3
// // TimePeriod.swift // DateTools // // Created by Grayson Webster on 8/17/16. // Copyright © 2016 Grayson Webster. All rights reserved. // import Foundation /** * In DateTools, time periods are represented by the TimePeriod protocol. * Required variables and method impleementations are bound below. An inheritable * implementation of the TimePeriodProtocol is available through the TimePeriodClass * * [Visit our github page](https://github.com/MatthewYork/DateTools#time-periods) for more information. */ public protocol TimePeriodProtocol { // MARK: - Variables /** * The start date for a TimePeriod representing the starting boundary of the time period */ var beginning: Date? {get set} /** * The end date for a TimePeriod representing the ending boundary of the time period */ var end: Date? {get set} } public extension TimePeriodProtocol { // MARK: - Information /** * True if the `TimePeriod`'s duration is zero */ var isMoment: Bool { return self.beginning == self.end } /** * The duration of the `TimePeriod` in years. * Returns the max int if beginning or end are nil. */ var years: Int { if self.beginning != nil && self.end != nil { return self.beginning!.yearsEarlier(than: self.end!) } return Int.max } /** * The duration of the `TimePeriod` in weeks. * Returns the max int if beginning or end are nil. */ var weeks: Int { if self.beginning != nil && self.end != nil { return self.beginning!.weeksEarlier(than: self.end!) } return Int.max } /** * The duration of the `TimePeriod` in days. * Returns the max int if beginning or end are nil. */ var days: Int { if self.beginning != nil && self.end != nil { return self.beginning!.daysEarlier(than: self.end!) } return Int.max } /** * The duration of the `TimePeriod` in hours. * Returns the max int if beginning or end are nil. */ var hours: Int { if self.beginning != nil && self.end != nil { return self.beginning!.hoursEarlier(than: self.end!) } return Int.max } /** * The duration of the `TimePeriod` in minutes. * Returns the max int if beginning or end are nil. */ var minutes: Int { if self.beginning != nil && self.end != nil { return self.beginning!.minutesEarlier(than: self.end!) } return Int.max } /** * The duration of the `TimePeriod` in seconds. * Returns the max int if beginning or end are nil. */ var seconds: Int { if self.beginning != nil && self.end != nil { return self.beginning!.secondsEarlier(than: self.end!) } return Int.max } /** * The duration of the `TimePeriod` in a time chunk. * Returns a time chunk with all zeroes if beginning or end are nil. */ var chunk: TimeChunk { if beginning != nil && end != nil { return beginning!.chunkBetween(date: end!) } return TimeChunk(seconds: 0, minutes: 0, hours: 0, days: 0, weeks: 0, months: 0, years: 0) } /** * The length of time between the beginning and end dates of the * `TimePeriod` as a `TimeInterval`. */ var duration: TimeInterval { if self.beginning != nil && self.end != nil { return abs(self.beginning!.timeIntervalSince(self.end!)) } return TimeInterval(Double.greatestFiniteMagnitude) } // MARK: - Time Period Relationships /** * The relationship of the self `TimePeriod` to the given `TimePeriod`. * Relations are stored in Enums.swift. Formal defnitions available in the provided * links: * [GitHub](https://github.com/MatthewYork/DateTools#relationships), * [CodeProject](http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET) * * - parameter period: The time period to compare to self * * - returns: The relationship between self and the given time period */ func relation(to period: TimePeriodProtocol) -> Relation { //Make sure that all start and end points exist for comparison if (self.beginning != nil && self.end != nil && period.beginning != nil && period.end != nil) { //Make sure time periods are of positive durations if (self.beginning!.isEarlier(than: self.end!) && period.beginning!.isEarlier(than: period.end!)) { //Make comparisons if (period.end!.isEarlier(than: self.beginning!)) { return .after } else if (period.end!.equals(self.beginning!)) { return .startTouching } else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isEarlier(than: self.end!)) { return .startInside } else if (period.beginning!.equals(self.beginning!) && period.end!.isLater(than: self.end!)) { return .insideStartTouching } else if (period.beginning!.equals(self.beginning!) && period.end!.isEarlier(than: self.end!)) { return .enclosingStartTouching } else if (period.beginning!.isLater(than: self.beginning!) && period.end!.isEarlier(than: self.end!)) { return .enclosing } else if (period.beginning!.isLater(than: self.beginning!) && period.end!.equals(self.end!)) { return .enclosingEndTouching } else if (period.beginning!.equals(self.beginning!) && period.end!.equals(self.end!)) { return .exactMatch } else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isLater(than: self.end!)) { return .inside } else if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.equals(self.end!)) { return .insideEndTouching } else if (period.beginning!.isEarlier(than: self.end!) && period.end!.isLater(than: self.end!)) { return .endInside } else if (period.beginning!.equals(self.end!) && period.end!.isLater(than: self.end!)) { return .endTouching } else if (period.beginning!.isLater(than: self.end!)) { return .before } } } return .none; } /** * If `self.beginning` and `self.end` are equal to the beginning and end of the * given `TimePeriod`. * * - parameter period: The time period to compare to self * * - returns: True if the periods are the same */ func equals(_ period: TimePeriodProtocol) -> Bool { return self.beginning == period.beginning && self.end == period.end } /** * If the given `TimePeriod`'s beginning is before `self.beginning` and * if the given 'TimePeriod`'s end is after `self.end`. * * - parameter period: The time period to compare to self * * - returns: True if self is inside of the given `TimePeriod` */ func isInside(of period: TimePeriodProtocol) -> Bool { return period.beginning!.isEarlierThanOrEqual(to: self.beginning!) && period.end!.isLaterThanOrEqual(to: self.end!) } /** * If the given Date is after `self.beginning` and before `self.end`. * * - parameter period: The time period to compare to self * - parameter interval: Whether the edge of the date is included in the calculation * * - returns: True if the given `TimePeriod` is inside of self */ func contains(_ date: Date, interval: Interval) -> Bool { if (interval == .open) { return self.beginning!.isEarlier(than: date) && self.end!.isLater(than: date) } else if (interval == .closed){ return (self.beginning!.isEarlierThanOrEqual(to: date) && self.end!.isLaterThanOrEqual(to: date)) } return false } /** * If the given `TimePeriod`'s beginning is after `self.beginning` and * if the given 'TimePeriod`'s after is after `self.end`. * * - parameter period: The time period to compare to self * * - returns: True if the given `TimePeriod` is inside of self */ func contains(_ period: TimePeriodProtocol) -> Bool { return self.beginning!.isEarlierThanOrEqual(to: period.beginning!) && self.end!.isLaterThanOrEqual(to: period.end!) } /** * If self and the given `TimePeriod` share any sub-`TimePeriod`. * * - parameter period: The time period to compare to self * * - returns: True if there is a period of time that is shared by both `TimePeriod`s */ func overlaps(with period: TimePeriodProtocol) -> Bool { //Outside -> Inside if (period.beginning!.isEarlier(than: self.beginning!) && period.end!.isLater(than: self.beginning!)) { return true } //Enclosing else if (period.beginning!.isLaterThanOrEqual(to: self.beginning!) && period.end!.isEarlierThanOrEqual(to: self.end!)){ return true } //Inside -> Out else if(period.beginning!.isEarlier(than: self.end!) && period.end!.isLater(than: self.end!)){ return true } return false } /** * If self and the given `TimePeriod` overlap or the period's edges touch. * * - parameter period: The time period to compare to self * * - returns: True if there is a period of time or moment that is shared by both `TimePeriod`s */ func intersects(with period: TimePeriodProtocol) -> Bool { return self.relation(to: period) != .after && self.relation(to: period) != .before } /** * If self and the given `TimePeriod` have no overlap or touching edges. * * - parameter period: The time period to compare to self * * - returns: True if there is a period of time between self and the given `TimePeriod` not contained by either period */ func hasGap(between period: TimePeriodProtocol) -> Bool { return self.isBefore(period: period) || self.isAfter(period: period) } /** * The period of time between self and the given `TimePeriod` not contained by either. * * - parameter period: The time period to compare to self * * - returns: The gap between the periods. Zero if there is no gap. */ func gap(between period: TimePeriodProtocol) -> TimeInterval { if (self.end!.isEarlier(than: period.beginning!)) { return abs(self.end!.timeIntervalSince(period.beginning!)); } else if (period.end!.isEarlier(than: self.beginning!)){ return abs(period.end!.timeIntervalSince(self.beginning!)); } return 0 } /** * The period of time between self and the given `TimePeriod` not contained by either * as a `TimeChunk`. * * - parameter period: The time period to compare to self * * - returns: The gap between the periods, zero if there is no gap */ func gap(between period: TimePeriodProtocol) -> TimeChunk? { if self.end != nil && period.beginning != nil { return (self.end?.chunkBetween(date: period.beginning!))! } return nil } /** * If self is after the given `TimePeriod` chronologically. (A gap must exist between the two). * * - parameter period: The time period to compare to self * * - returns: True if self is after the given `TimePeriod` */ func isAfter(period: TimePeriodProtocol) -> Bool { return self.relation(to: period) == .after } /** * If self is before the given `TimePeriod` chronologically. (A gap must exist between the two). * * - parameter period: The time period to compare to self * * - returns: True if self is after the given `TimePeriod` */ func isBefore(period: TimePeriodProtocol) -> Bool { return self.relation(to: period) == .before } // MARK: - Shifts //MARK: In Place /** * In place, shift the `TimePeriod` by a `TimeInterval` * * - parameter timeInterval: The time interval to shift the period by */ mutating func shift(by timeInterval: TimeInterval) { self.beginning?.addTimeInterval(timeInterval) self.end?.addTimeInterval(timeInterval) } /** * In place, shift the `TimePeriod` by a `TimeChunk` * * - parameter chunk: The time chunk to shift the period by */ mutating func shift(by chunk: TimeChunk) { self.beginning = self.beginning?.add(chunk) self.end = self.end?.add(chunk) } // MARK: - Lengthen / Shorten // MARK: In Place /** * In place, lengthen the `TimePeriod`, anchored at the beginning, end or center * * - parameter timeInterval: The time interval to lengthen the period by * - parameter anchor: The anchor point from which to make the change */ mutating func lengthen(by timeInterval: TimeInterval, at anchor: Anchor) { switch anchor { case .beginning: self.end = self.end?.addingTimeInterval(timeInterval) break case .center: self.beginning = self.beginning?.addingTimeInterval(-timeInterval/2.0) self.end = self.end?.addingTimeInterval(timeInterval/2.0) break case .end: self.beginning = self.beginning?.addingTimeInterval(-timeInterval) break } } /** * In place, lengthen the `TimePeriod`, anchored at the beginning or end * * - parameter chunk: The time chunk to lengthen the period by * - parameter anchor: The anchor point from which to make the change */ mutating func lengthen(by chunk: TimeChunk, at anchor: Anchor) { switch anchor { case .beginning: self.end = self.end?.add(chunk) break case .center: // Do not lengthen by TimeChunk at center print("Mutation via chunk from center anchor is not supported.") break case .end: self.beginning = self.beginning?.subtract(chunk) break } } /** * In place, shorten the `TimePeriod`, anchored at the beginning, end or center * * - parameter timeInterval: The time interval to shorten the period by * - parameter anchor: The anchor point from which to make the change */ mutating func shorten(by timeInterval: TimeInterval, at anchor: Anchor) { switch anchor { case .beginning: self.end = self.end?.addingTimeInterval(-timeInterval) break case .center: self.beginning = self.beginning?.addingTimeInterval(timeInterval/2.0) self.end = self.end?.addingTimeInterval(-timeInterval/2.0) break case .end: self.beginning = self.beginning?.addingTimeInterval(timeInterval) break } } /** * In place, shorten the `TimePeriod`, anchored at the beginning or end * * - parameter chunk: The time chunk to shorten the period by * - parameter anchor: The anchor point from which to make the change */ mutating func shorten(by chunk: TimeChunk, at anchor: Anchor) { switch anchor { case .beginning: self.end = self.end?.subtract(chunk) break case .center: // Do not shorten by TimeChunk at center print("Mutation via chunk from center anchor is not supported.") break case .end: self.beginning = self.beginning?.add(chunk) break } } } /** * In DateTools, time periods are represented by the case TimePeriod class * and come with a suite of initializaiton, manipulation, and comparison methods * to make working with them a breeze. * * [Visit our github page](https://github.com/MatthewYork/DateTools#time-periods) for more information. */ open class TimePeriod: TimePeriodProtocol { // MARK: - Variables /** * The start date for a TimePeriod representing the starting boundary of the time period */ public var beginning: Date? /** * The end date for a TimePeriod representing the ending boundary of the time period */ public var end: Date? // MARK: - Initializers public init() { } public init(beginning: Date?, end: Date?) { self.beginning = beginning self.end = end } public init(beginning: Date, duration: TimeInterval) { self.beginning = beginning self.end = beginning + duration } public init(end: Date, duration: TimeInterval) { self.end = end self.beginning = end.addingTimeInterval(-duration) } public init(beginning: Date, chunk: TimeChunk) { self.beginning = beginning self.end = beginning + chunk } public init(end: Date, chunk: TimeChunk) { self.end = end self.beginning = end - chunk } public init(chunk: TimeChunk) { self.beginning = Date() self.end = self.beginning?.add(chunk) } // MARK: - Shifted /** * Shift the `TimePeriod` by a `TimeInterval` * * - parameter timeInterval: The time interval to shift the period by * * - returns: The new, shifted `TimePeriod` */ public func shifted(by timeInterval: TimeInterval) -> TimePeriod { let timePeriod = TimePeriod() timePeriod.beginning = self.beginning?.addingTimeInterval(timeInterval) timePeriod.end = self.end?.addingTimeInterval(timeInterval) return timePeriod } /** * Shift the `TimePeriod` by a `TimeChunk` * * - parameter chunk: The time chunk to shift the period by * * - returns: The new, shifted `TimePeriod` */ public func shifted(by chunk: TimeChunk) -> TimePeriod { let timePeriod = TimePeriod() timePeriod.beginning = self.beginning?.add(chunk) timePeriod.end = self.end?.add(chunk) return timePeriod } // MARK: - Lengthen / Shorten // MARK: New /** * Lengthen the `TimePeriod` by a `TimeInterval` * * - parameter timeInterval: The time interval to lengthen the period by * - parameter anchor: The anchor point from which to make the change * * - returns: The new, lengthened `TimePeriod` */ public func lengthened(by timeInterval: TimeInterval, at anchor: Anchor) -> TimePeriod { let timePeriod = TimePeriod() switch anchor { case .beginning: timePeriod.beginning = self.beginning timePeriod.end = self.end?.addingTimeInterval(timeInterval) break case .center: timePeriod.beginning = self.beginning?.addingTimeInterval(-timeInterval) timePeriod.end = self.end?.addingTimeInterval(timeInterval) break case .end: timePeriod.beginning = self.beginning?.addingTimeInterval(-timeInterval) timePeriod.end = self.end break } return timePeriod } /** * Lengthen the `TimePeriod` by a `TimeChunk` * * - parameter chunk: The time chunk to lengthen the period by * - parameter anchor: The anchor point from which to make the change * * - returns: The new, lengthened `TimePeriod` */ public func lengthened(by chunk: TimeChunk, at anchor: Anchor) -> TimePeriod { let timePeriod = TimePeriod() switch anchor { case .beginning: timePeriod.beginning = beginning timePeriod.end = end?.add(chunk) break case .center: print("Mutation via chunk from center anchor is not supported.") break case .end: timePeriod.beginning = beginning?.add(-chunk) timePeriod.end = end break } return timePeriod } /** * Shorten the `TimePeriod` by a `TimeInterval` * * - parameter timeInterval: The time interval to shorten the period by * - parameter anchor: The anchor point from which to make the change * * - returns: The new, shortened `TimePeriod` */ public func shortened(by timeInterval: TimeInterval, at anchor: Anchor) -> TimePeriod { let timePeriod = TimePeriod() switch anchor { case .beginning: timePeriod.beginning = beginning timePeriod.end = end?.addingTimeInterval(-timeInterval) break case .center: timePeriod.beginning = beginning?.addingTimeInterval(-timeInterval/2) timePeriod.end = end?.addingTimeInterval(timeInterval/2) break case .end: timePeriod.beginning = beginning?.addingTimeInterval(timeInterval) timePeriod.end = end break } return timePeriod } /** * Shorten the `TimePeriod` by a `TimeChunk` * * - parameter chunk: The time chunk to shorten the period by * - parameter anchor: The anchor point from which to make the change * * - returns: The new, shortened `TimePeriod` */ public func shortened(by chunk: TimeChunk, at anchor: Anchor) -> TimePeriod { let timePeriod = TimePeriod() switch anchor { case .beginning: timePeriod.beginning = beginning timePeriod.end = end?.subtract(chunk) break case .center: print("Mutation via chunk from center anchor is not supported.") break case .end: timePeriod.beginning = beginning?.add(-chunk) timePeriod.end = end break } return timePeriod } // MARK: - Operator Overloads /** * Operator overload for checking if two `TimePeriod`s are equal */ public static func ==(leftAddend: TimePeriod, rightAddend: TimePeriod) -> Bool { return leftAddend.equals(rightAddend) } // Default anchor = beginning /** * Operator overload for lengthening a `TimePeriod` by a `TimeInterval` */ public static func +(leftAddend: TimePeriod, rightAddend: TimeInterval) -> TimePeriod { return leftAddend.lengthened(by: rightAddend, at: .beginning) } /** * Operator overload for lengthening a `TimePeriod` by a `TimeChunk` */ public static func +(leftAddend: TimePeriod, rightAddend: TimeChunk) -> TimePeriod { return leftAddend.lengthened(by: rightAddend, at: .beginning) } // Default anchor = beginning /** * Operator overload for shortening a `TimePeriod` by a `TimeInterval` */ public static func -(minuend: TimePeriod, subtrahend: TimeInterval) -> TimePeriod { return minuend.shortened(by: subtrahend, at: .beginning) } /** * Operator overload for shortening a `TimePeriod` by a `TimeChunk` */ public static func -(minuend: TimePeriod, subtrahend: TimeChunk) -> TimePeriod { return minuend.shortened(by: subtrahend, at: .beginning) } /** * Operator overload for checking if a `TimePeriod` is equal to a `TimePeriodProtocol` */ public static func ==(left: TimePeriod, right: TimePeriodProtocol) -> Bool { return left.equals(right) } }
8486af1245a4fdff08ed2fdda4255219
32.877437
127
0.589418
false
false
false
false
IngmarStein/swift
refs/heads/master
test/Profiler/coverage_label.swift
apache-2.0
48
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -suppress-warnings -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_label %s | %FileCheck %s // CHECK-LABEL: sil_coverage_map {{.*}}// coverage_label.foo func foo() { // CHECK-DAG: [[@LINE]]:12 -> [[@LINE+19]]:2 : 0 var x : Int32 = 0 label1: do { // CHECK-DAG: [[@LINE]]:14 -> [[@LINE+4]]:4 : 0 x += 1 break label1 x += 2 // CHECK-DAG: [[@LINE]]:5 -> [[@LINE+1]]:4 : zero } label2: do { // CHECK-DAG: [[@LINE]]:14 -> [[@LINE+7]]:4 : 0 x += 3 // CHECK-DAG: [[@LINE+1]]:11 -> [[@LINE+1]]:17 : 0 while (true) { // CHECK-DAG: [[@LINE]]:18 -> [[@LINE+3]]:6 : 1 x += 4 break label2 // Note: This exit affects the condition counter expr @ L15. } // CHECK-DAG: [[@LINE]]:6 -> [[@LINE+2]]:4 : (0 - 1) x += 5 } x += 6 } foo()
1cec5ddeb679db37bc5410c0c4a33901
34.96
193
0.517241
false
false
false
false
realm/SwiftLint
refs/heads/main
Source/SwiftLintFramework/Rules/Lint/OrphanedDocCommentRule.swift
mit
1
import IDEUtils struct OrphanedDocCommentRule: SourceKitFreeRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "orphaned_doc_comment", name: "Orphaned Doc Comment", description: "A doc comment should be attached to a declaration.", kind: .lint, nonTriggeringExamples: [ Example(""" /// My great property var myGreatProperty: String! """), Example(""" ////////////////////////////////////// // // Copyright header. // ////////////////////////////////////// """), Example(""" /// Look here for more info: https://github.com. var myGreatProperty: String! """), Example(""" /// Look here for more info: /// https://github.com. var myGreatProperty: String! """) ], triggeringExamples: [ Example(""" ↓/// My great property // Not a doc string var myGreatProperty: String! """), Example(""" ↓/// Look here for more info: https://github.com. // Not a doc string var myGreatProperty: String! """) ] ) func validate(file: SwiftLintFile) -> [StyleViolation] { file.syntaxClassifications .filter { $0.kind != .none } .pairs() .compactMap { first, second in let firstByteRange = first.range.toSourceKittenByteRange() guard let second = second, first.kind == .docLineComment || first.kind == .docBlockComment, second.kind == .lineComment || second.kind == .blockComment, let firstString = file.stringView.substringWithByteRange(firstByteRange), // These patterns are often used for "file header" style comments !firstString.starts(with: "////") && !firstString.starts(with: "/***") else { return nil } return StyleViolation(ruleDescription: Self.description, severity: configuration.severity, location: Location(file: file, byteOffset: firstByteRange.location)) } } } private extension Sequence { func pairs() -> Zip2Sequence<Self, [Element?]> { return zip(self, Array(dropFirst()) + [nil]) } }
0f88ee2bf91dc99b4510e1ad38d22d59
34.090909
106
0.484826
false
true
false
false
1457792186/JWSwift
refs/heads/master
SwiftWX/LGWeChatKit/LGChatKit/conversion/view/LGChatVideoCell.swift
apache-2.0
1
// // LGChatVideoCell.swift // LGWeChatKit // // Created by jamy on 11/4/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit import AVFoundation class LGChatVideoCell: LGChatBaseCell { let videoIndicator: UIImageView override init(style: UITableViewCellStyle, reuseIdentifier: String?) { videoIndicator = UIImageView() super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundImageView.addSubview(videoIndicator) videoIndicator.translatesAutoresizingMaskIntoConstraints = false backgroundImageView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 160)) backgroundImageView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 120)) contentView.addConstraint(NSLayoutConstraint(item: videoIndicator, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)) contentView.addConstraint(NSLayoutConstraint(item: videoIndicator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 40)) contentView.addConstraint(NSLayoutConstraint(item: videoIndicator, attribute: .centerY, relatedBy: .equal, toItem: backgroundImageView, attribute: .centerY, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: videoIndicator, attribute: .centerX, relatedBy: .equal, toItem: backgroundImageView, attribute: .centerX, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: -5)) videoIndicator.image = UIImage(named: "MessageVideoPlay") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setMessage(_ message: Message) { super.setMessage(message) let message = message as! videoMessage let asset = AVAsset(url: message.url as URL) let imageGenerator = AVAssetImageGenerator(asset: asset) do { let cgImage = try imageGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil) backgroundImageView.image = UIImage(cgImage: cgImage) try! FileManager.default.removeItem(at: message.url as URL) } catch let error as NSError { NSLog("%@", error) } } }
0d8fad21c7fd71c3fe8a6826b502fc4d
51.153846
198
0.713127
false
false
false
false
nohirap/ANActionSheet
refs/heads/master
ANActionSheet/Classes/Models/ANHeaderViewModel.swift
mit
1
// // ANHeaderViewModel.swift // Pods // // Created by nohirap on 2016/06/10. // Copyright © 2016 nohirap. All rights reserved. // struct ANHeaderViewModel { var title = "" var message = "" var headerBackgroundColor = UIColor.defaultBackgroundColor() var titleColor = UIColor.defaultTextColor() var messageColor = UIColor.defaultTextColor() }
a7a8d5d9c139fafafdcc9e792ff522f8
23.533333
64
0.69837
false
false
false
false
jkolb/Swiftish
refs/heads/master
Sources/Swiftish/PerspectiveProjection.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015-2017 Justin Kolb 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. */ /* fovy Specifies the field of view angle (in radians) in the y direction. aspect Indicates the aspect ratio. This value determines the field of view in the x direction and is the ratio of x (width) to y (height). x/y zNear Specifies the distance from the viewer to the closest clipping plane. This value must be positive. zNear must never be set to 0. zFar Specifies the distance from the viewer to the farthest clipping plane. This value must be positive. Similar to gluPerspective: https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml Given: f = cotangent(fovy / 2) ( f ) | ------ 0 0 0 | | aspect | | | | | | 0 f 0 0 | | | | | | zFar+zNear 2*zFar*zNear | | 0 0 ---------- ------------ | | zNear-zFar zNear-zFar | | | | | | 0 0 -1 0 | ( ) */ public struct PerspectiveProjection<T: Vectorable> : Hashable { public var fovx: T { get { return 2 * T.atan(T.tan(fovy / 2) * aspectRatio) } set { fovy = 2 * T.atan(T.tan(newValue / 2) * inverseAspectRatio) } } public var fovy: T public var aspectRatio: T public var inverseAspectRatio: T { get { return 1 / aspectRatio; } set { aspectRatio = 1 / newValue } } public var zNear: T public var zFar: T public init(fovx: T, aspectRatio: T, zNear: T, zFar: T) { precondition(fovx > 0) precondition(fovx < T.pi) self.init( fovy: 2 * T.atan(T.tan(fovx / 2) * (1 / aspectRatio)), aspectRatio: aspectRatio, zNear: zNear, zFar: zFar ) } public init(fovy: T, aspectRatio: T, zNear: T, zFar: T) { precondition(fovy > 0) precondition(fovy < T.pi) precondition(aspectRatio > 0) precondition(zNear > 0) precondition(zFar > zNear) self.fovy = fovy self.aspectRatio = aspectRatio self.zNear = zNear self.zFar = zFar } public var matrix: Matrix4x4<T> { let x = fovy / 2 let s = T.sin(x) let c = T.cos(x) // cotangent(x) = cos(x) / sin(x) let f = c / s let col0 = Vector4<T>( f / aspectRatio, 0, 0, 0 ) let col1 = Vector4<T>( 0, f, 0, 0 ) let col2 = Vector4<T>( 0, 0, (zFar + zNear) / (zNear - zFar), -1 ) let col3 = Vector4<T>( 0, 0, (2 * zFar * zNear) / (zNear - zFar), 0 ) return Matrix4x4(col0, col1, col2, col3) } public var frustum: Frustum<T> { return Frustum<T>(fovx: fovx, fovy: fovy, zNear: zNear, zFar: zFar) } }
6772a100eea3a23bc3df1d0303bbb3d4
32.02963
143
0.519175
false
false
false
false
ColinConduff/BlocFit
refs/heads/master
BlocFit/Auxiliary Components/Friend Table/FriendCell/FriendCellController.swift
mit
1
// // FriendCellController.swift // BlocFit // // Created by Colin Conduff on 12/24/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import Foundation protocol FriendCellControllerProtocol: class { var username: String? { get } var trusted: String? { get } var firstname: String? { get } var hiddenFirstname: Bool? { get } var score: String? { get } init(blocMember: BlocMember) } class FriendCellController: FriendCellControllerProtocol { var username: String? var trusted: String? var firstname: String? var hiddenFirstname: Bool? var score: String? required init(blocMember: BlocMember) { setBlocMemberData(blocMember: blocMember) } private func setBlocMemberData(blocMember: BlocMember) { username = blocMember.username ?? "NA" trusted = stringFor(trusted: blocMember.trusted) firstname = blocMember.firstname hiddenFirstname = (firstname == nil) score = String(blocMember.totalScore) } private func stringFor(trusted: Bool) -> String { return trusted ? "Trusted" : "Untrusted" } }
2e9d750132db5088fd47261edfdec3e3
24.8
60
0.657192
false
false
false
false
metova/MetovaBase
refs/heads/master
MetovaBaseTests/BaseViewControllerTests/NotificationHelper.swift
mit
1
// // NotificationHelper.swift // MetovaBase // // Created by Nick Griffith on 4/22/16. // Copyright (c) 2016 Metova Inc. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit func keyboardFrameBeginNotificationNoUserInfo() -> Notification { return Notification(name: Notification.Name(rawValue: UIResponder.keyboardFrameBeginUserInfoKey), object: nil) } func keyboardFrameEndNotificationNoUserInfo() -> Notification { return Notification(name: Notification.Name(rawValue: UIResponder.keyboardFrameEndUserInfoKey), object: nil) } func keyboardFrameBeginNotification(beginFrame: CGRect?, endFrame: CGRect?) -> Notification { return frame(withNotificationName: UIResponder.keyboardFrameBeginUserInfoKey, beginFrame: beginFrame, endFrame: endFrame) } func keyboardFrameEndNotification(beginFrame: CGRect?, endFrame: CGRect?) -> Notification { return frame(withNotificationName: UIResponder.keyboardFrameEndUserInfoKey, beginFrame: beginFrame, endFrame: endFrame) } private func frame(withNotificationName name: String, beginFrame: CGRect?, endFrame: CGRect?) -> Notification { var userInfo = [String: AnyObject]() if let beginFrame = beginFrame { userInfo[UIResponder.keyboardFrameBeginUserInfoKey] = NSValue(cgRect: beginFrame) } if let endFrame = endFrame { userInfo[UIResponder.keyboardFrameEndUserInfoKey] = NSValue(cgRect: endFrame) } return Notification(name: Notification.Name(rawValue: name), object: nil, userInfo: userInfo) }
5182a2acfba1e033d9d4f5cb20dabb24
42.15
125
0.758594
false
false
false
false
tanjo/TJTrigram
refs/heads/master
TJTrigram/Classes/TJTrigram.swift
mit
1
// // TJTrigram.swift // import UIKit public class TJTrigram: NSObject { public var content: String? { didSet { guard let content = self.content else { return } self.container = self.split(content) } } var container: [String] = [] // MARK: - Initializer public convenience init(content: String) { self.init() self.content = content self.container = self.split(content) } private override init() { super.init() } // MARK: - Public methods private func result(target: String) -> ([String], [String]) { let targetContainer = self.split(target) var sharedTrigram: [String] = [] for ownedWord in self.container { for targetWord in targetContainer { if ownedWord == targetWord { sharedTrigram.append(ownedWord) } } } return (Array(Set(sharedTrigram)), Array(Set(self.container + targetContainer))) } public func result(target: String) -> Double { let (sharedWords, allWords) = self.result(target) return Double(sharedWords.count) / Double(allWords.count) } // MARK: - Private methods private func split(target: String?) -> [String] { guard let target = target where target.characters.count > 2 else { return [] } var container: [String] = [] for i in 0..<target.characters.count - 2 { let startIndex = target.startIndex.advancedBy(i) let endIndex = target.startIndex.advancedBy(i + 2) container.append(target.substringWithRange(startIndex...endIndex)) } return container } }
6e4fbc3f1053cd7d6a9fb28cb123f6fb
26
88
0.546841
false
false
false
false
Witcast/witcast-ios
refs/heads/develop
OMS-WH/Utilities/Libs/RefreshControl/Source/Classes/ElasticRefreshHeader.swift
apache-2.0
4
// // ElasticRefreshHeader.swift // PullToRefreshKit // // Created by huangwenchen on 16/7/29. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit open class ElasticRefreshHeader: UIView,RefreshableHeader { let control:ElasticRefreshControl open let textLabel:UILabel = UILabel(frame: CGRect(x: 0,y: 0,width: 120,height: 40)) open let imageView:UIImageView = UIImageView(frame: CGRect.zero) fileprivate var textDic = [RefreshKitHeaderText:String]() fileprivate let totalHegiht:CGFloat = 80.0 override init(frame: CGRect) { control = ElasticRefreshControl(frame: frame) let adjustFrame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: totalHegiht) super.init(frame: adjustFrame) self.autoresizingMask = .flexibleWidth self.backgroundColor = UIColor.white imageView.sizeToFit() imageView.frame = CGRect(x: 0, y: 0, width: 16, height: 16) textLabel.font = UIFont.systemFont(ofSize: 12) textLabel.textAlignment = .center textLabel.textColor = UIColor.darkGray addSubview(control) addSubview(textLabel) addSubview(imageView) textDic[.refreshSuccess] = PullToRefreshKitHeaderString.refreshSuccess textDic[.refreshFailure] = PullToRefreshKitHeaderString.refreshFailure textLabel.text = textDic[.pullToRefresh] } open func setText(_ text:String,mode:RefreshKitHeaderText){ textDic[mode] = text } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func layoutSubviews() { super.layoutSubviews() control.frame = self.bounds imageView.center = CGPoint(x: frame.width/2 - 40 - 40, y: totalHegiht * 0.75) textLabel.center = CGPoint(x: frame.size.width/2, y: totalHegiht * 0.75); } open override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if let superView = newSuperview{ self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: superView.frame.size.width, height: self.frame.size.height) } } // MARK: - Refreshable Header - open func heightForRefreshingState() -> CGFloat { return totalHegiht/2.0 } open func heightForFireRefreshing()->CGFloat{ return totalHegiht } open func percentUpdateDuringScrolling(_ percent:CGFloat){ self.control.animating = false if percent > 0.5 && percent <= 1.0{ self.control.progress = (percent - 0.5)/0.5 }else if percent <= 0.5{ self.control.progress = 0.0 }else{ self.control.progress = 1.0 } } open func didBeginRefreshingState() { self.control.animating = true } open func didBeginEndRefershingAnimation(_ result:RefreshResult) { switch result { case .success: self.control.isHidden = true imageView.isHidden = false textLabel.isHidden = false textLabel.text = textDic[.refreshSuccess] imageView.image = UIImage(named: "success", in: Bundle(for: DefaultRefreshHeader.self), compatibleWith: nil) case .failure: self.control.isHidden = true imageView.isHidden = false textLabel.isHidden = false textLabel.text = textDic[.refreshFailure] imageView.image = UIImage(named: "failure", in: Bundle(for: DefaultRefreshHeader.self), compatibleWith: nil) case .none: self.control.isHidden = false imageView.isHidden = true textLabel.isHidden = true textLabel.text = textDic[.pullToRefresh] imageView.image = nil } } open func didCompleteEndRefershingAnimation(_ result:RefreshResult) { self.control.isHidden = false self.imageView.isHidden = true self.textLabel.isHidden = true } }
eaf28776d26bd8302c438eb1ff402876
38.153846
146
0.648821
false
false
false
false
zhouxj6112/ARKit
refs/heads/master
ARKitInteraction/ARKitInteraction/Additional View Controllers/VirtualObjectSelection.swift
apache-2.0
1
/* See LICENSE folder for this sample’s licensing information. Abstract: Popover view controller for choosing virtual objects to place in the AR scene. */ import UIKit // MARK: - ObjectCell class ObjectCell: UITableViewCell { static let reuseIdentifier = "ObjectCell" @IBOutlet weak var objectTitleLabel: UILabel! @IBOutlet weak var objectImageView: UIImageView! var modelName = "" { didSet { objectTitleLabel.text = modelName.capitalized objectImageView.image = UIImage(named: modelName) // 加载Assets里面的图片 } } } // MARK: - VirtualObjectSelectionViewControllerDelegate /// A protocol for reporting which objects have been selected. protocol VirtualObjectSelectionViewControllerDelegate: class { func virtualObjectSelectionViewController(_ selectionViewController: VirtualObjectSelectionViewController, didSelectObject: VirtualObject) func virtualObjectSelectionViewController(_ selectionViewController: VirtualObjectSelectionViewController, didDeselectObject: VirtualObject) } /// A custom table view controller to allow users to select `VirtualObject`s for placement in the scene. class VirtualObjectSelectionViewController: UITableViewController { /// The collection of `VirtualObject`s to select from. var virtualObjects = [VirtualObject]() /// The rows of the currently selected `VirtualObject`s. var selectedVirtualObjectRows = IndexSet() weak var delegate: VirtualObjectSelectionViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() tableView.separatorEffect = UIVibrancyEffect(blurEffect: UIBlurEffect(style: .light)) } override func viewWillLayoutSubviews() { preferredContentSize = CGSize(width: 250, height: tableView.contentSize.height) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let object = virtualObjects[indexPath.row] // Check if the current row is already selected, then deselect it. if selectedVirtualObjectRows.contains(indexPath.row) { delegate?.virtualObjectSelectionViewController(self, didDeselectObject: object) } else { delegate?.virtualObjectSelectionViewController(self, didSelectObject: object) } dismiss(animated: true, completion: nil) } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return virtualObjects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: ObjectCell.reuseIdentifier, for: indexPath) as? ObjectCell else { fatalError("Expected `\(ObjectCell.self)` type for reuseIdentifier \(ObjectCell.reuseIdentifier). Check the configuration in Main.storyboard.") } cell.modelName = virtualObjects[indexPath.row].modelName if selectedVirtualObjectRows.contains(indexPath.row) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) cell?.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) } override func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) cell?.backgroundColor = .clear } }
b29cbb6a0024d426689f3d311f4ce05b
36.336634
155
0.710422
false
false
false
false
fcanas/Compass
refs/heads/master
Compass/GeoVector.swift
mit
1
// // GeoVector.swift // Compass // // Created by Fabian Canas on 6/3/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import CoreLocation func bearing(start: CLLocationCoordinate2D, end: CLLocationCoordinate2D) -> Radian { let (lat1, lng1) = start.asRadians let (lat2, lng2) = end.asRadians return Radian(atan2(sin(lng2 - lng1) * cos(lat2), cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(lng2-lng1))) } extension Vector3 { public init(coordinate: CLLocationCoordinate2D) { let latitude :Radian = Radian(angle: Degree(coordinate.latitude)) let longitude :Radian = Radian(angle: Degree(coordinate.longitude)) dx = sin(longitude) * cos(latitude) dy = cos(longitude) * cos(latitude) dz = sin(latitude) } } extension CLLocationCoordinate2D { init(v: Vector3) { longitude = Degree(angle:Radian(atan2( v.dy, v.dx ))).value latitude = Degree(angle: Radian(acos( v.dz / magnitude(v) ))).value assert(CLLocationCoordinate2DIsValid(self), "Making an invalid coordinate from a vector") } var asRadians :(latitude: Radian, longitude: Radian){ get { return (latitude: Radian(angle:Degree(self.latitude)), longitude: Radian(angle:Degree(self.latitude))) } } } func distance(c1: CLLocationCoordinate2D, c2: CLLocationCoordinate2D) -> CLLocationDistance { let angularDistance :Radian = distance(c1, c2) return angularDistance.value * 6373000 } func distance(c1: CLLocationCoordinate2D, c2: CLLocationCoordinate2D) -> Radian { let (lat1, lng1) = c1.asRadians let (lat2, lng2) = c2.asRadians let dLat_2 = (lat1 - lat2).value/2 let dLng_2 = (lng1 - lng2).value/2 let a = sin(dLat_2) * sin(dLat_2) + sin(dLng_2) * sin(dLng_2) * cos(lat1) * cos(lat2) return Radian(2 * atan2(sqrt(a), sqrt(1-a))) }
001301d2e73d536f0eb41d5612de6b00
33.592593
114
0.662206
false
false
false
false
bryanrezende/Audiobook-Player
refs/heads/master
Audiobook Player/ListBooksViewController.swift
gpl-3.0
1
// // ListBooksViewController.swift // Audiobook Player // // Created by Gianni Carlo on 7/7/16. // Copyright © 2016 Tortuga Power. All rights reserved. // import UIKit import MediaPlayer import Chameleon import MBProgressHUD class ListBooksViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var emptyListContainerView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var footerView: UIView! @IBOutlet weak var footerImageView: UIImageView! @IBOutlet weak var footerTitleLabel: UILabel! @IBOutlet weak var footerHeightConstraint: NSLayoutConstraint! @IBOutlet weak var footerPlayButton: UIButton! //keep in memory images to toggle play/pause let miniPlayImage = UIImage(named: "miniPlayButton") let miniPauseButton = UIImage(named: "miniPauseButton") //TableView's datasource var bookArray = [Book]() //keep in memory current Documents folder let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() //pull-down-to-refresh support self.refreshControl.attributedTitle = NSAttributedString(string: "Pull down to reload books") self.refreshControl.addTarget(self, action: #selector(loadFiles), for: .valueChanged) self.tableView.addSubview(self.refreshControl) //enables pop gesture on pushed controller self.navigationController!.interactivePopGestureRecognizer!.delegate = self //fixed tableview having strange offset self.edgesForExtendedLayout = UIRectEdge() //set colors self.navigationController?.navigationBar.barTintColor = UIColor.flatSkyBlue() self.footerView.backgroundColor = UIColor.flatSkyBlue() self.footerView.isHidden = true self.tableView.tableFooterView = UIView() //set external control listeners let skipForward = MPRemoteCommandCenter.shared().skipForwardCommand skipForward.isEnabled = true skipForward.addTarget(self, action: #selector(self.forwardPressed(_:))) skipForward.preferredIntervals = [30] let skipRewind = MPRemoteCommandCenter.shared().skipBackwardCommand skipRewind.isEnabled = true skipRewind.addTarget(self, action: #selector(self.rewindPressed(_:))) skipRewind.preferredIntervals = [30] let playCommand = MPRemoteCommandCenter.shared().playCommand playCommand.isEnabled = true playCommand.addTarget(self, action: #selector(self.didPressPlay(_:))) let pauseCommand = MPRemoteCommandCenter.shared().pauseCommand pauseCommand.isEnabled = true pauseCommand.addTarget(self, action: #selector(self.didPressPlay(_:))) //set tap handler to show detail on tap on footer view let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.didPressShowDetail(_:))) self.footerView.addGestureRecognizer(tapRecognizer) //register to audio-interruption notifications NotificationCenter.default.addObserver(self, selector: #selector(self.handleAudioInterruptions(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: nil) //register for appDelegate openUrl notifications NotificationCenter.default.addObserver(self, selector: #selector(self.loadFiles), name: Notification.Name.AudiobookPlayer.openURL, object: nil) //register for percentage change notifications NotificationCenter.default.addObserver(self, selector: #selector(self.updatePercentage(_:)), name: Notification.Name.AudiobookPlayer.updatePercentage, object: nil) //register for book end notifications NotificationCenter.default.addObserver(self, selector: #selector(self.bookEnd(_:)), name: Notification.Name.AudiobookPlayer.bookEnd, object: nil) //register for remote events UIApplication.shared.beginReceivingRemoteControlEvents() self.loadFiles() self.footerHeightConstraint.constant = 0 } //no longer need to deregister observers for iOS 9+! //https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11NotificationCenter deinit { //for iOS 8 NotificationCenter.default.removeObserver(self) UIApplication.shared.endReceivingRemoteControlEvents() } //Playback may be interrupted by calls. Handle pause @objc func handleAudioInterruptions(_ notification:Notification){ guard let audioPlayer = PlayerManager.sharedInstance.audioPlayer else { return } if audioPlayer.isPlaying { self.didPressPlay(self.footerPlayButton) } } /** * Load local files and process them (rename them if necessary) * Spaces in file names can cause side effects when trying to load the data */ @objc func loadFiles() { //load local files let loadingWheel = MBProgressHUD.showAdded(to: self.view, animated: true) loadingWheel?.labelText = "Loading Books" DataManager.loadBooks { (books) in self.bookArray = books self.refreshControl.endRefreshing() MBProgressHUD.hideAllHUDs(for: self.view, animated: true) //show/hide instructions view self.emptyListContainerView.isHidden = !self.bookArray.isEmpty self.tableView.reloadData() } } /** * Set play or pause image on button */ func setPlayImage(){ if PlayerManager.sharedInstance.isPlaying() { self.footerPlayButton.setImage(self.miniPauseButton, for: UIControlState()) }else{ self.footerPlayButton.setImage(self.miniPlayImage, for: UIControlState()) } } func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if(navigationController!.viewControllers.count > 1){ return true } return false } @IBAction func didPressReload(_ sender: UIBarButtonItem) { self.loadFiles() } @IBAction func didPressPlay(_ sender: UIButton) { PlayerManager.sharedInstance.playPressed() self.setPlayImage() } @objc func forwardPressed(_ sender: UIButton) { PlayerManager.sharedInstance.forwardPressed() } @objc func rewindPressed(_ sender: UIButton) { PlayerManager.sharedInstance.rewindPressed() } @IBAction func didPressShowDetail(_ sender: UIButton) { guard let indexPath = self.tableView.indexPathForSelectedRow else { return } self.tableView(self.tableView, didSelectRowAt: indexPath) } //percentage callback @objc func updatePercentage(_ notification:Notification) { guard let userInfo = notification.userInfo, let fileURL = userInfo["fileURL"] as? URL, let percentageString = userInfo["percentageString"] as? String else { return } guard let index = (self.bookArray.index { (book) -> Bool in return book.fileURL == fileURL }), let cell = self.tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? BookCellView else { return } cell.completionLabel.text = percentageString } @objc func bookEnd(_ notification:Notification) { self.setPlayImage() } } extension ListBooksViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.bookArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "BookCellView", for: indexPath) as! BookCellView let book = self.bookArray[indexPath.row] cell.titleLabel.text = book.title cell.titleLabel.highlightedTextColor = UIColor.black cell.authorLabel.text = book.author //NOTE: we should have a default image for artwork cell.artworkImageView.image = book.artwork //load stored percentage value cell.completionLabel.text = UserDefaults.standard.string(forKey: self.bookArray[indexPath.row].identifier + "_percentage") ?? "0%" cell.completionLabel.textColor = UIColor.flatGreenColorDark() return cell } } extension ListBooksViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .default, title: "Delete") { (action, indexPath) in let alert = UIAlertController(title: "Confirmation", message: "Are you sure you would like to remove this audiobook?", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { action in tableView.setEditing(false, animated: true) })) alert.addAction(UIAlertAction(title: "Yes", style: .destructive, handler: { action in let book = self.bookArray.remove(at: indexPath.row) try! FileManager.default.removeItem(at: book.fileURL) tableView.beginUpdates() tableView.deleteRows(at: [indexPath], with: .none) tableView.endUpdates() self.emptyListContainerView.isHidden = !self.bookArray.isEmpty })) alert.popoverPresentationController?.sourceView = self.view alert.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(alert, animated: true, completion: nil) } deleteAction.backgroundColor = UIColor.red return [deleteAction] } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 86 } func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { guard let index = tableView.indexPathForSelectedRow else { return indexPath } tableView.deselectRow(at: index, animated: true) return indexPath } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let book = self.bookArray[indexPath.row] let cell = tableView.cellForRow(at: indexPath) as! BookCellView let title = cell.titleLabel.text ?? book.fileURL.lastPathComponent let author = cell.authorLabel.text ?? "Unknown Author" let storyboard = UIStoryboard(name: "Main", bundle: nil) let playerVC = storyboard.instantiateViewController(withIdentifier: "PlayerViewController") as! PlayerViewController playerVC.currentBook = book //show the current player self.presentModal(playerVC, animated: true) { self.footerView.isHidden = false self.footerTitleLabel.text = title + " - " + author self.footerImageView.image = cell.artworkImageView.image self.footerHeightConstraint.constant = 55 self.setPlayImage() } } } extension ListBooksViewController:UIDocumentMenuDelegate { @IBAction func didPressImportOptions(_ sender: UIBarButtonItem) { let sheet = UIAlertController(title: "Import Books", message: nil, preferredStyle: .actionSheet) let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) let localButton = UIAlertAction(title: "From Local Apps", style: .default) { (action) in let providerList = UIDocumentMenuViewController(documentTypes: ["public.audio"], in: .import) providerList.delegate = self; providerList.popoverPresentationController?.sourceView = self.view providerList.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(providerList, animated: true, completion: nil) } let airdropButton = UIAlertAction(title: "AirDrop", style: .default) { (action) in self.showAlert("AirDrop", message: "Make sure AirDrop is enabled.\n\nOnce you transfer the file to your device via AirDrop, choose 'BookPlayer' from the app list that will appear", style: .alert) } sheet.addAction(localButton) sheet.addAction(airdropButton) sheet.addAction(cancelButton) sheet.popoverPresentationController?.sourceView = self.view sheet.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(sheet, animated: true, completion: nil) } func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { //show document picker documentPicker.delegate = self; documentPicker.popoverPresentationController?.sourceView = self.view documentPicker.popoverPresentationController?.sourceRect = CGRect(x: Double(self.view.bounds.size.width / 2.0), y: Double(self.view.bounds.size.height-45), width: 1.0, height: 1.0) self.present(documentPicker, animated: true, completion: nil) } } extension ListBooksViewController:UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { //Documentation states that the file might not be imported due to being accessed from somewhere else do { try FileManager.default.attributesOfItem(atPath: url.path) }catch{ self.showAlert("Error", message: "File import fail, try again later", style: .alert) return } let trueName = url.lastPathComponent var finalPath = self.documentsPath+"/"+(trueName) if trueName.contains(" ") { finalPath = finalPath.replacingOccurrences(of: " ", with: "_") } let fileURL = URL(fileURLWithPath: finalPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) do { try FileManager.default.moveItem(at: url, to: fileURL) }catch{ self.showAlert("Error", message: "File import fail, try again later", style: .alert) return } self.loadFiles() } } extension ListBooksViewController { override func remoteControlReceived(with event: UIEvent?) { guard let event = event else { return } //TODO: after decoupling AVAudioPlayer from the PlayerViewController switch event.subtype { case .remoteControlTogglePlayPause: print("toggle play/pause") case .remoteControlBeginSeekingBackward: print("seeking backward") case .remoteControlEndSeekingBackward: print("end seeking backward") case .remoteControlBeginSeekingForward: print("seeking forward") case .remoteControlEndSeekingForward: print("end seeking forward") case .remoteControlPause: print("control pause") case .remoteControlPlay: print("control play") case .remoteControlStop: print("stop") case .remoteControlNextTrack: print("next track") case .remoteControlPreviousTrack: print("previous track") default: print(event.description) } } } class BookCellView: UITableViewCell { @IBOutlet weak var artworkImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var completionLabel: UILabel! }
42399b5ecbdfe6434918116bf7dc3dc2
40.043689
207
0.658013
false
false
false
false
Aprobado/Automatic.Writer
refs/heads/master
AutomaticWriter/AutomatParser/ConvertibleToken.swift
mit
1
// // ConvertibleToken.swift // AutomaticWriter // // Created by Raphael on 19.02.15. // Copyright (c) 2015 HEAD Geneva. All rights reserved. // import Foundation class ConvertibleToken: HighlightToken { var captureGroups:[String] init(_ranges: [NSRange], _type: HighlightType, _text:String) { captureGroups = [String]() for range in _ranges { if range.length == 0 { captureGroups += [""] continue } let begining = advance(_text.startIndex, range.location) let end = advance(begining, range.length-1) captureGroups += [_text.substringWithRange(begining...end)] } super.init(_ranges: _ranges, _type: _type) } override var description:String { var descr = "Token type: \"\(type.description)\", with range 0:{loc:\(ranges[0].location), len:\(ranges[0].length)}, text:\n" for element in captureGroups { descr += "\"\(element)\"\n" } return descr } }
d6940361a78794cc301e01de24bb6588
27.864865
133
0.561387
false
false
false
false
jerrypupu111/LearnDrawingToolSet
refs/heads/good
SwiftGL-Demo/lib/SwiftColorPicker/HueView.swift
mit
1
// // MainColorView.swift // SwiftColorPicker // // Created by cstad on 12/15/14. // import UIKit extension UIView { func getLimitXCoordinate(_ coord:CGFloat)->CGFloat { if coord < 0 { return 0 } else if coord > frame.width { return frame.width } return coord } func getLimitYCoordinate(_ coord:CGFloat)->CGFloat { if coord < 0 { return 0 } else if coord > frame.height { return frame.height } return coord } } public class HueView: UIView { var color: UIColor! var point: CGPoint! var knob:UIView! weak var delegate: ColorPicker? init(frame: CGRect, color: UIColor) { super.init(frame: frame) } var width:CGFloat! var width_2:CGFloat! var hasLayouted = false override public func layoutSubviews() { super.layoutSubviews() if !hasLayouted { backgroundColor = UIColor.clear width = frame.height width_2 = width*0.5 let colorLayer = CAGradientLayer() colorLayer.colors = [ UIColor(hue: 0.0, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.1, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.2, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.3, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.4, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.5, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.6, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.7, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.8, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 0.9, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor, UIColor(hue: 1.0, saturation: 1.0, brightness: 1.0, alpha: 1.0).cgColor ] //colorLayer.locations = [0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95] colorLayer.locations = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.75, 0.8, 0.9,1.0] colorLayer.startPoint = CGPoint(x: 0, y: 0.5) colorLayer.endPoint = CGPoint(x: 1, y: 0.5) colorLayer.frame = frame colorLayer.frame.origin = CGPoint.zero // Insert the colorLayer into this views layer as a sublayer self.layer.insertSublayer(colorLayer, below: layer) self.color = UIColor.black point = getPointFromColor(color) knob = UIView(frame: CGRect(x: -3, y: -2, width: 6, height: width+4)) knob.layer.cornerRadius = 3 knob.layer.borderWidth = 1 knob.layer.borderColor = UIColor.lightGray.cgColor knob.backgroundColor = UIColor.white knob.layer.shadowColor = UIColor.black.cgColor // knob.layer.shadowOffset = CGSize(width: 0, height: -3) hasLayouted = true addSubview(knob) layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowOpacity = 0.8 } } override public func awakeFromNib() { } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // Set reference to the location of the touch in member point let touch = touches.first moveKnob(touch!,duration: 0.5) /* point = touch!.locationInView(self) point.x = getLimitXCoordinate(point.x) point.y = width_2 DLog("\(point)") // Notify delegate of the new new color selection let color = getColorFromPoint(point) delegate?.mainColorSelected(color, point: point) // Update display when possible UIView.animateWithDuration(0.5, animations: { self.knob.layer.transform = CATransform3DMakeTranslation(self.point.x-self.width_2, 0, 0) self.knob.backgroundColor = color }) */ } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // Set reference to the location of the touchesMoved in member point let touch = touches.first moveKnob(touch!,duration: 0.1) } func moveKnob(_ touch:UITouch,duration:TimeInterval) { point = touch.location(in: self) point.x = getLimitXCoordinate(point.x) point.y = width_2 // Notify delegate of the new new color selection let color = getColorFromPoint(point) delegate?.mainColorSelected(color, point: point) UIView.animate(withDuration: duration, animations: { self.knob.layer.transform = CATransform3DMakeTranslation(self.point.x, 0, 0) }) } func getColorFromPoint(_ point: CGPoint) -> UIColor { return UIColor(hue: point.x/frame.width, saturation: 1, brightness: 1, alpha: 1) } override public func draw(_ rect: CGRect) { /* if (point != nil) { let context = UIGraphicsGetCurrentContext() // Drawing properties: // Set line width to 1 CGContextSetLineWidth(context, 1) // Set color to black CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) // Draw selector CGContextBeginPath(context) CGContextMoveToPoint(context, 1, getYCoordinate(point.y) - 4) CGContextAddLineToPoint(context, 9, getYCoordinate(point.y)) CGContextAddLineToPoint(context, 1, getYCoordinate(point.y) + 4) CGContextStrokePath(context) CGContextBeginPath(context) CGContextMoveToPoint(context, 29, getYCoordinate(point.y) - 4) CGContextAddLineToPoint(context, 21, getYCoordinate(point.y)) CGContextAddLineToPoint(context, 29, getYCoordinate(point.y) + 4) CGContextStrokePath(context) } */ } // Determine crosshair coordinates from a color func getPointFromColor(_ color: UIColor) -> CGPoint { var hue: CGFloat = 0.0, saturation: CGFloat = 0.0, brightness: CGFloat = 0.0, alpha: CGFloat = 0.0 let ok: Bool = color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if (!ok) { print("ColorPicker: exception <The color provided to ColorPicker is not convertible to HSB>", terminator: "") } return CGPoint(x: 15, y: frame.height - (hue * frame.height)) } // Thanks to mbanasiewicz for this method // https://gist.github.com/mbanasiewicz/940677042f5f293caf57 }
1bfa71fc11b4ddbfec18249e17de16c2
35.566327
121
0.574578
false
false
false
false
pixyzehn/EsaKit
refs/heads/master
Sources/EsaKit/Models/Comment.swift
mit
1
// // Comment.swift // EsaKit // // Created by pixyzehn on 2016/11/26. // Copyright © 2016 pixyzehn. All rights reserved. // import Foundation public struct Comment: AutoEquatable, AutoHashable { public let id: Int public let bodyMd: String public let bodyHTML: String public let createdAt: Date public let updatedAt: Date public let url: URL public let createdBy: MinimumUser public let stargazersCount: UInt public let star: Bool enum Key: String { case id case bodyMd = "body_md" case bodyHTML = "body_html" case createdAt = "created_at" case updatedAt = "updated_at" case url case createdBy = "created_by" case stargazersCount = "stargazers_count" case star } } extension Comment: Decodable { // swiftlint:disable line_length public static func decode(json: Any) throws -> Comment { guard let dictionary = json as? [String: Any] else { throw DecodeError.invalidFormat(json: json) } guard let id = dictionary[Key.id.rawValue] as? Int else { throw DecodeError.missingValue(key: Key.id.rawValue, actualValue: dictionary[Key.id.rawValue]) } guard let bodyMd = dictionary[Key.bodyMd.rawValue] as? String else { throw DecodeError.missingValue(key: Key.bodyMd.rawValue, actualValue: dictionary[Key.bodyMd.rawValue]) } guard let bodyHTML = dictionary[Key.bodyHTML.rawValue] as? String else { throw DecodeError.missingValue(key: Key.bodyHTML.rawValue, actualValue: dictionary[Key.bodyHTML.rawValue]) } guard let createdAtString = dictionary[Key.createdAt.rawValue] as? String, let createdAt = DateFormatter.iso8601.date(from: createdAtString) else { throw DecodeError.missingValue(key: Key.createdAt.rawValue, actualValue: dictionary[Key.createdAt.rawValue]) } guard let updatedAtString = dictionary[Key.updatedAt.rawValue] as? String, let updatedAt = DateFormatter.iso8601.date(from: updatedAtString) else { throw DecodeError.missingValue(key: Key.updatedAt.rawValue, actualValue: dictionary[Key.updatedAt.rawValue]) } guard let urlString = dictionary[Key.url.rawValue] as? String, let url = URL(string: urlString) else { throw DecodeError.missingValue(key: Key.url.rawValue, actualValue: dictionary[Key.url.rawValue]) } guard let createdByJSON = dictionary[Key.createdBy.rawValue] else { throw DecodeError.missingValue(key: Key.createdBy.rawValue, actualValue: dictionary[Key.createdBy.rawValue]) } let createdBy: MinimumUser do { createdBy = try MinimumUser.decode(json: createdByJSON) } catch { throw DecodeError.custom(error.localizedDescription) } guard let stargazersCount = dictionary[Key.stargazersCount.rawValue] as? UInt else { throw DecodeError.missingValue(key: Key.stargazersCount.rawValue, actualValue: dictionary[Key.stargazersCount.rawValue]) } guard let star = dictionary[Key.star.rawValue] as? Bool else { throw DecodeError.missingValue(key: Key.star.rawValue, actualValue: dictionary[Key.star.rawValue]) } return Comment( id: id, bodyMd: bodyMd, bodyHTML: bodyHTML, createdAt: createdAt, updatedAt: updatedAt, url: url, createdBy: createdBy, stargazersCount: stargazersCount, star: star ) } }
bfead19df9a6938e1437a4d7d30b957a
35.929293
132
0.64907
false
false
false
false
qingtianbuyu/Mono
refs/heads/master
Moon/Classes/Explore/Model/MNTea.swift
mit
1
// // MNTea.swift // Moon // // Created by YKing on 16/5/25. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNTea: NSObject { var start: Int = 0 var entity_list: [MNExploreEntity]? var kind: Int = 2 var share_text: String? var push_msg: String? var title: String? var sub_title: String? var bg_img_url: String? var release_date: Date? var intro: String? var read_time: String? var share_time: String? var share_image: String? var id: Int = 0 init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "entity_list" { guard let array = (value as?[[String : AnyObject]]) else { return } var tmpArray = [MNExploreEntity]() for dict in array { tmpArray.append(MNExploreEntity(dict:dict)) } entity_list = tmpArray return } super.setValue(value, forKey: key) } }
54a9bf52e275a79d1b21b06efc19ef4a
18.188679
66
0.600787
false
false
false
false
JiriTrecak/Laurine
refs/heads/master
Example/Laurine/Classes/Model/API/ContributorAPI.swift
mit
2
// // ContributorAPI.swift // Laurine Example Project // // Created by Jiří Třečák // Copyright © 2015 Jiri Trecak. All rights reserved. // // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Import import Foundation import Alamofire // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- //MARK: - Definitions private let BASE_URL_CONTRIBUTORS : String = "https://api.github.com/repos/JiriTrecak/Laurine/contributors" // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Protocols // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Implementation // Declare variable to store singleton into private let _sharedObject = ContributorAPI() class ContributorAPI { // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Properties class var sharedInstance: ContributorAPI { return _sharedObject; } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- // MARK: - Public func getContributors(_ handler : @escaping (_ contributors : [Contributor]?, _ error : NSError?) -> ()) { Alamofire.request(BASE_URL_CONTRIBUTORS, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { (response:DataResponse<Any>) in if let JSON = response.result.value as? [NSDictionary] { // Create contributors var output : [Contributor] = [] JSON.forEach({ (data) -> () in output.append(Contributor(fromDictionary: data)) }) // Notify caller handler(output, nil) } else { handler(nil, response.result.error as NSError?) } } } func updateContributor(_ contributor : Contributor, handler : @escaping (_ contributor : Contributor?, _ error : NSError?) -> ()) { Alamofire.request(contributor.detailURL, method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { (response:DataResponse<Any>) in if let JSON = response.result.value as? NSDictionary { // Update contributor if contributor.updateWithDictionary(JSON) { // Notify caller handler(contributor, nil) } } else { handler(nil, response.result.error as? NSError) } } } }
0ed36df870d8dfc7bf0fa1374dbbdbfa
31.590909
158
0.42643
false
false
false
false
pjamroz/UniversalPagingController
refs/heads/master
Example/UniversalPagingControllerDemo/UniversalPagingControllerDemo/UniversalPagingController.swift
mit
1
// // UniversalPagingController.swift // UniversalPagingControllerDemo // // Created by Piotr Jamróz on 24.07.2016. // Copyright © 2016 Piotr Jamróz. All rights reserved. // import UIKit class UniversalPagingController: UIViewController, UIGestureRecognizerDelegate { // MARK: - Properties private let scrollView: UIScrollView private let containerView: UIView private let viewControllers: [UIViewController] private var visibleViewControllerIndex = 0 // MARK: - Life cycle init() { scrollView = UIScrollView() containerView = UIView() viewControllers = [UIViewController]() super.init(nibName: nil, bundle:nil) } init(viewControllers: [UIViewController]) { scrollView = UIScrollView() containerView = UIView() self.viewControllers = viewControllers super.init(nibName: nil, bundle:nil) } required init?(coder: NSCoder) { scrollView = UIScrollView() containerView = UIView() viewControllers = [UIViewController]() super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() setupAppearance() setupChildViewControllers(viewControllers) let leftEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(UniversalPagingController.userSwipedFromEdge(_:))) leftEdgeGestureRecognizer.edges = .Left leftEdgeGestureRecognizer.delegate = self self.view.addGestureRecognizer(leftEdgeGestureRecognizer) let rightEdgeGestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(UniversalPagingController.userSwipedFromEdge(_:))) rightEdgeGestureRecognizer.edges = .Right rightEdgeGestureRecognizer.delegate = self self.view.addGestureRecognizer(rightEdgeGestureRecognizer) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) viewControllers[visibleViewControllerIndex].beginAppearanceTransition(true, animated: true) } override func viewDidAppear(animated: Bool) { super.viewWillAppear(animated) viewControllers[visibleViewControllerIndex].endAppearanceTransition() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) viewControllers[visibleViewControllerIndex].beginAppearanceTransition(false, animated: true) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) viewControllers[visibleViewControllerIndex].endAppearanceTransition() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func shouldAutomaticallyForwardAppearanceMethods() -> Bool { return false } // MARK: - Orientation change override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) // Code here will execute before the rotation begins. scrollView.scrollEnabled = false coordinator.animateAlongsideTransition({ [unowned self] (UIViewControllerTransitionCoordinatorContext) in // Code here to perform animations during the rotation. self.scrollView.setContentOffset(CGPoint(x: self.containerView.frame.size.width * CGFloat(self.visibleViewControllerIndex), y: 0), animated: false) }) { [unowned self] (UIViewControllerTransitionCoordinatorContext) in // Code here will execute after the rotation has finished. self.scrollView.scrollEnabled = true } } // MARK: - UIGestureRecognizerDelegate func userSwipedFromEdge(sender: UIScreenEdgePanGestureRecognizer) { if sender.edges == UIRectEdge.Left && sender.state == .Ended { if visibleViewControllerIndex > 0 { scrollItemsForward(false) } else { // } } else if sender.edges == UIRectEdge.Right && sender.state == .Ended { if visibleViewControllerIndex+1 < viewControllers.count { scrollItemsForward(true) } else { // } } } // MARK: - Private private func setupAppearance() { view.addSubview(containerView) centerConstraintsForView(containerView) containerView.addSubview(scrollView) centerConstraintsForView(scrollView) scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.bounces = false scrollView.pagingEnabled = true scrollView.scrollEnabled = false } private func setupChildViewControllers(viewControllers: [UIViewController]) { for (index, viewController) in viewControllers.enumerate() { addChildViewController(viewController) scrollView.addSubview(viewController.view) viewController.didMoveToParentViewController(self) viewController.view.translatesAutoresizingMaskIntoConstraints = false // constraint height and width let heightConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Height, relatedBy: .Equal, toItem: containerView, attribute: .Height, multiplier: 1.0, constant: 0.0) let widthConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Width, relatedBy: .Equal, toItem: containerView, attribute: .Width, multiplier: 1.0, constant: 0.0) heightConstraint.active = true widthConstraint.active = true // contraint top and bottom let topConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Top, relatedBy: .Equal, toItem: scrollView, attribute: .Top, multiplier: 1.0, constant: 0.0) let bottomConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Bottom, relatedBy: .Equal, toItem: scrollView, attribute: .Bottom, multiplier: 1.0, constant: 0.0) topConstraint.active = true bottomConstraint.active = true if index == 0 { let leadingConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Leading, relatedBy: .Equal, toItem: scrollView, attribute: .Leading, multiplier: 1.0, constant: 0.0) leadingConstraint.active = true } else { let leadingConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Leading, relatedBy: .Equal, toItem: viewControllers[index-1].view, attribute: .Trailing, multiplier: 1.0, constant: 0.0) leadingConstraint.active = true } if index == viewControllers.count-1 { let trailingConstraint = NSLayoutConstraint(item: viewController.view, attribute: .Trailing, relatedBy: .Equal, toItem: scrollView, attribute: .Trailing, multiplier: 1.0, constant: 0.0) trailingConstraint.active = true } } } private func scrollItemsForward(forward: Bool) { let visibleViewControllerIndexBeforeTransition = visibleViewControllerIndex let visibleViewControllerIndexAfterTransition = forward ? visibleViewControllerIndex + 1 : visibleViewControllerIndex - 1 viewControllers[visibleViewControllerIndexBeforeTransition].beginAppearanceTransition(false, animated: true) viewControllers[visibleViewControllerIndexAfterTransition].beginAppearanceTransition(true, animated: true) scrollView.setContentOffset(CGPoint(x: containerView.frame.size.width * CGFloat(visibleViewControllerIndexAfterTransition), y: 0), animated: true) viewControllers[visibleViewControllerIndexAfterTransition].endAppearanceTransition() viewControllers[visibleViewControllerIndexBeforeTransition].endAppearanceTransition() visibleViewControllerIndex = visibleViewControllerIndexAfterTransition } private func centerConstraintsForView(view: UIView) { view.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal, toItem: view.superview, attribute: .Top, multiplier: 1.0, constant: 0.0) let bottomConstraint = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: view.superview, attribute: .Bottom, multiplier: 1.0, constant: 0.0) let leadingConstraint = NSLayoutConstraint(item: view, attribute: .Leading, relatedBy: .Equal, toItem: view.superview, attribute: .Leading, multiplier: 1.0, constant: 0.0) let trailingConstraint = NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: view.superview, attribute: .Trailing, multiplier: 1.0, constant: 0.0) topConstraint.active = true bottomConstraint.active = true leadingConstraint.active = true trailingConstraint.active = true } }
2af34700031b57ade727bb4a2ab7caad
47.795455
159
0.500388
false
false
false
false
einsteinx2/iSub
refs/heads/master
Frameworks/EX2Kit/RingBuffer.swift
gpl-3.0
1
// // RingBuffer.swift // iSub // // Created by Benjamin Baron on 1/26/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation final class RingBuffer { fileprivate let lock = NSRecursiveLock() fileprivate var buffer: UnsafeMutablePointer<UInt8> fileprivate var readPosition: Int = 0 fileprivate var writePosition: Int = 0 fileprivate(set) var size: Int var maximumSize: Int var freeSpace: Int { return lock.synchronizedResult { return size - filledSpace } } var filledSpace: Int { return lock.synchronizedResult { if readPosition <= writePosition { return writePosition - readPosition } else { // The write position has looped around return size - readPosition + writePosition } } } convenience init(size: Int, maximumSize: Int) { self.init(size: size) self.maximumSize = maximumSize } init(size: Int) { self.size = size self.maximumSize = size // default to no expansion self.buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: size) } func fill(with data: Data) -> Bool { return data.withUnsafeBytes { fill(with: $0, length: data.count) } } func fill(with bytes: UnsafeRawPointer, length: Int) -> Bool { return lock.synchronizedResult { // Make sure there is space if freeSpace > length { let bytesUntilEnd = size - writePosition if length > bytesUntilEnd { // Split it between the end and beginning memcpy(buffer + writePosition, bytes, bytesUntilEnd) memcpy(buffer, bytes + bytesUntilEnd, length - bytesUntilEnd) } else { // Just copy in the bytes memcpy(buffer + writePosition, bytes, length); } advanceWritePosition(length: length) return true } else if size < maximumSize { // Expand the buffer and try to fill it again if expand() { return fill(with: bytes, length: length) } } return false } } func drain(into bytes: UnsafeMutableRawPointer, length: Int) -> Int { return lock.synchronizedResult { let readLength = filledSpace >= length ? length : filledSpace if readLength > 0 { let bytesUntilEnd = size - readPosition if readLength > bytesUntilEnd { // Split it between the end and beginning memcpy(bytes, buffer + readPosition, bytesUntilEnd) memcpy(bytes + bytesUntilEnd, buffer, readLength - bytesUntilEnd) } else { // Just copy in the bytes memcpy(bytes, buffer + readPosition, readLength) } advanceReadPosition(length: readLength) } return readLength } } func drainData(length: Int) -> Data { let dataBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: length) let readLength = drain(into: dataBuffer, length: length) let data = Data(bytes: dataBuffer, count: readLength) dataBuffer.deinitialize(count: length) dataBuffer.deallocate() return data } func hasSpace(length: Int) -> Bool { return freeSpace >= length } func reset() { lock.synchronized { readPosition = 0 writePosition = 0 } } func expand() -> Bool { return lock.synchronizedResult { let additionalSize = Int(Double(size) * 0.25) return expand(additionalSize: additionalSize) } } func expand(additionalSize: Int) -> Bool { return lock.synchronizedResult { // First try to expand the buffer let totalSize = size + additionalSize if let rawPointer = realloc(buffer, totalSize * MemoryLayout<UInt8>.size) { let tempBuffer = rawPointer.assumingMemoryBound(to: UInt8.self) // Drain all the bytes into the new buffer let filledSize = filledSpace _ = drain(into: tempBuffer, length: filledSize) buffer = tempBuffer // Adjust the read and write positions readPosition = 0 writePosition = filledSize return true } return false } } fileprivate func advanceWritePosition(length: Int) { lock.synchronized { writePosition += length if writePosition >= size { writePosition = writePosition - size } } } fileprivate func advanceReadPosition(length: Int) { lock.synchronized { readPosition += length if readPosition >= size { readPosition = readPosition - size; } } } }
3d5f39b7dccf05a54263529b3d70999c
30.857143
87
0.533445
false
false
false
false
danstorre/CookIt
refs/heads/master
CookIt/CookIt/CoreDataCollectionViewController.swift
mit
1
// // CoreDataCollectionViewController.swift // VirtualTourist // // Created by Daniel Torres on 1/14/17. // Copyright © 2017 Daniel Torres. All rights reserved. // import UIKit import CoreData class CoreDataCollectionViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var blockOperations: [BlockOperation] = [] // MARK: Properties var fetchedResultsController : NSFetchedResultsController<NSFetchRequestResult>? { didSet { // Whenever the frc changes, we execute the search and // reload the table fetchedResultsController?.delegate = self executeSearch() } } // Do not worry about this initializer. I has to be implemented // because of the way Swift interfaces with an Objective C // protocol called NSArchiving. It's not relevant. required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } // MARK: - executeSearch CoreDataCollectionViewController extension CoreDataCollectionViewController{ func executeSearch(){ if let fc = fetchedResultsController{ do{ try fc.performFetch() }catch let e as NSError{ print("Error while trying to perform a search: \n\(e)\n\(fetchedResultsController)") } } } } // MARK: - CoreDataCollectionViewController (Collection Data Source) extension CoreDataCollectionViewController : UICollectionViewDataSource { // MARK: UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { if let fc = fetchedResultsController { return fc.sections!.count } else { return 1 } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let fc = fetchedResultsController { return fc.sections![section].numberOfObjects } else { return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { fatalError("This method MUST be implemented by a subclass of CoreDataTableViewController") } } // MARK: - CoreDataTableViewController: NSFetchedResultsControllerDelegate extension CoreDataCollectionViewController: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch(type){ case .insert: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.insertItems(at: [newIndexPath!]) } }) ) case .delete: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.deleteItems(at: [indexPath!]) } }) ) case .update: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.reloadItems(at: [indexPath!]) } }) ) case .move: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.moveItem(at: indexPath!, to: newIndexPath!) } }) ) } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch(type){ case .insert: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.insertSections(IndexSet(integer: sectionIndex)) } }) ) case .update: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.reloadSections(IndexSet(integer: sectionIndex)) } }) ) case .delete: blockOperations.append( BlockOperation(block: { [weak self] in if let this = self { this.collectionView!.deleteSections(IndexSet(integer: sectionIndex)) } }) ) default: break } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { collectionView!.performBatchUpdates({ () -> Void in for operation: BlockOperation in self.blockOperations { operation.start() } }, completion: { (finished) -> Void in self.blockOperations.removeAll(keepingCapacity: false) }) } }
769696c177c50dc542a135d72ce92e3d
31.594118
209
0.567407
false
false
false
false
adrfer/swift
refs/heads/master
stdlib/public/core/Reverse.swift
apache-2.0
1
//===--- Reverse.swift - Lazy sequence reversal ---------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public protocol ReverseIndexType : BidirectionalIndexType { associatedtype Base : BidirectionalIndexType /// A type that can represent the number of steps between pairs of /// `ReverseIndex` values where one value is reachable from the other. associatedtype Distance: _SignedIntegerType = Base.Distance /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. var base: Base { get } init(_ base: Base) } extension BidirectionalIndexType where Self : ReverseIndexType { /// Returns the next consecutive value after `self`. /// /// - Requires: The next value is representable. public func successor() -> Self { return Self(base.predecessor()) } /// Returns the previous consecutive value before `self`. /// /// - Requires: The previous value is representable. public func predecessor() -> Self { return Self(base.successor()) } } /// A wrapper for a `BidirectionalIndexType` that reverses its /// direction of traversal. public struct ReverseIndex<Base: BidirectionalIndexType> : BidirectionalIndexType, ReverseIndexType { public typealias Distance = Base.Distance public init(_ base: Base) { self.base = base } /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. public let base: Base @available(*, unavailable, renamed="Base") public typealias I = Base } @warn_unused_result public func == <Base> ( lhs: ReverseIndex<Base>, rhs: ReverseIndex<Base> ) -> Bool { return lhs.base == rhs.base } /// A wrapper for a `RandomAccessIndexType` that reverses its /// direction of traversal. public struct ReverseRandomAccessIndex<Base: RandomAccessIndexType> : RandomAccessIndexType, ReverseIndexType { public typealias Distance = Base.Distance public init(_ base: Base) { self.base = base } /// The successor position in the underlying (un-reversed) /// collection. /// /// If `self` is `advance(c.reverse.startIndex, n)`, then: /// - `self.base` is `advance(c.endIndex, -n)`. /// - if `n` != `c.count`, then `c.reverse[self]` is /// equivalent to `[self.base.predecessor()]`. public let base: Base public func distanceTo(other: ReverseRandomAccessIndex) -> Distance { return other.base.distanceTo(base) } public func advancedBy(n: Distance) -> ReverseRandomAccessIndex { return ReverseRandomAccessIndex(base.advancedBy(-n)) } @available(*, unavailable, renamed="Base") public typealias I = Base } public protocol _ReverseCollectionType : CollectionType { associatedtype Index : ReverseIndexType associatedtype Base : CollectionType var _base: Base { get } } extension CollectionType where Self : _ReverseCollectionType, Self.Base.Index : RandomAccessIndexType { public var startIndex : ReverseRandomAccessIndex<Self.Base.Index> { return ReverseRandomAccessIndex(_base.endIndex) } } extension _ReverseCollectionType where Self : CollectionType, Self.Index.Base == Self.Base.Index { public var startIndex : Index { return Self.Index(_base.endIndex) } public var endIndex : Index { return Self.Index(_base.startIndex) } public subscript(position: Index) -> Self.Base.Generator.Element { return _base[position.base.predecessor()] } } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reverse()` where `x` is a /// collection having bidirectional indices. /// /// The `reverse()` method is always lazy when applied to a collection /// with bidirectional indices, but does not implicitly confer /// laziness on algorithms applied to its result. In other words, for /// ordinary collections `c` having bidirectional indices: /// /// * `c.reverse()` does not create new storage /// * `c.reverse().map(f)` maps eagerly and returns a new array /// * `c.lazy.reverse().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - See also: `ReverseRandomAccessCollection` public struct ReverseCollection< Base : CollectionType where Base.Index : BidirectionalIndexType > : CollectionType, _ReverseCollectionType { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) public init(_ base: Base) { self._base = base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReverseIndex<Base.Index> /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. public typealias Generator = IndexingGenerator<ReverseCollection> public let _base: Base @available(*, unavailable, renamed="Base") public typealias T = Base } /// A Collection that presents the elements of its `Base` collection /// in reverse order. /// /// - Note: This type is the result of `x.reverse()` where `x` is a /// collection having random access indices. /// - See also: `ReverseCollection` public struct ReverseRandomAccessCollection< Base : CollectionType where Base.Index : RandomAccessIndexType > : _ReverseCollectionType { /// Creates an instance that presents the elements of `base` in /// reverse order. /// /// - Complexity: O(1) public init(_ base: Base) { self._base = base } /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = ReverseRandomAccessIndex<Base.Index> /// A type that provides the *sequence*'s iteration interface and /// encapsulates its iteration state. public typealias Generator = IndexingGenerator< ReverseRandomAccessCollection > public let _base: Base @available(*, unavailable, renamed="Base") public typealias T = Base } extension CollectionType where Index : BidirectionalIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> ReverseCollection<Self> { return ReverseCollection(self) } } extension CollectionType where Index : RandomAccessIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> ReverseRandomAccessCollection<Self> { return ReverseRandomAccessCollection(self) } } extension LazyCollectionType where Index : BidirectionalIndexType, Elements.Index : BidirectionalIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> LazyCollection< ReverseCollection<Elements> > { return ReverseCollection(elements).lazy } } extension LazyCollectionType where Index : RandomAccessIndexType, Elements.Index : RandomAccessIndexType { /// Return the elements of `self` in reverse order. /// /// - Complexity: O(1) @warn_unused_result public func reverse() -> LazyCollection< ReverseRandomAccessCollection<Elements> > { return ReverseRandomAccessCollection(elements).lazy } } /// Return an `Array` containing the elements of `source` in reverse /// order. @available(*, unavailable, message="call the 'reverse()' method on the collection") public func reverse<C:CollectionType where C.Index: BidirectionalIndexType>( source: C ) -> [C.Generator.Element] { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="ReverseCollection") public struct BidirectionalReverseView< Base : CollectionType where Base.Index : BidirectionalIndexType > {} @available(*, unavailable, renamed="ReverseRandomAccessCollection") public struct RandomAccessReverseView< Base : CollectionType where Base.Index : RandomAccessIndexType > {} // ${'Local Variables'}: // eval: (read-only-mode 1) // End:
a50b8a7ea3e38822855b72812ffeebfa
31.609489
83
0.700951
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/MGalleryVideoItem.swift
gpl-2.0
1
// // MGalleryVideoItem.swift // TelegramMac // // Created by keepcoder on 19/12/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import TelegramCore import Postbox import SwiftSignalKit import TGUIKit import AVFoundation import AVKit class MGalleryVideoItem: MGalleryItem { var startTime: TimeInterval = 0 private var playAfter:Bool = false private let controller: SVideoController var playerState: Signal<AVPlayerState, NoError> { return controller.status |> map { value in switch value.status { case .playing: return .playing(duration: value.duration) case .paused: return .paused(duration: value.duration) case let .buffering(initial, whilePlaying): if whilePlaying { return .playing(duration: value.duration) } else if !whilePlaying && !initial { return .paused(duration: value.duration) } else { return .waiting } } } |> deliverOnMainQueue } override init(_ context: AccountContext, _ entry: GalleryEntry, _ pagerSize: NSSize) { controller = SVideoController(postbox: context.account.postbox, reference: entry.fileReference(entry.file!)) super.init(context, entry, pagerSize) controller.togglePictureInPictureImpl = { [weak self] enter, control in guard let `self` = self else {return} let frame = control.view.window!.convertToScreen(control.view.convert(control.view.bounds, to: nil)) if enter, let viewer = viewer { closeGalleryViewer(false) showPipVideo(control: control, viewer: viewer, item: self, origin: frame.origin, delegate: viewer.delegate, contentInteractions: viewer.contentInteractions, type: viewer.type) } else if !enter { exitPictureInPicture() } } } deinit { updateMagnifyDisposable.dispose() } override func singleView() -> NSView { return controller.genericView } private var isPausedGlobalPlayer: Bool = false private let updateMagnifyDisposable = MetaDisposable() override func appear(for view: NSView?) { super.appear(for: view) pausepip() if let pauseMusic = context.audioPlayer?.pause() { isPausedGlobalPlayer = pauseMusic } controller.play(startTime) controller.viewDidAppear(false) self.startTime = 0 updateMagnifyDisposable.set((magnify.get() |> deliverOnMainQueue).start(next: { [weak self] value in if value < 1.0 { _ = self?.hideControls(forceHidden: true) } else { _ = self?.unhideControls(forceUnhidden: true) } })) } override var maxMagnify: CGFloat { return min(pagerSize.width / sizeValue.width, pagerSize.height / sizeValue.height) } override func disappear(for view: NSView?) { super.disappear(for: view) if isPausedGlobalPlayer { _ = context.audioPlayer?.play() } if controller.style != .pictureInPicture { controller.pause() } controller.viewDidDisappear(false) updateMagnifyDisposable.set(nil) playAfter = false } override var status:Signal<MediaResourceStatus, NoError> { if media.isStreamable { return .single(.Local) } else { return realStatus } } override var realStatus:Signal<MediaResourceStatus, NoError> { if let message = entry.message { return chatMessageFileStatus(context: context, message: message, file: media) } else { return context.account.postbox.mediaBox.resourceStatus(media.resource) } } var media:TelegramMediaFile { return entry.file! } private var examinatedSize: CGSize? var dimensions: CGSize? { if let examinatedSize = examinatedSize { return examinatedSize } if let dimensions = media.dimensions { return dimensions.size } let linked = link(path: context.account.postbox.mediaBox.resourcePath(media.resource), ext: "mp4") guard let path = linked else { return media.dimensions?.size } let url = URL(fileURLWithPath: path) guard let track = AVURLAsset(url: url).tracks(withMediaType: .video).first else { return media.dimensions?.size } try? FileManager.default.removeItem(at: url) let size = track.naturalSize.applying(track.preferredTransform) self.examinatedSize = NSMakeSize(abs(size.width), abs(size.height)) return examinatedSize } override var notFittedSize: NSSize { if let size = dimensions { return size.fitted(pagerSize) } return pagerSize } override var sizeValue: NSSize { if let size = dimensions { var pagerSize = self.pagerSize var size = size if size.width == 0 || size.height == 0 { size = NSMakeSize(300, 300) } let aspectRatio = size.width / size.height let addition = max(300 - size.width, 300 - size.height) if addition > 0 { size.width += addition * aspectRatio size.height += addition } // let addition = max(400 - size.width, 400 - size.height) // if addition > 0 { // size.width += addition // size.height += addition // } size = size.fitted(pagerSize) return size } return pagerSize } func hideControls(forceHidden: Bool = false) -> Bool { return controller.hideControlsIfNeeded(forceHidden) } func unhideControls(forceUnhidden: Bool = true) -> Bool { return controller.unhideControlsIfNeeded(forceUnhidden) } override func toggleFullScreen() { controller.toggleFullScreen() } override func togglePlayerOrPause() { controller.togglePlayerOrPause() } override func rewindBack() { controller.rewindBackward() } override func rewindForward() { controller.rewindForward() } var isFullscreen: Bool { return controller.isFullscreen } override func request(immediately: Bool) { super.request(immediately: immediately) let signal:Signal<ImageDataTransformation,NoError> = chatMessageVideo(postbox: context.account.postbox, fileReference: entry.fileReference(media), scale: System.backingScale, synchronousLoad: true) let size = sizeValue let arguments = TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: NSEdgeInsets(), resizeMode: .none) let result = signal |> mapToThrottled { data -> Signal<CGImage?, NoError> in return .single(data.execute(arguments, data.data)?.generateImage()) } path.set(context.account.postbox.mediaBox.resourceData(media.resource) |> mapToSignal { (resource) -> Signal<String, NoError> in if resource.complete { return .single(link(path:resource.path, ext:kMediaVideoExt)!) } return .never() }) self.image.set(media.previewRepresentations.isEmpty ? .single(GPreviewValueClass(.image(nil, nil))) |> deliverOnMainQueue : result |> map { GPreviewValueClass(.image($0 != nil ? NSImage(cgImage: $0!, size: $0!.backingSize) : nil, nil)) } |> deliverOnMainQueue) fetch() } override func fetch() -> Void { if !media.isStreamable { if let parent = entry.message { _ = messageMediaFileInteractiveFetched(context: context, messageId: parent.id, messageReference: .init(parent), file: media, userInitiated: true).start() } else { _ = freeMediaFileInteractiveFetched(context: context, fileReference: FileMediaReference.standalone(media: media)).start() } } } }
93916d8d562bb868d04b5ed2f89930fa
32.639216
268
0.588832
false
false
false
false
lioonline/v2ex-lio
refs/heads/master
V2ex/V2ex/AppDelegate.swift
mit
1
// // AppDelegate.swift // V2ex // // Created by Cocoa Lee on 9/28/15. // Copyright © 2015 lio. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.makeKeyAndVisible() let home = HomeViewController() let nav = UINavigationController(rootViewController: home) self.window?.rootViewController = nav let fpsLabel = V2FPSLabel(frame: CGRectMake(Screen_W - 80, Screen_H-40, 55, 20)); self.window?.addSubview(fpsLabel); // let strtt = "https://segmentfault.com/q/1010000000584340是一个@儿子&的的&oooooo&&dfsafsdg#话题#ooodd😄pppp🐷0000email:[email protected] 999 [email protected] phone 13641423304 username:tatoao " // LeeLabel.transformString(strtt) return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
7e612773ef35d95e6b4e13c1ed97e6ff
45.616667
285
0.727208
false
false
false
false
nkirby/Humber
refs/heads/master
Humber/_src/Table View Cells/SingleRepoHeaderCell.swift
mit
1
// ======================================================= // Humber // Nathaniel Kirby // ======================================================= import UIKit import HMCore import HMGithub // ======================================================= class SingleRepoHeaderCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func prepareForReuse() { super.prepareForReuse() self.titleLabel.text = "" self.descriptionLabel.text = "" } // ======================================================= internal func render(model model: GithubRepoModel) { self.backgroundColor = Theme.color(type: .CellBackgroundColor) let titleAttrString = NSAttributedString(string: model.name, attributes: [ NSFontAttributeName: Theme.font(type: .Bold(16.0)), NSForegroundColorAttributeName: Theme.color(type: .PrimaryTextColor) ]) self.titleLabel.attributedText = titleAttrString if model.repoDescription != "" { let descAttrString = NSAttributedString(string: model.repoDescription, attributes: [ NSFontAttributeName: Theme.font(type: .Regular(12.0)), NSForegroundColorAttributeName: Theme.color(type: .SecondaryTextColor) ]) self.descriptionLabel.attributedText = descAttrString } else { let descAttrString = NSAttributedString(string: "None Specified", attributes: [ NSFontAttributeName: Theme.font(type: .Italic(12.0)), NSForegroundColorAttributeName: Theme.color(type: .SecondaryTextColor) ]) self.descriptionLabel.attributedText = descAttrString } } }
4b7d7b9a65f8c9a3d1d9eed9d448eece
32.103448
96
0.547396
false
false
false
false
tomasharkema/LivePhotoExporter
refs/heads/master
LivePhotoExporter/ViewController.swift
mit
1
// // ViewController.swift // LivePhotoExporter // // Created by Tomas Harkema on 11-10-15. // Copyright © 2015 Tomas Harkema. All rights reserved. // import UIKit import Photos import PhotosUI import Regift class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var livePhotoView: UIView! var liveView: PHLivePhotoView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.layoutIfNeeded() liveView = PHLivePhotoView(frame: livePhotoView.bounds) livePhotoView.addSubview(liveView) liveView.contentMode = .ScaleAspectFit } @IBAction func chooseImagePressed(sender: AnyObject) { let imagePicker = UIImagePickerController() imagePicker.sourceType = .PhotoLibrary imagePicker.delegate = self presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func exportPressed(sender: AnyObject) { if let livePhoto = liveView.livePhoto { exportLivePhoto(livePhoto) } } func createGifFromVideoUrl(url: NSURL) { let regift = Regift(sourceFileURL: url, frameCount: 25, delayTime: 0).createGif() if let dataUrl = regift { let data = NSData(contentsOfURL: dataUrl)! dispatch_async(dispatch_get_main_queue()) { let activityViewController = UIActivityViewController(activityItems: [data], applicationActivities: nil) self.presentViewController(activityViewController, animated: true, completion: nil) } } } func exportLivePhoto(livePhoto: PHLivePhoto) { let resources = PHAssetResource.assetResourcesForLivePhoto(livePhoto).filter { $0.type == .PairedVideo } if let resource = resources.first { let options = PHAssetResourceRequestOptions() let folder = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! let guid = NSUUID().UUIDString let url = folder.URLByAppendingPathComponent("\(guid)-livePhoto.MOV") PHAssetResourceManager.defaultManager().writeDataForAssetResource(resource, toFile: url, options: options, completionHandler: { (error) in if let error = error { print(error) return } self.createGifFromVideoUrl(url) }) } } func livePhotoSelected(livePhoto: PHLivePhoto) { liveView.livePhoto = livePhoto liveView.startPlaybackWithStyle(PHLivePhotoViewPlaybackStyle.Full) } func fetchImageFromURL(url: NSURL) { let asset = PHAsset.fetchAssetsWithALAssetURLs([url], options: nil).firstObject as! PHAsset let size = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) PHImageManager.defaultManager().requestLivePhotoForAsset(asset, targetSize: size, contentMode: PHImageContentMode.Default, options: nil) { (livePhoto, options) in if let livePhoto = livePhoto { self.livePhotoSelected(livePhoto) } else { self.alertNoLivePhoto() } } } func alertNoLivePhoto() { let alertController = UIAlertController(title: "No Live Photo!", message: "Please, select an live-photo!", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default) { action in alertController.dismissViewControllerAnimated(true, completion: nil) self.chooseImagePressed(self.view) } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action in alertController.dismissViewControllerAnimated(true, completion: nil) } alertController.addAction(okAction) alertController.addAction(cancelAction) presentViewController(alertController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { picker.dismissViewControllerAnimated(true) { if let url = info[UIImagePickerControllerReferenceURL] as? NSURL { self.fetchImageFromURL(url) } } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } func previewingContext(previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { return self } }
75957ea00747c03a2a6eb250f8020473
35.294118
166
0.73605
false
false
false
false
getsentry/sentry-swift
refs/heads/master
Tests/SentryTests/Networking/SentryTransportInitializerTests.swift
mit
1
@testable import Sentry import XCTest class SentryTransportInitializerTests: XCTestCase { private static let dsnAsString = TestConstants.dsnAsString(username: "SentryTransportInitializerTests") private static let dsn = TestConstants.dsn(username: "SentryTransportInitializerTests") private var fileManager: SentryFileManager! override func setUp() { super.setUp() do { let options = Options() options.dsn = SentryTransportInitializerTests.dsnAsString fileManager = try SentryFileManager(options: options, andCurrentDateProvider: TestCurrentDateProvider()) } catch { XCTFail("SentryDsn could not be created") } } func testDefault() throws { let options = try Options(dict: ["dsn": SentryTransportInitializerTests.dsnAsString]) let result = TransportInitializer.initTransport(options, sentryFileManager: fileManager) XCTAssertTrue(result.isKind(of: SentryHttpTransport.self)) } }
46a52bb372509df8061bfc804d660e47
35.034483
116
0.691866
false
true
false
false
EasySwift/EasySwift
refs/heads/master
Carthage/Checkouts/Loggerithm/Demo/Demo/ViewController.swift
apache-2.0
2
// // ViewController.swift // Demo // // Created by Honghao Zhang on 2014-12-10. // Copyright (c) 2014 HonghaoZ. All rights reserved. // import UIKit class ViewController: UIViewController { var cleanLogger = Loggerithm() func setupLocalLogger() { cleanLogger.showDateTime = false cleanLogger.showLogLevel = false cleanLogger.showFileName = false cleanLogger.showLineNumber = false cleanLogger.showFunctionName = false } override func viewDidLoad() { super.viewDidLoad() // Logger is setup in AppDelegate.swift setupLocalLogger() // TODO: If you installed XcodeColors, remove comments for these two lines log.useColorfulLog = true cleanLogger.useColorfulLog = true // Usage example log.verbose("Verbose message...") log.debug("Debug message...") log.info("Info message...") log.warning("Warning message...") log.error("Error message...") log.emptyLine() log.showDateTime = false log.info("date time is turned off.") log.showLineNumber = false log.info("Line number is turned off.") log.showFileName = false log.info("File name is turned off.") log.showFunctionName = false log.info("Function name is turned off.") log.showLogLevel = false log.info("Log level is turned off.") log.emptyLine() log.info("Restoring to full format...") log.showDateTime = true log.showLogLevel = true log.showFileName = true log.showLineNumber = true log.showFunctionName = true log.verbose("I can use format: %d + %d = %d", args: 1, 1, 2) // Customize Color // TODO: If you installed XcodeColors, remove comments for these lines // cleanLogger.emptyLine() // log.useColorfulLog = false // log.info("Color is turned off.") // log.useColorfulLog = true // log.info("Color is turned on.") cleanLogger.emptyLine() cleanLogger.info("Customizing color...") log.verboseColor = UIColor.gray log.debugColor = UIColor.green log.infoColor = UIColor.yellow log.warningColor = UIColor.orange log.errorColor = UIColor.red log.verbose("Verbose message...") log.debug("Debug message...") log.info("Info message...") log.warning("Warning message...") log.error("Error message...") } }
d4212d8cd30fe2b04c67ce6eb0b58111
23.966667
76
0.681798
false
false
false
false
edwios/nRF5_WS2812B
refs/heads/master
iOS/MagicLightLE/MagicLightLE/HSBColorPicker.swift
bsd-3-clause
1
// // ColorPickerView.swift // MagicLightLE // // Originally written by Joel Teply. // Adapted by Edwin Tam with bug fixes on 12/12/2016. // import Foundation import UIKit @objc protocol HSBColorPickerDelegate : class { func HSBColorColorPickerTouched(sender:HSBColorPicker, color:UIColor, point:CGPoint, state:UIGestureRecognizerState) } // NSObjectProtocol @IBDesignable class HSBColorPicker : UIView { @IBOutlet weak var delegate: HSBColorPickerDelegate? let saturationExponentTop:Float = 2.0 let saturationExponentBottom:Float = 1.3 @IBInspectable var elementSize: CGFloat = 10.0 { didSet { setNeedsDisplay() } } private func initialize() { self.clipsToBounds = true let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(HSBColorPicker.touchedColor(_:))) touchGesture.minimumPressDuration = 0 touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude self.addGestureRecognizer(touchGesture) } override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() for y in stride(from: 0, to: rect.height, by: elementSize) { var saturation = y < rect.height / 2.0 ? CGFloat(2 * y) / rect.height : 2.0 * CGFloat(rect.height - y) / rect.height saturation = CGFloat(powf(Float(saturation), y < rect.height / 2.0 ? saturationExponentTop : saturationExponentBottom)) let brightness = y < rect.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect.height - y) / rect.height for x in stride(from: 0, to: rect.width, by: elementSize) { let hue = x / rect.width let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) context!.setFillColor(color.cgColor) context!.fill(CGRect(x:x, y:y, width:elementSize,height:elementSize)) } } } func getColorAtPoint(point:CGPoint) -> UIColor { let roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)), y:elementSize * CGFloat(Int(point.y / elementSize))) var saturation = roundedPoint.y < self.bounds.height / 2.0 ? CGFloat(2 * roundedPoint.y) / self.bounds.height : 2.0 * CGFloat(self.bounds.height - roundedPoint.y) / self.bounds.height saturation = CGFloat(powf(Float(saturation), roundedPoint.y < self.bounds.height / 2.0 ? saturationExponentTop : saturationExponentBottom)) let brightness = roundedPoint.y < self.bounds.height / 2.0 ? CGFloat(1.0) : (roundedPoint.y > (self.bounds.height - elementSize)) ? CGFloat(0.0):2.0 * CGFloat(self.bounds.height - roundedPoint.y) / self.bounds.height let hue = roundedPoint.x < 0 ? CGFloat(0.0) : roundedPoint.x > self.bounds.width ? CGFloat(1.0) : roundedPoint.x / self.bounds.width return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) } func getPointForColor(color:UIColor) -> CGPoint { var hue:CGFloat=0; var saturation:CGFloat=0; var brightness:CGFloat=0; color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: nil); var yPos:CGFloat = 0 let halfHeight = (self.bounds.height / 2) if (brightness >= 0.99) { let percentageY = powf(Float(saturation), 1.0 / saturationExponentTop) yPos = CGFloat(percentageY) * halfHeight } else { //use brightness to get Y yPos = halfHeight + halfHeight * (1.0 - brightness) } let xPos = hue * self.bounds.width return CGPoint(x: xPos, y: yPos) } func touchedColor(_ gestureRecognizer: UILongPressGestureRecognizer){ let point = gestureRecognizer.location(in: self) let color = getColorAtPoint(point: point) self.delegate?.HSBColorColorPickerTouched(sender: self, color: color, point: point, state:gestureRecognizer.state) } }
76925e00de124a4c295c2c1efc978397
40.788462
224
0.634607
false
false
false
false
DarrenKong/firefox-ios
refs/heads/master
ClientTests/TestBookmarks.swift
mpl-2.0
12
/* 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/. */ @testable import Client import Foundation import Shared import Storage import XCTest class TestBookmarks: ProfileTest { func testBookmarks() { withTestProfile { profile -> Void in for i in 0...10 { let bookmark = ShareItem(url: "http://www.example.com/\(i)", title: "Example \(i)", favicon: nil) profile.bookmarks.shareItem(bookmark) } let expectation = self.expectation(description: "asynchronous request") profile.bookmarks.modelFactory >>== { $0.modelForFolder(BookmarkRoots.MobileFolderGUID).upon { result in guard let model = result.successValue else { XCTFail("Should not have failed to get mock bookmarks.") expectation.fulfill() return } // 11 bookmarks plus our two suggested sites. XCTAssertEqual(model.current.count, 11, "We create \(model.current.count) stub bookmarks in the Mobile Bookmarks folder.") let bookmark = model.current[0] XCTAssertTrue(bookmark is BookmarkItem) XCTAssertTrue((bookmark as! BookmarkItem).url.hasPrefix("http://www.example.com/"), "Example URL found.") expectation.fulfill() } } self.waitForExpectations(timeout: 10.0, handler:nil) // This'll do. try! profile.files.remove("mock.db") } } }
8b414c470f1a4d43b392299f258cdcbf
40.809524
142
0.575171
false
true
false
false