repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
hryk224/InfiniteCollectionView
Example/Example/Pattern1ViewController.swift
1
2765
// // Pattern1ViewController.swift // Example // // Created by hiroyuki yoshida on 2016/01/04. // Copyright © 2016年 hiroyuki yoshida. All rights reserved. // import UIKit import InfiniteCollectionView final class Pattern1ViewController: UIViewController { var itemsCount: Int = 5 @IBOutlet weak var collectionView: InfiniteCollectionView! { didSet { collectionView.infiniteDataSource = self collectionView.infiniteDelegate = self collectionView.register(ImageCollectionViewCell.nib, forCellWithReuseIdentifier: ImageCollectionViewCell.identifier) } } @IBOutlet weak var layout: UICollectionViewFlowLayout! { didSet { layout.itemSize = UIScreen.main.bounds.size } } @IBOutlet weak var pageControl: UIPageControl! { didSet { pageControl.numberOfPages = itemsCount } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default.addObserver(self, selector: #selector(Pattern1ViewController.rotate(_:)), name: .UIDeviceOrientationDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: .UIDeviceOrientationDidChange, object: nil) } static func createFromStoryboard() -> Pattern1ViewController { let storyboard = UIStoryboard(name: "Pattern1", bundle: nil) return storyboard.instantiateInitialViewController() as! Pattern1ViewController } func rotate(_ notification: Notification) { layout.itemSize = UIScreen.main.bounds.size layout.invalidateLayout() collectionView.rotate(notification) collectionView.layoutIfNeeded() collectionView.setNeedsLayout() } } // MARK: - InfiniteCollectionViewDataSource, InfiniteCollectionViewDelegate extension Pattern1ViewController: InfiniteCollectionViewDataSource, InfiniteCollectionViewDelegate { func number(ofItems collectionView: UICollectionView) -> Int { return itemsCount } func collectionView(_ collectionView: UICollectionView, dequeueForItemAt dequeueIndexPath: IndexPath, cellForItemAt usableIndexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCollectionViewCell.identifier, for: dequeueIndexPath) as! ImageCollectionViewCell cell.configure(indexPath: usableIndexPath) return cell } func infiniteCollectionView(_ collectionView: UICollectionView, didSelectItemAt usableIndexPath: IndexPath) { print("didSelectItemAt: \(usableIndexPath.item)") } func scrollView(_ scrollView: UIScrollView, pageIndex: Int) { pageControl.currentPage = pageIndex } }
mit
c6865e0b6406d3bd2316f99cbb69422f
40.223881
173
0.726285
5.636735
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Aggregations/LocationSharing/MXBeaconAggregations.swift
1
17602
// // Copyright 2022 The Matrix.org Foundation C.I.C // // 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 /// MXBeaconAggregations aggregates related beacon info events and beacon info events into a summary object MXBeaconInfoSummary @objcMembers public class MXBeaconAggregations: NSObject { // MARK: - Properties private unowned let session: MXSession private var perRoomListeners: [MXBeaconInfoSummaryPerRoomListener] = [] private var perRoomDeletionListeners: [MXBeaconInfoSummaryDeletionPerRoomListener] = [] private var allRoomListeners: [MXBeaconInfoSummaryAllRoomListener] = [] private var allRoomDeletionListeners: [MXBeaconInfoSummaryDeletionAllRoomListener] = [] private var beaconInfoSummaryStore: MXBeaconInfoSummaryStoreProtocol // MARK: - Setup public init(session: MXSession, store: MXBeaconInfoSummaryStoreProtocol) { self.session = session self.beaconInfoSummaryStore = store super.init() } // MARK: - Public /// Get MXBeaconInfoSummary from the first beacon info event id public func beaconInfoSummary(for eventId: String, inRoomWithId roomId: String) -> MXBeaconInfoSummaryProtocol? { return self.beaconInfoSummaryStore.getBeaconInfoSummary(withIdentifier: eventId, inRoomWithId: roomId) } /// Get all MXBeaconInfoSummary in a room public func getBeaconInfoSummaries(inRoomWithId roomId: String) -> [MXBeaconInfoSummaryProtocol] { return self.beaconInfoSummaryStore.getAllBeaconInfoSummaries(inRoomWithId: roomId) } /// Get all MXBeaconInfoSummary in a room for a user public func getBeaconInfoSummaries(for userId: String, inRoomWithId roomId: String) -> [MXBeaconInfoSummaryProtocol] { return self.beaconInfoSummaryStore.getBeaconInfoSummaries(for: userId, inRoomWithId: roomId) } /// Get all MXBeaconInfoSummary for a user public func getBeaconInfoSummaries(for userId: String) -> [MXBeaconInfoSummaryProtocol] { return self.beaconInfoSummaryStore.getAllBeaconInfoSummaries(forUserId: userId) } /// Update a MXBeaconInfoSummary device id that belongs to the current user. /// Enables to recognize that a beacon info has been started on the device public func updateBeaconInfoSummary(with eventId: String, deviceId: String, inRoomWithId roomId: String) { guard let beaconInfoSummary = self.beaconInfoSummaryStore.getBeaconInfoSummary(withIdentifier: eventId, inRoomWithId: roomId) else { return } guard beaconInfoSummary.userId == session.myUserId else { return } if beaconInfoSummary.updateWithDeviceId(deviceId) { self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId) self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary) } } public func clearData(inRoomWithId roomId: String) { // TODO: Notify data clear self.beaconInfoSummaryStore.deleteAllBeaconInfoSummaries(inRoomWithId: roomId) } // MARK: Data update public func handleBeacon(event: MXEvent) { guard let roomId = event.roomId else { return } guard event.isRedactedEvent() == false else { return } guard let beacon = MXBeacon(mxEvent: event) else { return } guard let beaconInfoSummary = self.getBeaconInfoSummary(withIdentifier: beacon.beaconInfoEventId, inRoomWithId: roomId), self.canAddBeacon(beacon, to: beaconInfoSummary) else { return } if beaconInfoSummary.updateWithLastBeacon(beacon) { self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId) self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary) } } public func handleBeaconInfo(event: MXEvent) { guard let roomId = event.roomId else { return } if event.isRedactedEvent() { self.handleRedactedBeaconInfo(with: event, roomId: roomId) return } guard let beaconInfo = MXBeaconInfo(mxEvent: event) else { return } self.addOrUpdateBeaconInfo(beaconInfo, inRoomWithId: roomId) } private func handleRedactedBeaconInfo(with event: MXEvent, roomId: String) { guard let beaconInfoEventId = event.eventId else { return } // If `m.beacon_info` event is redacted remove the associated MXbeaconInfoSummary if exists. if let beaconInfoSummary = self.beaconInfoSummaryStore.getBeaconInfoSummary(withIdentifier: beaconInfoEventId, inRoomWithId: roomId) { // Delete beacon info summary self.beaconInfoSummaryStore.deleteBeaconInfoSummary(with: beaconInfoEventId, inRoomWithId: roomId) // If the beacon info belongs to the current user if beaconInfoSummary.userId == session.myUserId { // Redact associated stopped beacon info if exists self.redactStoppedBeaconInfoAssociatedToBeaconInfo(eventId: beaconInfoEventId, inRoomWithId: roomId) // Redact associated beacon events self.redactBeaconsRelatedToBeaconInfo(with: beaconInfoEventId, inRoomWithId: beaconInfoSummary.roomId) } self.notifyBeaconInfoSummaryDeletionListeners(ofRoomWithId: roomId, beaconInfoEventId: beaconInfoEventId) } } private func redactBeaconsRelatedToBeaconInfo(with eventId: String, inRoomWithId roomId: String) { guard let room = self.session.room(withRoomId: roomId) else { return } let relationEvents = self.session.store.relations(forEvent: eventId, inRoom: roomId, relationType: MXEventRelationTypeReference) for relationEvent in relationEvents where relationEvent.eventType == .beacon && relationEvent.isRedactedEvent() == false { room.redactEvent(relationEvent.eventId, reason: nil) { response in if case .failure(let error) = response { MXLog.error("[MXBeaconAggregations] Failed to redact m.beacon event", context: error) } } } } private func redactStoppedBeaconInfoAssociatedToBeaconInfo(eventId beaconInfoEnventId: String, inRoomWithId roomId: String) { guard let room = self.session.room(withRoomId: roomId) else { return } self.session.locationService.getStoppedBeaconInfo(for: beaconInfoEnventId, inRoomWithId: roomId) { stoppedBeaconInfo in if let eventId = stoppedBeaconInfo?.originalEvent?.eventId { // Redact stopped beacon info room.redactEvent(eventId, reason: nil) { response in if case .failure(let error) = response { MXLog.error("[MXBeaconAggregations] Failed to redact stopped m.beacon_info event", context: error) } } } } } // MARK: Data update listener /// Listen to all beacon info summary updates in a room public func listenToBeaconInfoSummaryUpdateInRoom(withId roomId: String, handler: @escaping (MXBeaconInfoSummaryProtocol) -> Void) -> AnyObject? { let listener = MXBeaconInfoSummaryPerRoomListener(roomId: roomId, notificationHandler: handler) perRoomListeners.append(listener) return listener } /// Listen to all beacon info summary update in all rooms public func listenToBeaconInfoSummaryUpdate(handler: @escaping (_ roomId: String, MXBeaconInfoSummaryProtocol) -> Void) -> AnyObject? { let listener = MXBeaconInfoSummaryAllRoomListener(notificationHandler: handler) allRoomListeners.append(listener) return listener } /// Listen to all beacon info summary deletion in a room public func listenToBeaconInfoSummaryDeletionInRoom(withId roomId: String, handler: @escaping (_ beaconInfoEventId: String) -> Void) -> AnyObject? { let listener = MXBeaconInfoSummaryDeletionPerRoomListener(roomId: roomId, notificationHandler: handler) perRoomDeletionListeners.append(listener) return listener } /// Listen to all beacon info summary deletion in all rooms public func listenToBeaconInfoSummaryDeletion(handler: @escaping (_ roomId: String, _ beaconInfoEventId: String) -> Void) -> AnyObject? { let listener = MXBeaconInfoSummaryDeletionAllRoomListener(notificationHandler: handler) allRoomDeletionListeners.append(listener) return listener } public func removeListener(_ listener: Any) { if let perRoomListener = listener as? MXBeaconInfoSummaryPerRoomListener { perRoomListeners.removeAll(where: { $0 === perRoomListener }) } else if let allRoomListener = listener as? MXBeaconInfoSummaryAllRoomListener { allRoomListeners.removeAll(where: { $0 === allRoomListener }) } else if let perRoomDeletionListener = listener as? MXBeaconInfoSummaryDeletionPerRoomListener { perRoomDeletionListeners.removeAll(where: { $0 === perRoomDeletionListener }) } else if let allRoomDeletionListener = listener as? MXBeaconInfoSummaryDeletionAllRoomListener { allRoomDeletionListeners.removeAll(where: { $0 === allRoomDeletionListener }) } } // MARK: - Private private func addOrUpdateBeaconInfo(_ beaconInfo: MXBeaconInfo, inRoomWithId roomId: String) { guard let eventId = beaconInfo.originalEvent?.eventId else { return } var beaconInfoSummary: MXBeaconInfoSummary? // A new beacon info is emitted to set a current one to stop state. if beaconInfo.isLive == false { // If no corresponding BeaconInfoSummary exists, discard this beacon info if let existingBeaconInfoSummary = self.getBeaconInfoSummary(withStoppedBeaconInfo: beaconInfo, inRoomWithId: roomId), existingBeaconInfoSummary.hasStopped == false { existingBeaconInfoSummary.updateWithBeaconInfo(beaconInfo) beaconInfoSummary = existingBeaconInfoSummary } else { MXLog.error("[MXBeaconAggregations] Fails to find beacon info summary associated to stopped beacon info", context: [ "event_id": eventId ]) } } else if let existingBeaconInfoSummary = self.getBeaconInfoSummary(withIdentifier: eventId, inRoomWithId: roomId) { // Check if a beacon info summary exist with the same beacon info event id // If beacon info is older than existing one, do not take it into account if beaconInfo.timestamp > existingBeaconInfoSummary.beaconInfo.timestamp { existingBeaconInfoSummary.updateWithBeaconInfo(beaconInfo) beaconInfoSummary = existingBeaconInfoSummary } } else { var shouldStopNewBeaconInfo = false if let userId = beaconInfo.userId { // Retrieve existing live beacon info summaries for the user let existingLiveBeaconInfoSummaries = self.beaconInfoSummaryStore.getBeaconInfoSummaries(for: userId, inRoomWithId: roomId).sorted { firstSummary, secondSummary in firstSummary.beaconInfo.timestamp < secondSummary.beaconInfo.timestamp } let beaconInfoSummariesToStop: [MXBeaconInfoSummary] let lastBeaconInfoSummary = existingLiveBeaconInfoSummaries.last if let lastBeaconInfoSummary = lastBeaconInfoSummary, beaconInfo.timestamp < lastBeaconInfoSummary.beaconInfo.timestamp { // The received live beacon info is older than last existing one mark it as stopped shouldStopNewBeaconInfo = true // Do not stop the last live beacon info beaconInfoSummariesToStop = existingLiveBeaconInfoSummaries.filter({ summary in summary.id != lastBeaconInfoSummary.id }) } else { // Received beacon info is newer than existing one, stop other beacon info beaconInfoSummariesToStop = existingLiveBeaconInfoSummaries } // Stop other existing live beacon info summaries for beaconInfoSummary in beaconInfoSummariesToStop { let stoppedBeaconInfo = beaconInfoSummary.beaconInfo.stopped() beaconInfoSummary.updateWithBeaconInfo(stoppedBeaconInfo) self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId) self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary) } } let finalBeaconInfo: MXBeaconInfo // We can only have one **live** beacon info per user and per room // If the received live beacon info is older than other existing live, mark it as stopped if shouldStopNewBeaconInfo { finalBeaconInfo = beaconInfo.stopped() } else { finalBeaconInfo = beaconInfo } beaconInfoSummary = MXBeaconInfoSummary(beaconInfo: finalBeaconInfo) } if let beaconInfoSummary = beaconInfoSummary { self.beaconInfoSummaryStore.addOrUpdateBeaconInfoSummary(beaconInfoSummary, inRoomWithId: roomId) self.notifyBeaconInfoSummaryListeners(ofRoomWithId: roomId, beaconInfoSummary: beaconInfoSummary) } } private func canAddBeacon(_ beacon: MXBeacon, to beaconInfoSummary: MXBeaconInfoSummary) -> Bool { guard beaconInfoSummary.hasStopped == false, beaconInfoSummary.hasExpired == false, beacon.timestamp < beaconInfoSummary.expiryTimestamp else { return false } if let lastBeacon = beaconInfoSummary.lastBeacon, beacon.timestamp < lastBeacon.timestamp { return false } return true } private func notifyBeaconInfoSummaryListeners(ofRoomWithId roomId: String, beaconInfoSummary: MXBeaconInfoSummary) { for listener in perRoomListeners where listener.roomId == roomId { listener.notificationHandler(beaconInfoSummary) } for listener in allRoomListeners { listener.notificationHandler(roomId, beaconInfoSummary) } } private func notifyBeaconInfoSummaryDeletionListeners(ofRoomWithId roomId: String, beaconInfoEventId: String) { for listener in perRoomDeletionListeners where listener.roomId == roomId { listener.notificationHandler(beaconInfoEventId) } for listener in allRoomDeletionListeners { listener.notificationHandler(roomId, beaconInfoEventId) } } /// Get MXBeaconInfoSummary class instead of MXBeaconInfoSummaryProtocol to have access to internal methods private func getBeaconInfoSummary(withIdentifier identifier: String, inRoomWithId roomId: String) -> MXBeaconInfoSummary? { return self.beaconInfoSummaryStore.getBeaconInfoSummary(withIdentifier: identifier, inRoomWithId: roomId) } private func getLiveBeaconInfoSummaries(for userId: String, inRoomWithId roomId: String) -> [MXBeaconInfoSummary] { let beaconInfoSummaries = self.beaconInfoSummaryStore.getBeaconInfoSummaries(for: userId, inRoomWithId: roomId) return beaconInfoSummaries.filter { beaconInfoSummary in return beaconInfoSummary.beaconInfo.isLive } } private func getBeaconInfoSummary(withStoppedBeaconInfo beaconInfo: MXBeaconInfo, inRoomWithId roomId: String) -> MXBeaconInfoSummary? { guard beaconInfo.isLive == false else { return nil } guard let userId = beaconInfo.userId else { return nil } return self.beaconInfoSummaryStore.getBeaconInfoSummary(withUserId: userId, description: beaconInfo.desc, timeout: beaconInfo.timeout, timestamp: beaconInfo.timestamp, inRoomWithId: roomId) } }
apache-2.0
189c69b9fb8c2fe4fff13d8058e029bc
44.133333
197
0.662254
6.275223
false
false
false
false
kevll/LLImagePicker
LLImagePickerDemo/ViewController.swift
1
620
// // ViewController.swift // LLImagePickerDemo // // Created by kevin on 2017/4/8. // Copyright © 2017年 Ecommerce. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let imgPickerView = LLImagePickerView.init(frame: self.view.bounds) imgPickerView.addPhotoImage = UIImage.init(named: "add_photo") imgPickerView.deletePhotoImage = UIImage.init(named: "hongcha") imgPickerView.columns = 4 imgPickerView.maxSelectNum = 5 self.view.addSubview(imgPickerView) } }
mit
949c18084e114a68fd91f1783486e10a
21.035714
75
0.679092
4.226027
false
false
false
false
Eonil/EditorLegacy
Modules/Editor/Sources/Documents/Workspace/WorkspaceDocument.swift
1
14472
// // WorkspaceDocument.swift // Editor // // Created by Hoon H. on 2015/01/12. // Copyright (c) 2015 Eonil. All rights reserved. // import Foundation import AppKit import LLDBWrapper import EonilFileSystemEvents import EditorCommon import EditorModel import EditorUIComponents import EditorToolComponents import EditorWorkspaceNavigationFeature import EditorIssueListingFeature import EditorDebuggingFeature /// A document to edit Eonil Editor Workspace. (`.eewsN` file, `N` is single integer version number) /// /// Manages interaction with Cocoa document system. final class WorkspaceDocument: NSDocument { var model: Workspace { get { return _model! } } private var _model : Workspace? // private var _menureconf : WorkspaceMenuReconfigurator? override init() { super.init() internals = InternalController(owner: self) } // var projectMenuController:MenuController { // get { // return internals!.projectMenuController // } // } // var debugMenuController:MenuController { // get { // return internals!.debuggingController.menuController // } // } override func makeWindowControllers() { // Turning off the undo will effectively make autosave to be disabled. // See "Not Supporting Undo" chapter. // https://developer.apple.com/library/mac/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/StandardBehaviors/StandardBehaviors.html // // This does not affect editing of each data-file. hasUndoManager = false super.makeWindowControllers() self.addWindowController(internals!.mainWindowController) assert(internals!.mainWindowController.fileNavigationViewController.delegate != nil) } //// private var internals = nil as InternalController? { willSet { assert(internals == nil, "You can set this only once.") } } private var _rootLocation = nil as FileLocation? private var rootLocation:FileLocation { get { return _rootLocation! // This cannot be `nil` if this document has been configured properly. } } } /// MARK: /// MARK: Overriding default behaviors. extension WorkspaceDocument { override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { fatalError("Saving features all should be overridden to save current data file instead of workspace document. This method shouldn't be called.") } override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { assert(internals!.mainWindowController.fileNavigationViewController.delegate != nil) let u2 = self.fileURL!.URLByDeletingLastPathComponent! _model = Workspace(rootDirectoryURL: u2) // _menureconf = WorkspaceMenuReconfigurator(workspace: _model!) _rootLocation = FileLocation(u2) internals!.mainWindowController.fileNavigationViewController.URLRepresentation = u2 let p1 = u2.path! // fileSystemMonitor = FileSystemEventMonitor(pathsToWatch: [p1]) { [weak self] events in // for ev in events { // self?.postprocessFileSystemEventAtURL(ev) // } // // sm.routeEvent(u1) // } return true } // private func postprocessFileSystemEventAtURL(event:FileSystemEvent) { // let isDir = (event.flag & EonilFileSystemEventFlag.ItemIsDir) == EonilFileSystemEventFlag.ItemIsDir // let u1 = NSURL(fileURLWithPath: event.path, isDirectory: isDir)! // // if u1 == rootLocation.stringExpression { // if u1.existingAsDirectoryFile == false || u1.fileReferenceURL()! != rootLocation.fileSystemNode { // // Root location has been deleted. // self.performClose(self) // return // } // } // // //// // // Debug.log(event.flag) // enum Operation { // init(flag:FileSystemEventFlag) { // let isDelete = (flag & EonilFileSystemEventFlag.ItemRemoved) == EonilFileSystemEventFlag.ItemRemoved // if isDelete { // self = Delete // return // } // let isCreate = (flag & EonilFileSystemEventFlag.ItemCreated) == EonilFileSystemEventFlag.ItemCreated // if isCreate { // self = Create // return // } // let isMove = (flag & EonilFileSystemEventFlag.ItemRenamed) == EonilFileSystemEventFlag.ItemRenamed // if isMove { // self = Move // return // } // let isModified = (flag & EonilFileSystemEventFlag.ItemModified) == EonilFileSystemEventFlag.ItemModified // if isModified { // self = Modify // return // } // //// fatalError("Unknown file system event flag.") // self = None // } // case None // case Create // case Move // case Modify // case Delete // } // // switch Operation(flag: event.flag) { // case .None: // Debug.log("NONE: \(u1)") // // case .Create: // Debug.log("CREATE: \(u1)") // // case .Move: // Debug.log("MOVE: \(u1)") // if u1 == mainWindowController.codeEditingViewController.URLRepresentation { // self.postprocessDisappearingOfFileAtURL(u1) // } // // case .Delete: // Debug.log("DELETE: \(u1)") // if u1 == mainWindowController.codeEditingViewController.URLRepresentation { // self.postprocessDisappearingOfFileAtURL(u1) // } // // case .Modify: // Debug.log("MODIFY: \(u1)") // } // // mainWindowController.fileNavigationViewController.invalidateNodeForURL(u1) // } // private func postprocessDisappearingOfFileAtURL(u:NSURL) { // if u == mainWindowController.codeEditingViewController.URLRepresentation { // mainWindowController.codeEditingViewController.URLRepresentation = nil // } // } } /// MARK: /// MARK: Static menu handling via First Responder chain extension WorkspaceDocument { /// Overridden to save currently editing data file. @objc @IBAction override func saveDocument(AnyObject?) { // Do not route save messages to current document. // Saving of a project will be done at somewhere else, and this makes annoying alerts. // This prevents the alerts. // super.saveDocument(sender) internals!.mainWindowController.codeEditingViewController.trySavingInPlace() } @objc @IBAction override func saveDocumentAs(sender: AnyObject?) { fatalError("Not implemented yet.") } /// Closes data file if one is exists. /// Workspace cannot be closed with by calling this. /// You need to close the window of a workspace to close it. @objc @IBAction func performClose(AnyObject?) { self.close() } } /// MARK: /// MARK: InternalController /// Hardly-coupled internal subcomponent controller. private final class InternalController { unowned let owner : WorkspaceDocument let mainWindowController = WorkspaceMainWindowController() let debuggingController = WorkspaceDebuggingController() let commandQueue = WorkspaceCommandExecutionController() // let projectMenuController = ProjectMenuController() private var fileSystemMonitor = nil as FileSystemEventMonitor? init(owner: WorkspaceDocument) { self.owner = owner assert(mainWindowController.fileNavigationViewController.delegate == nil) mainWindowController.fileNavigationViewController.delegate = self mainWindowController.issueReportingViewController.delegate = self mainWindowController.executionNavigationViewController.delegate = self debuggingController.executionTreeViewController = self.mainWindowController.executionNavigationViewController debuggingController.variableTreeViewController = self.mainWindowController.variableInspectingViewController // debuggingController.delegate = self // projectMenuController.reconfigureForWorkspaceInternals(self) } deinit { } } extension InternalController { func buildWorkspace() { mainWindowController.issueReportingViewController.reset() commandQueue.cancelAllCommandExecution() commandQueue.queue(CargoCommand( workspaceRootURL: owner.rootLocation.stringExpression, subcommand: CargoCommand.Subcommand.Build, cargoDelegate: self)) commandQueue.runAllCommandExecution() } /// Build and run default project current workspace. /// By default, this runs `cargo` on workspace root. /// Customisation will be provided later. func runWorkspace() { mainWindowController.issueReportingViewController.reset() commandQueue.cancelAllCommandExecution() commandQueue.queue(CargoCommand( workspaceRootURL: owner.rootLocation.stringExpression, subcommand: CargoCommand.Subcommand.Build, cargoDelegate: self)) commandQueue.queue(LaunchDebuggingSessionCommand( debuggingController: debuggingController, workspaceRootURL: owner.rootLocation.stringExpression)) commandQueue.runAllCommandExecution() } func cleanWorkspace() { mainWindowController.issueReportingViewController.reset() commandQueue.cancelAllCommandExecution() commandQueue.queue(CargoCommand( workspaceRootURL: owner.rootLocation.stringExpression, subcommand: CargoCommand.Subcommand.Clean, cargoDelegate: self)) commandQueue.runAllCommandExecution() } func stopWorkspace() { debuggingController.terminateAllSessions() commandQueue.cancelAllCommandExecution() mainWindowController.executionNavigationViewController.snapshot = nil mainWindowController.variableInspectingViewController.snapshot = nil } } /// MARK: /// MARK: WorkspaceNavigationViewControllerDelegate extension InternalController: WorkspaceNavigationViewControllerDelegate { func workpaceNavigationViewControllerWantsToOpenFileAtURL(u: NSURL) { mainWindowController.codeEditingViewController.URLRepresentation = u } } /// MARK: /// MARK: ExecutionStateTreeViewControllerDelegate extension InternalController: ExecutionStateTreeViewControllerDelegate { private func executionStateTreeViewControllerDidSelectFrame(frame: LLDBFrame?) { mainWindowController.variableInspectingViewController.snapshot = VariableTreeViewController.Snapshot(frame) } } /// MARK: /// MARK: IssueListingViewControllerDelegate extension InternalController: IssueListingViewControllerDelegate { func issueListingViewControllerUserWantsToHighlightURL(file: NSURL?) { Debug.assertMainThread() } func issueListingViewControllerUserWantsToHighlightIssue(issue: Issue) { Debug.assertMainThread() if let o = issue.origin { mainWindowController.codeEditingViewController.URLRepresentation = o.URL mainWindowController.codeEditingViewController.codeTextViewController.codeTextView.navigateToCodeRange(o.range) } } } /// MARK: /// MARK: WorkspaceDebuggingControllerDelegate //extension InternalController: WorkspaceDebuggingControllerDelegate { // func workspaceDebuggingControllerDidLaunchSession() { // projectMenuController.reconfigureAvailabilitiesForWorkspaceInternals(self) // } // func workspaceDebuggingControllerDidTerminateSession() { // projectMenuController.reconfigureAvailabilitiesForWorkspaceInternals(self) // } //} /// MARK: /// MARK: CargoExecutionControllerDelegate extension InternalController: CargoExecutionControllerDelegate { func cargoExecutionControllerDidDiscoverRustCompilationIssue(issue: RustCompilerIssue) { Debug.assertMainThread() // let s = Issue(workspaceRootURL: owner.rootLocation.stringExpression, rust: issue) let s = Issue(rust: issue) mainWindowController.issueReportingViewController.push([s]) } func cargoExecutionControllerDidPrintMessage(s: String) { Debug.assertMainThread() println(s) } func cargoExecutionControllerRemoteProcessDidTerminate() { } } //extension InternalController: FileTreeViewController4Delegate { // func fileTreeViewController4QueryFileSystemSubnodeURLsOfURL(u: NSURL) -> [NSURL] { // Debug.assertMainThread() // // return subnodeAbsoluteURLsOfURL(u) // } // // func fileTreeViewController4UserWantsToCreateFolderInURL(parentFolderURL: NSURL) -> Resolution<NSURL> { // Debug.assertMainThread() // // return FileUtility.createNewFolderInFolder(parentFolderURL) // } // func fileTreeViewController4UserWantsToCreateFileInURL(parentFolderURL: NSURL) -> Resolution<NSURL> { // Debug.assertMainThread() // // return FileUtility.createNewFileInFolder(parentFolderURL) // } // func fileTreeViewController4UserWantsToRenameFileAtURL(from: NSURL, to: NSURL) -> Resolution<()> { // Debug.assertMainThread() // // return fileTreeViewController4UserWantsToMoveFileAtURL(from, to: to) // } // func fileTreeViewController4UserWantsToMoveFileAtURL(from: NSURL, to: NSURL) -> Resolution<()> { // Debug.assertMainThread() // // var err = nil as NSError? // let ok = NSFileManager.defaultManager().moveItemAtURL(from, toURL: to, error: &err) // assert(ok || err != nil) // if ok { // owner.mainWindowController.codeEditingViewController.URLRepresentation = to // } // return ok ? Resolution.success() : Resolution.failure(err!) // } // func fileTreeViewController4UserWantsToDeleteFilesAtURLs(us: [NSURL]) -> Resolution<()> { // Debug.assertMainThread() // // // Just always close the currently editing file. // // Deletion may fail, and then user may see closed document without deletion, // // but it doesn't seem to be bad. So this is an intended design. // owner.mainWindowController.codeEditingViewController.URLRepresentation = nil // // var err = nil as NSError? // for u in us { // let ok = NSFileManager.defaultManager().trashItemAtURL(u, resultingItemURL: nil, error: &err) // assert(ok || err != nil) // if !ok { // return Resolution.failure(err!) // } // } // return Resolution.success() // } // // func fileTreeViewController4UserWantsToEditFileAtURL(u: NSURL) -> Bool { // Debug.assertMainThread() // // owner.mainWindowController.codeEditingViewController.URLRepresentation = u // return true // } //} // //private func subnodeAbsoluteURLsOfURL(absoluteURL:NSURL) -> [NSURL] { // var us1 = [] as [NSURL] // if NSFileManager.defaultManager().fileExistsAtPathAsDirectoryFile(absoluteURL.path!) { // let u1 = absoluteURL // let it1 = NSFileManager.defaultManager().enumeratorAtURL(u1, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles | NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants, errorHandler: { (url:NSURL!, error:NSError!) -> Bool in // fatalError("Unhandled file I/O error!") // TODO: // return false // }) // let it2 = it1! // while let o1 = it2.nextObject() as? NSURL { // us1.append(o1) // } // } // return us1 //}
mit
4802de0fceaee18e6677bb6669eff334
20.004354
271
0.737839
3.930473
false
false
false
false
mozilla-mobile/firefox-ios
Sync/Synchronizers/Downloader.swift
2
9292
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Storage private let log = Logger.syncLogger class BatchingDownloader<T: CleartextPayloadJSON> { let client: Sync15CollectionClient<T> let collection: String let prefs: Prefs var batch: [Record<T>] = [] func store(_ records: [Record<T>]) { self.batch += records } func retrieve() -> [Record<T>] { let ret = self.batch self.batch = [] return ret } var _advance: (() -> Void)? func advance() { guard let f = self._advance else { return } self._advance = nil f() } init(collectionClient: Sync15CollectionClient<T>, basePrefs: Prefs, collection: String) { self.client = collectionClient self.collection = collection let branchName = "downloader." + collection + "." self.prefs = basePrefs.branch(branchName) log.info("Downloader configured with prefs '\(self.prefs.getBranchPrefix())'.") } static func resetDownloaderWithPrefs(_ basePrefs: Prefs, collection: String) { // This leads to stupid paths like 'profile.sync.synchronizer.history..downloader.history..'. // Sorry, but it's out in the world now... let branchName = "downloader." + collection + "." let prefs = basePrefs.branch(branchName) let lm = prefs.timestampForKey("lastModified") let bt = prefs.timestampForKey("baseTimestamp") log.debug("Resetting downloader prefs \(prefs.getBranchPrefix()). Previous values: \(lm ??? "nil"), \(bt ??? "nil").") prefs.removeObjectForKey("nextOffset") prefs.removeObjectForKey("offsetNewer") prefs.removeObjectForKey("baseTimestamp") prefs.removeObjectForKey("lastModified") } /** * Clients should provide the same set of parameters alongside an `offset` as was * provided with the initial request. The only thing that varies in our batch fetches * is `newer`, so we track the original value alongside. */ var nextFetchParameters: (String, Timestamp)? { get { let o = self.prefs.stringForKey("nextOffset") let n = self.prefs.timestampForKey("offsetNewer") guard let offset = o, let newer = n else { return nil } return (offset, newer) } set (value) { if let (offset, newer) = value { self.prefs.setString(offset, forKey: "nextOffset") self.prefs.setTimestamp(newer, forKey: "offsetNewer") } else { self.prefs.removeObjectForKey("nextOffset") self.prefs.removeObjectForKey("offsetNewer") } } } // Set after each batch, from record timestamps. var baseTimestamp: Timestamp { get { return self.prefs.timestampForKey("baseTimestamp") ?? 0 } set (value) { self.prefs.setTimestamp(value, forKey: "baseTimestamp") } } // Only set at the end of a batch, from headers. var lastModified: Timestamp { get { return self.prefs.timestampForKey("lastModified") ?? 0 } set (value) { self.prefs.setTimestamp(value, forKey: "lastModified") } } /** * Call this when a significant structural server change has been detected. */ func reset() -> Success { self.baseTimestamp = 0 self.lastModified = 0 self.nextFetchParameters = nil self.batch = [] self._advance = nil return succeed() } func go(_ info: InfoCollections, limit: Int) -> Deferred<Maybe<DownloadEndState>> { guard let modified = info.modified(self.collection) else { log.debug("No server modified time for collection \(self.collection).") return deferMaybe(.noNewData) } log.debug("Modified: \(modified); last \(self.lastModified).") if modified == self.lastModified { log.debug("No more data to batch-download.") return deferMaybe(.noNewData) } // If the caller hasn't advanced after the last batch, strange things will happen -- // potentially looping indefinitely. Warn. if self._advance != nil && !self.batch.isEmpty { log.warning("Downloading another batch without having advanced. This might be a bug.") } return self.downloadNextBatchWithLimit(limit, infoModified: modified) } func advanceTimestampTo(_ timestamp: Timestamp) { log.debug("Advancing downloader lastModified from \(self.lastModified) to \(timestamp).") self.lastModified = timestamp } // We're either fetching from our current base timestamp with no offset, // or the timestamp we were using when we last saved an offset. func fetchParameters() -> (String?, Timestamp) { if let (offset, since) = self.nextFetchParameters { return (offset, since) } return (nil, max(self.lastModified, self.baseTimestamp)) } func downloadNextBatchWithLimit(_ limit: Int, infoModified: Timestamp) -> Deferred<Maybe<DownloadEndState>> { let (offset, since) = self.fetchParameters() log.debug("Fetching newer=\(since), offset=\(offset ?? "nil").") let fetch = self.client.getSince(since, sort: SortOption.OldestFirst, limit: limit, offset: offset) func handleFailure(_ err: MaybeErrorType) -> Deferred<Maybe<DownloadEndState>> { log.debug("Handling failure.") guard let badRequest = err as? BadRequestError<[Record<T>]>, badRequest.response.metadata.status == 412 else { // Just pass through the failure. return deferMaybe(err) } // Conflict. Start again. log.warning("Server contents changed during offset-based batching. Stepping back.") self.nextFetchParameters = nil return deferMaybe(.interrupted) } func handleSuccess(_ response: StorageResponse<[Record<T>]>) -> Deferred<Maybe<DownloadEndState>> { log.debug("Handling success.") let nextOffset = response.metadata.nextOffset let responseModified = response.value.last?.modified // Queue up our metadata advance. We wait until the consumer has fetched // and processed this batch; they'll call .advance() on success. self._advance = { // Shift to the next offset. This might be nil, in which case… fine! // Note that we preserve the previous 'newer' value from the offset or the original fetch, // even as we update baseTimestamp. self.nextFetchParameters = nextOffset == nil ? nil : (nextOffset!, since) // If there are records, advance to just before the timestamp of the last. // If our next fetch with X-Weave-Next-Offset fails, at least we'll start here. // // This approach is only valid if we're fetching oldest-first. if let newBase = responseModified { log.debug("Advancing baseTimestamp to \(newBase) - 1") self.baseTimestamp = newBase - 1 } if nextOffset == nil { // If we can't get a timestamp from the header -- and we should always be able to -- // we fall back on the collection modified time in i/c, as supplied by the caller. // In any case where there is no racing writer these two values should be the same. // If they differ, the header should be later. If it's missing, and we use the i/c // value, we'll simply redownload some records. // All bets are off if we hit this case and are filtering somehow… don't do that. let lm = response.metadata.lastModifiedMilliseconds log.debug("Advancing lastModified to \(String(describing: lm)) ?? \(infoModified).") self.lastModified = lm ?? infoModified } } log.debug("Got success response with \(response.metadata.records ?? 0) records.") // Store the incoming records for collection. self.store(response.value) return deferMaybe(nextOffset == nil ? .complete : .incomplete) } return fetch.bind { result in guard let response = result.successValue else { return handleFailure(result.failureValue!) } return handleSuccess(response) } } } public enum DownloadEndState: String { case complete // We're done. Records are waiting for you. case incomplete // applyBatch was called, and we think there are more records. case noNewData // There were no records. case interrupted // We got a 412 conflict when fetching the next batch. }
mpl-2.0
9a048126b251729f0fcb101f77ce5e21
40.28
126
0.602498
4.961538
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBATrackedDataSelectionResult.swift
1
3878
// // SBATrackedDataResult.swift // BridgeAppSDK // // 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 open class SBATrackedDataSelectionResult: ORKQuestionResult { open var selectedItems: [SBATrackedDataObject]? override init() { super.init() } public override init(identifier: String) { super.init(identifier: identifier) self.questionType = .multipleChoice } open override var answer: Any? { get { return selectedItems } set { guard let items = newValue as? [SBATrackedDataObject] else { selectedItems = nil return } selectedItems = items } } // MARK: NSCoding public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.selectedItems = aDecoder.decodeObject(forKey: #keyPath(selectedItems)) as? [SBATrackedDataObject] } override open func encode(with aCoder: NSCoder) { super.encode(with: aCoder) aCoder.encode(self.selectedItems, forKey: #keyPath(selectedItems)) } // MARK: NSCopying override open func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) guard let result = copy as? SBATrackedDataSelectionResult else { return copy } result.selectedItems = self.selectedItems return result } // MARK: Equality open override func isEqual(_ object: Any?) -> Bool { guard super.isEqual(object), let obj = object as? SBATrackedDataSelectionResult else { return false } return SBAObjectEquality(self.selectedItems, obj.selectedItems) } override open var hash: Int { return super.hash ^ SBAObjectHash(self.selectedItems) } } extension SBATrackedDataSelectionResult { public override func jsonSerializedAnswer() -> AnswerKeyAndValue? { // Always return a non-nil result for items let selectedItems: NSArray? = self.selectedItems as NSArray? let value = selectedItems?.jsonObject() ?? [] return AnswerKeyAndValue(key: "items", value: value as AnyObject, questionType: .multipleChoice) } }
bsd-3-clause
e3db52b928d3befb20dfad4cdeb32941
36.640777
110
0.695899
4.976893
false
false
false
false
readmeplz/douyu
douyu/HomeViewController.swift
1
1496
// // HomeViewController.swift // douyu // // Created by Apple on 2017/1/22. // Copyright © 2017年 feng. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension HomeViewController{ public func setupUI(){ setupNavigationBar() } public func setupNavigationBar(){ //left buttons let btn = UIButton() btn.setImage(UIImage(named: "logo"),for:.normal) btn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn) //right buttons let historyItem = UIBarButtonItem(imageName: "Image_my_history_click", highImageName: "Image_my_history") //let historyItem = UIBarButtonItem.creatItem(imageName: "Image_my_history_click", highImageName: "Image_my_history") let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked") //let searchItem = UIBarButtonItem.creatItem(imageName: "btn_search", highImageName: "btn_search_clicked") let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click") //let qrcodeItem = UIBarButtonItem.creatItem(imageName: "Image_scan", highImageName: "Image_scan_click") navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } }
mit
c37b464bbb7cd57953e491b22249392b
29.469388
129
0.650368
4.847403
false
false
false
false
andrew8712/DCKit
DCKit/UITextFields/DCMandatoryEmailTextField.swift
2
1591
// // MandatoryEmailTextField.swift // DCKit // // Created by Andrey Gordeev on 02/03/15. // Copyright (c) 2015 Andrey Gordeev ([email protected]). All rights reserved. // import UIKit /// This field is also checks if the entered value is a valid email address. @IBDesignable open class DCMandatoryEmailTextField: DCMandatoryTextField { // MARK: - Initializers // IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out. // http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - Validation override open func isValid() -> Bool { var valid = isValidEmail(text ?? "") // If the field is Mandatory and empty - it's invalid if text == "" { valid = !isMandatory } isSelected = !valid return valid } /** Validates given email address. - note: http://stackoverflow.com/questions/5428304/email-validation-on-textfield-in-iphone-sdk - parameter email: An entered value. - returns: Whether the entered value is a valid email or not. */ open func isValidEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: email) } }
mit
dc256225e6da9d54e9576d18940a3cdf
27.410714
118
0.644249
4.007557
false
false
false
false
RemyDCF/tpg-offline
tpg offline/Project Requirements/App.swift
1
7863
// // App.swift // tpg offline // // Created by Rémy Da Costa Faro on 24/09/2017. // Copyright © 2018 Rémy Da Costa Faro. All rights reserved. // import UIKit import WatchConnectivity #if os(iOS) import Crashlytics import Solar import CoreLocation import Mapbox import FirebaseAnalytics #endif struct App { #if os(iOS) private static var watchSessionManager = WatchSessionManager.shared #endif static var lines: [Line] = [] static var stops: [Stop] = [] static var sortedStops: [String: [String]] = [:] static var stopsKeys: [String] { get { guard let a = (UserDefaults.standard.array(forKey: #function) as? [String]) else { let keys = ["location", "favorites"] + App.sortedStops.keys.sorted() UserDefaults.standard.set(keys, forKey: #function) return ["location", "favorites"] + App.sortedStops.keys.sorted() } return a } set { UserDefaults.standard.set(newValue, forKey: #function) } } static var favoritesStops: [Int] { get { return (UserDefaults.standard.object(forKey: #function) as? [Int]) ?? [] } set { UserDefaults.standard.set(newValue, forKey: #function) #if os(iOS) watchSessionManager.sync() #endif } } static var favoritesRoutes: [Route] { get { let jsonDecoder = JSONDecoder() let jsonData = try? jsonDecoder.decode([Route].self, from: UserDefaults.standard.data(forKey: #function) ?? "" .data(using: .utf8)!) return jsonData ?? [] } set { let jsonEncoder = JSONEncoder() let jsonData = try? jsonEncoder.encode(newValue) UserDefaults.standard.set(jsonData, forKey: #function) #if os(iOS) watchSessionManager.sync() #endif } } static var intentsVersionNumber: NSNumber = 1.0 static var replacementsNames: [String: String] { get { return (UserDefaults.standard.dictionary(forKey: #function) as? [String: String]) ?? [:] } set { UserDefaults.standard.set(newValue, forKey: #function) #if os(iOS) watchSessionManager.sync() #endif } } #if os(iOS) static var sunriseSunsetManager = Solar(coordinate: CLLocationCoordinate2D(latitude: 46.204391, longitude: 6.143158)) #endif static var darkMode: Bool { get { return (UserDefaults.standard.bool(forKey: #function)) } set { UserDefaults.standard.set(newValue, forKey: #function) #if os(iOS) ColorModeManager.shared.updateColorMode() #endif } } #if os(iOS) static var automaticDarkMode: Bool { // Here, get and set are inverted to set this value to true by default get { return !(UserDefaults.standard.bool(forKey: #function)) } set { UserDefaults.standard.set(!newValue, forKey: #function) } } #endif static var fabric: Bool { // Here, get and set are inverted to set this value to true by default get { return !(UserDefaults.standard.bool(forKey: #function)) } set { UserDefaults.standard.set(!newValue, forKey: #function) } } static var automaticDeparturesDownload: Bool { // Here, get and set are inverted to set this value to true by default get { return !(UserDefaults.standard.bool(forKey: #function)) } set { UserDefaults.standard.set(!newValue, forKey: #function) } } static var indexedStops: [Int] { get { return (UserDefaults.standard.array(forKey: #function) as? [Int]) ?? [] } set { UserDefaults.standard.set(newValue, forKey: #function) } } static var favoritesLines: [String] { get { return (UserDefaults.standard.array(forKey: #function) as? [String]) ?? [] } set { UserDefaults.standard.set(newValue, forKey: #function) } } static var filterFavoritesLines: Bool { get { return UserDefaults.standard.bool(forKey: #function) } set { UserDefaults.standard.set(newValue, forKey: #function) } } static var defaultTab: Int { get { return UserDefaults.standard.integer(forKey: #function) } set { UserDefaults.standard.set(newValue, forKey: #function) } } #if os(iOS) static var downloadMaps: Bool { // Here, get and set are inverted to set this value to true by default get { return !(UserDefaults.standard.bool(forKey: #function)) } set { UserDefaults.standard.set(!newValue, forKey: #function) if newValue == false { for pack in MGLOfflineStorage.shared.packs ?? [] { MGLOfflineStorage.shared.removePack(pack, withCompletionHandler: nil) } } } } static var allowDownloadWithMobileData: Bool { get { return UserDefaults.standard.bool(forKey: #function) } set { UserDefaults.standard.set(newValue, forKey: #function) } } #endif static var separatorColor: UIColor { return App.darkMode ? #colorLiteral(red: 0.2313459218, green: 0.2313911617, blue: 0.2313399315, alpha: 1) : .gray } @discardableResult static func loadStops(forceLocal: Bool = false) -> Bool { do { let data: Data if let dataA = UserDefaults.standard.data(forKey: "stops.json"), !forceLocal { data = dataA } else { do { data = try Data(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "stops", ofType: "json")!)) } catch { print("Can't load stops") //Crashlytics.sharedInstance().recordError(error) return false } } let decoder = JSONDecoder() let stops = try decoder.decode([Stop].self, from: data) App.stops = stops.sorted(by: { $0.name < $1.name }) for stop in App.stops.map({ $0.name }) { let character = "\(stop.first!)" App.sortedStops[character, default: []].append(stop) } for (i, id) in App.favoritesStops.enumerated() { if App.stops.filter({ $0.appId == id })[safe: 0] == nil { App.favoritesStops.remove(at: i) } } return true } catch { return loadStops(forceLocal: true) } } static var textColor: UIColor { return darkMode ? .white : #colorLiteral(red: 0.2392156863, green: 0.1960784314, blue: 0.1843137255, alpha: 1) } static var cellBackgroundColor: UIColor { return darkMode ? UIColor.black : .white } @discardableResult static func loadLines(forceLocal: Bool = false) -> Bool { do { let data: Data if let dataA = UserDefaults.standard.data(forKey: "lines.json"), !forceLocal { data = dataA } else { do { data = try Data(contentsOf: URL(fileURLWithPath: Bundle.main.path(forResource: "lines", ofType: "json")!)) } catch { print("Can't load lines") return false } } let decoder = JSONDecoder() let lines = try decoder.decode([Line].self, from: data) App.lines = lines.sorted(by: { if let a = Int($0.line), let b = Int($1.line) { return a < b } else { return $0.line < $1.line }}) return true } catch { return loadLines(forceLocal: true) } } #if os(iOS) static func log(_ string: String) { #if DEBUG print("🔸 \(string)") #else if App.fabric { CLSLogv("%@", getVaList([string])) } #endif } static func logEvent(_ name: String, attributes: [String: Any]) { #if DEBUG print("🔸 Event logged: \(name)") #else if App.fabric { Analytics.logEvent(name, parameters: attributes) } #endif } static func logEvent(_ name: String) { #if DEBUG print("🔸 Event logged: \(name)") #else if App.fabric { Analytics.logEvent(name, parameters: [:]) } #endif } #endif }
mit
c76973859d6383575520622f7d7f80a6
25.704082
117
0.610368
3.959153
false
false
false
false
KyoheiG3/TableViewDragger
TableViewDragger/TableViewDragger.swift
1
14033
// // TableViewDragger.swift // TableViewDragger // // Created by Kyohei Ito on 2015/09/24. // Copyright © 2015年 kyohei_ito. All rights reserved. // import UIKit @objc public protocol TableViewDraggerDelegate: class { /// If allow movement of cell, please return `true`. require a call to `moveRowAt:toIndexPath:` of UITableView and rearranged of data. func dragger(_ dragger: TableViewDragger, moveDraggingAt indexPath: IndexPath, newIndexPath: IndexPath) -> Bool /// If allow dragging of cell, prease return `true`. @objc optional func dragger(_ dragger: TableViewDragger, shouldDragAt indexPath: IndexPath) -> Bool @objc optional func dragger(_ dragger: TableViewDragger, willBeginDraggingAt indexPath: IndexPath) @objc optional func dragger(_ dragger: TableViewDragger, didBeginDraggingAt indexPath: IndexPath) @objc optional func dragger(_ dragger: TableViewDragger, willEndDraggingAt indexPath: IndexPath) @objc optional func dragger(_ dragger: TableViewDragger, didEndDraggingAt indexPath: IndexPath) } @objc public protocol TableViewDraggerDataSource: class { /// Return any cell if want to change the cell in drag. @objc optional func dragger(_ dragger: TableViewDragger, cellForRowAt indexPath: IndexPath) -> UIView? /// Return the indexPath if want to change the indexPath to start drag. @objc optional func dragger(_ dragger: TableViewDragger, indexPathForDragAt indexPath: IndexPath) -> IndexPath } open class TableViewDragger: NSObject { let longPressGesture = UILongPressGestureRecognizer() let panGesture = UIPanGestureRecognizer() var draggingCell: TableViewDraggerCell? var displayLink: CADisplayLink? var targetClipsToBounds = true weak var targetTableView: UITableView? private var draggingDirection: UIScrollView.DraggingDirection? /// It will be `true` if want to hide the original cell. open var isHiddenOriginCell: Bool = true /// Zoom scale of cell in drag. open var zoomScaleForCell: CGFloat = 1 /// Alpha of cell in drag. open var alphaForCell: CGFloat = 1 /// Opacity of cell shadow in drag. open var opacityForShadowOfCell: Float = 0.4 /// Velocity of auto scroll in drag. open var scrollVelocity: CGFloat = 1 open weak var delegate: TableViewDraggerDelegate? open weak var dataSource: TableViewDraggerDataSource? // open var availableHorizontalScroll : Bool = true open var tableView: UITableView? { return targetTableView } /// `UITableView` want to drag. public init(tableView: UITableView, _ minimumPressDuration: CFTimeInterval = 0.5) { super.init() self.targetTableView = tableView tableView.addGestureRecognizer(longPressGesture) tableView.addGestureRecognizer(panGesture) longPressGesture.addTarget(self, action: #selector(TableViewDragger.longPressGestureAction(_:))) longPressGesture.delegate = self longPressGesture.allowableMovement = 5.0 longPressGesture.minimumPressDuration = minimumPressDuration panGesture.addTarget(self, action: #selector(TableViewDragger.panGestureAction(_:))) panGesture.delegate = self panGesture.maximumNumberOfTouches = 1 } deinit { targetTableView?.removeGestureRecognizer(longPressGesture) targetTableView?.removeGestureRecognizer(panGesture) } func targetIndexPath(_ tableView: UITableView, draggingCell: TableViewDraggerCell) -> IndexPath { let location = draggingCell.location let offsetY = (draggingCell.viewHeight / 2) + 2 let offsetX = tableView.center.x let topPoint = CGPoint(x: offsetX, y: location.y - offsetY) let bottomPoint = CGPoint(x: offsetX, y: location.y + offsetY) let point = draggingDirection == .up ? topPoint : bottomPoint if let targetIndexPath = tableView.indexPathForRow(at: point) { if tableView.cellForRow(at: targetIndexPath) == nil { return draggingCell.dropIndexPath } let targetRect = tableView.rectForRow(at: targetIndexPath) let targetCenterY = targetRect.origin.y + (targetRect.height / 2) guard let direction = draggingDirection else { return draggingCell.dropIndexPath } switch direction { case .up: if (targetCenterY > point.y && draggingCell.dropIndexPath > targetIndexPath) { return targetIndexPath } case .down: if (targetCenterY < point.y && draggingCell.dropIndexPath < targetIndexPath) { return targetIndexPath } } } else { let section = (0..<tableView.numberOfSections).filter { section -> Bool in tableView.rect(forSection: section).contains(point) }.first if let section = section, tableView.numberOfRows(inSection: section) == 0 { return IndexPath(row: 0, section: section) } } return draggingCell.dropIndexPath } func dragCell(_ tableView: UITableView, draggingCell: TableViewDraggerCell) { let indexPath = targetIndexPath(tableView, draggingCell: draggingCell) if draggingCell.dropIndexPath.compare(indexPath) == .orderedSame { return } if let cell = tableView.cellForRow(at: draggingCell.dropIndexPath) { cell.isHidden = isHiddenOriginCell } if delegate?.dragger(self, moveDraggingAt: draggingCell.dropIndexPath, newIndexPath: indexPath) == true { draggingCell.dropIndexPath = indexPath } } func copiedCell(at indexPath: IndexPath) -> UIView? { if let view = dataSource?.dragger?(self, cellForRowAt: indexPath) { return view } if let cell = targetTableView?.cellForRow(at: indexPath) { if let view = cell.snapshotView(afterScreenUpdates: false) { return view } else if let view = cell.captured() { view.frame = cell.bounds return view } } return nil } func draggedCell(_ tableView: UITableView, indexPath: IndexPath) -> TableViewDraggerCell? { guard let copiedCell = copiedCell(at: indexPath) else { return nil } let cellRect = tableView.rectForRow(at: indexPath) copiedCell.frame.size = cellRect.size if let height = tableView.delegate?.tableView?(tableView, heightForRowAt: indexPath) { copiedCell.frame.size.height = height } let cell = TableViewDraggerCell(cell: copiedCell) cell.dragScale = zoomScaleForCell cell.dragAlpha = alphaForCell cell.dragShadowOpacity = opacityForShadowOfCell cell.dropIndexPath = indexPath return cell } } // MARK: - Dragging Cell extension TableViewDragger { private func draggingDidBegin(_ gesture: UIGestureRecognizer, indexPath: IndexPath) { displayLink?.invalidate() displayLink = UIScreen.main.displayLink(withTarget: self, selector: #selector(TableViewDragger.displayDidRefresh(_:))) displayLink?.add(to: .main, forMode: .default) displayLink?.isPaused = true let dragIndexPath = dataSource?.dragger?(self, indexPathForDragAt: indexPath) ?? indexPath delegate?.dragger?(self, willBeginDraggingAt: dragIndexPath) if let tableView = targetTableView { let actualCell = tableView.cellForRow(at: dragIndexPath) if let draggedCell = draggedCell(tableView, indexPath: dragIndexPath) { let point = gesture.location(in: actualCell) if availableHorizontalScroll == true{ draggedCell.offset = point draggedCell.transformToPoint(point) draggedCell.location = gesture.location(in: tableView) } else { draggedCell.offset = CGPoint(x: (draggedCell.frame.size.width)/2, y: point.y) draggedCell.transformToPoint(CGPoint(x: (draggedCell.frame.size.width)/2, y: point.y)) draggedCell.location = CGPoint(x: (draggedCell.frame.size.width)/2, y: gesture.location(in: tableView).y) } tableView.addSubview(draggedCell) draggingCell = draggedCell } actualCell?.isHidden = isHiddenOriginCell targetClipsToBounds = tableView.clipsToBounds tableView.clipsToBounds = false } delegate?.dragger?(self, didBeginDraggingAt: indexPath) } private func draggingDidChange(_ gesture: UIGestureRecognizer, direction: UIScrollView.DraggingDirection?) { guard let tableView = targetTableView, let draggingCell = draggingCell else { return } if availableHorizontalScroll == true{ draggingCell.location = gesture.location(in: tableView) } else { draggingCell.location = CGPoint(x: (draggingCell.frame.size.width)/2, y: gesture.location(in: tableView).y) } if let adjustedDirection = tableView.draggingDirection(at: draggingCell.adjustedCenter(on: tableView)) { displayLink?.isPaused = false draggingDirection = adjustedDirection } else { draggingDirection = direction } dragCell(tableView, draggingCell: draggingCell) } private func draggingDidEnd(_ gesture: UIGestureRecognizer) { displayLink?.invalidate() displayLink = nil guard let tableView = targetTableView, let draggingCell = draggingCell else { return } delegate?.dragger?(self, willEndDraggingAt: draggingCell.dropIndexPath) let targetRect = tableView.rectForRow(at: draggingCell.dropIndexPath) let center = CGPoint(x: targetRect.width / 2, y: targetRect.origin.y + (targetRect.height / 2)) draggingCell.drop(center) { self.delegate?.dragger?(self, didEndDraggingAt: draggingCell.dropIndexPath) if let cell = tableView.cellForRow(at: draggingCell.dropIndexPath) { cell.isHidden = false } tableView.clipsToBounds = self.targetClipsToBounds self.draggingCell = nil } } } // MARK: - Action Methods private extension TableViewDragger { @objc func displayDidRefresh(_ displayLink: CADisplayLink) { guard let tableView = targetTableView, let draggingCell = draggingCell else { return } let center = draggingCell.adjustedCenter(on: tableView) if let direction = tableView.draggingDirection(at: center) { draggingDirection = direction } else { displayLink.isPaused = true } tableView.contentOffset = tableView.preferredContentOffset(at: center, velocity: scrollVelocity) dragCell(tableView, draggingCell: draggingCell) if availableHorizontalScroll == true{ draggingCell.location = panGesture.location(in: tableView) } else { draggingCell.location = CGPoint(x: draggingCell.frame.size.width/2, y: panGesture.location(in: tableView).y) } } @objc func longPressGestureAction(_ gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: targetTableView?.isScrollEnabled = false let point = gesture.location(in: targetTableView) if let path = targetTableView?.indexPathForRow(at: point) { draggingDidBegin(gesture, indexPath: path) } case .ended, .cancelled: draggingDidEnd(gesture) targetTableView?.isScrollEnabled = true case .changed, .failed, .possible: break } } @objc func panGestureAction(_ gesture: UIPanGestureRecognizer) { guard targetTableView?.isScrollEnabled == false && gesture.state == .changed else { return } let offsetY = gesture.translation(in: targetTableView).y if offsetY < 0 { draggingDidChange(gesture, direction: .up) } else if offsetY > 0 { draggingDidChange(gesture, direction: .down) } else { draggingDidChange(gesture, direction: nil) } gesture.setTranslation(.zero, in: targetTableView) } } // MARK: - UIGestureRecognizerDelegate Methods extension TableViewDragger: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if gestureRecognizer == longPressGesture { let point = touch.location(in: targetTableView) if let indexPath = targetTableView?.indexPathForRow(at: point) { if let ret = delegate?.dragger?(self, shouldDragAt: indexPath) { return ret } } else { return false } } return true } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return gestureRecognizer == panGesture || otherGestureRecognizer == panGesture || gestureRecognizer == longPressGesture || otherGestureRecognizer == longPressGesture } } extension UIView { fileprivate func captured() -> UIView? { let data = NSKeyedArchiver.archivedData(withRootObject: self) return NSKeyedUnarchiver.unarchiveObject(with: data) as? UIView } }
mit
39980e65aae5abbbf327bd2a39645a29
37.333333
173
0.64191
5.56084
false
false
false
false
netease-app/NIMSwift
Example/NIMSwift/Classes/IM/Contact/IMTeamListControllerBase.swift
1
2588
// // IMTeamListControllerBase.swift // NIMSwift // // 群/团队的列表页面的父类 // // Created by 衡成飞 on 6/17/17. // Copyright © 2017 qianwang365. All rights reserved. // import UIKit class IMTeamListControllerBase: UIViewController,UITableViewDataSource,UITableViewDelegate,NIMTeamManagerDelegate{ @IBOutlet weak var tableView: UITableView! var myTeams:[NIMTeam]? = [] //选择的团队 var selectedIndexPaths:[IndexPath] = [] //选择的团队 var selectedGroups:[[String:String]] = [] /** 点击完成的回调 **/ var finishHandler:((_ groups:[[String:String]]) -> Void)? deinit { NIMSDK.shared().teamManager.remove(self) } override func viewDidLoad() { super.viewDidLoad() self.myTeams = fetchTeams() NIMSDK.shared().teamManager.add(self) tableView.tableFooterView = UIView() setupNavigation() } func setupNavigation(){ navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back_nav") navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "back_nav") navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil) } /** 子类实现 **/ func fetchTeams() -> [NIMTeam]?{ return nil } // MARK: - UITableViewDataSource,UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let n = myTeams?.count { return n } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "List Cell", for: indexPath) let t = myTeams![indexPath.row] cell.contentView.subviews.flatMap{$0 as? UIImageView}.first?.image = UIImage(named:"team_default") if let u = t.avatarUrl ,NSURL(string: u) != nil { cell.contentView.subviews.flatMap{$0 as? UIImageView}.first?.cf_setImage(url: NSURL(string:u)!, placeHolderImage: UIImage(named:"team_default")) } cell.contentView.subviews.flatMap{$0 as? UILabel}.first?.text = t.teamName return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
mit
b7ae48a5f68af2ea93d58ad281b4a67f
29.301205
156
0.635785
4.683426
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI/Appearance.swift
1
907
// // Appearance.swift // VBVMI // // Created by Thomas Carey on 27/02/16. // Copyright © 2016 Tom Carey. All rights reserved. // import UIKit enum Theme : Int { case `default` = 0 func applyTheme() { //UIButton.appearanceWhenContainedInInstancesOfClasses([UITableViewCell.self]).setTitleColor(StyleKit.darkGrey, forState: .Normal) //UILabel.appearanceWhenContainedInInstancesOfClasses([LessonTableViewCell.self]).textColor = StyleKit.darkGrey UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: StyleKit.darkGrey], for: UIControlState()) UIBarButtonItem.appearance().tintColor = StyleKit.darkGrey UISegmentedControl.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).tintColor = StyleKit.darkGrey TopicButton.appearance().tintColor = StyleKit.midGrey } }
mit
437b6a856b59709fbeaa63c3259bfa2a
33.846154
142
0.722958
5.298246
false
false
false
false
aliceatlas/daybreak
Classes/SBSectionListView.swift
1
15599
/* SBSectionListView.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike 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. 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 BLKGUI private let kSBSectionTitleHeight: CGFloat = 32.0 private let kSBSectionItemHeight: CGFloat = 32.0 private let kSBSectionMarginX: CGFloat = 10.0 private let kSBSectionTopMargin: CGFloat = 10.0 private let kSBSectionBottomMargin: CGFloat = 20.0 private let kSBSectionMarginY: CGFloat = kSBSectionTopMargin + kSBSectionBottomMargin private let kSBSectionInnerMarginX: CGFloat = 15.0 class SBSectionListView: SBView { private lazy var contentView: NSView = { NSView(frame: self.bounds) }() private var sectionGroupViews: [SBSectionGroupView] = [] private lazy var scrollView: NSScrollView = { let clipView = BLKGUI.ClipView(frame: self.bounds) let scrollView = NSScrollView(frame: self.bounds) scrollView.contentView = clipView scrollView.autoresizingMask = [.ViewWidthSizable, .ViewHeightSizable] scrollView.drawsBackground = false scrollView.hasHorizontalScroller = false scrollView.hasVerticalScroller = true scrollView.documentView = self.contentView scrollView.autohidesScrollers = true return scrollView }() var sections: [SBSectionGroup] = [] { didSet { if sections != oldValue { contentView.frame = contentViewRect contentView.scrollRectToVisible(NSMakeRect(0, contentView.frame.maxY, 0, 0)) constructSectionGroupViews() } } } override init(frame: NSRect) { super.init(frame: frame) addSubview(scrollView) } required init(coder: NSCoder) { fatalError("NSCoding not supported") } private var contentViewRect: NSRect { var r = NSZeroRect r.size.width = bounds.size.width - 20.0 for group in sections { r.size.height += CGFloat(group.items.count) * kSBSectionItemHeight + kSBSectionTitleHeight + kSBSectionMarginY } return r } private func groupViewRectAtIndex(index: Int) -> NSRect { var r = NSZeroRect let height = contentViewRect.size.height r.size.width = bounds.size.width - 20.0 for (i, group) in enumerate(sections) { let h = CGFloat(group.items.count) * kSBSectionItemHeight + kSBSectionTitleHeight + kSBSectionMarginY if i < index { r.origin.y += h } else { r.size.height = h break } } r.origin.y = height - r.maxY return r } private func constructSectionGroupViews() { for sectionView in sectionGroupViews { sectionView.removeFromSuperview() } sectionGroupViews = [] for (i, group) in enumerate(sections) { let gr = groupViewRectAtIndex(i) let groupView = SBSectionGroupView(frame: gr, group: group) groupView.autoresizingMask = .ViewWidthSizable for item in group.items { let itemView = SBSectionItemView(item: item) itemView.autoresizingMask = .ViewWidthSizable groupView.addItemView(itemView) } contentView.addSubview(groupView) } } } class SBSectionGroupView: SBView { var itemViews: [SBSectionItemView] = [] var group: SBSectionGroup init(frame: NSRect, group: SBSectionGroup) { self.group = group super.init(frame: frame) } required init(coder: NSCoder) { fatalError("NSCoding not supported") } private func itemViewRectAtIndex(index: Int) -> NSRect { var r = NSZeroRect r.size.width = bounds.size.width - kSBSectionMarginX * 2 r.size.height = kSBSectionItemHeight r.origin.x = kSBSectionMarginX r.origin.y = CGFloat(index) * kSBSectionItemHeight + kSBSectionTitleHeight + kSBSectionTopMargin r.origin.y = bounds.size.height - r.maxY return r } func addItemView(itemView: SBSectionItemView) { itemView.frame = itemViewRectAtIndex(itemViews.count) itemView.constructControl() itemViews.append(itemView) addSubview(itemView) } override func drawRect(rect: NSRect) { var r = bounds r.origin.x += kSBSectionMarginX r.origin.y += kSBSectionBottomMargin r.size.width -= kSBSectionMarginX * 2 r.size.height -= kSBSectionMarginY // Paths // Gray scales let path = NSBezierPath(roundedRect: r, xRadius: 8.0, yRadius: 8.0) let strokePath = NSBezierPath(roundedRect: NSInsetRect(r, 0.5, 0.5), xRadius: 8.0, yRadius: 8.0) let shadowColor = NSColor(calibratedWhite: 0.5, alpha: 1.0) let shadow = NSShadow() shadow.shadowColor = shadowColor shadow.shadowBlurRadius = 5.0 // Fill SBPreserveGraphicsState { shadow.shadowOffset = NSMakeSize(0.0, -2.0) shadow.set() NSColor.whiteColor().set() path.fill() } // Gradient SBPreserveGraphicsState { shadow.shadowOffset = NSMakeSize(0.0, 10.0) shadow.set() let gradient = NSGradient(startingColor: .init(deviceWhite: 0.9, alpha: 1.0), endingColor: .whiteColor())! gradient.drawInBezierPath(path, angle: 90) } // Stroke let strokeColor = NSColor(deviceWhite: 0.2, alpha: 1.0) strokeColor.set() strokePath.lineWidth = 0.5 strokePath.stroke() let groupTitle = group.title as NSString var attributes: [String: AnyObject] var tr = r tr.origin.x += kSBSectionInnerMarginX tr.size.height = 24.0 tr.origin.y += r.size.height - tr.size.height - 5.0 tr.size.width -= kSBSectionInnerMarginX * 2 attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(13.0), NSForegroundColorAttributeName: NSColor(calibratedWhite: 0.65, alpha: 1.0)] groupTitle.drawInRect(tr, withAttributes: attributes) tr.origin.y -= 1.0 tr.origin.x += 1.0 attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(13.0), NSForegroundColorAttributeName: NSColor(calibratedWhite: 0.55, alpha: 1.0)] groupTitle.drawInRect(tr, withAttributes: attributes) tr.origin.x -= 2.0 attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(13.0), NSForegroundColorAttributeName: NSColor(calibratedWhite: 0.55, alpha: 1.0)] groupTitle.drawInRect(tr, withAttributes: attributes) tr.origin.y -= 2.0 tr.origin.x += 1.0 attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(13.0), NSForegroundColorAttributeName: NSColor(calibratedWhite: 0.45, alpha: 1.0)] groupTitle.drawInRect(tr, withAttributes: attributes) tr.origin.y += 2.0 attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(13.0), NSForegroundColorAttributeName: NSColor.whiteColor()] groupTitle.drawInRect(tr, withAttributes: attributes) } } class SBSectionItemView: SBView, NSTextFieldDelegate { var item: SBSectionItem weak var currentImageView: NSImageView? weak var currentField: NSTextField? init(item: SBSectionItem) { self.item = item super.init(frame: .zero) } required init(coder: NSCoder) { fatalError("NSCoding not supported") } var titleRect: NSRect { var r = bounds r.size.width = r.size.width * 0.4 return r } var valueRect: NSRect { var r = bounds let margin: CGFloat = 10.0 r.origin.x = r.size.width * 0.4 + margin r.size.width = r.size.width * 0.6 - margin * 2 return r } func constructControl() { var r = valueRect if item.controlClass === NSPopUpButton.self { let string = SBPreferences.objectForKey(item.keyName) as? String r.origin.y = (r.size.height - 26.0) / 2 r.size.height = 26.0 let popUp = NSPopUpButton(frame: r, pullsDown: false) if let menu = item.context as? NSMenu { popUp.target = self popUp.action = #selector(select(_:)) popUp.menu = menu } if let selectedItem = popUp.menu!.selectItem(representedObject: string) { popUp.selectItem(selectedItem) } addSubview(popUp) } else if item.controlClass === NSTextField.self { r.origin.y = (r.size.height - 22.0) / 2 r.size.height = 22.0 let field = NSTextField(frame: r) field.delegate = self field.focusRingType = .None field.cell!.placeholderString = item.context as? String field.stringValue = (SBPreferences.objectForKey(item.keyName) as? String) ?? "" addSubview(field) } else if item.controlClass === NSOpenPanel.self { var fr = r var ir = r var br = r ir.size.width = 22 br.size.width = 120 fr.origin.x += ir.size.width fr.size.width -= ir.size.width + br.size.width br.origin.x += ir.size.width + fr.size.width ir.origin.y = (ir.size.height - 22.0) / 2 ir.size.height = 22.0 fr.origin.y = (fr.size.height - 22.0) / 2 fr.size.height = 22.0 br.origin.y = (br.size.height - 32.0) / 2 br.size.height = 32.0 let button = NSButton(frame: br) button.target = self button.action = #selector(open(_:)) button.title = NSLocalizedString("Open…", comment: "") button.setButtonType(.MomentaryLightButton) button.bezelStyle = .RoundedBezelStyle let imageView = NSImageView(frame: ir) let space = NSWorkspace.sharedWorkspace() let path = SBPreferences.objectForKey(item.keyName) as? String if let image = path !! space.iconForFile { image.size = NSMakeSize(16.0, 16.0) imageView.image = image } imageView.imageFrameStyle = .None let field = NSTextField(frame: fr) field.bordered = false field.selectable = false field.editable = false field.drawsBackground = false field.cell!.placeholderString = item.context as? String field.stringValue = path?.stringByAbbreviatingWithTildeInPath ?? "" addSubviews(imageView, field, button) currentImageView = imageView currentField = field } else if item.controlClass === NSButton.self { let enabled = SBPreferences.boolForKey(item.keyName) r.origin.y = (r.size.height - 18.0) / 2 r.size.height = 18.0 let button = NSButton(frame: r) button.target = self button.action = #selector(check(_:)) button.setButtonType(.SwitchButton) button.title = (item.context as? String) ?? "" button.state = enabled ? NSOnState : NSOffState addSubview(button) } } // MARK: Delegate override func controlTextDidChange(notification: NSNotification) { let field = notification.object as! NSTextField let text = field.stringValue SBPreferences.setObject(text, forKey: item.keyName) } // MARK: Actions func select(sender: AnyObject) { //kSBOpenURLFromApplications //kSBDefaultEncoding if let selectedItem = (sender as? NSPopUpButton)?.selectedItem, representedObject: AnyObject = selectedItem.representedObject { SBPreferences.setObject(representedObject, forKey: item.keyName) } } func open(sender: AnyObject) { let panel = SBOpenPanel() panel.allowsMultipleSelection = false panel.canChooseFiles = false panel.canChooseDirectories = true panel.beginSheetModalForWindow(window!) { panel.orderOut(nil) if $0 == NSFileHandlingPanelOKButton, let imageView = self.currentImageView, field = self.currentField { let space = NSWorkspace.sharedWorkspace() let path = panel.URL!.path! let image = space.iconForFile(path) image.size = NSMakeSize(16.0, 16.0) imageView.image = image field.stringValue = path.stringByAbbreviatingWithTildeInPath SBPreferences.setObject(path, forKey: self.item.keyName) } } } func check(sender: AnyObject) { let enabled = sender.state == NSOnState SBPreferences.setBool(enabled, forKey: item.keyName) } // MARK: Drawing override func drawRect(rect: NSRect) { var r = bounds // Stroke let margin: CGFloat = 10.0 let path = NSBezierPath() path.moveToPoint(NSMakePoint(r.origin.x + margin, r.maxY)) path.lineToPoint(NSMakePoint(r.maxX - margin * 2, r.maxY)) path.lineWidth = 0.5 NSColor(deviceWhite: 0.6, alpha: 1.0).set() path.stroke() let titleString: NSString = item.title + " :" var titleRect = self.titleRect let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Right let attributes = [NSFontAttributeName: NSFont.boldSystemFontOfSize(12.0), NSForegroundColorAttributeName: NSColor(calibratedWhite: 0.3, alpha: 1.0), NSParagraphStyleAttributeName: paragraphStyle] titleRect.size.height = titleString.sizeWithAttributes(attributes).height titleRect.origin.y = (bounds.size.height - titleRect.size.height) / 2 titleString.drawInRect(titleRect, withAttributes: attributes) } }
bsd-2-clause
f9bdbed40a964c8621007659e900f2ee
37.897756
122
0.614349
4.788763
false
false
false
false
cezheng/Fuzi
Sources/Queryable.swift
1
11054
// Queryable.swift // Copyright (c) 2015 Ce Zheng // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import libxml2 /** * The `Queryable` protocol is adopted by `XMLDocument`, `HTMLDocument` and `XMLElement`, denoting that they can search for elements using XPath or CSS selectors. */ public protocol Queryable { /** Returns the results for an XPath selector. - parameter xpath: XPath selector string. - returns: An enumerable collection of results. */ func xpath(_ xpath: String) -> NodeSet /** Returns the results for an XPath selector. - parameter xpath: XPath selector string. - returns: An enumerable collection of results. - Throws: last registered XMLError, most likely libXMLError with code and message. */ func tryXPath(_ xpath: String) throws -> NodeSet /** Returns the first elements matching an XPath selector, or `nil` if there are no results. - parameter xpath: The XPath selector. - returns: The child element. */ func firstChild(xpath: String) -> XMLElement? /** Returns the results for a CSS selector. - parameter css: The CSS selector string. - returns: An enumerable collection of results. */ func css(_ css: String) -> NodeSet /** Returns the first elements matching an CSS selector, or `nil` if there are no results. - parameter css: The CSS selector. - returns: The child element. */ func firstChild(css: String) -> XMLElement? /** Returns the result for evaluating an XPath selector that contains XPath function. - parameter xpath: The XPath query string. - returns: The eval function result. */ func eval(xpath: String) -> XPathFunctionResult? } /// Result for evaluating a XPath expression open class XPathFunctionResult { /// Boolean value open fileprivate(set) lazy var boolValue: Bool = { return self.cXPath.pointee.boolval != 0 }() /// Double value open fileprivate(set) lazy var doubleValue: Double = { return self.cXPath.pointee.floatval }() /// String value open fileprivate(set) lazy var stringValue: String = { return ^-^self.cXPath.pointee.stringval ?? "" }() fileprivate let cXPath: xmlXPathObjectPtr internal init?(cXPath: xmlXPathObjectPtr?) { guard let cXPath = cXPath else { return nil } self.cXPath = cXPath } deinit { xmlXPathFreeObject(cXPath) } } extension XMLDocument: Queryable { /** Returns the results for an XPath selector. - parameter xpath: XPath selector string. - returns: An enumerable collection of results. */ public func xpath(_ xpath: String) -> NodeSet { return root == nil ?XPathNodeSet.emptySet :root!.xpath(xpath) } /** - parameter xpath: XPath selector string. - returns: An enumerable collection of results. - Throws: last registered XMLError, most likely libXMLError with code and message. */ public func tryXPath(_ xpath: String) throws -> NodeSet { guard let rootNode = root else { return XPathNodeSet.emptySet } return try rootNode.tryXPath(xpath) } /** Returns the first elements matching an XPath selector, or `nil` if there are no results. - parameter xpath: The XPath selector. - returns: The child element. */ public func firstChild(xpath: String) -> XMLElement? { return root?.firstChild(xpath: xpath) } /** Returns the results for a CSS selector. - parameter css: The CSS selector string. - returns: An enumerable collection of results. */ public func css(_ css: String) -> NodeSet { return root == nil ?XPathNodeSet.emptySet :root!.css(css) } /** Returns the first elements matching an CSS selector, or `nil` if there are no results. - parameter css: The CSS selector. - returns: The child element. */ public func firstChild(css: String) -> XMLElement? { return root?.firstChild(css: css) } /** Returns the result for evaluating an XPath selector that contains XPath function. - parameter xpath: The XPath query string. - returns: The eval function result. */ public func eval(xpath: String) -> XPathFunctionResult? { return root?.eval(xpath: xpath) } } extension XMLElement: Queryable { /** Returns the results for an XPath selector. - parameter xpath: XPath selector string. - returns: An enumerable collection of results. */ public func xpath(_ xpath: String) -> NodeSet { guard let cXPath = try? self.cXPath(xpathString: xpath) else { return XPathNodeSet.emptySet } return XPathNodeSet(cXPath: cXPath, document: document) } /** - parameter xpath: XPath selector string. - returns: An enumerable collection of results. - Throws: last registered XMLError, most likely libXMLError with code and message. */ public func tryXPath(_ xpath: String) throws -> NodeSet { return XPathNodeSet(cXPath: try self.cXPath(xpathString: xpath), document: document) } /** Returns the first elements matching an XPath selector, or `nil` if there are no results. - parameter xpath: The XPath selector. - returns: The child element. */ public func firstChild(xpath: String) -> XMLElement? { return self.xpath(xpath).first } /** Returns the results for a CSS selector. - parameter css: The CSS selector string. - returns: An enumerable collection of results. */ public func css(_ css: String) -> NodeSet { return xpath(XPath(fromCSS:css)) } /** Returns the first elements matching an CSS selector, or `nil` if there are no results. - parameter css: The CSS selector. - returns: The child element. */ public func firstChild(css: String) -> XMLElement? { return self.css(css).first } /** Returns the result for evaluating an XPath selector that contains XPath function. - parameter xpath: The XPath query string. - returns: The eval function result. */ public func eval(xpath: String) -> XPathFunctionResult? { guard let cXPath = try? cXPath(xpathString: xpath) else { return nil } return XPathFunctionResult(cXPath: cXPath) } fileprivate func cXPath(xpathString: String) throws -> xmlXPathObjectPtr { guard let context = xmlXPathNewContext(cNode.pointee.doc) else { throw XMLError.lastError(defaultError: .xpathError(code: 1207)) } func withXMLChar(_ string: String, _ handler: (UnsafePointer<xmlChar>) -> Void) { string.utf8CString .map { xmlChar(bitPattern: $0) } .withUnsafeBufferPointer { handler($0.baseAddress!) } } context.pointee.node = cNode // Registers namespace prefixes declared in the document. var node = cNode while node.pointee.parent != nil { var curNs = node.pointee.nsDef while let ns = curNs { if let prefix = ns.pointee.prefix { xmlXPathRegisterNs(context, prefix, ns.pointee.href) } curNs = ns.pointee.next } node = node.pointee.parent } // Registers additional namespace prefixes. for (prefix, uri) in document.namespaces { withXMLChar(prefix) { prefix in withXMLChar(uri) { uri in xmlXPathRegisterNs(context, prefix, uri) } } } defer { xmlXPathFreeContext(context) } guard let xmlXPath = xmlXPathEvalExpression(xpathString, context) else { throw XMLError.lastError(defaultError: .xpathError(code: 1207)) } return xmlXPath } } private class RegexConstants { static let idRegex = try! NSRegularExpression(pattern: "\\#([\\w-_]+)", options: []) static let classRegex = try! NSRegularExpression(pattern: "\\.([^\\.]+)", options: []) static let attributeRegex = try! NSRegularExpression(pattern: "\\[([^\\[\\]]+)\\]", options: []) } internal func XPath(fromCSS css: String) -> String { var xpathExpressions = [String]() for expression in css.components(separatedBy: ",") where !expression.isEmpty { var xpathComponents = ["./"] var prefix: String? = nil let expressionComponents = expression.trimmingCharacters(in: CharacterSet.whitespaces).components(separatedBy: CharacterSet.whitespaces) for (idx, var token) in expressionComponents.enumerated() { switch token { case "*" where idx != 0: xpathComponents.append("/*") case ">": prefix = "" case "+": prefix = "following-sibling::*[1]/self::" case "~": prefix = "following-sibling::" default: if prefix == nil && idx != 0 { prefix = "descendant::" } if let symbolRange = token.rangeOfCharacter(from: CharacterSet(charactersIn: "#.[]")) { let symbol = symbolRange.lowerBound == token.startIndex ?"*" :"" var xpathComponent = String(token[..<symbolRange.lowerBound]) let nsrange = NSRange(location: 0, length: token.utf16.count) if let result = RegexConstants.idRegex.firstMatch(in: token, options: [], range: nsrange), result.numberOfRanges > 1 { xpathComponent += "\(symbol)[@id = '\(token[result.range(at: 1)])']" } for result in RegexConstants.classRegex.matches(in: token, options: [], range: nsrange) where result.numberOfRanges > 1 { xpathComponent += "\(symbol)[contains(concat(' ',normalize-space(@class),' '),' \(token[result.range(at: 1)]) ')]" } for result in RegexConstants.attributeRegex.matches(in: token, options: [], range: nsrange) where result.numberOfRanges > 1 { xpathComponent += "[@\(token[result.range(at: 1)])]" } token = xpathComponent } if prefix != nil { token = prefix! + token prefix = nil } xpathComponents.append(token) } } xpathExpressions.append(xpathComponents.joined(separator: "/")) } return xpathExpressions.joined(separator: " | ") }
mit
2ff85d55765c9fe59925353050faff73
29.535912
162
0.662113
4.464459
false
false
false
false
lllyyy/LY
U17-master/U17/Pods/Moya/Sources/Moya/Response.swift
3
5972
import Foundation /// Represents a response to a `MoyaProvider.request`. public final class Response: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: Data public let request: URLRequest? public let response: HTTPURLResponse? /// Initialize a new `Response`. public init(statusCode: Int, data: Data, request: URLRequest? = nil, response: HTTPURLResponse? = nil) { self.statusCode = statusCode self.data = data self.request = request self.response = response } /// A text description of the `Response`. public var description: String { return "Status Code: \(statusCode), Data Length: \(data.count)" } /// A text description of the `Response`. Suitable for debugging. public var debugDescription: String { return description } public static func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } } public extension Response { /** Returns the `Response` if the `statusCode` falls within the specified range. - parameters: - statusCodes: The range of acceptable status codes. - throws: `MoyaError.statusCode` when others are encountered. */ public func filter(statusCodes: ClosedRange<Int>) throws -> Response { guard statusCodes.contains(statusCode) else { throw MoyaError.statusCode(self) } return self } /** Returns the `Response` if it has the specified `statusCode`. - parameters: - statusCode: The acceptable status code. - throws: `MoyaError.statusCode` when others are encountered. */ public func filter(statusCode: Int) throws -> Response { return try filter(statusCodes: statusCode...statusCode) } /** Returns the `Response` if the `statusCode` falls within the range 200 - 299. - throws: `MoyaError.statusCode` when others are encountered. */ public func filterSuccessfulStatusCodes() throws -> Response { return try filter(statusCodes: 200...299) } /** Returns the `Response` if the `statusCode` falls within the range 200 - 399. - throws: `MoyaError.statusCode` when others are encountered. */ public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filter(statusCodes: 200...399) } /// Maps data received from the signal into a UIImage. func mapImage() throws -> Image { guard let image = Image(data: data) else { throw MoyaError.imageMapping(self) } return image } /// Maps data received from the signal into a JSON object. func mapJSON(failsOnEmptyData: Bool = true) throws -> Any { do { return try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch { if data.count < 1 && !failsOnEmptyData { return NSNull() } throw MoyaError.jsonMapping(self) } } /// Maps data received from the signal into a String. /// /// - parameter atKeyPath: Optional key path at which to parse string. public func mapString(atKeyPath keyPath: String? = nil) throws -> String { if let keyPath = keyPath { // Key path was provided, try to parse string at key path guard let jsonDictionary = try mapJSON() as? NSDictionary, let string = jsonDictionary.value(forKeyPath: keyPath) as? String else { throw MoyaError.stringMapping(self) } return string } else { // Key path was not provided, parse entire response as string guard let string = String(data: data, encoding: .utf8) else { throw MoyaError.stringMapping(self) } return string } } /// Maps data received from the signal into a Decodable object. /// /// - parameter atKeyPath: Optional key path at which to parse object. /// - parameter using: A `JSONDecoder` instance which is used to decode data to an object. func map<D: Decodable>(_ type: D.Type, atKeyPath keyPath: String? = nil, using decoder: JSONDecoder = JSONDecoder()) throws -> D { let serializeToData: (Any) throws -> Data? = { (jsonObject) in guard JSONSerialization.isValidJSONObject(jsonObject) else { return nil } do { return try JSONSerialization.data(withJSONObject: jsonObject) } catch { throw MoyaError.jsonMapping(self) } } let jsonData: Data if let keyPath = keyPath { guard let jsonObject = (try mapJSON() as? NSDictionary)?.value(forKeyPath: keyPath) else { throw MoyaError.jsonMapping(self) } if let data = try serializeToData(jsonObject) { jsonData = data } else { let wrappedJsonObject = ["value": jsonObject] let wrappedJsonData: Data if let data = try serializeToData(wrappedJsonObject) { wrappedJsonData = data } else { throw MoyaError.jsonMapping(self) } do { return try decoder.decode(DecodableWrapper<D>.self, from: wrappedJsonData).value } catch let error { throw MoyaError.objectMapping(error, self) } } } else { jsonData = data } do { return try decoder.decode(D.self, from: jsonData) } catch let error { throw MoyaError.objectMapping(error, self) } } } private struct DecodableWrapper<T: Decodable>: Decodable { let value: T }
mit
14d0563fc3c1693985f0e07936246de3
34.129412
134
0.596785
5.06961
false
false
false
false
juheon0615/GhostHandongSwift
HandongAppSwift/HyoamViewController.swift
3
8191
// // HyoamViewController.swift // HandongAppSwift // // Created by csee on 2015. 2. 6.. // Copyright (c) 2015년 GHOST. All rights reserved. // import Foundation import UIKit class HyoamViewController: UIViewController { let rootTag = "hyoam" let itemTag = "menu" let dateTag = "date" let specialTag = "special" let normalTag = "normal" let unitTag = "unit" let menuTag = "name" let priceTag = "price" var itemYPos: Double = 0.0 var boxYPos: Double = 2.0 var hyoamItem = Array<HyoamModel>() var idx: Int? var actInd = UIActivityIndicatorView() @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var scrollView: UIScrollView! override func viewDidLoad() { Util.showActivityIndicatory(self.view, indicator: &self.actInd) dateSetter() let data = Util.readFile(Util.TodaysHyoamInfoName) if data != nil { self.parseHyoamXML(data!) } self.makeViewWithData() } func dateSetter() { let today = Util.getToday() let weekdayString = Util.weekdayChanger(today.weekday) + "요일" let monthString = String(today.month) + "월 " let dateString = String(today.day) + "일 " self.dateLabel.text = monthString + dateString + weekdayString } func parseHyoamXML(data: NSString) { let xmlDom = SWXMLHash.parse(data as String) var alldayMenuCount = xmlDom[rootTag][itemTag].all.count for i in 0 ..< alldayMenuCount { var allNormal = Array<String?>() var allNormalPrice = Array<String?>() let allNoramlTags = xmlDom[rootTag][itemTag][i][normalTag][unitTag].all for j in 0 ..< allNoramlTags.count { allNormal.append(allNoramlTags[j][menuTag].element!.text) allNormalPrice.append(allNoramlTags[j][priceTag].element!.text) } let model = HyoamModel( date: xmlDom[rootTag][itemTag][i][dateTag].element!.text!, special: xmlDom[rootTag][itemTag][i][specialTag][unitTag][menuTag].element!.text, specialPrice: xmlDom[rootTag][itemTag][i][specialTag][unitTag][priceTag].element!.text, normal: allNormal, normalPrice: allNormalPrice) hyoamItem.append(model) } } func noDataHandler() { let backColor = UIColor(red: 0.9843, green: 0.8196, blue: 0.2509, alpha: 0.2) let screenWidth = Double(UIScreen.mainScreen().applicationFrame.width) // ADD No DATA Label let noDataLabel = UILabel(frame: CGRect(x: 5.0, y: 5.0, width: screenWidth - 10, height: 100.0)) noDataLabel.backgroundColor = backColor noDataLabel.numberOfLines = 0 noDataLabel.text = "금일 식단정보가 없습니다.\n또랑 운영 여부를 확인해주시기 바랍니다.\n(전화 :054-260-1267)" self.scrollView.addSubview(noDataLabel) // Loading END Util.hideActivityIndicator(&self.actInd) } func makeViewWithData() { if self.hyoamItem.count == 0 { self.noDataHandler() return } if self.idx == nil { let today = Util.getToday() self.idx = -1 for i in 0 ..< self.hyoamItem.count { if self.hyoamItem[i].month.toInt() == today.month && self.hyoamItem[i].date.toInt() == today.day { idx = i break } } if idx == -1 { // no data for today idx = nil self.noDataHandler() return } } let backColor = UIColor(red: 0.9843, green: 0.8196, blue: 0.2509, alpha: 0.2) let screenWidth = Double(UIScreen.mainScreen().applicationFrame.width) // SPECIAL MENU let specialCont = UIView(frame: CGRectZero) let specialHead = UILabel(frame: CGRect(x: 5.0, y: self.itemYPos, width: screenWidth, height: 30.0)) self.itemYPos += 32.0 specialHead.text = "특선" specialHead.font = UIFont(name: specialHead.font.fontName, size: 19) specialCont.addSubview(specialHead) let specialDivBar = UIView(frame: CGRect(x: 5.0, y: self.itemYPos, width: screenWidth - 30.0, height: 1)) specialDivBar.backgroundColor = UIColor.darkGrayColor() self.itemYPos += 2.0 specialCont.addSubview(specialDivBar) let specialMenuLabel = UILabel(frame: CGRect(x: 8.0, y: self.itemYPos, width: screenWidth/4*3 - 8, height: 30.0)) specialMenuLabel.text = hyoamItem[idx!].special.menu specialMenuLabel.numberOfLines = 0 specialMenuLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping specialCont.addSubview(specialMenuLabel) let specialPriceLabel = UILabel(frame: CGRect(x: screenWidth/4*3, y: self.itemYPos, width: screenWidth/4, height: 30.0)) self.itemYPos += 30.0 specialPriceLabel.text = hyoamItem[idx!].special.price specialPriceLabel.numberOfLines = 0 specialPriceLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping specialCont.addSubview(specialPriceLabel) // add Container View to Scroll View specialCont.frame = CGRect(x: 10.0, y: self.boxYPos, width: screenWidth - 20.0, height: itemYPos) specialCont.backgroundColor = backColor specialCont.opaque = true self.scrollView.addSubview(specialCont) self.boxYPos += self.itemYPos + 5.0 self.itemYPos = 0.0 // NORMAL MENUs let normalCont = UIView(frame: CGRectZero) let normalHead = UILabel(frame: CGRect(x: 5.0, y: self.itemYPos, width: screenWidth, height: 30.0)) self.itemYPos += 32.0 normalHead.text = "일반메뉴" normalHead.font = UIFont(name: normalHead.font.fontName, size: 19) normalCont.addSubview(normalHead) let normalDivBar = UIView(frame: CGRect(x: 5.0, y: self.itemYPos, width: screenWidth - 30.0, height: 1)) normalDivBar.backgroundColor = UIColor.darkGrayColor() self.itemYPos += 2.0 normalCont.addSubview(normalDivBar) var lineCount: Double = 0.0 for i in 0 ..< hyoamItem[idx!].normal.count { lineCount = Double(hyoamItem[idx!].normal[i].menu.componentsSeparatedByString("\n").count * 25) let normalMenuLabel = UILabel(frame: CGRect(x: 8.0, y: self.itemYPos, width: screenWidth/4*3 - 8, height: lineCount)) normalMenuLabel.text = hyoamItem[idx!].normal[i].menu normalMenuLabel.numberOfLines = 0 normalMenuLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping normalCont.addSubview(normalMenuLabel) let normalPriceLabel = UILabel(frame: CGRect(x: screenWidth/4*3, y: self.itemYPos, width: screenWidth/4, height: lineCount)) self.itemYPos += lineCount normalPriceLabel.text = hyoamItem[idx!].normal[i].price normalPriceLabel.numberOfLines = 0 normalPriceLabel.lineBreakMode = NSLineBreakMode.ByCharWrapping normalCont.addSubview(normalPriceLabel) } // add Container View to Scroll View normalCont.frame = CGRect(x: 10.0, y: self.boxYPos, width: screenWidth - 20.0, height: itemYPos) normalCont.backgroundColor = backColor normalCont.opaque = true self.scrollView.addSubview(normalCont) self.boxYPos += self.itemYPos + 5.0 self.itemYPos = 0.0 // Loading END Util.hideActivityIndicator(&self.actInd) self.scrollView.contentSize = CGSizeMake(CGFloat(screenWidth), CGFloat(self.boxYPos)) } }
mit
d6bc8feeb155a98fe23c42531ba8d8e0
35.863636
136
0.589838
4.450604
false
false
false
false
nickfalk/BSImagePicker
Pod/Classes/Controller/PreviewViewController.swift
2
2964
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 final class PreviewViewController : UIViewController { var imageView: UIImageView? fileprivate var fullscreen = false override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) view.backgroundColor = UIColor.white imageView = UIImageView(frame: view.bounds) imageView?.contentMode = .scaleAspectFit imageView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(imageView!) let tapRecognizer = UITapGestureRecognizer() tapRecognizer.numberOfTapsRequired = 1 tapRecognizer.addTarget(self, action: #selector(PreviewViewController.toggleFullscreen)) view.addGestureRecognizer(tapRecognizer) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func loadView() { super.loadView() } func toggleFullscreen() { fullscreen = !fullscreen UIView.animate(withDuration: 0.3, animations: { () -> Void in self.toggleNavigationBar() self.toggleStatusBar() self.toggleBackgroundColor() }) } func toggleNavigationBar() { navigationController?.setNavigationBarHidden(fullscreen, animated: true) } func toggleStatusBar() { self.setNeedsStatusBarAppearanceUpdate() } func toggleBackgroundColor() { let aColor: UIColor if self.fullscreen { aColor = UIColor.black } else { aColor = UIColor.white } self.view.backgroundColor = aColor } override var prefersStatusBarHidden : Bool { return fullscreen } }
mit
6f0e91338b916389e730164ef43337a8
33.858824
96
0.679042
5.319569
false
false
false
false
emilstahl/swift
stdlib/public/core/StringBuffer.swift
9
7986
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// struct _StringBufferIVars { init(_ elementWidth: Int) { _sanityCheck(elementWidth == 1 || elementWidth == 2) usedEnd = nil capacityAndElementShift = elementWidth - 1 } init( usedEnd: UnsafeMutablePointer<RawByte>, byteCapacity: Int, elementWidth: Int ) { _sanityCheck(elementWidth == 1 || elementWidth == 2) _sanityCheck((byteCapacity & 0x1) == 0) self.usedEnd = usedEnd self.capacityAndElementShift = byteCapacity + (elementWidth - 1) } // This stored property should be stored at offset zero. We perform atomic // operations on it using _HeapBuffer's pointer. var usedEnd: UnsafeMutablePointer<RawByte> var capacityAndElementShift: Int var byteCapacity: Int { return capacityAndElementShift & ~0x1 } var elementShift: Int { return capacityAndElementShift & 0x1 } } // FIXME: Wanted this to be a subclass of // _HeapBuffer<_StringBufferIVars,UTF16.CodeUnit>, but // <rdar://problem/15520519> (Can't call static method of derived // class of generic class with dependent argument type) prevents it. public struct _StringBuffer { // Make this a buffer of UTF-16 code units so that it's properly // aligned for them if that's what we store. typealias _Storage = _HeapBuffer<_StringBufferIVars, UTF16.CodeUnit> typealias HeapBufferStorage = _HeapBufferStorage<_StringBufferIVars, UTF16.CodeUnit> init(_ storage: _Storage) { _storage = storage } public init(capacity: Int, initialSize: Int, elementWidth: Int) { _sanityCheck(elementWidth == 1 || elementWidth == 2) _sanityCheck(initialSize <= capacity) // We don't check for elementWidth overflow and underflow because // elementWidth is known to be 1 or 2. let elementShift = elementWidth &- 1 // We need at least 1 extra byte if we're storing 8-bit elements, // because indexing will always grab 2 consecutive bytes at a // time. let capacityBump = 1 &- elementShift // Used to round capacity up to nearest multiple of 16 bits, the // element size of our storage. let divRound = 1 &- elementShift _storage = _Storage( HeapBufferStorage.self, _StringBufferIVars(elementWidth), (capacity + capacityBump + divRound) >> divRound ) self.usedEnd = start + (initialSize << elementShift) _storage.value.capacityAndElementShift = ((_storage._capacity() - capacityBump) << 1) + elementShift } @warn_unused_result static func fromCodeUnits< Encoding : UnicodeCodecType, Input : CollectionType // SequenceType? where Input.Generator.Element == Encoding.CodeUnit >( encoding: Encoding.Type, input: Input, repairIllFormedSequences: Bool, minimumCapacity: Int = 0 ) -> (_StringBuffer?, hadError: Bool) { // Determine how many UTF-16 code units we'll need let inputStream = input.generate() guard let (utf16Count, isAscii) = UTF16.measure(encoding, input: inputStream, repairIllFormedSequences: repairIllFormedSequences) else { return (.None, true) } // Allocate storage let result = _StringBuffer( capacity: max(utf16Count, minimumCapacity), initialSize: utf16Count, elementWidth: isAscii ? 1 : 2) if isAscii { var p = UnsafeMutablePointer<UTF8.CodeUnit>(result.start) let sink: (UTF32.CodeUnit) -> Void = { (p++).memory = UTF8.CodeUnit($0) } let hadError = transcode( encoding, UTF32.self, input.generate(), sink, stopOnError: true) _sanityCheck(!hadError, "string can not be ASCII if there were decoding errors") return (result, hadError) } else { var p = result._storage.baseAddress let sink: (UTF16.CodeUnit) -> Void = { (p++).memory = $0 } let hadError = transcode( encoding, UTF16.self, input.generate(), sink, stopOnError: !repairIllFormedSequences) return (result, hadError) } } /// A pointer to the start of this buffer's data area. public var start: UnsafeMutablePointer<RawByte> { return UnsafeMutablePointer(_storage.baseAddress) } /// A past-the-end pointer for this buffer's stored data. var usedEnd: UnsafeMutablePointer<RawByte> { get { return _storage.value.usedEnd } set(newValue) { _storage.value.usedEnd = newValue } } var usedCount: Int { return (usedEnd - start) >> elementShift } /// A past-the-end pointer for this buffer's available storage. var capacityEnd: UnsafeMutablePointer<RawByte> { return start + _storage.value.byteCapacity } /// The number of elements that can be stored in this buffer. public var capacity: Int { return _storage.value.byteCapacity >> elementShift } /// 1 if the buffer stores UTF-16; 0 otherwise. var elementShift: Int { return _storage.value.elementShift } /// The number of bytes per element. var elementWidth: Int { return elementShift + 1 } // Return true iff we have the given capacity for the indicated // substring. This is what we need to do so that users can call // reserveCapacity on String and subsequently use that capacity, in // two separate phases. Operations with one-phase growth should use // "grow()," below. @warn_unused_result func hasCapacity( cap: Int, forSubRange r: Range<UnsafePointer<RawByte>> ) -> Bool { // The substring to be grown could be pointing in the middle of this // _StringBuffer. let offset = (r.startIndex - UnsafePointer(start)) >> elementShift return cap + offset <= capacity } /// Attempt to claim unused capacity in the buffer. /// /// Operation succeeds if there is sufficient capacity, and either: /// - the buffer is uniquely-refereced, or /// - `oldUsedEnd` points to the end of the currently used capacity. /// /// - parameter subRange: Range of the substring that the caller tries /// to extend. /// - parameter newUsedCount: The desired size of the substring. mutating func grow( subRange: Range<UnsafePointer<RawByte>>, newUsedCount: Int ) -> Bool { var newUsedCount = newUsedCount // The substring to be grown could be pointing in the middle of this // _StringBuffer. Adjust the size so that it covers the imaginary // substring from the start of the buffer to `oldUsedEnd`. newUsedCount += (subRange.startIndex - UnsafePointer(start)) >> elementShift if _slowPath(newUsedCount > capacity) { return false } let newUsedEnd = start + (newUsedCount << elementShift) if _fastPath(self._storage.isUniquelyReferenced()) { usedEnd = newUsedEnd return true } // Optimization: even if the buffer is shared, but the substring we are // trying to grow is located at the end of the buffer, it can be grown in // place. The operation should be implemented in a thread-safe way, // though. // // if usedEnd == subRange.endIndex { // usedEnd = newUsedEnd // return true // } let usedEndPhysicalPtr = UnsafeMutablePointer<UnsafeMutablePointer<RawByte>>(_storage._value) var expected = UnsafeMutablePointer<RawByte>(subRange.endIndex) if _stdlib_atomicCompareExchangeStrongPtr( object: usedEndPhysicalPtr, expected: &expected, desired: newUsedEnd) { return true } return false } var _anyObject: AnyObject? { return _storage.storage != nil ? .Some(_storage.storage!) : .None } var _storage: _Storage }
apache-2.0
d42b8a9075cac581a0f78a9ba7a263d6
32.554622
86
0.668044
4.511864
false
false
false
false
taketo1024/SwiftyAlgebra
Sources/SwmCore/Abstract/MathSet.swift
1
3808
// // BasicTypes.swift // SwiftyMath // // Created by Taketo Sano on 2017/06/05. // Copyright © 2017年 Taketo Sano. All rights reserved. // public protocol MathSet: Equatable, CustomStringConvertible { static var symbol: String { get } } extension MathSet { public func asSubset<S: Subset>(of: S.Type) -> S where S.Super == Self { assert(S.contains(self), "\(S.self) does not contain \(self).") return S.init(self) } public static var symbol: String { "\(Self.self)" } } public protocol FiniteSet: MathSet { static var allElements: [Self] { get } static var countElements: Int { get } } public protocol Subset: MathSet { associatedtype Super: MathSet init(_ a: Super) var asSuper: Super { get } static func contains(_ a: Super) -> Bool } extension Subset { public var description: String { asSuper.description } } public protocol ProductSet: MathSet { associatedtype Left: MathSet associatedtype Right: MathSet init(_ left: Left, _ right: Right) var left: Left { get } var right: Right { get } } public extension ProductSet { var description: String { "(\(left), \(right))" } } public struct Pair<Left: MathSet, Right: MathSet>: ProductSet { public let left: Left public let right: Right public init(_ left: Left, _ right: Right) { self.left = left self.right = right } public static var symbol: String { "\(Left.symbol)×\(Right.symbol)" } } public protocol QuotientSet: MathSet { associatedtype Base: MathSet init (_ a: Base) var representative: Base { get } static func isEquivalent(_ a: Base, _ b: Base) -> Bool } public extension QuotientSet { var description: String { representative.description } static func == (a: Self, b: Self) -> Bool { isEquivalent(a.representative, b.representative) } } extension QuotientSet where Base: ExpressibleByIntegerLiteral { public init(integerLiteral value: Base.IntegerLiteralType) { self.init(Base(integerLiteral: value)) } } public protocol MapType: MathSet { associatedtype Domain: MathSet associatedtype Codomain: MathSet init (_ f: @escaping (Domain) -> Codomain) var function: (Domain) -> Codomain { get } func callAsFunction(_ x: Domain) -> Codomain static func ∘<G: MapType>(g: G, f: Self) -> Map<Self.Domain, G.Codomain> where Self.Codomain == G.Domain } public extension MapType { init(_ f: Map<Domain, Codomain>) { self.init(f.function) } var asMap: Map<Domain, Codomain> { Map(function) } @inlinable func callAsFunction(_ x: Domain) -> Codomain { function(x) } static func ∘<G: MapType>(g: G, f: Self) -> Map<Self.Domain, G.Codomain> where Self.Codomain == G.Domain { Map<Self.Domain, G.Codomain>{ x in g(f(x)) } } } public struct Map<Domain: MathSet, Codomain: MathSet>: MapType { public let function: (Domain) -> Codomain public init(_ f: @escaping (Domain) -> Codomain) { self.function = f } public static func == (lhs: Self, rhs: Self) -> Bool { fatalError("MapType is not equatable.") } public var description: String { "map: \(Domain.self) -> \(Codomain.self)" } } public protocol EndType: MapType where Domain == Codomain { static var identity: Self { get } static func ∘(g: Self, f: Self) -> Self } public extension EndType { static var identity: Self { Self { $0 } } static func ∘(g: Self, f: Self) -> Self { Self { x in g(f(x)) } } } extension Map: EndType where Domain == Codomain{} public typealias End<Domain: MathSet> = Map<Domain, Domain>
cc0-1.0
5f3462c9bef03452b9f1094f93a17e71
23.810458
110
0.619336
3.869521
false
false
false
false
blstream/AugmentedSzczecin_iOS
AugmentedSzczecin/AugmentedSzczecin/Database/ASPOI.swift
1
1313
import CoreLocation @objc(ASPOI) class ASPOI: _ASPOI { func getAddress(geocoder: CLGeocoder, completionHandler: (address: CLPlacemark?) -> Void) { var location:CLLocation = CLLocation(latitude: self.latitude as! Double, longitude: self.longitude as! Double) geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in if (error != nil) { println("Reverse geocoder failed with error" + error.localizedDescription) completionHandler(address: nil) return } let placemark = placemarks.first as? CLPlacemark if placemark == nil { println("Problem with the data received from geocoder") } completionHandler(address: placemark) }) } // func getCoorditantesFromAddress(geocoder: CLGeocoder, completionHandler: (placemark: CLPlacemark?) -> Void) { // var address = String() // if (self.street != "") { // address = self.street // } // else { // return // } // if // // geocoder.geocodeAddressString(address, completionHandler: <#CLGeocodeCompletionHandler!##([AnyObject]!, NSError!) -> Void#>) // } }
apache-2.0
c487fb3f28a5b93d967c04f2d24ece4e
34.486486
134
0.578065
4.93609
false
false
false
false
RedRoma/Lexis-Database
LexisDatabase/WordType+JSON.swift
1
4078
// // WordType+JSON.swift // LexisDatabase // // Created by Wellington Moreno on 9/19/16. // Copyright © 2016 RedRoma, Inc. All rights reserved. // import Foundation import Archeota fileprivate class Keys { static let caseType = "caseType" static let declension = "declension" static let gender = "gender" static let conjugation = "conjugation" static let verbType = "verbType" static let wordTypeKey = "wordType" } extension WordType: JSONConvertible { public func asJSON() -> Any? { var object = [String: Any]() let wordTypeKey = Keys.wordTypeKey switch self { case .Adjective : object[wordTypeKey] = "Adjective" case .Adverb : object[wordTypeKey] = "Adverb" case .Conjunction : object[wordTypeKey] = "Conjunction" case .Interjection : object[wordTypeKey] = "Interjection" case let .Noun(declension, gender) : object[wordTypeKey] = "Noun" object[Keys.gender] = gender.name object[Keys.declension] = declension.name case .Numeral : object[wordTypeKey] = "Numeral" case .PersonalPronoun : object[wordTypeKey] = "PersonalPronoun" case let .Preposition(caseType) : object[wordTypeKey] = "Preposition" object[Keys.caseType] = caseType.name case .Pronoun : object[wordTypeKey] = "Pronoun" case let .Verb(conjugation, verbType): object[wordTypeKey] = "Verb" object[Keys.conjugation] = conjugation.name object[Keys.verbType] = verbType.name } return object } static func fromJSON(json: Any) -> JSONConvertible? { guard let object = json as? [String: Any] else { LOG.error("Expected Dictionary, but instead: \(json)") return nil } let key = Keys.wordTypeKey guard let type = object[key] as? String else { return nil } if type == "Adjective" { return WordType.Adjective } if type == "Adverb" { return WordType.Adverb } if type == "Conjunction" { return WordType.Conjunction } if type == "Interjection" { return WordType.Interjection } if type == "Noun", let declensionString = object[Keys.declension] as? String, let declension = Declension.from(name: declensionString), let genderString = object[Keys.gender] as? String, let gender = Gender.from(name: genderString) { return WordType.Noun(declension, gender) } if type == "Numeral" { return WordType.Numeral } if type == "PersonalPronoun" { return WordType.PersonalPronoun } if type == "Preposition", let caseTypeString = object[Keys.caseType] as? String, let caseType = CaseType.from(name: caseTypeString) { return WordType.Preposition(caseType) } if type == "Pronoun" { return WordType.Pronoun } if type == "Verb", let conjugationString = object[Keys.conjugation] as? String, let conjugation = Conjugation.from(name: conjugationString), let verbTypeString = object[Keys.verbType] as? String, let verbType = VerbType.from(name: verbTypeString) { return WordType.Verb(conjugation, verbType) } return nil } }
apache-2.0
b5f77826489da56d476516a1127ffc6d
26.734694
72
0.5065
5.226923
false
false
false
false
frootloops/swift
test/SILGen/metatypes.swift
1
4315
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -enable-sil-ownership %s | %FileCheck %s import Swift protocol SomeProtocol { func method() func static_method() } protocol A {} struct SomeStruct : A {} class SomeClass : SomeProtocol { func method() {} func static_method() {} } class SomeSubclass : SomeClass {} // CHECK-LABEL: sil hidden @_T09metatypes07static_A0{{[_0-9a-zA-Z]*}}F func static_metatypes() -> (SomeStruct.Type, SomeClass.Type, SomeClass.Type) { // CHECK: [[STRUCT:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[CLASS:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[SUBCLASS:%[0-9]+]] = metatype $@thick SomeSubclass.Type // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[STRUCT]] : {{.*}}, [[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (SomeStruct.self, SomeClass.self, SomeSubclass.self) } // CHECK-LABEL: sil hidden @_T09metatypes07struct_A0{{[_0-9a-zA-Z]*}}F func struct_metatypes(s: SomeStruct) -> (SomeStruct.Type, SomeStruct.Type) { // CHECK: [[STRUCT1:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[STRUCT2:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: tuple ([[STRUCT1]] : {{.*}}, [[STRUCT2]] : {{.*}}) return (type(of: s), SomeStruct.self) } // CHECK-LABEL: sil hidden @_T09metatypes06class_A0{{[_0-9a-zA-Z]*}}F func class_metatypes(c: SomeClass, s: SomeSubclass) -> (SomeClass.Type, SomeClass.Type) { // CHECK: [[CLASS:%[0-9]+]] = value_metatype $@thick SomeClass.Type, // CHECK: [[SUBCLASS:%[0-9]+]] = value_metatype $@thick SomeSubclass.Type, // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (type(of: c), type(of: s)) } // CHECK-LABEL: sil hidden @_T09metatypes010archetype_A0{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*T): func archetype_metatypes<T>(t: T) -> (T.Type, T.Type) { // CHECK: [[STATIC_T:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[DYN_T:%[0-9]+]] = value_metatype $@thick T.Type, %0 // CHECK: tuple ([[STATIC_T]] : {{.*}}, [[DYN_T]] : {{.*}}) return (T.self, type(of: t)) } // CHECK-LABEL: sil hidden @_T09metatypes012existential_A0{{[_0-9a-zA-Z]*}}F func existential_metatypes(p: SomeProtocol) -> SomeProtocol.Type { // CHECK: existential_metatype $@thick SomeProtocol.Type return type(of: p) } struct SomeGenericStruct<T> {} func generic_metatypes<T>(x: T) -> (SomeGenericStruct<T>.Type, SomeGenericStruct<SomeStruct>.Type) { // CHECK: metatype $@thin SomeGenericStruct<T> // CHECK: metatype $@thin SomeGenericStruct<SomeStruct> return (SomeGenericStruct<T>.self, SomeGenericStruct<SomeStruct>.self) } // rdar://16610078 // CHECK-LABEL: sil hidden @_T09metatypes30existential_metatype_from_thinypXpyF : $@convention(thin) () -> @thick Any.Type // CHECK: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin() -> Any.Type { return SomeStruct.self } // CHECK-LABEL: sil hidden @_T09metatypes36existential_metatype_from_thin_valueypXpyF : $@convention(thin) () -> @thick Any.Type // CHECK: [[T1:%.*]] = metatype $@thin SomeStruct.Type // CHECK: [[T0:%.*]] = function_ref @_T09metatypes10SomeStructV{{[_0-9a-zA-Z]*}}fC // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: debug_value [[T2]] : $SomeStruct, let, name "s" // CHECK-NEXT: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin_value() -> Any.Type { let s = SomeStruct() return type(of: s) } // CHECK-LABEL: sil hidden @_T09metatypes20specialized_metatypes10DictionaryVySSSiGyF // CHECK: metatype $@thin Dictionary<String, Int>.Type func specialized_metatype() -> Dictionary<String, Int> { let dict = Swift.Dictionary<Swift.String, Int>() return dict }
apache-2.0
2bcd6653e14cd5ef9bd9eab8e014ca64
38.227273
128
0.64241
3.34237
false
false
false
false
Suninus/HTTPDNSLib-for-iOS
src/DNSCache/DNSCache/dnscache/model/IpModel.swift
1
3477
/** * * 项目名称: DNSCache * 类名称: HttpDnsPack * 类描述: 将httpdns返回的数据封装一层,方便日后httpdns接口改动不影响数据库模型。 并且该接口还会标识httpdns错误之后的一些信息用来上报 * 创建人: fenglei * 创建时间: 2015-7-23 上午11:20:11 * * 修改人: * 修改时间: * 修改备注: * * @version V1.0 */ import Foundation class IpModel{ /** * 自增id <br> * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_ID 字段 <br> */ var id:Long = -1 ; /** * domain id 关联id * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_DOMAIN_ID 字段 <br> */ var d_id:Long = -1 ; /** * 服务器ip地址 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_PORT 字段 <br> */ var ip:String = "" ; /** * ip服务器对应的端口 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_PORT 字段 <br> */ var port:Int = -1 ; /** * ip服务器对应的sp运营商 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_SP 字段 <br> */ var sp:String = "" ; /** * ip过期时间 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_TTL 字段 <br> */ var ttl:String = "0" ; /** * ip服务器优先级-排序算法策略使用 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_PRIORITY 字段 <br> */ var priority:String = "0" ; /** * 最后测速下行速度值 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_FINALLY_SPEED 字段 <br> */ var finally_speed:String = "0" ; /** * ip服务器链接产生的成功数 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_SUCCESS_NUM 字段 <br> */ var success_num:String = "0" ; /** * ip服务器链接产生的错误数 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_ERR_NUM 字段 <br> */ var err_num:String = "0" ; /** * ip服务器最后成功链接时间 * * 该字段映射类 {@link com.sina.util.dnscache.cache.DBConstants } IP_COLUMN_FINALLY_SUCCESS_TIME 字段 <br> */ var finally_success_time:String = "0" ; /** * 评估体系 评分分值 */ var grade:Float = 0 ; func toString()->String{ var str = "*\n" str += "-- 服务器id = " + id + "\n" str += "-- 服务器ip = " + ip + "\n" str += "-- 域名ID索引 = " + d_id + "\n" str += "-- 服务器端口 = " + port + "\n" str += "-- 运营商 = " + sp + "\n" str += "-- 过期时间 = " + ttl + "\n" str += "-- 优先级 = " + priority + "\n" str += "-- 最后速度分值 = " + finally_speed + "\n" str += "-- 历史成功次数 = " + success_num + "\n" str += "-- 历史错误次数 = " + err_num + "\n" str += "-- 最后一次访问成功时间 = " + Tools.getStringDateShort(finally_success_time) + "\n" str += "-- 系统对服务器的评分 = " + grade + "\n" str += "\n" return str } }
bsd-2-clause
3e86bce9028b1fed471f07a771429827
21.109375
101
0.510074
3.003185
false
false
false
false
mikaoj/BSImagePicker
Sources/View/ImageView.swift
1
4556
// The MIT License (MIT) // // Copyright (c) 2018 Joakim Gyllström // // 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 @IBDesignable public class ImageView: UIView { private let imageView: UIImageView = UIImageView(frame: .zero) override public var isUserInteractionEnabled: Bool { didSet { imageView.isUserInteractionEnabled = isUserInteractionEnabled } } override public var tintColor: UIColor! { didSet { imageView.tintColor = tintColor } } override public var contentMode: UIView.ContentMode { didSet { setNeedsLayout() layoutIfNeeded() } } override public init(frame: CGRect) { super.init(frame: frame) addSubview(imageView) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addSubview(imageView) } override public func layoutSubviews() { super.layoutSubviews() if let image = imageView.image { imageView.frame = ImageViewLayout.frameForImageWithSize(image.size, previousFrame: imageView.frame, inContainerWithSize: bounds.size, usingContentMode: contentMode) } else { imageView.frame = .zero } } } // MARK: UIImageView API extension ImageView { /// See UIImageView documentation public convenience init(image: UIImage?) { self.init(frame: .zero) imageView.image = image } /// See UIImageView documentation public convenience init(image: UIImage?, highlightedImage: UIImage?) { self.init(frame: .zero) imageView.image = image imageView.highlightedImage = highlightedImage } /// See UIImageView documentation @IBInspectable open var image: UIImage? { get { return imageView.image } set { imageView.image = newValue setNeedsLayout() layoutIfNeeded() } } /// See UIImageView documentation @IBInspectable open var highlightedImage: UIImage? { get { return imageView.highlightedImage } set { imageView.highlightedImage = newValue } } /// See UIImageView documentation @IBInspectable open var isHighlighted: Bool { get { return imageView.isHighlighted } set { imageView.isHighlighted = newValue } } /// See UIImageView documentation open var animationImages: [UIImage]? { get { return imageView.animationImages } set { imageView.animationImages = newValue } } /// See UIImageView documentation open var highlightedAnimationImages: [UIImage]? { get { return imageView.highlightedAnimationImages } set { imageView.highlightedAnimationImages = newValue } } /// See UIImageView documentation open var animationDuration: TimeInterval { get { return imageView.animationDuration } set { imageView.animationDuration = newValue } } /// See UIImageView documentation open var animationRepeatCount: Int { get { return imageView.animationRepeatCount } set { imageView.animationRepeatCount = newValue } } /// See UIImageView documentation open func startAnimating() { imageView.startAnimating() } /// See UIImageView documentation open func stopAnimating() { imageView.stopAnimating() } /// See UIImageView documentation open var isAnimating: Bool { get { return imageView.isAnimating } } }
mit
af4544ddf110b2e8d3d69d968d71e14c
30.413793
176
0.674863
5.308858
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/DynamoDBStreams/DynamoDBStreams_Error.swift
1
3956
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for DynamoDBStreams public struct DynamoDBStreamsErrorType: AWSErrorType { enum Code: String { case expiredIteratorException = "ExpiredIteratorException" case internalServerError = "InternalServerError" case limitExceededException = "LimitExceededException" case resourceNotFoundException = "ResourceNotFoundException" case trimmedDataAccessException = "TrimmedDataAccessException" } private let error: Code public let context: AWSErrorContext? /// initialize DynamoDBStreams public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The shard iterator has expired and can no longer be used to retrieve stream records. A shard iterator expires 15 minutes after it is retrieved using the GetShardIterator action. public static var expiredIteratorException: Self { .init(.expiredIteratorException) } /// An error occurred on the server side. public static var internalServerError: Self { .init(.internalServerError) } /// There is no limit to the number of daily on-demand backups that can be taken. Up to 50 simultaneous table operations are allowed per account. These operations include CreateTable, UpdateTable, DeleteTable,UpdateTimeToLive, RestoreTableFromBackup, and RestoreTableToPointInTime. The only exception is when you are creating a table with one or more secondary indexes. You can have up to 25 such requests running at a time; however, if the table or index specifications are complex, DynamoDB might temporarily reduce the number of concurrent operations. There is a soft account quota of 256 tables. public static var limitExceededException: Self { .init(.limitExceededException) } /// The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be ACTIVE. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// The operation attempted to read past the oldest stream record in a shard. In DynamoDB Streams, there is a 24 hour limit on data retention. Stream records whose age exceeds this limit are subject to removal (trimming) from the stream. You might receive a TrimmedDataAccessException if: You request a shard iterator with a sequence number older than the trim point (24 hours). You obtain a shard iterator, but before you use the iterator in a GetRecords request, a stream record in the shard exceeds the 24 hour period and is trimmed. This causes the iterator to access a record that no longer exists. public static var trimmedDataAccessException: Self { .init(.trimmedDataAccessException) } } extension DynamoDBStreamsErrorType: Equatable { public static func == (lhs: DynamoDBStreamsErrorType, rhs: DynamoDBStreamsErrorType) -> Bool { lhs.error == rhs.error } } extension DynamoDBStreamsErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
7c1f208fe02fd6be0b567ce272ba4bce
56.333333
611
0.721183
5.232804
false
false
false
false
cuappdev/podcast-ios
old/Podcast/ActionSheetHeaderView.swift
1
2337
// // ActionSheetHeaderView.swift // Podcast // // Created by Natasha Armbrust on 3/16/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import UIKit class ActionSheetHeaderView: UIView { var imageView: ImageView! var titleLabel: UILabel! var descriptionLabel: UILabel! let episodeNameLabelY: CGFloat = 27 let episodeNameLabelX: CGFloat = 86.5 let episodeNameLabelRightX: CGFloat = 21 let episodeNameLabelHeight: CGFloat = 18 let descriptionLabelX: CGFloat = 86.5 let descriptionLabelY: CGFloat = 47.5 var descriptionLabelHeight: CGFloat = 14.5 var padding: CGFloat = 18 let smallPadding: CGFloat = 2 var imageViewSize: CGFloat = 60 init(frame: CGRect, image: UIImage, title: String, description: String) { super.init(frame: frame) backgroundColor = .offWhite imageView = ImageView() titleLabel = UILabel() descriptionLabel = UILabel() titleLabel.font = ._14SemiboldFont() titleLabel.textColor = .offBlack titleLabel.numberOfLines = 2 descriptionLabel.font = ._12RegularFont() descriptionLabel.textColor = .charcoalGrey descriptionLabel.numberOfLines = 2 imageView.image = image titleLabel.text = title descriptionLabel.text = description addSubview(imageView) addSubview(titleLabel) addSubview(descriptionLabel) imageView.snp.makeConstraints { make in make.top.equalToSuperview().inset(padding) make.leading.equalToSuperview().inset(padding) make.size.equalTo(imageViewSize) } imageView.addCornerRadius(height: imageViewSize) titleLabel.snp.makeConstraints { make in make.leading.equalTo(imageView.snp.trailing).offset(padding) make.trailing.equalToSuperview().inset(padding) make.top.equalTo(imageView.snp.top) } descriptionLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(smallPadding) make.leading.equalTo(titleLabel.snp.leading) make.trailing.equalTo(titleLabel.snp.trailing) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
00d4e3086e3ffa6829a1dfdb99e57555
29.337662
77
0.665668
4.856549
false
false
false
false
ichu501/FillableLoaders
Source/FillableLoader.swift
3
11126
// // FillableLoader.swift // PQFFillableLoaders // // Created by Pol Quintana on 25/7/15. // Copyright (c) 2015 Pol Quintana. All rights reserved. // import UIKit public class FillableLoader: UIView { internal var shapeLayer = CAShapeLayer() internal var strokeLayer = CAShapeLayer() internal var path: CGPath! internal var loaderView = UIView() internal var animate: Bool = false internal var extraHeight: CGFloat = 0 internal var oldYPoint: CGFloat = 0 internal let mainBgColor = UIColor(white: 0.2, alpha: 0.6) // MARK: Public Variables /// Duration of the animation (Default: 10.0) public var duration: NSTimeInterval = 10.0 /// Loader background height (Default: ScreenHeight/6 + 30) public var rectSize: CGFloat = UIScreen.mainScreen().bounds.height/6 + 30 /// A Boolean value that determines whether the loader should have a swing effect while going up (Default: true) public var swing: Bool = true /// A Boolean value that determines whether the loader movement is progress based or not (Default: false) public var progressBased: Bool = false // MARK: Custom Getters and Setters internal var _backgroundColor: UIColor? internal var _loaderColor: UIColor? internal var _loaderBackgroundColor: UIColor? internal var _loaderStrokeColor: UIColor? internal var _loaderStrokeWidth: CGFloat = 0.5 internal var _loaderAlpha: CGFloat = 1.0 internal var _cornerRadius: CGFloat = 0.0 internal var _progress: CGFloat = 0.0 /// Loader view background color (Default: Clear) override public var backgroundColor: UIColor? { get { return _backgroundColor } set { super.backgroundColor = mainBgColor _backgroundColor = newValue loaderView.backgroundColor = newValue loaderView.layer.backgroundColor = newValue?.CGColor } } /// Filled loader color (Default: Blue) public var loaderColor: UIColor? { get { return _loaderColor } set { _loaderColor = newValue shapeLayer.fillColor = newValue?.CGColor } } /// Unfilled loader color (Default: White) public var loaderBackgroundColor: UIColor? { get { return _loaderBackgroundColor } set { _loaderBackgroundColor = newValue strokeLayer.fillColor = newValue?.CGColor } } /// Loader outline line color (Default: Black) public var loaderStrokeColor: UIColor? { get { return _loaderStrokeColor } set { _loaderStrokeColor = newValue strokeLayer.strokeColor = newValue?.CGColor } } /// Loader outline line width (Default: 0.5) public var loaderStrokeWidth: CGFloat { get { return _loaderStrokeWidth } set { _loaderStrokeWidth = newValue strokeLayer.lineWidth = newValue } } /// Loader view alpha (Default: 1.0) public var loaderAlpha: CGFloat { get { return _loaderAlpha } set { _loaderAlpha = newValue loaderView.alpha = newValue } } /// Loader view corner radius (Default: 0.0) public var cornerRadius: CGFloat { get { return _cornerRadius } set { _cornerRadius = newValue loaderView.layer.cornerRadius = newValue } } /// Loader fill progress from 0.0 to 1.0 . It will automatically fire an animation to update the loader fill progress (Default: 0.0) public var progress: CGFloat { get { return _progress } set { if (!progressBased || newValue > 1.0 || newValue < 0.0) { return } _progress = newValue applyProgress() } } // MARK: Initializers Methods /** Creates and SHOWS a loader with the given path :param: path Loader CGPath :returns: The loader that's already being showed */ public static func showLoaderWithPath(path: CGPath) -> Self { let loader = createLoaderWithPath(path: path) loader.showLoader() return loader } /** Creates and SHOWS a progress based loader with the given path :param: path Loader CGPath :returns: The loader that's already being showed */ public static func showProgressBasedLoaderWithPath(path: CGPath) -> Self { let loader = createProgressBasedLoaderWithPath(path: path) loader.showLoader() return loader } /** Creates a loader with the given path :param: path Loader CGPath :returns: The created loader */ public static func createLoaderWithPath(path thePath: CGPath) -> Self { let loader = self.init() loader.initialSetup() loader.addPath(thePath) return loader } /** Creates a progress based loader with the given path :param: path Loader CGPath :returns: The created loader */ public static func createProgressBasedLoaderWithPath(path thePath: CGPath) -> Self { let loader = self.init() loader.progressBased = true loader.initialSetup() loader.addPath(thePath) return loader } internal func initialSetup() { //Setting up frame let window = UIApplication.sharedApplication().delegate?.window! self.frame = window!.frame self.center = CGPointMake(CGRectGetMidX(window!.bounds), CGRectGetMidY(window!.bounds)) window!.addSubview(self) //Initial Values defaultValues() //Setting up loaderView loaderView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, rectSize) loaderView.center = CGPointMake(CGRectGetWidth(frame)/2, CGRectGetHeight(frame)/2) loaderView.layer.cornerRadius = cornerRadius //Add loader to its superview self.addSubview(loaderView) //Initially hidden hidden = true } internal func addPath(thePath: CGPath) { let bounds = CGPathGetBoundingBox(thePath) let center = bounds.origin let height = bounds.height let width = bounds.width assert(height <= loaderView.frame.height, "The height(\(height)) of the path has to fit the dimensions (Height: \(loaderView.frame.height) Width: \(frame.width))") assert(width <= loaderView.frame.height, "The width(\(width)) of the path has to fit the dimensions (Height: \(loaderView.frame.width) Width: \(frame.width))") var transformation = CGAffineTransformMakeTranslation(-center.x - width/2 + loaderView.frame.width/2, -center.y - height/2 + loaderView.frame.height/2) path = CGPathCreateCopyByTransformingPath(thePath, &transformation) } // MARK: Prepare Loader /** Shows the loader. Atention: do not use this method after creating a loader with `showLoaderWithPath(path:)` */ public func showLoader() { hidden = false animate = true generateLoader() startAnimating() } /** Stops loader animations and removes it from its superview */ public func removeLoader() { hidden = false animate = false removeFromSuperview() } internal func layoutPath() { let maskingLayer = CAShapeLayer() maskingLayer.frame = loaderView.bounds maskingLayer.path = path strokeLayer = CAShapeLayer() strokeLayer.frame = loaderView.bounds strokeLayer.path = path strokeLayer.strokeColor = loaderStrokeColor?.CGColor strokeLayer.lineWidth = loaderStrokeWidth strokeLayer.fillColor = loaderBackgroundColor?.CGColor loaderView.layer.addSublayer(strokeLayer) let baseLayer = CAShapeLayer() baseLayer.frame = loaderView.bounds baseLayer.mask = maskingLayer shapeLayer.fillColor = loaderColor?.CGColor shapeLayer.lineWidth = 0.2 shapeLayer.strokeColor = UIColor.blackColor().CGColor shapeLayer.frame = loaderView.bounds oldYPoint = rectSize + extraHeight shapeLayer.position = CGPoint(x: shapeLayer.position.x, y: oldYPoint) loaderView.layer.addSublayer(baseLayer) baseLayer.addSublayer(shapeLayer) } internal func defaultValues() { duration = 10.0 backgroundColor = UIColor.clearColor() loaderColor = UIColor(red: 0.41, green: 0.728, blue: 0.892, alpha: 1.0) loaderBackgroundColor = UIColor.whiteColor() loaderStrokeColor = UIColor.blackColor() loaderStrokeWidth = 0.5 loaderAlpha = 1.0 cornerRadius = 0.0 } //MARK: Animations internal func startMoving(up: Bool) { if (progressBased) { return } let key = up ? "up" : "down" let moveAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y") moveAnimation.values = up ? [loaderView.frame.height/2 + rectSize/2, loaderView.frame.height/2 - rectSize/2 - extraHeight] : [loaderView.frame.height/2 - rectSize/2 - extraHeight, loaderView.frame.height/2 + rectSize/2] moveAnimation.duration = duration moveAnimation.removedOnCompletion = false moveAnimation.fillMode = kCAFillModeForwards moveAnimation.delegate = self moveAnimation.setValue(key, forKey: "animation") shapeLayer.addAnimation(moveAnimation, forKey: key) } internal func applyProgress() { let yPoint = (rectSize + extraHeight)*(1-progress) let progressAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position.y") progressAnimation.values = [oldYPoint, yPoint] progressAnimation.duration = 0.2 progressAnimation.removedOnCompletion = false progressAnimation.fillMode = kCAFillModeForwards shapeLayer.addAnimation(progressAnimation, forKey: "progress") oldYPoint = yPoint } internal func startswinging() { let swingAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") swingAnimation.values = [0, randomAngle(), -randomAngle(), randomAngle(), -randomAngle(), randomAngle(), 0] swingAnimation.duration = 12.0 swingAnimation.removedOnCompletion = false swingAnimation.fillMode = kCAFillModeForwards swingAnimation.delegate = self swingAnimation.setValue("rotation", forKey: "animation") shapeLayer.addAnimation(swingAnimation, forKey: "rotation") } internal func randomAngle() -> Double { return M_PI_4/(Double(arc4random_uniform(16)) + 8) } //MARK: Abstract methods internal func generateLoader() { preconditionFailure("This method must be overridden") } internal func startAnimating() { preconditionFailure("This method must be overridden") } }
mit
06e67106245345f352fe3306856aae63
32.92378
227
0.638235
5.054975
false
false
false
false
openhab/openhab.ios
openHAB/SwitchUITableViewCell.swift
1
1834
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import OpenHABCore import os.log import UIKit class SwitchUITableViewCell: GenericUITableViewCell { @IBOutlet private var widgetSwitch: UISwitch! required init?(coder: NSCoder) { super.init(coder: coder) initialize() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) initialize() } override func initialize() { selectionStyle = .none separatorInset = .zero } override func displayWidget() { customTextLabel?.text = widget.labelText var state = widget.state // if state is nil or empty using the item state ( OH 1.x compatability ) if state.isEmpty { state = (widget.item?.state) ?? "" } customDetailTextLabel?.text = widget.labelValue ?? "" widgetSwitch?.isOn = state.parseAsBool() widgetSwitch?.addTarget(self, action: .switchChange, for: .valueChanged) super.displayWidget() } @objc func switchChange() { if (widgetSwitch?.isOn)! { os_log("Switch to ON", log: .viewCycle, type: .info) widget.sendCommand("ON") } else { os_log("Switch to OFF", log: .viewCycle, type: .info) widget.sendCommand("OFF") } } } private extension Selector { static let switchChange = #selector(SwitchUITableViewCell.switchChange) }
epl-1.0
46083b2915bac0138965948a74cc12ab
29.065574
81
0.647219
4.366667
false
false
false
false
alexjohnj/spotijack
LibSpotijack/Scripting Bridge Compatibility/Audio Hijack/AudioHijackScripting.swift
1
545
public enum AudioHijackScripting: String { case application = "application" case browserWindow = "browser window" case applicationSession = "application session" case audioDeviceSession = "audio device session" case radioDeviceSession = "radio device session" case systemAudioSession = "system audio session" case session = "session" case timer = "timer" case audioDevice = "audio device" case audioInput = "audio input" case audioOutput = "audio output" case audioRecording = "audio recording" }
mit
20bc6889fb3538dea8db982b5b41b79d
37.928571
52
0.719266
4.73913
false
false
false
false
timd/ProiOSTableCollectionViews
Ch14/WatchTable/WatchTarget Extension/InterfaceController.swift
1
3585
// // InterfaceController.swift // WatchTarget Extension // // Created by Tim on 03/12/15. // Copyright © 2015 Tim Duckett. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var watchTable: WKInterfaceTable! var dataArray = [String]() override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. setupData() updateTable() } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func setupData() { dataArray.append("Bob") dataArray.append("Felix") dataArray.append("Jim") dataArray.append("Fred") } func updateTable() { // Create array to hold the row types var rowTypes = [String]() // Add header row as the row 0 rowTypes.append("HeaderRow") // Add a contact row for each object in the dataArray for _ in dataArray { rowTypes.append("ContactRow") } // Add a footer row as the last row rowTypes.append("FooterRow") // Configure the table to display the rows as defined in the rowsArray watchTable.setRowTypes(rowTypes) // Retrieve each contact row and set the contents from the dataArray // Start at row 1, because row 0 is the header row for index in 0..<dataArray.count { let contactRow = watchTable.rowControllerAtIndex(index+1) as! ContactRowController let rowContent = dataArray[index] contactRow.nameLabel!.setText(rowContent) if let image = UIImage(named: rowContent) { contactRow.avatarImage.setImage(image) } } // Get the last row, and configure it as the footer let contactCount = dataArray.count let footerRow = watchTable.rowControllerAtIndex(contactCount + 1) as! FooterRowController footerRow.footerLabel.setText("\(contactCount) messages") } override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { table.setRowTypes(["HeaderCell", "DataCell", "DataCell", "FooterCell"]) for index in 0..<dataArray.count { let contactRow = watchTable.rowControllerAtIndex(index+1) as! ContactRowController contactRow.nameLabel!.setTextColor(UIColor.whiteColor()) } let selectedRow = watchTable.rowControllerAtIndex(rowIndex) as! ContactRowController selectedRow.nameLabel.setTextColor(UIColor.redColor()) let contextDictionary = ["selectedName" : self.dataArray[rowIndex - 1]] self.pushControllerWithName("DetailInterface", context: contextDictionary) } override func contextForSegueWithIdentifier(segueIdentifier: String, inTable table: WKInterfaceTable, rowIndex: Int) -> AnyObject? { if segueIdentifier == "PushDetailScreenSegue" { return ["selectedName" : dataArray[rowIndex - 1]] } return nil } }
mit
a33a5d2652d19f68a8dd76f9f2d9f7bb
29.372881
136
0.60519
5.505376
false
false
false
false
iOSTestApps/SceneKitFrogger
4-Challenge/SCNFrogger-4/SCNFrogger/LabelNode.swift
8
564
// // LabelNode.swift // SCNFrogger // // Created by Kim Pedersen on 11/12/14. // Copyright (c) 2014 RWDevCon. All rights reserved. // import SpriteKit class LabelNode : SKLabelNode { init(position: CGPoint, size: CGFloat, color: SKColor, text: String, name: String) { super.init() self.name = name self.text = text self.position = position fontName = "Early-Gameboy" fontSize = size fontColor = color } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
eb4682b0a10ef6bf03c53a392f65e739
19.142857
86
0.64539
3.662338
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Photo/PublishCropperViewController.swift
1
4405
// // PublishCropperViewController.swift // Whereami // // Created by A on 16/5/23. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit import BABCropperView import PureLayout //import MBProgressHUD import SVProgressHUD class PublishCropperViewController: UIViewController { var photoImage:UIImage? = nil var cropperView:BABCropperView? = nil var type:editType? = nil override func viewDidLoad() { super.viewDidLoad() self.setUI() // Do any additional setup after loading the view. } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } func setUI(){ self.cropperView = BABCropperView() self.cropperView?.image = photoImage self.cropperView!.cropSize = CGSize(width: LScreenW,height: LScreenW) self.cropperView!.cropsImageToCircle = false self.view.addSubview(self.cropperView!) self.cropperView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0, 0, 0, 0)) let button = UIButton() button.setTitle("next", forState: .Normal) button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.rac_signalForControlEvents(.TouchUpInside).subscribeNext { (button) in self.cropperView?.renderCroppedImage({ (image, rect) in self.runInMainQueue({ if self.type == editType.avator { self.updateAvator(image) } else{ self.push2FilterViewController(image) } }) }) } self.view.addSubview(button) button.autoPinEdgeToSuperviewEdge(.Bottom) button.autoPinEdgeToSuperviewEdge(.Right) button.autoSetDimensionsToSize(CGSize(width: 100,height: 100)) } func push2FilterViewController(image:UIImage){ let viewController = PhotoEditingViewController() viewController.photoImage = image self.navigationController?.pushViewController(viewController, animated: true) } func updateAvator(image:UIImage){ let currentUser = UserModel.getCurrentUser() var dic = [String:AnyObject]() dic["userId"] = currentUser?.id dic["type"] = "jpg" dic["content"] = UIImageJPEGRepresentation(image, 1.0) self.runInMainQueue { SVProgressHUD.show() } SocketManager.sharedInstance.sendMsg("uploadImageFile", data: dic, onProto: "uploadImageFileed", callBack: { (code, objs) -> Void in if code == statusCode.Normal.rawValue { let file = objs[0]["file"] as! String var dict = [String:AnyObject]() dict["accountId"] = currentUser?.id dict["headPortrait"] = file SocketManager.sharedInstance.sendMsg("accountUpdate", data: dict, onProto: "accountUpdateed") { (code, objs) in self.runInMainQueue({ if code == statusCode.Normal.rawValue { currentUser?.headPortraitUrl = file CoreDataManager.sharedInstance.increaseOrUpdateUser(currentUser!) NSNotificationCenter.defaultCenter().postNotificationName("KNotificationChangeAvatar", object: image) SVProgressHUD.dismiss() self.dismissViewControllerAnimated(true, completion: nil) } else{ self.uploadErrorAction() } }) } } else{ self.runInMainQueue({ self.uploadErrorAction() }) } }) } func uploadErrorAction(){ SVProgressHUD.showErrorWithStatus("upload error") self.performSelector(#selector(self.dismissVC), withObject: nil, afterDelay: 2) } func dismissVC(){ self.dismissViewControllerAnimated(true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
94341afdd8b13920351b959dce307b3e
34.788618
140
0.579964
5.658098
false
false
false
false
onevcat/Hedwig
Sources/MailStream.swift
1
7572
// // MailStream.swift // Hedwig // // Created by Wei Wang on 2017/1/3. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation typealias DataHandler = ([UInt8]) -> Void let bufferLength = 76 * 24 * 7 enum MailStreamError: Error { case streamNotExist case streamReadingFailed case encoding case fileNotExist } class MailStream: NSObject { var onData: DataHandler? = nil var inputStream: InputStream? var buffer = Array<UInt8>(repeating: 0, count: bufferLength) var shouldEncode = false let mail: Mail init(mail: Mail, onData: DataHandler?) { self.mail = mail self.onData = onData } func stream() throws { try streamHeader() if mail.hasAttachment { try streamMixed() } else { try streamText() } } func streamHeader() throws { let header = mail.headersString + CRLF send(header) } func streamText() throws { let text = mail.text.embededForText() try streamText(text: text) } func streamMixed() throws { let boundary = String.createBoundary() let mixedHeader = String.mixedHeader(boundary: boundary) send(mixedHeader) send(boundary.startLine) if mail.alternative != nil { try streamAlternative() } else { try streamText() } try streamAttachments(mail.attachments, boundary: boundary) } func streamAlternative() throws { let boundary = String.createBoundary() let alternativeHeader = String.alternativeHeader(boundary: boundary) send(alternativeHeader) send(boundary.startLine) try streamText() let alternative = mail.alternative! send(boundary.startLine) try streamAttachment(attachment: alternative) send(boundary.endLine) } func streamAttachment(attachment: Attachment) throws { let relatedBoundary: String let hasRelated = !attachment.related.isEmpty if hasRelated { relatedBoundary = String.createBoundary() let relatedHeader = String.relatedHeader(boundary: relatedBoundary) send(relatedHeader) send(relatedBoundary.startLine) } else { relatedBoundary = "" } let attachmentHeader = attachment.headerString + CRLF + CRLF send(attachmentHeader) switch attachment.type { case .file(let file): try streamFile(at: file.path) case .html(let html): try streamHTML(text: html.content) case .data(let data): try streamData(data: data.data) } send(CRLF) if hasRelated { send("\(CRLF)\(CRLF)") try streamAttachments(attachment.related, boundary: relatedBoundary) } } func streamAttachments(_ attachments: [Attachment], boundary: String) throws { for attachement in attachments { send(boundary.startLine) try streamAttachment(attachment: attachement) } send(boundary.endLine) } func streamFile(at path: String) throws { var isDirectory: ObjCBool = false let fileExist = FileManager.default .fileExists(atPath: path, isDirectory: &isDirectory) #if os(Linux) let directory: Bool = isDirectory #else let directory: Bool = isDirectory.boolValue #endif guard fileExist && !directory else { throw MailStreamError.fileNotExist } shouldEncode = true inputStream = InputStream(fileAtPath: path)! try loadBytes() shouldEncode = false } func streamData(data: Data) throws { shouldEncode = true inputStream = InputStream(data: data) try loadBytes() shouldEncode = false } func streamHTML(text: String) throws { shouldEncode = true try streamText(text: text) shouldEncode = false } func streamText(text: String) throws { inputStream = try InputStream(text: text) try loadBytes() } func send(_ text: String) { onData?(Array(text.utf8)) } private func loadBytes() throws { guard let stream = inputStream else { throw MailStreamError.streamNotExist } stream.open() defer { stream.close() } while stream.streamStatus != .atEnd && stream.streamStatus != .error { let count = stream.read(&buffer, maxLength: bufferLength) if count != 0 { let toSend = Array(buffer.dropLast(bufferLength - count)) onData?( shouldEncode ? toSend.base64Encoded : toSend ) } } guard stream.streamStatus == .atEnd else { throw MailStreamError.streamReadingFailed } } } extension InputStream { convenience init(text: String) throws { guard let data = text.data(using: .utf8, allowLossyConversion: false) else { throw MailStreamError.encoding } self.init(data: data) } } extension String { static func createBoundary() -> String { return UUID().uuidString.replacingOccurrences(of: "-", with: "") } static let plainTextHeader = "Content-Type: text/plain; charset=utf-8\(CRLF)Content-Transfer-Encoding: 7bit\(CRLF)Content-Disposition: inline\(CRLF)\(CRLF)" static func mixedHeader(boundary: String) -> String { return "Content-Type: multipart/mixed; boundary=\"\(boundary)\"\(CRLF)\(CRLF)" } static func alternativeHeader(boundary: String) -> String { return "Content-Type: multipart/alternative; boundary=\"\(boundary)\"\(CRLF)\(CRLF)" } static func relatedHeader(boundary: String) -> String { return "Content-Type: multipart/related; boundary=\"\(boundary)\"\(CRLF)\(CRLF)" } func embededForText() -> String { return "\(String.plainTextHeader)\(self)\(CRLF)\(CRLF)" } } extension String { var startLine: String { return "--\(self)\(CRLF)" } var endLine: String { return "\(CRLF)--\(self)--\(CRLF)\(CRLF)" } }
mit
099ddca71f7c621b3e2a06b565c4bd84
28.694118
160
0.607501
4.82293
false
false
false
false
vishw3/IOSChart-IOS-7.0-Support
VisChart/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
2
10390
// // ChartXAxisRendererHorizontalBarChart.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart); } public override func computeAxis(#xValAverageLength: Float, xValues: [String]) { _xAxis.values = xValues; var longest = _xAxis.getLongestLabel() as NSString; var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]); _xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5); _xAxis.labelHeight = longestSize.height; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil) { return; } var xoffset = _xAxis.xOffset; if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left); } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right); } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left); } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right); } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentLeft, align: .Left); drawLabels(context: context, pos: viewPortHandler.contentRight, align: .Left); } } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment) { var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; var step = bd.dataSetCount; for (var i = 0; i < _xAxis.values.count; i += _xAxis.axisLabelModulus) { position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0; // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0; } transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { var label = _xAxis.values[i]; ChartUtils.drawText(context: context, text: label, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderGridLines(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor); CGContextSetLineWidth(context, _xAxis.gridLineWidth); if (_xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; // take into consideration that multiple DataSets increase _deltaX var step = bd.dataSetCount; for (var i = 0; i < _xAxis.values.count; i += _xAxis.axisLabelModulus) { position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5; transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { _gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _gridLineSegmentsBuffer[0].y = position.y; _gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _gridLineSegmentsBuffer[1].y = position.y; CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderAxisLine(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled) { return; } CGContextSaveGState(context); CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor); CGContextSetLineWidth(context, _xAxis.axisLineWidth); if (_xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } if (_xAxis.labelPosition == .Top || _xAxis.labelPosition == .TopInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } CGContextRestoreGState(context); } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines; if (limitLines.count == 0) { return; } CGContextSaveGState(context); var trans = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; position.x = 0.0; position.y = CGFloat(l.limit); position = CGPointApplyAffineTransform(position, trans); _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _limitLineSegmentsBuffer[0].y = position.y; _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _limitLineSegmentsBuffer[1].y = position.y; CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor); CGContextSetLineWidth(context, l.lineWidth); if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2); var label = l.label; // if drawing the limit-value label is enabled if (label.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) > 0) { var labelLineHeight = l.valueFont.lineHeight; let add = CGFloat(4.0); var xOffset: CGFloat = add; var yOffset: CGFloat = l.lineWidth + labelLineHeight / 2.0; if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } } } CGContextRestoreGState(context); } }
mit
741e2b6fe6ce4d49cbbdcd040c5fd639
36.785455
241
0.570356
5.448348
false
false
false
false
safx/ObservableArray-RxSwift
ObservableArray/ObservableArray.swift
1
6488
// // ObservableArray.swift // ObservableArray // // Created by Safx Developer on 2015/02/19. // Copyright (c) 2016 Safx Developers. All rights reserved. // import Foundation import RxSwift public struct ArrayChangeEvent { public let insertedIndices: [Int] public let deletedIndices: [Int] public let updatedIndices: [Int] fileprivate init(inserted: [Int] = [], deleted: [Int] = [], updated: [Int] = []) { assert(inserted.count + deleted.count + updated.count > 0) insertedIndices = inserted deletedIndices = deleted updatedIndices = updated } } public struct ObservableArray<Element>: ExpressibleByArrayLiteral { public typealias EventType = ArrayChangeEvent internal var eventSubject: PublishSubject<EventType>! internal var elementsSubject: BehaviorSubject<[Element]>! internal var elements: [Element] public init() { elements = [] } public init(count: Int, repeatedValue: Element) { elements = Array(repeating: repeatedValue, count: count) } public init<S : Sequence>(_ s: S) where S.Iterator.Element == Element { elements = Array(s) } public init(arrayLiteral elements: Element...) { self.elements = elements } } extension ObservableArray { public mutating func rx_elements() -> Observable<[Element]> { if elementsSubject == nil { elementsSubject = BehaviorSubject<[Element]>(value: elements) } return elementsSubject } public mutating func rx_events() -> Observable<EventType> { if eventSubject == nil { eventSubject = PublishSubject<EventType>() } return eventSubject } fileprivate func arrayDidChange(_ event: EventType) { elementsSubject?.onNext(elements) eventSubject?.onNext(event) } } extension ObservableArray: Collection { public var capacity: Int { return elements.capacity } /*public var count: Int { return elements.count }*/ public var startIndex: Int { return elements.startIndex } public var endIndex: Int { return elements.endIndex } public func index(after i: Int) -> Int { return elements.index(after: i) } } extension ObservableArray: MutableCollection { public mutating func reserveCapacity(_ minimumCapacity: Int) { elements.reserveCapacity(minimumCapacity) } public mutating func append(_ newElement: Element) { elements.append(newElement) arrayDidChange(ArrayChangeEvent(inserted: [elements.count - 1])) } public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Element { let end = elements.count elements.append(contentsOf: newElements) guard end != elements.count else { return } arrayDidChange(ArrayChangeEvent(inserted: Array(end..<elements.count))) } public mutating func appendContentsOf<C : Collection>(_ newElements: C) where C.Iterator.Element == Element { guard !newElements.isEmpty else { return } let end = elements.count elements.append(contentsOf: newElements) arrayDidChange(ArrayChangeEvent(inserted: Array(end..<elements.count))) } @discardableResult public mutating func removeLast() -> Element { let e = elements.removeLast() arrayDidChange(ArrayChangeEvent(deleted: [elements.count])) return e } public mutating func insert(_ newElement: Element, at i: Int) { elements.insert(newElement, at: i) arrayDidChange(ArrayChangeEvent(inserted: [i])) } @discardableResult public mutating func remove(at index: Int) -> Element { let e = elements.remove(at: index) arrayDidChange(ArrayChangeEvent(deleted: [index])) return e } public mutating func removeAll(_ keepCapacity: Bool = false) { guard !elements.isEmpty else { return } let es = elements elements.removeAll(keepingCapacity: keepCapacity) arrayDidChange(ArrayChangeEvent(deleted: Array(0..<es.count))) } public mutating func insertContentsOf(_ newElements: [Element], atIndex i: Int) { guard !newElements.isEmpty else { return } elements.insert(contentsOf: newElements, at: i) arrayDidChange(ArrayChangeEvent(inserted: Array(i..<i + newElements.count))) } public mutating func popLast() -> Element? { let e = elements.popLast() if e != nil { arrayDidChange(ArrayChangeEvent(deleted: [elements.count])) } return e } } extension ObservableArray: RangeReplaceableCollection { public mutating func replaceSubrange<C : Collection>(_ subRange: Range<Int>, with newCollection: C) where C.Iterator.Element == Element { let oldCount = elements.count elements.replaceSubrange(subRange, with: newCollection) let first = subRange.lowerBound let newCount = elements.count let end = first + (newCount - oldCount) + subRange.count arrayDidChange(ArrayChangeEvent(inserted: Array(first..<end), deleted: Array(subRange.lowerBound..<subRange.upperBound))) } } extension ObservableArray: CustomDebugStringConvertible { public var description: String { return elements.description } } extension ObservableArray: CustomStringConvertible { public var debugDescription: String { return elements.debugDescription } } extension ObservableArray: Sequence { public subscript(index: Int) -> Element { get { return elements[index] } set { elements[index] = newValue if index == elements.count { arrayDidChange(ArrayChangeEvent(inserted: [index])) } else { arrayDidChange(ArrayChangeEvent(updated: [index])) } } } public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { return elements[bounds] } set { elements[bounds] = newValue let first = bounds.lowerBound arrayDidChange(ArrayChangeEvent(inserted: Array(first..<first + newValue.count), deleted: Array(bounds.lowerBound..<bounds.upperBound))) } } }
mit
b640e7dba8f5864bbe23fe5b64145e82
29.317757
141
0.63394
5.100629
false
false
false
false
likumb/SimpleMemo
SimpleMemo/CoreData/CoreDataStack.swift
2
1092
// // CoreDataStack.swift // SimpleMemo // // Created by  李俊 on 2017/2/25. // Copyright © 2017年 Lijun. All rights reserved. // import Foundation import CoreData class CoreDataStack { static let `default` = CoreDataStack() lazy var persistentContainer: NSPersistentContainer = { return self.fetchPersistentContainer(with: "SimpleMemo") }() lazy var managedContext: NSManagedObjectContext = { return self.persistentContainer.viewContext }() func saveContext () { if managedContext.hasChanges { do { try managedContext.save() } catch { let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } func fetchPersistentContainer(with name: String) -> NSPersistentContainer { let container = NSPersistentContainer(name: name) container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container } }
mit
a9cfebcb68e4b508fcdde051e3f7d962
23.088889
84
0.677122
4.733624
false
false
false
false
YoungGary/Sina
Sina/Sina/Classes/Home首页/ImageBrowerViewController.swift
1
6151
// // ImageBrowerViewController.swift // Sina // // Created by YOUNG on 16/9/23. // Copyright © 2016年 Young. All rights reserved. // import UIKit import SnapKit import SVProgressHUD //collectionView-> scrollView-> imageView class ImageBrowerViewController: UIViewController { //MARK:存储属性 var indexPath : NSIndexPath var picUrls : [NSURL] //创建子控件 lazy var photoCollectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: photoBrowerFlowLayout()) lazy var closeButton : UIButton = UIButton() lazy var saveButton : UIButton = UIButton() //override init 存储属性 init(indexPath : NSIndexPath , picUrls : [NSURL]){ self.indexPath = indexPath self.picUrls = picUrls super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blackColor() setupUI() //滚到相应的图片 photoCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false) } override func loadView() { super.loadView() view.frame.size.width += 20 } } //MARK:UI extension ImageBrowerViewController{ private func setupUI(){ view.addSubview(photoCollectionView) view.addSubview(closeButton) view.addSubview(saveButton) //frame photoCollectionView.frame = view.bounds closeButton.snp_makeConstraints { (make) in make.left.equalTo(20) make.bottom.equalTo(-20) make.size.equalTo(CGSize(width: 80, height: 30)) } saveButton.snp_makeConstraints { (make) in make.right.equalTo(-20) make.bottom.equalTo(-20) make.size .equalTo(CGSize(width: 80, height: 30)) } //设置button属性 closeButton.setTitle("关 闭", forState: .Normal) closeButton.titleLabel?.font = UIFont.systemFontOfSize(14) closeButton.backgroundColor = UIColor.lightGrayColor() closeButton.addTarget(self, action: #selector(ImageBrowerViewController.didClickCloseButton), forControlEvents: .TouchUpInside) saveButton.setTitle("保 存", forState: .Normal) saveButton.titleLabel?.font = UIFont.systemFontOfSize(14) saveButton.backgroundColor = UIColor.lightGrayColor() saveButton.addTarget(self, action: #selector(ImageBrowerViewController.didClickSaveButton), forControlEvents: .TouchUpInside) //collectionView photoCollectionView.dataSource = self photoCollectionView.registerClass(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: "photo") } } //MARK:事件监听 extension ImageBrowerViewController{ //关闭 @objc private func didClickCloseButton(){ dismissViewControllerAnimated(true, completion: nil) } //保存图片 @objc private func didClickSaveButton(){ let cell = photoCollectionView.visibleCells().first as! PhotoCollectionViewCell guard let image = cell.imageView.image else{ return } UIImageWriteToSavedPhotosAlbum(image, self, #selector(ImageBrowerViewController.image(_:didFinishSavingWithError:contextInfo:)), nil) } // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo; @objc private func image(image : UIImage , didFinishSavingWithError : NSError? ,contextInfo : AnyObject?){ if didFinishSavingWithError != nil { SVProgressHUD.showErrorWithStatus("保存失败") }else{ SVProgressHUD.showSuccessWithStatus("保存成功") } } } //MARK:UICollectionViewDataSource extension ImageBrowerViewController : UICollectionViewDataSource{ func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return picUrls.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photo", forIndexPath: indexPath) as! PhotoCollectionViewCell cell.picURL = picUrls[indexPath.item] cell.delegate = self return cell } } //MARK:实现代理方法 extension ImageBrowerViewController : photoCollectionViewDelegate{ func imageViewClick() { didClickCloseButton() } } // MARK:- 遵守AnimationDismissDelegate extension ImageBrowerViewController : AnimationDismissDelegate { func indexPathForDimissView() -> NSIndexPath { // 1.获取当前正在显示的indexPath let cell = photoCollectionView.visibleCells().first! return photoCollectionView.indexPathForCell(cell)! } func imageViewForDimissView() -> UIImageView { // 1.创建UIImageView对象 let imageView = UIImageView() // 2.设置imageView的frame let cell = photoCollectionView.visibleCells().first as! PhotoCollectionViewCell imageView.frame = cell.imageView.frame imageView.image = cell.imageView.image // 3.设置imageView的属性 imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView } } //MARK:自定义flowlayout class photoBrowerFlowLayout : UICollectionViewFlowLayout{ override func prepareLayout() { super.prepareLayout() itemSize = collectionView!.frame.size minimumLineSpacing = 0 minimumInteritemSpacing = 0 scrollDirection = .Horizontal collectionView?.pagingEnabled = true collectionView?.showsVerticalScrollIndicator = false collectionView?.showsHorizontalScrollIndicator = false } }
apache-2.0
9d0012f56ec5856ac6bafcab2f514955
29.571429
141
0.667891
5.690408
false
false
false
false
urdnot-ios/ShepardAppearanceConverter
ShepardAppearanceConverter/ShepardAppearanceConverter/Views/Shepard Class/ShepardClassController.swift
1
2312
// // ShepardClassController.swift // ShepardAppearanceConverter // // Created by Emily Ivie on 7/29/15. // Copyright © 2015 urdnot. All rights reserved. // import UIKit class ShepardClassController: UIViewController { @IBOutlet weak var soldierRadio: FauxRadioRow! @IBOutlet weak var engineerRadio: FauxRadioRow! @IBOutlet weak var adeptRadio: FauxRadioRow! @IBOutlet weak var infiltratorRadio: FauxRadioRow! @IBOutlet weak var sentinelRadio: FauxRadioRow! @IBOutlet weak var vanguardRadio: FauxRadioRow! override func viewDidLoad() { super.viewDidLoad() setupPage() } func setupPage() { soldierRadio.onClick = { App.currentGame.shepard.classTalent = .Soldier App.currentGame.shepard.saveAnyChanges() self.setupRadios() } engineerRadio.onClick = { App.currentGame.shepard.classTalent = .Engineer App.currentGame.shepard.saveAnyChanges() self.setupRadios() } adeptRadio.onClick = { App.currentGame.shepard.classTalent = .Adept App.currentGame.shepard.saveAnyChanges() self.setupRadios() } infiltratorRadio.onClick = { App.currentGame.shepard.classTalent = .Infiltrator App.currentGame.shepard.saveAnyChanges() self.setupRadios() } sentinelRadio.onClick = { App.currentGame.shepard.classTalent = .Sentinel App.currentGame.shepard.saveAnyChanges() self.setupRadios() } vanguardRadio.onClick = { App.currentGame.shepard.classTalent = .Vanguard App.currentGame.shepard.saveAnyChanges() self.setupRadios() } setupRadios() } func setupRadios() { soldierRadio.isOn = App.currentGame.shepard.classTalent == .Soldier engineerRadio.isOn = App.currentGame.shepard.classTalent == .Engineer adeptRadio.isOn = App.currentGame.shepard.classTalent == .Adept infiltratorRadio.isOn = App.currentGame.shepard.classTalent == .Infiltrator sentinelRadio.isOn = App.currentGame.shepard.classTalent == .Sentinel vanguardRadio.isOn = App.currentGame.shepard.classTalent == .Vanguard } }
mit
8dffac6cff60e31db42a6e77711f768d
34.015152
83
0.645608
4.735656
false
false
false
false
Pstoppani/swipe
sample/sample/SwipeVideoController.swift
1
10463
// // SwipeVideoController.swift // iheadunit // // Created by satoshi on 11/22/16. // Copyright © 2016 Satoshi Nakajima. All rights reserved. // import UIKit import AVFoundation class SwipeVideoController: UIViewController { static var playerItemContext = "playerItemContext" fileprivate var document = [String:Any]() fileprivate var pages = [[String:Any]]() fileprivate weak var delegate:SwipeDocumentViewerDelegate? fileprivate var url:URL? fileprivate let videoPlayer = AVPlayer() fileprivate var videoLayer:AVPlayerLayer! fileprivate let overlayLayer = CALayer() fileprivate var index = 0 fileprivate var observer:Any? fileprivate var layers = [String:CALayer]() fileprivate var dimension = CGSize(width:320, height:568) deinit { print("SVideoC deinit") } override func viewDidLoad() { super.viewDidLoad() videoLayer = AVPlayerLayer(player: self.videoPlayer) overlayLayer.masksToBounds = true view.layer.addSublayer(self.videoLayer) view.layer.addSublayer(self.overlayLayer) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let frame = CGRect(origin: .zero, size: dimension) self.videoLayer.frame = frame self.overlayLayer.frame = frame let viewSize = view.bounds.size let scale = min(viewSize.width / dimension.width, viewSize.height / dimension.height) var xf = CATransform3DMakeScale(scale, scale, 0) xf = CATransform3DTranslate(xf, (viewSize.width - dimension.width) / 2.0 / scale, (viewSize.height - dimension.height) / 2.0 / scale, 0.0) self.videoLayer.transform = xf self.overlayLayer.transform = xf } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension SwipeVideoController: SwipeDocumentViewer { func documentTitle() -> String? { return document["title"] as? String } func loadDocument(_ document:[String:Any], size:CGSize, url:URL?, state:[String:Any]?, callback:@escaping (Float, NSError?)->(Void)) throws { self.document = document self.url = url guard let filename = document["video"] as? String, let pages = document["pages"] as? [[String:Any]] else { throw SwipeError.invalidDocument } self.pages = pages if let dimension = document["dimension"] as? [CGFloat], dimension.count == 2 { self.dimension = CGSize(width: dimension[0], height: dimension[1]) } guard let videoURL = Bundle.main.url(forResource: filename, withExtension: nil) else { return } let playerItem = AVPlayerItem(url:videoURL) videoPlayer.replaceCurrentItem(with: playerItem) if let elements = document["elements"] as? [[String:Any]] { print("elements", elements) for element in elements { if let id = element["id"] as? String, let h = element["h"] as? CGFloat, let w = element["w"] as? CGFloat { let layer = CALayer() layer.frame = CGRect(origin: .zero, size: CGSize(width: w, height: h)) layer.backgroundColor = UIColor.blue.cgColor layers[id] = layer } } } //moveToPageAt(index: 0) playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.old, .new], context: &SwipeVideoController.playerItemContext) callback(1.0, nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard context == &SwipeVideoController.playerItemContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } if keyPath == #keyPath(AVPlayerItem.status) { let status: AVPlayerItemStatus // Get the status change from the change dictionary if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItemStatus(rawValue: statusNumber.intValue)! } else { status = .unknown } // Switch over the status switch status { case .readyToPlay: print("ready") moveToPageAt(index: 0) if let playerItem = videoPlayer.currentItem { playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &SwipeVideoController.playerItemContext) } default: break } } } func hideUI() -> Bool { return true } func landscape() -> Bool { return false // we might want to change it later } func setDelegate(_ delegate:SwipeDocumentViewerDelegate) { self.delegate = delegate } func becomeZombie() { // no op } func saveState() -> [String:Any]? { return nil } func languages() -> [[String:Any]]? { return nil } func reloadWithLanguageId(_ langId:String) { // no op } private func removeObserver() { if let observer = self.observer { videoPlayer.removeTimeObserver(observer) self.observer = nil print("SVideoC remove observer") } } func moveToPageAt(index:Int) { print("SVideoC moveToPageAt", index) if index < pages.count { self.index = index let page = pages[self.index] let start = page["start"] as? Double ?? 0.0 let duration = page["duration"] as? Double ?? 0.0 let videoPlayer = self.videoPlayer // local guard let playerItem = videoPlayer.currentItem else { return // something is wrong } removeObserver() let time = CMTime(seconds: start, preferredTimescale: 600) let tolerance = CMTimeMake(10, 600) // 1/60sec playerItem.seek(to: time, toleranceBefore: tolerance, toleranceAfter: tolerance) { (success) in //print("seek complete", success) if duration > 0 { videoPlayer.play() let end = CMTime(seconds: start + duration, preferredTimescale: 600) self.observer = videoPlayer.addBoundaryTimeObserver(forTimes: [end as NSValue], queue: nil) { [weak self] in print("SVideoC pausing", index) videoPlayer.pause() self?.removeObserver() } } } CATransaction.begin() CATransaction.setDisableActions(true) if let sublayers = overlayLayer.sublayers { for layer in sublayers { layer.removeFromSuperlayer() } } if let elements = page["elements"] as? [[String:Any]] { for element in elements { if let id = element["id"] as? String, let layer = layers[id] { layer.removeAllAnimations() layer.transform = CATransform3DIdentity let x = element["x"] as? CGFloat ?? 0 let y = element["y"] as? CGFloat ?? 0 let frame = CGRect(origin: CGPoint(x:x, y:y), size: layer.frame.size) layer.frame = frame layer.opacity = element["opacity"] as? Float ?? 1.0 overlayLayer.addSublayer(layer) if let to = element["to"] as? [String:Any] { var beginTime:CFTimeInterval? if let start = to["start"] as? Double { beginTime = layer.convertTime(CACurrentMediaTime(), to: nil) + start } let aniDuration = to["duration"] as? Double ?? duration if let tx = to["translate"] as? [CGFloat], tx.count == 2 { let ani = CABasicAnimation(keyPath: "transform") let transform = CATransform3DMakeTranslation(tx[0], tx[1], 0.0) ani.fromValue = CATransform3DIdentity as NSValue ani.toValue = transform as NSValue // NSValue(caTransform3D : transform) ani.fillMode = kCAFillModeBoth if let beginTime = beginTime { ani.beginTime = beginTime } ani.duration = aniDuration layer.add(ani, forKey: "transform") layer.transform = transform } if let opacity = to["opacity"] as? Float { let ani = CABasicAnimation(keyPath: "opacity") ani.fromValue = layer.opacity as NSValue ani.toValue = opacity as NSValue ani.fillMode = kCAFillModeBoth if let beginTime = beginTime { ani.beginTime = beginTime } ani.duration = aniDuration layer.add(ani, forKey: "transform") layer.opacity = opacity } } } } } CATransaction.commit() } } func pageIndex() -> Int? { return index } func pageCount() -> Int? { return pages.count } }
mit
75bab8d6be9e5ca431327b110e765950
38.330827
152
0.51711
5.471757
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/MeasureNumberNode.swift
1
1203
// // MeasureNumberNode.swift // denm_view // // Created by James Bean on 10/6/15. // Copyright © 2015 James Bean. All rights reserved. // import QuartzCore // TO-DO: PADS AT INIT public class MeasureNumberNode: ViewNode { public var height: CGFloat = 0 public var measureNumbers: [MeasureNumber] = [] public init(height: CGFloat = 0) { self.height = height super.init() layoutFlow_vertical = .Top } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(layer: AnyObject) { super.init(layer: layer) } public func addMeasureNumber(measureNumber: MeasureNumber) { measureNumbers.append(measureNumber) addNode(measureNumber) } public func addMeasureNumberWithNumber(number: Int, atX x: CGFloat) { let measureNumber = MeasureNumber(number: number, x: x, top: 0, height: height) addMeasureNumber(measureNumber) } public func getMeasureNumberAtX(x: CGFloat) -> MeasureNumber? { for measureNumber in measureNumbers { if measureNumber.position.x == x { return measureNumber } } return nil } }
gpl-2.0
8314991e257c2d338b7fa109f8550df1
27.642857
87
0.652246
4.40293
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/AccountRecovery/SeedPhrase/SeedPhraseReducer.swift
1
21800
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Combine import ComposableArchitecture import DIKit import FeatureAuthenticationDomain import Localization import ToolKit import WalletPayloadKit // MARK: - Type public enum WalletRecoveryIds { public struct RecoveryId: Hashable {} public struct ImportId: Hashable {} public struct AccountRecoveryAfterResetId: Hashable {} public struct WalletFetchAfterRecoveryId: Hashable {} } public enum SeedPhraseAction: Equatable { public enum URLContent { case contactSupport var url: URL? { switch self { case .contactSupport: return URL(string: Constants.SupportURL.ResetAccount.contactSupport) } } } public enum AlertAction: Equatable { case show(title: String, message: String) case dismiss } case alert(AlertAction) case didChangeSeedPhrase(String) case didChangeSeedPhraseScore(MnemonicValidationScore) case validateSeedPhrase case setResetPasswordScreenVisible(Bool) case setResetAccountBottomSheetVisible(Bool) case setLostFundsWarningScreenVisible(Bool) case setImportWalletScreenVisible(Bool) case setSecondPasswordNoticeVisible(Bool) case resetPassword(ResetPasswordAction) case resetAccountWarning(ResetAccountWarningAction) case lostFundsWarning(LostFundsWarningAction) case importWallet(ImportWalletAction) case secondPasswordNotice(SecondPasswordNotice.Action) case restoreWallet(WalletRecovery) case restored(Result<Either<EmptyValue, WalletFetchedContext>, WalletRecoveryError>) case imported(Result<EmptyValue, WalletRecoveryError>) case accountCreation(Result<WalletCreatedContext, WalletCreationServiceError>) case accountRecovered(AccountResetContext) case walletFetched(Result<Either<EmptyValue, WalletFetchedContext>, WalletFetcherServiceError>) case informWalletFetched(WalletFetchedContext) case triggerAuthenticate // needed for legacy wallet flow case open(urlContent: URLContent) case none } public enum AccountRecoveryContext: Equatable { case troubleLoggingIn case restoreWallet case none } public struct AccountResetContext: Equatable { let walletContext: WalletCreatedContext let offlineToken: NabuOfflineToken } // MARK: - Properties public struct SeedPhraseState: Equatable { var context: AccountRecoveryContext var emailAddress: String var nabuInfo: WalletInfo.Nabu? var seedPhrase: String var seedPhraseScore: MnemonicValidationScore var isResetPasswordScreenVisible: Bool var isResetAccountBottomSheetVisible: Bool var isLostFundsWarningScreenVisible: Bool var isImportWalletScreenVisible: Bool var isSecondPasswordNoticeVisible: Bool var resetPasswordState: ResetPasswordState? var resetAccountWarningState: ResetAccountWarningState? var lostFundsWarningState: LostFundsWarningState? var importWalletState: ImportWalletState? var secondPasswordNoticeState: SecondPasswordNotice.State? var failureAlert: AlertState<SeedPhraseAction>? var isLoading: Bool var accountResettable: Bool { guard let nabuInfo = nabuInfo else { return false } return nabuInfo.recoverable } init(context: AccountRecoveryContext, emailAddress: String = "", nabuInfo: WalletInfo.Nabu? = nil) { self.context = context self.emailAddress = emailAddress self.nabuInfo = nabuInfo seedPhrase = "" seedPhraseScore = .none isResetPasswordScreenVisible = false isResetAccountBottomSheetVisible = false isLostFundsWarningScreenVisible = false isImportWalletScreenVisible = false isSecondPasswordNoticeVisible = false failureAlert = nil isLoading = false } } struct SeedPhraseEnvironment { let mainQueue: AnySchedulerOf<DispatchQueue> let validator: SeedPhraseValidatorAPI let externalAppOpener: ExternalAppOpener let passwordValidator: PasswordValidatorAPI let analyticsRecorder: AnalyticsEventRecorderAPI let walletRecoveryService: WalletRecoveryService let walletCreationService: WalletCreationService let walletFetcherService: WalletFetcherService let accountRecoveryService: AccountRecoveryServiceAPI let errorRecorder: ErrorRecording let featureFlagsService: FeatureFlagsServiceAPI let recaptchaService: GoogleRecaptchaServiceAPI init( mainQueue: AnySchedulerOf<DispatchQueue>, validator: SeedPhraseValidatorAPI = resolve(), passwordValidator: PasswordValidatorAPI = resolve(), externalAppOpener: ExternalAppOpener, analyticsRecorder: AnalyticsEventRecorderAPI, walletRecoveryService: WalletRecoveryService, walletCreationService: WalletCreationService, walletFetcherService: WalletFetcherService, accountRecoveryService: AccountRecoveryServiceAPI, errorRecorder: ErrorRecording, recaptchaService: GoogleRecaptchaServiceAPI, featureFlagsService: FeatureFlagsServiceAPI = resolve() ) { self.mainQueue = mainQueue self.validator = validator self.passwordValidator = passwordValidator self.externalAppOpener = externalAppOpener self.analyticsRecorder = analyticsRecorder self.walletRecoveryService = walletRecoveryService self.walletCreationService = walletCreationService self.walletFetcherService = walletFetcherService self.accountRecoveryService = accountRecoveryService self.errorRecorder = errorRecorder self.recaptchaService = recaptchaService self.featureFlagsService = featureFlagsService } } let seedPhraseReducer = Reducer.combine( secondPasswordNoticeReducer .optional() .pullback( state: \SeedPhraseState.secondPasswordNoticeState, action: /SeedPhraseAction.secondPasswordNotice, environment: { SecondPasswordNotice.Environment( externalAppOpener: $0.externalAppOpener ) } ), importWalletReducer .optional() .pullback( state: \SeedPhraseState.importWalletState, action: /SeedPhraseAction.importWallet, environment: { ImportWalletEnvironment( mainQueue: $0.mainQueue, passwordValidator: $0.passwordValidator, externalAppOpener: $0.externalAppOpener, analyticsRecorder: $0.analyticsRecorder, walletRecoveryService: $0.walletRecoveryService, walletCreationService: $0.walletCreationService, walletFetcherService: $0.walletFetcherService, featureFlagsService: $0.featureFlagsService, recaptchaService: $0.recaptchaService ) } ), resetAccountWarningReducer .optional() .pullback( state: \SeedPhraseState.resetAccountWarningState, action: /SeedPhraseAction.resetAccountWarning, environment: { ResetAccountWarningEnvironment( analyticsRecorder: $0.analyticsRecorder ) } ), lostFundsWarningReducer .optional() .pullback( state: \SeedPhraseState.lostFundsWarningState, action: /SeedPhraseAction.lostFundsWarning, environment: { LostFundsWarningEnvironment( mainQueue: $0.mainQueue, analyticsRecorder: $0.analyticsRecorder, passwordValidator: $0.passwordValidator, externalAppOpener: $0.externalAppOpener, errorRecorder: $0.errorRecorder ) } ), resetPasswordReducer .optional() .pullback( state: \SeedPhraseState.resetPasswordState, action: /SeedPhraseAction.resetPassword, environment: { ResetPasswordEnvironment( mainQueue: $0.mainQueue, passwordValidator: $0.passwordValidator, externalAppOpener: $0.externalAppOpener, errorRecorder: $0.errorRecorder ) } ), Reducer< SeedPhraseState, SeedPhraseAction, SeedPhraseEnvironment > { state, action, environment in switch action { case .didChangeSeedPhrase(let seedPhrase): state.seedPhrase = seedPhrase return Effect(value: .validateSeedPhrase) case .didChangeSeedPhraseScore(let score): state.seedPhraseScore = score return .none case .validateSeedPhrase: return environment .validator .validate(phrase: state.seedPhrase) .receive(on: environment.mainQueue) .catchToEffect() .map { result -> SeedPhraseAction in guard case .success(let score) = result else { return .none } return .didChangeSeedPhraseScore(score) } case .setResetPasswordScreenVisible(let isVisible): state.isResetPasswordScreenVisible = isVisible if isVisible { state.resetPasswordState = .init() } return .none case .setResetAccountBottomSheetVisible(let isVisible): state.isResetAccountBottomSheetVisible = isVisible if isVisible { state.resetAccountWarningState = .init() } return .none case .setLostFundsWarningScreenVisible(let isVisible): state.isLostFundsWarningScreenVisible = isVisible if isVisible { state.lostFundsWarningState = .init() } return .none case .setImportWalletScreenVisible(let isVisible): state.isImportWalletScreenVisible = isVisible if isVisible { state.importWalletState = .init(mnemonic: state.seedPhrase) } return .none case .setSecondPasswordNoticeVisible(let isVisible): state.isSecondPasswordNoticeVisible = isVisible if isVisible { state.secondPasswordNoticeState = .init() } return .none case .resetPassword: // handled in reset password reducer return .none case .resetAccountWarning(.retryButtonTapped), .resetAccountWarning(.onDisappear): return Effect(value: .setResetAccountBottomSheetVisible(false)) case .resetAccountWarning(.continueResetButtonTapped): return .concatenate( Effect(value: .setResetAccountBottomSheetVisible(false)), Effect(value: .setLostFundsWarningScreenVisible(true)) ) case .lostFundsWarning(.goBackButtonTapped): return Effect(value: .setLostFundsWarningScreenVisible(false)) case .lostFundsWarning(.resetPassword(.reset(let password))): guard let nabuInfo = state.nabuInfo else { return .none } let accountName = CreateAccountStepOneLocalization.defaultAccountName return .concatenate( Effect(value: .triggerAuthenticate), environment.walletCreationService .createWallet( state.emailAddress, password, accountName, nil ) .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: CreateAccountStepTwoIds.CreationId(), cancelInFlight: true) .map(SeedPhraseAction.accountCreation) ) case .accountCreation(.failure(let error)): let title = LocalizationConstants.Errors.error let message = error.localizedDescription state.lostFundsWarningState?.resetPasswordState?.isLoading = false return .merge( Effect( value: .alert( .show( title: title, message: message ) ) ), .cancel(id: CreateAccountStepTwoIds.CreationId()) ) case .accountCreation(.success(let context)): guard let nabuInfo = state.nabuInfo else { return .none } return .merge( .cancel(id: CreateAccountStepTwoIds.CreationId()), environment.accountRecoveryService .recoverUser( guid: context.guid, sharedKey: context.sharedKey, userId: nabuInfo.userId, recoveryToken: nabuInfo.recoveryToken ) .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: WalletRecoveryIds.AccountRecoveryAfterResetId(), cancelInFlight: false) .map { result -> SeedPhraseAction in guard case .success(let offlineToken) = result else { environment.analyticsRecorder.record( event: AnalyticsEvents.New.AccountRecoveryFlow.accountRecoveryFailed ) // show recovery failures if the endpoint fails return .lostFundsWarning( .resetPassword( .setResetAccountFailureVisible(true) ) ) } environment.analyticsRecorder.record( event: AnalyticsEvents.New.AccountRecoveryFlow .accountPasswordReset(hasRecoveryPhrase: false) ) return .accountRecovered( AccountResetContext( walletContext: context, offlineToken: offlineToken ) ) } ) case .accountRecovered(let info): // NOTE: The effects of fetching a wallet still happen on the CoreCoordinator // Unfortunately Resetting an account and wallet fetching are related // In order to save the token wallet metadata we need // to have a fully loaded wallet so the following happens: // 1) Fetch the wallet // 2) Store the offlineToken to the wallet metadata // There's no error handling as any error will be overruled by the CoreCoordinator return .merge( .cancel(id: WalletRecoveryIds.AccountRecoveryAfterResetId()), environment.walletFetcherService .fetchWalletAfterAccountRecovery( info.walletContext.guid, info.walletContext.sharedKey, info.walletContext.password, info.offlineToken ) .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: WalletRecoveryIds.WalletFetchAfterRecoveryId()) .map(SeedPhraseAction.walletFetched) ) case .walletFetched(.success(.left(.noValue))): // this is for legacy JS flow, to be removed return .none case .walletFetched(.success(.right(let context))): return Effect(value: .informWalletFetched(context)) case .walletFetched(.failure(let error)): let title = LocalizationConstants.ErrorAlert.title let message = error.errorDescription ?? LocalizationConstants.ErrorAlert.message return Effect( value: .alert( .show(title: title, message: message) ) ) case .informWalletFetched: // handled in WelcomeReducer return .none case .lostFundsWarning: return .none case .importWallet(.goBackButtonTapped): return Effect(value: .setImportWalletScreenVisible(false)) case .importWallet(.createAccount(.triggerAuthenticate)): return Effect(value: .triggerAuthenticate) case .importWallet: return .none case .secondPasswordNotice: return .none case .restoreWallet(.metadataRecovery(let mnemonic)): state.isLoading = true return .concatenate( Effect(value: .triggerAuthenticate), environment.walletRecoveryService .recoverFromMetadata(mnemonic) .receive(on: environment.mainQueue) .mapError(WalletRecoveryError.restoreFailure) .catchToEffect() .cancellable(id: WalletRecoveryIds.RecoveryId(), cancelInFlight: true) .map(SeedPhraseAction.restored) ) case .restoreWallet: return .none case .restored(.success(.left(.noValue))): state.isLoading = false return .cancel(id: WalletRecoveryIds.RecoveryId()) case .restored(.success(.right(let context))): state.isLoading = false return .merge( .cancel(id: WalletRecoveryIds.RecoveryId()), Effect(value: .informWalletFetched(context)) ) case .restored(.failure(.restoreFailure(.recovery(.unableToRecoverFromMetadata)))): state.isLoading = false return .merge( .cancel(id: WalletRecoveryIds.RecoveryId()), Effect(value: .setImportWalletScreenVisible(true)) ) case .restored(.failure(.restoreFailure(let error))): state.isLoading = false let title = LocalizationConstants.Errors.error let message = error.errorDescription ?? LocalizationConstants.Errors.genericError return .merge( .cancel(id: WalletRecoveryIds.RecoveryId()), Effect(value: .alert(.show(title: title, message: message))) ) case .imported(.success): return .cancel(id: WalletRecoveryIds.ImportId()) case .imported(.failure(let error)): guard state.importWalletState != nil else { return .none } return Effect(value: .importWallet(.importWalletFailed(error))) case .open(let urlContent): guard let url = urlContent.url else { return .none } environment.externalAppOpener.open(url) return .none case .triggerAuthenticate: return .none case .alert(.show(let title, let message)): state.failureAlert = AlertState( title: TextState(verbatim: title), message: TextState(verbatim: message), dismissButton: .default( TextState(LocalizationConstants.okString), action: .send(.alert(.dismiss)) ) ) return .none case .alert(.dismiss): state.failureAlert = nil return .none case .none: return .none } } ) .analytics() // MARK: - Extension extension Reducer where Action == SeedPhraseAction, State == SeedPhraseState, Environment == SeedPhraseEnvironment { /// Helper reducer for analytics tracking fileprivate func analytics() -> Self { combined( with: Reducer< SeedPhraseState, SeedPhraseAction, SeedPhraseEnvironment > { _, action, environment in switch action { case .setResetPasswordScreenVisible(true): environment.analyticsRecorder.record( event: .recoveryPhraseEntered ) return .none case .setImportWalletScreenVisible(true): environment.analyticsRecorder.record( event: .recoveryPhraseEntered ) return .none case .setResetAccountBottomSheetVisible(true): environment.analyticsRecorder.record( event: .resetAccountClicked ) return .none case .setResetAccountBottomSheetVisible(false): environment.analyticsRecorder.record( event: .resetAccountCancelled ) return .none case .setLostFundsWarningScreenVisible(true): environment.analyticsRecorder.record( event: .resetAccountCancelled ) return .none default: return .none } } ) } }
lgpl-3.0
2f198e22b2c1bf5e9b55f940f9c8aee2
36.584483
108
0.59099
6.470466
false
false
false
false
randallli/material-components-ios
components/Tabs/examples/supplemental/TabBarIconExampleSupplemental.swift
1
10298
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length // swiftlint:disable line_length import UIKit import MaterialComponents.MaterialButtons import MaterialComponents.MaterialButtons_ButtonThemer extension TabBarIconSwiftExample { func setupAlignmentButton() -> MDCButton { let alignmentButton = MDCButton() let buttonScheme = MDCButtonScheme() buttonScheme.colorScheme = colorScheme buttonScheme.typographyScheme = typographyScheme MDCContainedButtonThemer.applyScheme(buttonScheme, to: alignmentButton) alignmentButton.setTitle("Change Alignment", for: .normal) alignmentButton.setTitleColor(.white, for: .normal) self.view.addSubview(alignmentButton) alignmentButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: alignmentButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: alignmentButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -40).isActive = true return alignmentButton } func setupAppBar() -> MDCAppBar { let appBar = MDCAppBar() self.addChildViewController(appBar.headerViewController) appBar.headerViewController.headerView.backgroundColor = UIColor.white appBar.headerViewController.headerView.minMaxHeightIncludesSafeArea = false appBar.headerViewController.headerView.minimumHeight = 56 + 72 appBar.headerViewController.headerView.tintColor = MDCPalette.blue.tint500 appBar.headerStackView.bottomBar = self.tabBar appBar.headerStackView.setNeedsLayout() return appBar } func setupExampleViews() { view.backgroundColor = UIColor.white appBar.addSubviewsToParent() let badgeIncrementItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:#selector(incrementDidTouch(sender: ))) self.navigationItem.rightBarButtonItem = badgeIncrementItem self.title = "Tabs With Icons" setupScrollingContent() } func setupScrollView() -> UIScrollView { let scrollView = UIScrollView(frame: CGRect()) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isPagingEnabled = false scrollView.isScrollEnabled = false self.view.addSubview(scrollView) scrollView.backgroundColor = UIColor.red let views = ["scrollView": scrollView, "header": self.appBar.headerStackView] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:[header][scrollView]|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)) return scrollView } func setupScrollingContent() { // The scrollView will have two UIViews (pages.) One has a label with text (infoLabel); we call // this infoPage. Another has 1+ star images; we call this self.starPage. Tapping on the 'INFO' // tab will show the infoPage and tapping on the 'STARS' tab will show the self.starPage. // Create the first view and its content. Then add to scrollView. let infoPage = UIView(frame: CGRect()) infoPage.translatesAutoresizingMaskIntoConstraints = false infoPage.backgroundColor = MDCPalette.lightBlue.tint300 scrollView.addSubview(infoPage) let infoLabel = UILabel(frame: CGRect()) infoLabel.translatesAutoresizingMaskIntoConstraints = false infoLabel.textColor = UIColor.white infoLabel.numberOfLines = 0 infoLabel.text = "Tabs enable content organization at a high level," + " such as switching between views" infoPage.addSubview(infoLabel) // Layout the views to be equal height and width to each other and self.view, // hug the edges of the scrollView and meet in the middle. NSLayoutConstraint(item: infoLabel, attribute: .centerX, relatedBy: .equal, toItem: infoPage, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: infoLabel, attribute: .centerY, relatedBy: .equal, toItem: infoPage, attribute: .centerY, multiplier: 1, constant: -50).isActive = true NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[infoLabel]-50-|", options: [], metrics: nil, views: ["infoLabel": infoLabel])) NSLayoutConstraint(item: infoPage, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: infoPage, attribute: .height, relatedBy: .equal, toItem: self.scrollView, attribute: .height, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: self.starPage, attribute: .width, relatedBy: .equal, toItem: infoPage, attribute: .width, multiplier: 1, constant: 0).isActive = true let views = ["infoPage": infoPage, "starPage": self.starPage] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[infoPage][starPage]|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[infoPage]|", options: [], metrics: nil, views: views)) addStar(centered: true) } func setupStarPage() -> UIView { let starPage = UIView(frame: CGRect()) starPage.translatesAutoresizingMaskIntoConstraints = false starPage.backgroundColor = MDCPalette.lightBlue.tint200 self.scrollView.addSubview(starPage) return starPage } func addStar(centered: Bool) { let starImage = UIImage(named:"TabBarDemo_ic_star", in:Bundle(for: TabBarIconSwiftExample.self), compatibleWith:nil) let starView = UIImageView(image: starImage) starView.translatesAutoresizingMaskIntoConstraints = false starPage.addSubview(starView) starView.sizeToFit() let x = centered ? 1.0 : (CGFloat(arc4random_uniform(199) + 1) / 100.0) // 0 < x <=2 let y = centered ? 1.0 : (CGFloat(arc4random_uniform(199) + 1) / 100.0) // 0 < y <=2 NSLayoutConstraint(item: starView, attribute: .centerX, relatedBy: .equal, toItem: starPage, attribute: .centerX, multiplier: x, constant: 0).isActive = true NSLayoutConstraint(item: starView, attribute: .centerY, relatedBy: .equal, toItem: self.starPage, attribute: .centerY, multiplier: y, constant: 0).isActive = true } } extension TabBarIconSwiftExample { override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { (_) in if let selectedItem = self.tabBar.selectedItem { self.tabBar(self.tabBar, didSelect: selectedItem) } }, completion: nil) super.viewWillTransition(to: size, with: coordinator) } } // MARK: - Catalog by convention extension TabBarIconSwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Tab Bar", "Icons and Text (Swift)"] } @objc class func catalogIsPrimaryDemo() -> Bool { return false } func catalogShouldHideNavigation() -> Bool { return true } }
apache-2.0
3ebfbc0f66019f752857d6dc968c67e9
38.914729
110
0.570014
5.973318
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/Device/Device+Capability.swift
1
2036
// // Xcore // Copyright © 2014 Xcore // MIT license, see LICENSE file for details // import SwiftUI extension Device { /// A structure representing the device’s capabilities. public struct Capability: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } /// - SeeAlso: `Device.current.biometrics.isAvailable` and `Device.current.biometrics.kind`. public static let touchID = Capability(rawValue: 1 << 0) /// - SeeAlso: `Device.current.biometrics.isAvailable` and `Device.current.biometrics.kind`. public static let faceID = Capability(rawValue: 1 << 1) public static let notch = Capability(rawValue: 1 << 2) public static let homeIndicator = Capability(rawValue: 1 << 3) public static let iPhoneXSeries: Capability = [.notch, .faceID, .homeIndicator] } } extension Device { public var capability: Capability { var capability: Capability = [] if hasTopNotch { capability.update(with: .notch) } if hasHomeIndicator { capability.update(with: .homeIndicator) } switch biometrics.kind { case .touchID: capability.update(with: .touchID) case .faceID: capability.update(with: .faceID) case .none: break } return capability } } extension Device { private var hasTopNotch: Bool { // Notch: 44 on iPhone X, XS, XS Max, XR. // No Notch: 24 on iPad Pro 12.9" 3rd generation, 20 on iPhone 8 AppConstants.statusBarHeight > 24 } private var hasHomeIndicator: Bool { let safeAreaInsets = UIApplication .sharedOrNil? .firstSceneKeyWindow? .safeAreaInsets // Home indicator: 34 on iPhone X, XS, XS Max, XR. // Home indicator: 20 on iPad Pro 12.9" 3rd generation. return safeAreaInsets?.bottom ?? 0 > 0 } }
mit
9753c3e40b6f38e5e5565eebf0bd884e
28.042857
100
0.599606
4.599548
false
false
false
false
Daltron/NotificationBanner
Example/NotificationBanner/ExampleView.swift
1
7180
// // NotificationBannerView.swift // NotificationBanner // // Created by Dalton Hinterscher on 3/22/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit protocol ExampleViewDelegate : AnyObject { func numberOfCells(for section: Int) -> Int func notificationBannerTitle(for section: Int) -> String func blockColor(at indexPath: IndexPath) -> UIColor func notificationTitles(at indexPath: IndexPath) -> (String, String?) func notificationImage(at indexPath: IndexPath) -> UIImage? func basicNotificationCellSelected(at index: Int) func basicNotificationCellWithSideViewsSelected(at index: Int) func basicCustomNotificationCellSelected(at index: Int) func basicGrowingNotificationCellSelected(at index: Int) func basicFloatingNotificationCellSelected(at index: Int) func basicSimulanteousFloatingNotificationCellSelected(at index: Int) func basicStatusBarNotificationCellSelected(at index: Int) } class ExampleView: UIView { weak var delegate: ExampleViewDelegate? var queuePositionSegmentedControl: UISegmentedControl! var bannerPositionSegmentedControl: UISegmentedControl! init(delegate: ExampleViewDelegate) { super.init(frame: .zero) self.delegate = delegate let queuePositionContentView = UIView() addSubview(queuePositionContentView) let queuePositionSegmentLabel = UILabel() queuePositionSegmentLabel.font = UIFont.systemFont(ofSize: 12.5) queuePositionSegmentLabel.text = "Queue Position:" queuePositionContentView.addSubview(queuePositionSegmentLabel) queuePositionSegmentedControl = UISegmentedControl(items: ["Front", "Back"]) queuePositionSegmentedControl.selectedSegmentIndex = 1 queuePositionContentView.addSubview(queuePositionSegmentedControl) let bannerPositionContentView = UIView() addSubview(bannerPositionContentView) let bannerPositionSegmentLabel = UILabel() bannerPositionSegmentLabel.font = UIFont.systemFont(ofSize: 12.5) bannerPositionSegmentLabel.text = "Banner Position:" bannerPositionContentView.addSubview(bannerPositionSegmentLabel) bannerPositionSegmentedControl = UISegmentedControl(items: ["Top", "Bottom"]) bannerPositionSegmentedControl.selectedSegmentIndex = 0 bannerPositionContentView.addSubview(bannerPositionSegmentedControl) let tableView = UITableView(frame: .zero, style: .grouped) tableView.rowHeight = 75.0 tableView.dataSource = self tableView.delegate = self addSubview(tableView) queuePositionContentView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(5) make.left.equalToSuperview() make.width.equalToSuperview().multipliedBy(0.5) make.bottom.equalTo(queuePositionSegmentedControl) } queuePositionSegmentLabel.snp.makeConstraints { (make) in make.top.equalToSuperview() make.centerX.equalToSuperview() } queuePositionSegmentedControl.snp.makeConstraints { (make) in make.top.equalTo(queuePositionSegmentLabel.snp.bottom).offset(3.5) make.width.equalTo(150) make.height.equalTo(25) make.centerX.equalToSuperview() } bannerPositionContentView.snp.makeConstraints { (make) in make.top.equalTo(queuePositionContentView) make.left.equalTo(self.snp.centerX) make.width.equalTo(queuePositionContentView) make.height.equalTo(queuePositionContentView) } bannerPositionSegmentLabel.snp.makeConstraints { (make) in make.top.equalToSuperview() make.centerX.equalToSuperview() } bannerPositionSegmentedControl.snp.makeConstraints { (make) in make.top.equalTo(queuePositionSegmentedControl) make.width.equalTo(queuePositionSegmentedControl) make.height.equalTo(queuePositionSegmentedControl) make.centerX.equalToSuperview() } tableView.snp.makeConstraints { (make) in make.top.equalTo(queuePositionContentView.snp.bottom).offset(10) make.left.equalToSuperview() make.right.equalToSuperview() make.bottom.equalToSuperview() } backgroundColor = tableView.backgroundColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ExampleView : UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 7 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return delegate!.numberOfCells(for: section) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return delegate!.notificationBannerTitle(for: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let reuseIdentifier = "BasicNotificationBannerCell" var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) as? BasicNotificationBannerCell if cell == nil { cell = BasicNotificationBannerCell(reuseIdentifier: reuseIdentifier) } return cell! } } extension ExampleView : UITableViewDelegate { func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let (title, subtitle) = delegate!.notificationTitles(at: indexPath) let blockColor = delegate!.blockColor(at: indexPath) let image = delegate!.notificationImage(at: indexPath) if let bannerCell = cell as? BasicNotificationBannerCell { bannerCell.update(blockColor: blockColor, image: image, title: title, subtitle: subtitle) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) if indexPath.section == 0 { delegate?.basicNotificationCellSelected(at: indexPath.row) } else if indexPath.section == 1 { delegate?.basicNotificationCellWithSideViewsSelected(at: indexPath.row) } else if indexPath.section == 2 { delegate?.basicCustomNotificationCellSelected(at: indexPath.row) } else if indexPath.section == 3 { delegate?.basicGrowingNotificationCellSelected(at: indexPath.row) } else if indexPath.section == 4 { delegate?.basicFloatingNotificationCellSelected(at: indexPath.row) } else if indexPath.section == 5 { delegate?.basicSimulanteousFloatingNotificationCellSelected(at: indexPath.row) } else if indexPath.section == 6 { delegate?.basicStatusBarNotificationCellSelected(at: indexPath.row) } } }
mit
5319fbb9916efa5ee82541ac508e253d
39.789773
113
0.6838
5.573758
false
false
false
false
RoverPlatform/rover-ios
Sources/Data/Extensions/Data.OSLog.swift
1
592
// // OSLog.swift // RoverData // // Created by Sean Rucker on 2018-09-27. // Copyright © 2018 Rover Labs Inc. All rights reserved. // import os.log extension OSLog { public static let context = OSLog(subsystem: "io.rover", category: "Context") public static let events = OSLog(subsystem: "io.rover", category: "Events") public static let networking = OSLog(subsystem: "io.rover", category: "Networking") public static let persistence = OSLog(subsystem: "io.rover", category: "Persistence") public static let sync = OSLog(subsystem: "io.rover", category: "Sync") }
apache-2.0
c09bb438af7c6dff38055e15907480b8
33.764706
89
0.695431
3.740506
false
false
false
false
skylib/SnapPageableArray
Example/LocalDataFillerHelpers.swift
1
5301
import Foundation import SnapPageableArray import CoreLocation // filler supporting structs struct TypeA { let A: CLLocationCoordinate2D? let B: CLLocationAccuracy? let C: Double init() { A = genOptCoordinate() B = genDouble() C = genDouble() } } struct TypeB: DTOProtocol { let id: UInt64? var B: URL? var C: UIImage? init() { id = genId() B = genOptImageUrl() as URL? C = nil } } struct TypeC { let A: UInt64 let B: String let C: String var D: Bool let E: Bool? let F: Int? let G: URL? var H: UIImage? = nil fileprivate(set) var I: TypeI? = nil init() { A = genId() B = genString(Int.random(lower: 3, upper: 19)) C = genString(Int.random(lower: 3, upper: 19)) D = genBool() E = genOptBool() F = genOptInt() G = genOptImageUrl() as URL? H = nil I = TypeI() } } struct TypeD { let A: Date let B: Date let C: Date let D: Date init() { A = Date(timeIntervalSinceNow: genDouble()) B = Date(timeIntervalSinceNow: genDouble()) C = Date(timeIntervalSinceNow: genDouble()) D = Date(timeIntervalSinceNow: genDouble()) } } struct TypeE { var A: UInt64 let B: UInt64 let C: UInt64? var D: TypeH init() { A = UInt64.random() B = UInt64.random() C = UInt64.random() D = TypeH() } } struct TypeF { var A: [TypeJ] let B: Bool init() { A = [TypeJ(), TypeJ()] B = genBool() } } struct TypeG { let A: TypeE let B: EnumA let C: UInt let D: UInt let E: UInt64 let F: String? let G: Bool? let H: Bool? init() { A = TypeE() B = EnumA(rawValue: Int.random(lower: 0, upper: 5)) ?? EnumA.a C = UInt.random() D = UInt.random() E = UInt64.random() F = genString(Int.random(lower: 3, upper: 19)) G = genOptBool() H = genOptBool() } } enum EnumA: Int { case a = 0 case b = 1 case c = 2 case d = 3 case e = 4 case f = 5 } struct TypeH { let A: String let B: String let C: String init() { A = genString(Int.random(lower: 3, upper: 19)) B = genString(Int.random(lower: 3, upper: 19)) C = genString(Int.random(lower: 3, upper: 19)) } } struct TypeI: DTOProtocol { let id: UInt64? var B: TypeK var C: String var D: String var E: String var F: TypeB? var G: Bool let H: Date let I: EnumB let J: String var K: Bool let L: Bool var M: Bool let N: Bool var O: Bool let P: Bool let Q: Bool let R: UInt let S: UInt let T: UInt let U: UInt let V: UInt64 let W: String var X: [TypeL] let Y: [String] let Z: [String] init() { id = genId() B = TypeK() C = genString(Int.random(lower: 3, upper: 19)) D = genString(Int.random(lower: 3, upper: 19)) E = genString(Int.random(lower: 3, upper: 19)) F = TypeB() G = genBool() H = Date(timeIntervalSinceNow: genDouble()) I = EnumB.random() J = genString(Int.random(lower: 3, upper: 19)) K = genBool() L = genBool() M = genBool() N = genBool() O = genBool() P = genBool() Q = genBool() R = UInt.random() S = UInt.random() T = UInt.random() U = UInt.random() V = UInt64.random() W = genString(Int.random(lower: 3, upper: 19)) X = [TypeL(), TypeL()] Y = [genString(Int.random(lower: 3, upper: 6)), genString(Int.random(lower: 3, upper: 6)), genString(Int.random(lower: 3, upper: 6))] Z = [genString(Int.random(lower: 3, upper: 6)), genString(Int.random(lower: 3, upper: 6)), genString(Int.random(lower: 3, upper: 6))] } } enum EnumB: String { case A case B = "B-value" case C = "C-value" static func random() -> EnumB { switch Int.random(lower: 0, upper: 2) { case 0: return EnumB.A case 1: return EnumB.B default: return EnumB.C } } } struct TypeJ { let A: String var B: EnumC init() { A = genString(Int.random(lower: 3, upper: 19)) B = EnumC(rawValue: Int.random(lower: 0, upper: 2)) ?? EnumC.a } } public enum EnumC: Int { case a = 0 case b case c } struct TypeK { var A: Bool var B: String? var C: Bool? init() { A = genBool() B = genString(Int.random(lower: 3, upper: 19)) C = genOptBool() } } struct TypeL { let A: EnumD let B: String let C: String init() { A = EnumD.random() B = genString(Int.random(lower: 3, upper: 19)) C = genString(Int.random(lower: 3, upper: 19)) } } enum EnumD: String { case A = "A-value" case B = "B-value" case C static func random() -> EnumD { switch Int.random(lower: 0, upper: 2) { case 0: return EnumD.A case 1: return EnumD.B default: return EnumD.C } } }
bsd-3-clause
b4657280fc1ce85c4412d261604f3cb0
17.864769
141
0.508961
3.402439
false
false
false
false
iSapozhnik/home-surveillance-osx
HomeSurveillance/SignalProvider/DefaultCameraProvider.swift
1
1417
// // DefaultCameraProvider.swift // HomeSurveillance // // Created by Sapozhnik Ivan on 22/03/17. // Copyright © 2017 Sapozhnik Ivan. All rights reserved. // import Cocoa import AVFoundation class DefaultCameraProvider: SignalProviderItem { var captureDevice: AVCaptureDevice! static func provider(withCaptureDevice device: AVCaptureDevice) -> SignalProviderItem { let provider = DefaultCameraProvider() provider.captureDevice = device return provider } func startPreview(forView view: PreviewView) -> Bool { let session = AVCaptureSession() let input = (try! AVCaptureDeviceInput(device: captureDevice)) let output = AVCaptureVideoDataOutput() session.addOutput(output) session.addInput(input) let layerPreview = AVCaptureVideoPreviewLayer(session: session) layerPreview?.videoGravity = AVLayerVideoGravityResizeAspectFill layerPreview?.frame = view.bounds view.layer = layerPreview view.wantsLayer = true session.startRunning() return true } func name() -> String { let manufacturer = captureDevice.manufacturer != nil ? captureDevice.manufacturer! : "" return manufacturer.isEmpty ? captureDevice.localizedName : captureDevice.localizedName + " (\(manufacturer))" } }
mit
94455cbd87ff08b7bbf5a01b6cc89588
29.12766
118
0.663136
5.552941
false
false
false
false
vzool/ios-nanodegree-earth-diary
Earth Diary/NSDate.swift
1
1476
// // NSDate.swift // Earth Diary // // Created by Abdelaziz Elrashed on 8/22/15. // Copyright (c) 2015 Abdelaziz Elrashed. All rights reserved. // import Foundation extension NSDate { func isGreaterThanDate(dateToCompare : NSDate) -> Bool { //Declare Variables var isGreater = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending { isGreater = true } //Return Result return isGreater } func isLessThanDate(dateToCompare : NSDate) -> Bool { //Declare Variables var isLess = false //Compare Values if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending { isLess = true } //Return Result return isLess } func addDays(daysToAdd : Int) -> NSDate { var secondsInDays : NSTimeInterval = Double(daysToAdd) * 60 * 60 * 24 var dateWithDaysAdded : NSDate = self.dateByAddingTimeInterval(secondsInDays) //Return Result return dateWithDaysAdded } func addHours(hoursToAdd : Int) -> NSDate { var secondsInHours : NSTimeInterval = Double(hoursToAdd) * 60 * 60 var dateWithHoursAdded : NSDate = self.dateByAddingTimeInterval(secondsInHours) //Return Result return dateWithHoursAdded } }
mit
8a9a3481b948e881e373d543d677e040
22.822581
87
0.590108
5.142857
false
false
false
false
LQJJ/demo
125-iOSTips-master/SwiftTipsDemo/DCTool/DCTool/Regex.swift
1
5517
// // Regex.swift // SwiftTipsDemo // // Created by Dariel on 2019/1/28. // Copyright © 2019 Dariel. All rights reserved. // import Foundation public struct Regex { private let regularExpression: NSRegularExpression public init(_ pattern: String, options: Options = []) throws { regularExpression = try NSRegularExpression( pattern: pattern, options: options.toNSRegularExpressionOptions ) } // 正则匹配验证(true表示匹配成功) public func matches(_ string: String) -> Bool { return firstMatch(in: string) != nil } // 获取第一个匹配结果 public func firstMatch(in string: String) -> Match? { let firstMatch = regularExpression .firstMatch(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) .map { Match(result: $0, in: string) } return firstMatch } // 获取所有的匹配结果 public func matches(in string: String) -> [Match] { let matches = regularExpression .matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count)) .map { Match(result: $0, in: string) } return matches } // 正则替换 public func replacingMatches(in input: String, with template: String, count: Int? = nil) -> String { var output = input let matches = self.matches(in: input) let rangedMatches = Array(matches[0..<min(matches.count, count ?? .max)]) for match in rangedMatches.reversed() { let replacement = match.string(applyingTemplate: template) output.replaceSubrange(match.range, with: replacement) } return output } } // 正则匹配可选项 extension Regex { /// Options 定义了正则表达式匹配时的行为 public struct Options: OptionSet { // 忽略字母 public static let ignoreCase = Options(rawValue: 1) // 忽略元字符 public static let ignoreMetacharacters = Options(rawValue: 1 << 1) // 默认情况下,“^”匹配字符串的开始和结束的“$”匹配字符串,无视任何换行。 // 使用这个配置,“^”将匹配的每一行的开始,和“$”将匹配的每一行的结束。 public static let anchorsMatchLines = Options(rawValue: 1 << 2) /// 默认情况下,"."匹配除换行符(\n)之外的所有字符。使用这个配置,选项将允许“.”匹配换行符 public static let dotMatchesLineSeparators = Options(rawValue: 1 << 3) // OptionSet的 raw value public let rawValue: Int // 将Regex.Options 转换成对应的 NSRegularExpression.Options var toNSRegularExpressionOptions: NSRegularExpression.Options { var options = NSRegularExpression.Options() if contains(.ignoreCase) { options.insert(.caseInsensitive) } if contains(.ignoreMetacharacters) { options.insert(.ignoreMetacharacters) } if contains(.anchorsMatchLines) { options.insert(.anchorsMatchLines) } if contains(.dotMatchesLineSeparators) { options.insert(.dotMatchesLineSeparators) } return options } // OptionSet 初始化 public init(rawValue: Int) { self.rawValue = rawValue } } } // 正则匹配结果 extension Regex { // Match 封装有单个匹配结果 public class Match: CustomStringConvertible { // 匹配的字符串 public lazy var string: String = { return String(describing: self.baseString[self.range]) }() // 匹配的字符范围 public lazy var range: Range<String.Index> = { return Range(self.result.range, in: self.baseString)! }() // 正则表达式中每个捕获组匹配的字符串 public lazy var captures: [String?] = { let captureRanges = stride(from: 0, to: result.numberOfRanges, by: 1) .map(result.range) .dropFirst() .map { [unowned self] in Range($0, in: self.baseString) } return captureRanges.map { [unowned self] captureRange in if let captureRange = captureRange { return String(describing: self.baseString[captureRange]) } return nil } }() private let result: NSTextCheckingResult private let baseString: String // 初始化 internal init(result: NSTextCheckingResult, in string: String) { precondition( result.regularExpression != nil, "NSTextCheckingResult必需使用正则表达式" ) self.result = result self.baseString = string } // 返回一个新字符串,根据“模板”替换匹配的字符串。 public func string(applyingTemplate template: String) -> String { let replacement = result.regularExpression!.replacementString( for: result, in: baseString, offset: 0, template: template ) return replacement } // 藐视信息 public var description: String { return "Match<\"\(string)\">" } } }
apache-2.0
c2f9137a8a1d078cde10b84a3fa71421
34.856115
82
0.575441
4.679812
false
false
false
false
EMart86/WhitelabelApp
Whitelabel/ViewModel/MasterViewModel.swift
1
5225
// // MasterViewModel.swift // Whitelabel // // Created by Martin Eberl on 27.02.17. // Copyright © 2017 Martin Eberl. All rights reserved. // import Foundation import AlamofireObjectMapper import CoreLocation import ObjectMapper class MasterViewModel: MasterViewModelProtocol { internal func load() {} private let loader: ContentLoader? fileprivate let locationProvider: LocationProvider? let title = "Master" private(set) var content: [Time]? private(set) var sections: [Section]? private(set) var isLoading: Bool = false private var timer: Timer? private let timeStore: TimeStore weak var delegate: MasterViewModelDelegate? init(loader: ContentLoader? = nil, locationProvider: LocationProvider? = nil, timeStore: TimeStore) { self.loader = loader self.locationProvider = locationProvider self.timeStore = timeStore content = timeStore.models()?.value timeStore.models()?.onValueChanged {[weak self] (models: [Time]) in self?.content = models self?.delegate?.signalUpdate() } setupContent() if LocationProvider.authorizationStatus == .authorizedWhenInUse { locationProvider?.delegate = self } } init(content: [Any], timeStore: TimeStore) { self.content = nil self.loader = nil self.locationProvider = nil self.timeStore = timeStore } // func load() { // guard let loader = loader else { return } // // locationProvider?.startLocationUpdate() // // isLoading = true // delegate?.signalUpdate() // // loader.load(contentResponse: {[weak self] response in // self?.isLoading = false // switch response { // case .success(let content): // self?.content = content // self?.setupContent() // break // case .fail(let error): // self?.content = nil // self?.setupContent() // break // } // self?.delegate?.signalUpdate() // }) // } var numberOfItems: Int? { guard let sections = sections else { return nil } return sections.count } func nuberOfCellItems(at index: Int) -> Int { guard let section = section(at: index) else { return 0 } return section.content?.count ?? 0 } func sectionViewModel(at index: Int) -> OverviewHeaderView.ViewModel? { guard let section = section(at: index), let title = section.title else { return nil } return OverviewHeaderView.ViewModel(title: title, buttonTitle: section.action) } func numberOfCells(at index: Int) -> Int? { guard let section = section(at: index) else { return nil } return section.content?.count } func cellViewModel(at indexPath: IndexPath) -> ViewCell.ViewModel? { guard let section = section(at: indexPath.section), let contents = section.content, contents.indices.contains(indexPath.row) else { return nil } let content = contents[indexPath.row] return ViewCell.ViewModel( imageUrl: nil, title: "", description: "", distance: nil) } func did(change searchText: String) { //TODO: filter text by search text delegate?.signalUpdate() } func didCloseSearch() { setupContent() delegate?.signalUpdate() } func add() { guard let time: Time = timeStore.new() else { return } time.value = NSDate() timeStore.add(model: time) } //MARK: - Private Methods private func section(at index: Int) -> Section? { guard let sections = sections, sections.indices.contains(index) else { return nil } return sections[index] } private func setupContent() { sections = [ Section(title: "Section 1", action: "Show more", content: timeStore.models()?.value) ] } private func stopLocationUpdates() { locationProvider?.endLocationUpdate() } fileprivate func stopLocationUpdates(after seconds: TimeInterval) { guard timer == nil else { return } timer = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false, block: {[weak self] _ in self?.timer = nil self?.stopLocationUpdates() }) } } extension MasterViewModel: OverviewHeaderViewDelegate { func didPressButton(overview: OverviewHeaderView) { } } extension MasterViewModel: LocationProviderDelegate { func didUpdate(authorizationStatus: CLAuthorizationStatus) {} func didUpdate(location: CLLocation) { delegate?.signalUpdate() stopLocationUpdates(after: 10) } }
apache-2.0
82807f30552ea05a78cb5800c8cfb330
26.494737
105
0.56585
5.023077
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/ALCameraViewController/ALCameraViewController/Utilities/Utilities.swift
1
4103
// // ALUtilities.swift // ALCameraViewController // // Created by Alex Littlejohn on 2015/06/25. // Copyright (c) 2015 zero. All rights reserved. // import UIKit import AVFoundation internal func radians(_ degrees: Double) -> Double { return degrees / 180 * Double.pi } internal func localizedString(_ key: String) -> String { var bundle: Bundle { if Bundle.main.path(forResource: CameraGlobals.shared.stringsTable, ofType: "strings") != nil { return Bundle.main } return CameraGlobals.shared.bundle } return NSLocalizedString(key, tableName: CameraGlobals.shared.stringsTable, bundle: bundle, comment: key) } internal func currentRotation(_ oldOrientation: UIInterfaceOrientation, newOrientation: UIInterfaceOrientation) -> Double { switch oldOrientation { case .portrait: switch newOrientation { case .landscapeLeft: return 90 case .landscapeRight: return -90 case .portraitUpsideDown: return 180 default: return 0 } case .landscapeLeft: switch newOrientation { case .portrait: return -90 case .landscapeRight: return 180 case .portraitUpsideDown: return 90 default: return 0 } case .landscapeRight: switch newOrientation { case .portrait: return 90 case .landscapeLeft: return 180 case .portraitUpsideDown: return -90 default: return 0 } default: return 0 } } internal func largestPhotoSize() -> CGSize { let scale = UIScreen.main.scale let screenSize = UIScreen.main.bounds.size let size = CGSize(width: screenSize.width * scale, height: screenSize.height * scale) return size } internal func errorWithKey(_ key: String, domain: String) -> NSError { let errorString = localizedString(key) let errorInfo = [NSLocalizedDescriptionKey: errorString] let error = NSError(domain: domain, code: 0, userInfo: errorInfo) return error } internal func normalizedRect(_ rect: CGRect, orientation: UIImageOrientation) -> CGRect { let normalizedX = rect.origin.x let normalizedY = rect.origin.y let normalizedWidth = rect.width let normalizedHeight = rect.height var normalizedRect: CGRect switch orientation { case .up, .upMirrored: normalizedRect = CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight) case .down, .downMirrored: normalizedRect = CGRect(x: 1-normalizedX-normalizedWidth, y: 1-normalizedY-normalizedHeight, width: normalizedWidth, height: normalizedHeight) case .left, .leftMirrored: normalizedRect = CGRect(x: 1-normalizedY-normalizedHeight, y: normalizedX, width: normalizedHeight, height: normalizedWidth) case .right, .rightMirrored: normalizedRect = CGRect(x: normalizedY, y: 1-normalizedX-normalizedWidth, width: normalizedHeight, height: normalizedWidth) } return normalizedRect } internal func flashImage(_ mode: AVCaptureFlashMode) -> String { let image: String switch mode { case .auto: image = "flashAutoIcon" case .on: image = "flashOnIcon" case .off: image = "flashOffIcon" } return image } struct ScreenSize { static let SCREEN_WIDTH = UIScreen.main.bounds.size.width static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT) } struct DeviceConfig { static let SCREEN_MULTIPLIER : CGFloat = { if UIDevice.current.userInterfaceIdiom == .phone { switch ScreenSize.SCREEN_MAX_LENGTH { case 568.0: return 1.5 case 667.0: return 2.0 case 736.0: return 4.0 default: return 1.0 } } else { return 1.0 } }() }
mit
111e553972af548aa4ca256d821855be
31.563492
150
0.635389
4.782051
false
false
false
false
stripe/stripe-ios
StripeCardScan/StripeCardScan/Source/CardVerify/ZoomedInCGImage.swift
1
5636
// // ZoomedInCGImage.swift // CardScan // // Created by Jaime Park on 6/19/20. // import UIKit class ZoomedInCGImage { private let image: CGImage private let imageWidth: CGFloat private let imageHeight: CGFloat private let imageMidHeight: CGFloat private let imageMidWidth: CGFloat private let imageCenterMinX: CGFloat private let imageCenterMaxX: CGFloat private let imageCenterMinY: CGFloat private let imageCenterMaxY: CGFloat private let finalCropWidth: CGFloat = 448.0 private let finalCropHeight: CGFloat = 448.0 private let cropQuarterWidth: CGFloat = 112.0 // finalCropWidth / 4 private let cropQuarterHeight: CGFloat = 112.0 // finalCropHeight / 4 init( image: CGImage ) { self.image = image self.imageWidth = CGFloat(image.width) self.imageHeight = CGFloat(image.height) self.imageMidHeight = imageHeight / 2.0 self.imageMidWidth = imageWidth / 2.0 self.imageCenterMinX = imageMidWidth - cropQuarterWidth self.imageCenterMaxX = imageMidWidth + cropQuarterWidth self.imageCenterMinY = imageMidHeight - cropQuarterHeight self.imageCenterMaxY = imageMidHeight + cropQuarterHeight } // Create a zoomed-in image by resizing image pieces in a 3x3 grid, row by row with createResizeLayer func zoomedInImage() -> UIImage? { guard let topLayer = createResizeLayer( yMin: 0.0, imageHeight: imageCenterMinY, cropHeight: cropQuarterHeight ) else { return nil } guard let midLayer = createResizeLayer( yMin: imageCenterMinY, imageHeight: cropQuarterHeight * 2, cropHeight: cropQuarterHeight * 2 ) else { return nil } guard let bottomLayer = createResizeLayer( yMin: imageCenterMaxY, imageHeight: imageCenterMinY, cropHeight: cropQuarterHeight ) else { return nil } let zoomedImageSize = CGSize(width: finalCropWidth, height: finalCropHeight) UIGraphicsBeginImageContextWithOptions(zoomedImageSize, true, 1.0) topLayer.draw(in: CGRect(x: 0.0, y: 0.0, width: finalCropWidth, height: cropQuarterHeight)) midLayer.draw( in: CGRect( x: 0.0, y: cropQuarterHeight, width: finalCropWidth, height: cropQuarterHeight * 2 ) ) bottomLayer.draw( in: CGRect( x: 0.0, y: cropQuarterHeight * 3, width: finalCropWidth, height: cropQuarterHeight ) ) let zoomedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return zoomedImage } // Resize layer starting at image height coordinate (yMin) with the height within the image (imageHeight) resizing to the input cropping height (cropHeight) private func createResizeLayer( yMin: CGFloat, imageHeight: CGFloat, cropHeight: CGFloat ) -> UIImage? { let leftCropRect = CGRect(x: 0.0, y: yMin, width: imageCenterMinX, height: imageHeight) let midCropRect = CGRect( x: imageCenterMinX, y: yMin, width: cropQuarterWidth * 2, height: imageHeight ) let rightCropRect = CGRect( x: imageCenterMaxX, y: yMin, width: imageCenterMinX, height: imageHeight ) guard let leftCropImage = self.image.cropping(to: leftCropRect), let leftResizedImage = resize( image: leftCropImage, targetSize: CGSize(width: cropQuarterWidth, height: cropHeight) ) else { return nil } guard let midCropImage = self.image.cropping(to: midCropRect), let midResizedImage = resize( image: midCropImage, targetSize: CGSize(width: cropQuarterWidth * 2, height: cropHeight) ) else { return nil } guard let rightCropImage = self.image.cropping(to: rightCropRect), let rightResizedImage = resize( image: rightCropImage, targetSize: CGSize(width: cropQuarterWidth, height: cropHeight) ) else { return nil } let layerSize = CGSize(width: finalCropWidth, height: cropHeight) UIGraphicsBeginImageContextWithOptions(layerSize, false, 1.0) leftResizedImage.draw( in: CGRect(x: 0.0, y: 0.0, width: cropQuarterWidth, height: cropHeight) ) midResizedImage.draw( in: CGRect(x: cropQuarterWidth, y: 0.0, width: cropQuarterWidth * 2, height: cropHeight) ) rightResizedImage.draw( in: CGRect(x: cropQuarterWidth * 3, y: 0.0, width: cropQuarterWidth, height: cropHeight) ) let layerImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return layerImage } private func resize(image: CGImage, targetSize: CGSize) -> UIImage? { let image = UIImage(cgImage: image) let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height) UIGraphicsBeginImageContextWithOptions(targetSize, true, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
mit
200a07b54caa13343f28e8fa36327e86
34.006211
160
0.611781
5.2282
false
false
false
false
mbigatti/StatusApp
StatusApp/Buttons.swift
1
2848
// // Buttons.swift // BMXFlatButton // https://github.com/mbigatti/BMXFlatButton // // Copyright (c) 2014 Massimiliano Bigatti. All rights reserved. // import UIKit /** Abstract base class for CircularButton and FlatButton. */ @IBDesignable public class AbstractButton: UIButton { /// button normal background color, default to clear @IBInspectable public var normalColor : UIColor = UIColor.clearColor() { didSet { updateButtonColor() } } /// button highlighted background color. If not specified use the normal background color darkened of 0.2% @IBInspectable public var highlightedColor : UIColor? { didSet { updateButtonColor() } } /// button border width, defaults to 0 @IBInspectable public var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } /// button border color, defaults to clear @IBInspectable public var borderColor: UIColor = UIColor.clearColor() { didSet { layer.borderColor = borderColor.CGColor } } public override var highlighted : Bool { didSet { updateButtonColor() } } public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** Update the button background color based on the highlighted state */ func updateButtonColor() { if highlighted { if (highlightedColor != nil) { self.backgroundColor = highlightedColor! } else { self.backgroundColor = normalColor.darkerColor(0.2) } } else { self.backgroundColor = normalColor } } } /** Simple flat button, with adjustable corner radius */ @IBDesignable public class FlatButton: AbstractButton { public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// button corner radius, defaults to 2px @IBInspectable public var cornerRadius : CGFloat = 2 { didSet { self.layer.cornerRadius = cornerRadius } } } /** Simple circular button. For correct appearance it is required to have a square size. */ @IBDesignable public class CircularButton: AbstractButton { public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func layoutSubviews() { super.layoutSubviews() let wide = max(frame.size.width, frame.size.height) layer.cornerRadius = wide / 2 } }
mit
00b681cbe8dfdcbbccacbfe092a85a53
23.765217
110
0.616924
4.860068
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/RxSwift/RxSwift/RxSwift/Subjects/Subject.swift
2
3651
// // Subject.swift // Rx // // Created by Krunoslav Zaher on 2/11/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class Subscription<Element> : Disposable { typealias ObserverType = Observer<Element> typealias KeyType = Bag<Void>.KeyType private let subject : Subject<Element> private var key: KeyType private var lock = Lock() private var observer: ObserverType? init(subject: Subject<Element>, key: KeyType, observer: ObserverType) { self.key = key self.subject = subject self.observer = observer } func dispose() { lock.performLocked { if let observer = self.observer { self.observer = nil self.subject.unsubscribe(self.key) } } } } public class Subject<Element> : SubjectType<Element, Element>, Disposable { typealias ObserverOf = Observer<Element> typealias KeyType = Bag<Void>.KeyType typealias Observers = Bag<ObserverOf> typealias State = ( disposed: Bool, observers: Observers, stoppedEvent: Event<Element>? ) private var lock = Lock() private var state: State = ( disposed: false, observers: Observers(), stoppedEvent: nil ) public override init() { super.init() } public func dispose() { self.lock.performLocked { state.disposed = true state.observers.removeAll() } } public override func on(event: Event<Element>) { switch event { case .Next(let value): let observers = lock.calculateLocked { () -> [ObserverOf]? in let state = self.state let shouldReturnImmediatelly = state.disposed || state.stoppedEvent != nil let observers: [Observer]? = shouldReturnImmediatelly ? nil : state.observers.all return observers } if let observers = observers { dispatch(event, observers) } return default: break } let observers: [Observer] = lock.calculateLocked { () -> [ObserverOf] in let state = self.state var observers = self.state.observers.all switch event { case .Completed: fallthrough case .Error: if state.stoppedEvent == nil { self.state.stoppedEvent = event self.state.observers.removeAll() } default: rxFatalError("Something went wrong") } return observers } dispatch(event, observers) } public override func subscribe<O : ObserverType where O.Element == Element>(observer: O) -> Disposable { return lock.calculateLocked { if let stoppedEvent = state.stoppedEvent { observer.on(stoppedEvent) return DefaultDisposable() } if state.disposed { sendError(observer, DisposedError) return DefaultDisposable() } let key = state.observers.put(Observer.normalize(observer)) return Subscription(subject: self, key: key, observer: Observer.normalize(observer)) } } func unsubscribe(key: KeyType) { self.lock.performLocked { _ = state.observers.removeKey(key) } } }
mit
9592c813ca12e85be3f996c1ec14d713
26.877863
108
0.540948
5.329927
false
false
false
false
Laptopmini/SwiftyArtik
Source/MachineLearningModel.swift
1
3891
// // MachineLearningModel.swift // SwiftyArtik // // Created by Paul-Valentin Mini on 1/11/18. // Copyright © 2018 Paul-Valentin Mini. All rights reserved. // import Foundation import ObjectMapper import PromiseKit open class MachineLearningModel: Mappable, RemovableArtikInstance { public enum ModelType: String { case prediction = "prediction" case anomalyDetection = "anomalyDetectionUsingPrediction" } public enum Status: String { case training = "training" case ready = "ready" case error = "error" } public class Source: Mappable { var did: String? var field: String? public init(did: String, field: String) { self.did = did self.field = field } public required init?(map: Map) {} public func mapping(map: Map) { did <- map["did"] field <- map["field"] } } public class InputOutput: Mappable { var name: String? var type: String? var value: String? var confidence: String? init(name: String, type: String) { self.name = name self.type = type } init(name: String, value: String, confidence: String? = nil) { self.name = name self.value = value self.confidence = confidence } public required init?(map: Map) {} public func mapping(map: Map) { name <- map["name"] type <- map["type"] value <- map["value"] confidence <- map["confidence"] } } public var id: String? public var uid: String? public var aid: String? public var inputs: [InputOutput]? public var outputs: [InputOutput]? public var sources: [Source]? public var trainingCron: String? public var type: ModelType? public var sourceToPredict: Source? public var anomalyDetectionSensitivity: UInt64? public var predictIn: UInt64? public var status: Status? public var origin: String? public var version: Int64? public required init?(map: Map) {} public init() {} public func mapping(map: Map) { id <- map["id"] uid <- map["uid"] aid <- map["aid"] inputs <- map["inputs"] outputs <- map["outputs"] sources <- map["data.sources"] trainingCron <- map["trainingCron"] type <- map["type"] sourceToPredict <- map["parameters.sourceToPredict"] anomalyDetectionSensitivity <- map["parameters.anomalyDetectionSensitivity"] predictIn <- map["parameters.predictIn"] status <- map["status"] origin <- map["origin"] version <- map["version"] } public func predict(inputs: [InputOutput]) -> Promise<[InputOutput]> { let promise = Promise<[InputOutput]>.pending() if let id = id { MachineLearningAPI.predict(id: id, inputs: inputs).then { outputs -> Void in promise.fulfill(outputs) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } // MARK: - RemovableArtikInstance public func removeFromArtik() -> Promise<Void> { let promise = Promise<Void>.pending() if let id = id { MachineLearningAPI.delete(id: id).then { _ -> Void in promise.fulfill(()) }.catch { error -> Void in promise.reject(error) } } else { promise.reject(ArtikError.missingValue(reason: .noID)) } return promise.promise } }
mit
59bcac609a4813ecd98847e18009edbf
27.188406
88
0.548072
4.636472
false
false
false
false
brave/browser-ios
Client/Frontend/Widgets/AuralProgressBar.swift
1
8466
/* 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 AVFoundation import Shared import XCGLogger private let log = Logger.browserLogger private struct AuralProgressBarUX { static let TickPeriod = 1.0 static let TickDuration = 0.03 // VoiceOver's second tone of "screen changed" sound is approx. 1107-8 kHz, so make it C#6 which is 1108.73 static let VoiceOverScreenChangedSecondToneFrequency = 1108.73 // VoiceOver "screen changed" sound is two tones, let's denote them g1 and c2 (that is dominant and tonic). Then make TickFrequency to be f1 to make it subdominant and create a cadence (but it is quite spoiled by the pitch-varying progress sounds...). f1 is 5th halftone in a scale c1-c2. static let TickFrequency = AuralProgressBarUX.VoiceOverScreenChangedSecondToneFrequency * exp2(-1 + 5.0/12.0) static let TickVolume = 0.2 static let ProgressDuration = 0.02 static let ProgressStartFrequency = AuralProgressBarUX.TickFrequency static let ProgressEndFrequency = AuralProgressBarUX.TickFrequency * 2 static let ProgressVolume = 0.03 static let TickProgressPanSpread = 0.25 } class AuralProgressBar { fileprivate class UI { let engine: AVAudioEngine let progressPlayer: AVAudioPlayerNode let tickPlayer: AVAudioPlayerNode // lazy initialize tickBuffer because of memory consumption (~350 kB) var _tickBuffer: AVAudioPCMBuffer? var tickBuffer: AVAudioPCMBuffer { if _tickBuffer == nil { _tickBuffer = UI.tone(tickPlayer.outputFormat(forBus: 0), pitch: AuralProgressBarUX.TickFrequency, volume: AuralProgressBarUX.TickVolume, duration: AuralProgressBarUX.TickDuration, period: AuralProgressBarUX.TickPeriod) } return _tickBuffer! } init() { engine = AVAudioEngine() tickPlayer = AVAudioPlayerNode() tickPlayer.pan = -Float(AuralProgressBarUX.TickProgressPanSpread) engine.attach(tickPlayer) progressPlayer = AVAudioPlayerNode() progressPlayer.pan = +Float(AuralProgressBarUX.TickProgressPanSpread) engine.attach(progressPlayer) connectPlayerNodes() NotificationCenter.default.addObserver(self, selector: #selector(UI.handleAudioEngineConfigurationDidChangeNotification(_:)), name: NSNotification.Name.AVAudioEngineConfigurationChange, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(UI.handleAudioSessionInterruptionNotification(_:)), name: NSNotification.Name.AVAudioSessionInterruption, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVAudioEngineConfigurationChange, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVAudioSessionInterruption, object: nil) } func connectPlayerNodes() { let mainMixer = engine.mainMixerNode engine.connect(tickPlayer, to: mainMixer, format: mainMixer.outputFormat(forBus: 0)) engine.connect(progressPlayer, to: mainMixer, format: tickBuffer.format) } func disconnectPlayerNodes() { engine.disconnectNodeOutput(tickPlayer) engine.disconnectNodeOutput(progressPlayer) } func startEngine() { if !engine.isRunning { do { try engine.start() } catch { log.error("Unable to start AVAudioEngine: \(error)") } } } @objc func handleAudioSessionInterruptionNotification(_ notification: Notification) { if let interruptionTypeValue = notification.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt { if let interruptionType = AVAudioSessionInterruptionType(rawValue: interruptionTypeValue) { switch interruptionType { case .began: tickPlayer.stop() progressPlayer.stop() case .ended: if let interruptionOptionValue = notification.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt { let interruptionOption = AVAudioSessionInterruptionOptions(rawValue: interruptionOptionValue) if interruptionOption == .shouldResume { startEngine() } } } } } } @objc func handleAudioEngineConfigurationDidChangeNotification(_ notification: Notification) { disconnectPlayerNodes() connectPlayerNodes() } func start() { do { try engine.start() tickPlayer.play() progressPlayer.play() tickPlayer.scheduleBuffer(tickBuffer, at: nil, options: AVAudioPlayerNodeBufferOptions.loops) { } } catch { log.error("Unable to start AVAudioEngine. Tick & Progress player will not play : \(error)") } } func stop() { progressPlayer.stop() tickPlayer.stop() engine.stop() } func playProgress(_ progress: Double) { // using exp2 and log2 instead of exp and log as "log" clashes with XCGLogger.log let pitch = AuralProgressBarUX.ProgressStartFrequency * exp2(log2(AuralProgressBarUX.ProgressEndFrequency/AuralProgressBarUX.ProgressStartFrequency) * progress) let buffer = UI.tone(progressPlayer.outputFormat(forBus: 0), pitch: pitch, volume: AuralProgressBarUX.ProgressVolume, duration: AuralProgressBarUX.ProgressDuration) progressPlayer.scheduleBuffer(buffer, at: nil, options: .interrupts) { } } class func tone(_ format: AVAudioFormat, pitch: Double, volume: Double, duration: Double, period: Double? = nil) -> AVAudioPCMBuffer { // adjust durations to the nearest lower multiple of one pitch frequency's semiperiod to have tones end gracefully with 0 value let duration = Double(Int(duration * 2*pitch)) / (2*pitch) let pitchFrames = Int(duration * format.sampleRate) let frames = Int((period ?? duration) * format.sampleRate) guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)) else { print("AVAudioPCMBuffer is nil") // TODO: Better error handling than just throwing empty buffer? return AVAudioPCMBuffer() } buffer.frameLength = buffer.frameCapacity for channel in 0..<Int(format.channelCount) { let channelData = buffer.floatChannelData?[channel] var i = 0 for frame in 0..<frames { // TODO: consider some attack-sustain-release to make the tones sound little less "sharp" and robotic var val = 0.0 if frame < pitchFrames { val = volume * sin(pitch*Double(frame)*2*M_PI/format.sampleRate) } channelData?[i] = Float(val) i += buffer.stride } } return buffer } } fileprivate let ui = UI() var progress: Double? { didSet { if !hidden { if oldValue == nil && progress != nil { ui.start() } else if oldValue != nil && progress == nil { ui.stop() } if let progress = progress { ui.playProgress(progress) } } } } var hidden: Bool = true { didSet { if hidden != oldValue { if hidden { ui.stop() ui._tickBuffer = nil } else { if let progress = progress { ui.start() ui.playProgress(progress) } } } } } }
mpl-2.0
51ee9114b60bd43fa5a373ef45390814
43.09375
292
0.59922
5.454897
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/RxExample/RxExample/Services/ReachabilityService.swift
3
2324
// // ReachabilityService.swift // RxExample // // Created by Vodovozov Gleb on 10/22/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif import Foundation public enum ReachabilityStatus { case reachable(viaWiFi: Bool) case unreachable } extension ReachabilityStatus { var reachable: Bool { switch self { case .reachable: return true case .unreachable: return false } } } protocol ReachabilityService { var reachability: Observable<ReachabilityStatus> { get } } class DefaultReachabilityService : ReachabilityService { private let _reachabilitySubject: BehaviorSubject<ReachabilityStatus> var reachability: Observable<ReachabilityStatus> { return _reachabilitySubject.asObservable() } let _reachability: Reachability init() throws { let reachabilityRef = try Reachability.reachabilityForInternetConnection() let reachabilitySubject = BehaviorSubject<ReachabilityStatus>(value: .unreachable) // so main thread isn't blocked when reachability via WiFi is checked let backgroundQueue = DispatchQueue(label: "reachability.wificheck") reachabilityRef.whenReachable = { reachability in backgroundQueue.async { reachabilitySubject.on(.next(.reachable(viaWiFi: reachabilityRef.isReachableViaWiFi()))) } } reachabilityRef.whenUnreachable = { reachability in backgroundQueue.async { reachabilitySubject.on(.next(.unreachable)) } } try reachabilityRef.startNotifier() _reachability = reachabilityRef _reachabilitySubject = reachabilitySubject } deinit { _reachability.stopNotifier() } } extension ObservableConvertibleType { func retryOnBecomesReachable(_ valueOnFailure:E, reachabilityService: ReachabilityService) -> Observable<E> { return self.asObservable() .catchError { (e) -> Observable<E> in reachabilityService.reachability .filter { $0.reachable } .flatMap { _ in Observable.error(e) } .startWith(valueOnFailure) } .retry() } }
mit
f6aa3f6066f99c2108be01583289efd2
26.329412
113
0.6483
5.504739
false
false
false
false
1170197998/Swift-DEMO
ScreenRotation/ScreenRotation/ViewController.swift
1
5609
// // ViewController.swift // ScreenRotation // // Created by ShaoFeng on 12/03/2017. // Copyright © 2017 ShaoFeng. All rights reserved. // import UIKit import SnapKit class ViewController: UIViewController { var label: UILabel! = nil override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() UIApplication.shared.isStatusBarHidden = false } override func viewDidLoad() { super.viewDidLoad() label = UILabel() label.text = "横竖屏自适应DEMO" label.sizeToFit() label.textAlignment = .center label.backgroundColor = UIColor.gray view.addSubview(label) label.snp.makeConstraints({ (make) in make.top.equalTo(0) make.leading.trailing.equalTo(0) make.height.equalTo(label.snp.width).multipliedBy(9.0 / 16.0) }) addNotifications() } deinit { NotificationCenter.default.removeObserver(self) UIDevice.current.endGeneratingDeviceOrientationNotifications() } /// 添加通知 private func addNotifications() { // 检测设备方向 UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(deviceOrientationChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) // 检测状态栏方向 // NotificationCenter.default.addObserver(self, selector: #selector(statusBarOrientationChange), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil) } /// 设备方向改变 @objc fileprivate func deviceOrientationChange() { // 获取当前设备方向 let orientation = UIDevice.current.orientation // 如果手机硬件屏幕朝上或者屏幕朝下或者未知 if orientation == UIDeviceOrientation.faceUp || orientation == UIDeviceOrientation.faceDown || orientation == UIDeviceOrientation.unknown { return } let interfaceOrientation: UIInterfaceOrientation = UIInterfaceOrientation(rawValue: orientation.rawValue)! switch interfaceOrientation { //屏幕竖直,home键在上面 case UIInterfaceOrientation.portraitUpsideDown: break //屏幕竖直,home键在下面 case UIInterfaceOrientation.portrait: toOrientation(orientation: UIInterfaceOrientation.portrait); break //屏幕水平,home键在左 case UIInterfaceOrientation.landscapeLeft: toOrientation(orientation: UIInterfaceOrientation.landscapeLeft); break //屏幕水平,home键在右 case UIInterfaceOrientation.landscapeRight: toOrientation(orientation: UIInterfaceOrientation.landscapeRight); break default: break } } /// 状态栏方向改变 // @objc fileprivate func statusBarOrientationChange() { // //获取当前状态栏方向 // let currentOrientation = UIApplication.shared.statusBarOrientation // if currentOrientation == UIInterfaceOrientation.portrait { // toOrientation(orientation: UIInterfaceOrientation.portrait) // } else if currentOrientation == UIInterfaceOrientation.landscapeRight{ // toOrientation(orientation: UIInterfaceOrientation.landscapeRight) // } else if currentOrientation == UIInterfaceOrientation.landscapeLeft { // toOrientation(orientation: UIInterfaceOrientation.landscapeLeft) // } // } /// 旋转 /// /// - Parameter orientation: 要旋转的方向 private func toOrientation(orientation: UIInterfaceOrientation) { //获取当前状态栏的方向 let currentOrientation = UIApplication.shared.statusBarOrientation //如果当前的方向和要旋转的方向一致,直接return if currentOrientation == orientation { return } //根据要旋转的方向,用snapKit重新布局 if orientation != UIInterfaceOrientation.portrait { // 从全屏的一侧直接到全屏的另一侧不修改 if currentOrientation == UIInterfaceOrientation.portrait { label.snp.makeConstraints({ (make) in make.width.equalTo(UIScreen.main.bounds.size.height) make.height.equalTo(UIScreen.main.bounds.size.width) make.center.equalTo(UIApplication.shared.keyWindow!) }) } } //状态栏旋转 UIApplication.shared.setStatusBarOrientation(orientation, animated: false) UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(0.35) label.transform = CGAffineTransform.identity label.transform = getTransformRotationAngle() UIView.commitAnimations() } /// 获取旋转角度 private func getTransformRotationAngle() -> CGAffineTransform { let interfaceOrientation = UIApplication.shared.statusBarOrientation if interfaceOrientation == UIInterfaceOrientation.portrait { return CGAffineTransform.identity } else if interfaceOrientation == UIInterfaceOrientation.landscapeLeft { return CGAffineTransform(rotationAngle: (CGFloat)(-Double.pi / 2)) } else if (interfaceOrientation == UIInterfaceOrientation.landscapeRight) { return CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)) } return CGAffineTransform.identity } }
apache-2.0
e85e5682c7c03007c6c8b96fe1dd6cb0
37.859259
186
0.667937
5.598719
false
false
false
false
GoodMorningCody/EverybodySwift
SensorsDemo/SensorsDemo/AccelerometerViewController.swift
1
1610
// // AccelerometerViewController.swift // SensorsDemo // // Created by Cody on 2015. 1. 5.. // Copyright (c) 2015년 tiekle. All rights reserved. // import UIKit import CoreMotion class AccelerometerViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var motionManager = CMMotionManager() if motionManager.accelerometerAvailable==false { println("Accelerometer 센서를 사용할 수 없습니다.") } else { motionManager.accelerometerUpdateInterval = 0.2 motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: {(accelerometerData: CMAccelerometerData!, error: NSError!) in if error != nil { println("x : "+accelerometerData.acceleration.x.description) println("y : "+accelerometerData.acceleration.y.description) println("z : "+accelerometerData.acceleration.z.description) } }) } } 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. } */ }
mit
233907c9407cd384c28ab4a098772150
30.72
167
0.643758
5.394558
false
false
false
false
brentdax/swift
test/IRGen/dllimport.swift
2
2707
// RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -parse-stdlib -module-name dllimport %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT // RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -parse-stdlib -module-name dllimport -primary-file %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT // REQUIRES: CODEGENERATOR=ARM import dllexport public func get_ci() -> dllexport.c { return dllexport.ci } public func get_c_type() -> dllexport.c.Type { return dllexport.c.self } public class d : c { override init() { super.init() } @inline(never) func f(_ : dllexport.c) { } } struct s : p { func f() { } } func f(di : d) { di.f(get_ci()) } func blackhole<F>(_ : F) { } public func g() { blackhole({ () -> () in }) } // CHECK-NO-OPT-DAG: declare dllimport %swift.refcounted* @swift_allocObject(%swift.type*, i32, i32) // CHECK-NO-OPT-DAG: declare dllimport void @swift_deallocObject(%swift.refcounted*, i32, i32) // CHECK-NO-OPT-DAG: declare dllimport void @swift_release(%swift.refcounted*) // CHECK-NO-OPT-DAG: declare dllimport %swift.refcounted* @swift_retain(%swift.refcounted* returned) // CHECK-NO-OPT-DAG: @"$s9dllexport1cCN" = external dllimport global %swift.type // CHECK-NO-OPT-DAG: @"$s9dllexport1pMp" = external dllimport global %swift.protocol // CHECK-NO-OPT-DAG: @"$sytN" = external dllimport global %swift.full_type // CHECK-NO-OPT-DAG: @"$sBoWV" = external dllimport global i8* // CHECK-NO-OPT-DAG: declare dllimport swiftcc i8* @"$s9dllexport2ciAA1cCvau"() // CHECK-NO-OPT-DAG: declare dllimport swiftcc %swift.refcounted* @"$s9dllexport1cCfd"(%T9dllexport1cC* swiftself) // CHECK-NO-OPT-DAG: declare dllimport swiftcc %swift.metadata_response @"$s9dllexport1cCMa"(i32) // CHECK-NO-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32) // CHECK-OPT-DAG: declare dllimport %swift.refcounted* @swift_retain(%swift.refcounted* returned) local_unnamed_addr // CHECK-OPT-DAG: @"$sBoWV" = external dllimport global i8* // CHECK-OPT-DAG: @"$s9dllexport1cCN" = external dllimport global %swift.type // CHECK-OPT-DAG: @"__imp_$s9dllexport1pMp" = external externally_initialized constant %swift.protocol* // CHECK-OPT-DAG: declare dllimport swiftcc i8* @"$s9dllexport2ciAA1cCvau"() // CHECK-OPT-DAG: declare dllimport swiftcc %swift.metadata_response @"$s9dllexport1cCMa"(i32) // CHECK-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32) // CHECK-OPT-DAG: declare dllimport swiftcc %swift.refcounted* @"$s9dllexport1cCfd"(%T9dllexport1cC* swiftself)
apache-2.0
5da70bcee8f8f7ab5655440598526d57
44.881356
224
0.721832
3.199764
false
false
false
false
Liuyingao/SwiftRepository
OptionalChaining.swift
1
1825
//: Playground - noun: a place where people can play import UIKit class Person{ var residence: Residence? } class Room{ var name: String init(name: String){ self.name = name } } class Residence{ var rooms = [Room]() var numberOfRooms: Int{ return rooms.count } subscript(index: Int) -> Room{ get{ return rooms[index] } set{ rooms[index] = newValue } } func printNumberOfRooms(){ print("The number of rooms is \(numberOfRooms)") } var address: Address? } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName != nil { return buildingName! } else if buildingNumber != nil && street != nil { return "\(buildingNumber!) \(street!)" } else { return nil } } } var leo = Person() leo.residence = Residence() leo.residence?.rooms.append(Room(name: "Bath")) leo.residence?.rooms.append(Room(name: "Kitchen")) if let i = leo.residence?.numberOfRooms{ print("leo's residence has \(i) room(s).") }else{ print("Unable to retrieve the number of rooms.") } print(leo.residence?[0].name) print(leo.residence?.rooms[1].name) let someAddress = Address() someAddress.buildingNumber = "29" someAddress.street = "Acacia Road" leo.residence?.address = someAddress if let i = leo.residence?.address?.street{ print(i) }else{ print("No address") } print(leo.residence?.address?.buildingIdentifier()) print(leo.residence?.address?.buildingIdentifier()?.hasPrefix("29")) var testScores = ["Dave": [86, 82, 84], "Bev": [79, 94, 81]] print(testScores["Bev"]?[2]++) print(testScores["Bev"]?[2])
gpl-2.0
f8e68ced181583755af61c2f332ceab1
20.470588
68
0.608219
3.899573
false
false
false
false
totetero/fuhaha_engine
src_client/fuhahaEngine/ios/IosPluginSound.swift
1
6648
import Foundation import AVFoundation // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // プラグインクラス class IosPluginSound: NSObject{ fileprivate static var bgmList: Dictionary<UInt32, IosPluginSound.FuhahaBgmItem> = Dictionary<UInt32, IosPluginSound.FuhahaBgmItem>(); fileprivate static var seList: Dictionary<UInt32, IosPluginSound.FuhahaSeItem> = Dictionary<UInt32, IosPluginSound.FuhahaSeItem>(); fileprivate static var bgmZeroId: UInt32 = 0; fileprivate static var bgmCurrentId: UInt32 = 0; fileprivate static var seAudioPlayer: Array<AVAudioPlayer> = Array<AVAudioPlayer>(); fileprivate static var bgmToneDown: Float = 1.0; fileprivate static var bgmVolume: Float = 1.0; fileprivate static var seVolume: Float = 1.0; fileprivate static let soundSuffix: String = ".m4a"; // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ---------------------------------------------------------------- // BGM読込 @objc static internal func platformPluginSoundBgmLoad(_ bgmId: UInt32, src: String){ if(bgmId <= 0){return;} if(IosPluginSound.bgmList[bgmId] != nil){return;} IosPluginSound.bgmList[bgmId] = IosPluginSound.FuhahaBgmItem(src: src, bgmId: bgmId); } // BGM再生 @objc static internal func platformPluginSoundBgmPlay(_ bgmId: UInt32){ IosPluginSound.bgmZeroId = bgmId; let oldVolume = IosPluginSound.bgmVolume; if(oldVolume > 0){IosPluginSound.bgmPlay(bgmId);} } // BGM再生 static internal func bgmPlay(_ bgmId: UInt32){ IosPluginSound.bgmToneDown = 1.0; // 同じBGMを再生中なら何もしない if(IosPluginSound.bgmCurrentId == bgmId){return;} let playData: FuhahaBgmItem? = IosPluginSound.bgmList[bgmId]; if(playData == nil){IosPluginSound.bgmCurrentId = 0; return;} IosPluginSound.bgmCurrentId = bgmId; if(playData!.isPlaying){return;} playData!.play(); } // BGMトーンダウン @objc static internal func platformPluginSoundBgmToneDown(_ volume: Double){ IosPluginSound.bgmToneDown = Float(volume); } // BGM設定音量 @objc static internal func platformPluginSoundBgmVolume(_ volume: Double){ // 音量をゼロにした瞬間とゼロから戻した瞬間 let oldVolume = IosPluginSound.bgmVolume; if(oldVolume > 0 && volume <= 0){IosPluginSound.bgmPlay(0);} if(oldVolume <= 0 && volume > 0){IosPluginSound.bgmPlay(IosPluginSound.bgmZeroId);} IosPluginSound.bgmVolume = Float(volume); } // BGM情報クラス class FuhahaBgmItem: NSObject, AVAudioPlayerDelegate{ fileprivate let bgmId: UInt32; fileprivate let src: URL; fileprivate let countMax: Int = 30; fileprivate var countPrev: Int = 0; fileprivate var isPlaying: Bool = false; fileprivate var audioPlayer: AVAudioPlayer? = nil; fileprivate var settingVolume: Float = 0.0; // コンストラクタ init(src: String, bgmId: UInt32){ self.bgmId = bgmId; self.src = Bundle.main.url(forResource: src, withExtension: IosPluginSound.soundSuffix, subdirectory: "assets")!; } // 再生開始 func play(){ self.playTimer(nil); } // タイマーコールバック @objc func playTimer(_ timer: Timer?){ if(self.playing()){ Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.playTimer(_:)), userInfo: nil, repeats: false); } } // 再生関数 fileprivate func playing() -> Bool{ let isActive: Bool = (IosPluginSound.bgmCurrentId == self.bgmId); if(isActive || self.countPrev > 0){ if(!self.isPlaying){ // BGM作成と再生 do{ let audioPlayer: AVAudioPlayer = try AVAudioPlayer(contentsOf: self.src); audioPlayer.volume = 0.0; audioPlayer.delegate = self; audioPlayer.numberOfLoops = -1; audioPlayer.prepareToPlay(); audioPlayer.play(); self.countPrev = 0; self.isPlaying = true; self.audioPlayer = audioPlayer; self.settingVolume = 0.0; }catch{} } if(self.isPlaying){ // BGMのボリュームフェード監視 let countNext: Int = isActive ? Int(round(Float(self.countMax) * IosPluginSound.bgmToneDown)) : 0; if(self.countPrev != countNext || self.settingVolume != IosPluginSound.bgmVolume){ self.settingVolume = IosPluginSound.bgmVolume; if(countNext > self.countPrev){self.countPrev += 1;} if(countNext < self.countPrev){self.countPrev -= 1;} let effectVolume: Float = Float(self.countPrev) / Float(self.countMax); self.audioPlayer!.volume = self.settingVolume * effectVolume; } } return true; }else{ // BGMの停止と破棄 self.audioPlayer!.stop(); self.audioPlayer = nil; self.isPlaying = false; } return false; } } // ---------------------------------------------------------------- // SE読込 @objc static internal func platformPluginSoundSeLoad(_ seId: UInt32, src: String){ if(seId <= 0){return;} if(IosPluginSound.seList[seId] != nil){return;} IosPluginSound.seList[seId] = IosPluginSound.FuhahaSeItem(src: src); } // SE再生 @objc static internal func platformPluginSoundSePlay(_ seId: UInt32){ IosPluginSound.seList[seId]?.play(); } // SE設定音量 @objc static internal func platformPluginSoundSeVolume(_ volume: Double){ IosPluginSound.seVolume = Float(volume); } // SE情報クラス class FuhahaSeItem: NSObject, AVAudioPlayerDelegate{ fileprivate let src: URL; // コンストラクタ init(src: String){ self.src = Bundle.main.url(forResource: src, withExtension: IosPluginSound.soundSuffix, subdirectory: "assets")!; } // 再生開始 func play(){ do{ let audioPlayer: AVAudioPlayer = try AVAudioPlayer(contentsOf: self.src); IosPluginSound.seAudioPlayer.append(audioPlayer); audioPlayer.volume = IosPluginSound.seVolume; audioPlayer.delegate = self; audioPlayer.numberOfLoops = 0; audioPlayer.prepareToPlay(); audioPlayer.play(); }catch{} } // 再生完了 func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool){ let index: Int? = IosPluginSound.seAudioPlayer.index(of: player); if(index != nil){IosPluginSound.seAudioPlayer.remove(at: index!);} } } // ---------------------------------------------------------------- } // ---------------------------------------------------------------- // ---------------------------------------------------------------- // ----------------------------------------------------------------
mit
d54662df00e00bcb734d90df9ceb18e4
31.845361
135
0.626805
3.871203
false
false
false
false
hideya/viiw2
viiw/viiw/BackgroundWindow.swift
1
1272
// // BackgroundWindow.swift // viiw // // Created by hideya kawahara on 2/6/16. // Copyright © 2016 hideya kawahara. All rights reserved. // import Cocoa class BackgroundWindow : NSWindow { override init(contentRect: NSRect, styleMask aStyle: Int, backing bufferingType: NSBackingStoreType, `defer` flag: Bool) { super.init(contentRect: contentRect, styleMask: aStyle, backing: bufferingType, `defer`: flag) setFrameOrigin(CGPointZero) var mainScreenSize = NSScreen.mainScreen()!.frame.size mainScreenSize.height -= NSStatusBar.systemStatusBar().thickness setContentSize(mainScreenSize) collectionBehavior = [.Stationary, .Transient, .IgnoresCycle, .CanJoinAllSpaces] level = Int(CGWindowLevelForKey(CGWindowLevelKey.DesktopWindowLevelKey)) orderBack(self) backgroundColor = NSColor.blackColor() } required init?(coder: NSCoder) { super.init(coder: coder) } override var canBecomeMainWindow: Bool { get { return false } } override var canBecomeKeyWindow: Bool { get { return false } } override var acceptsFirstResponder: Bool { get { return false } } }
mit
7b6b99873d1e8f4ca2c94eee5978661c
25.479167
126
0.649095
4.621818
false
false
false
false
seyton/MultiConnect
GridPlay/MainTheme.swift
1
858
// // MainTheme.swift // GridPlay // // Created by Wesley Matlock on 4/17/15. // Copyright (c) 2015 insoc.net. All rights reserved. // import UIKit struct MainTheme { static let baseColor = UIColor(red: 204/255, green: 38/255.0, blue: 58/255.0, alpha: 1) static let navTextColor = UIColor.whiteColor() static let baseBackgroundColor = UIColor(red: 205/255, green: 210/255, blue: 216/255, alpha: 1) static let deepColor = UIColor(red: 0, green: 32/255, blue: 74/255, alpha: 1) static let neutralColor = UIColor(red: 0, green: 70/255, blue: 141/255, alpha: 1) static let accentColor = UIColor(red: 255, green: 116/255, blue: 40/255, alpha: 1) static let cellFont = UIFont(name: "Chalkduster", size: 40) static let buttonFont = UIFont(name: "Chalkduster", size: 15) static let labelFont = UIFont(name: "Chalkduster", size: 15) }
mit
328928f344941b9f74516fe0a547a82e
34.791667
97
0.689977
3.213483
false
false
false
false
5397chop/FriendlyChat-App
ios/swift/FriendlyChatSwift/FCViewController.swift
2
12334
// // Copyright (c) 2015 Google 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 Photos import UIKit import Firebase import GoogleSignIn import GoogleMobileAds /** * AdMob ad unit IDs are not currently stored inside the google-services.plist file. Developers * using AdMob can store them as custom values in another plist, or simply use constants. Note that * these ad units are configured to return only test ads, and should not be used outside this sample. */ let kBannerAdUnitID = "ca-app-pub-3940256099942544/2934735716" @objc(FCViewController) class FCViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, InviteDelegate { // Instance variables @IBOutlet weak var textField: UITextField! @IBOutlet weak var sendButton: UIButton! var ref: DatabaseReference! var messages: [DataSnapshot]! = [] var msglength: NSNumber = 10 fileprivate var _refHandle: DatabaseHandle? var storageRef: StorageReference! var remoteConfig: RemoteConfig! @IBOutlet weak var banner: GADBannerView! @IBOutlet weak var clientTable: UITableView! override func viewDidLoad() { super.viewDidLoad() self.clientTable.register(UITableViewCell.self, forCellReuseIdentifier: "tableViewCell") configureDatabase() configureStorage() configureRemoteConfig() fetchConfig() loadAd() logViewLoaded() } deinit { if let refHandle = _refHandle { self.ref.child("messages").removeObserver(withHandle: refHandle) } } func configureDatabase() { ref = Database.database().reference() // Listen for new messages in the Firebase database _refHandle = self.ref.child("messages").observe(.childAdded, with: { [weak self] (snapshot) -> Void in guard let strongSelf = self else { return } strongSelf.messages.append(snapshot) strongSelf.clientTable.insertRows(at: [IndexPath(row: strongSelf.messages.count-1, section: 0)], with: .automatic) }) } func configureStorage() { storageRef = Storage.storage().reference() } func configureRemoteConfig() { remoteConfig = RemoteConfig.remoteConfig() // Create Remote Config Setting to enable developer mode. // Fetching configs from the server is normally limited to 5 requests per hour. // Enabling developer mode allows many more requests to be made per hour, so developers // can test different config values during development. let remoteConfigSettings = RemoteConfigSettings(developerModeEnabled: true) remoteConfig.configSettings = remoteConfigSettings! } func fetchConfig() { var expirationDuration: Double = 3600 // If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from // the server. if self.remoteConfig.configSettings.isDeveloperModeEnabled { expirationDuration = 0 } // cacheExpirationSeconds is set to cacheExpiration here, indicating that any previously // fetched and cached config would be considered expired because it would have been fetched // more than cacheExpiration seconds ago. Thus the next fetch would go to the server unless // throttling is in progress. The default expiration duration is 43200 (12 hours). remoteConfig.fetch(withExpirationDuration: expirationDuration) { [weak self] (status, error) in if status == .success { print("Config fetched!") guard let strongSelf = self else { return } strongSelf.remoteConfig.activateFetched() let friendlyMsgLength = strongSelf.remoteConfig["friendly_msg_length"] if friendlyMsgLength.source != .static { strongSelf.msglength = friendlyMsgLength.numberValue! print("Friendly msg length config: \(strongSelf.msglength)") } } else { print("Config not fetched") if let error = error { print("Error \(error)") } } } } @IBAction func didPressFreshConfig(_ sender: AnyObject) { fetchConfig() } @IBAction func didSendMessage(_ sender: UIButton) { _ = textFieldShouldReturn(textField) } @IBAction func didPressCrash(_ sender: AnyObject) { FirebaseCrashMessage("Cause Crash button clicked") fatalError() } @IBAction func inviteTapped(_ sender: AnyObject) { if let invite = Invites.inviteDialog() { invite.setInviteDelegate(self) // NOTE: You must have the App Store ID set in your developer console project // in order for invitations to successfully be sent. // A message hint for the dialog. Note this manifests differently depending on the // received invitation type. For example, in an email invite this appears as the subject. invite.setMessage("Try this out!\n -\(Auth.auth().currentUser?.displayName ?? "")") // Title for the dialog, this is what the user sees before sending the invites. invite.setTitle("FriendlyChat") invite.setDeepLink("app_url") invite.setCallToActionText("Install!") invite.setCustomImage("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png") invite.open() } } func inviteFinished(withInvitations invitationIds: [String], error: Error?) { if let error = error { print("Failed: \(error.localizedDescription)") } else { print("Invitations sent") } } func logViewLoaded() { FirebaseCrashMessage("View loaded") } func loadAd() { self.banner.adUnitID = kBannerAdUnitID self.banner.rootViewController = self self.banner.load(GADRequest()) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.characters.count + string.characters.count - range.length return newLength <= self.msglength.intValue // Bool } // UITableViewDataSource protocol methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Dequeue cell let cell = self.clientTable .dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) // Unpack message from Firebase DataSnapshot let messageSnapshot: DataSnapshot! = self.messages[indexPath.row] guard let message = messageSnapshot.value as? [String:String] else { return cell } let name = message[Constants.MessageFields.name] ?? "" if let imageURL = message[Constants.MessageFields.imageURL] { if imageURL.hasPrefix("gs://") { Storage.storage().reference(forURL: imageURL).getData(maxSize: INT64_MAX) {(data, error) in if let error = error { print("Error downloading: \(error)") return } DispatchQueue.main.async { cell.imageView?.image = UIImage.init(data: data!) cell.setNeedsLayout() } } } else if let URL = URL(string: imageURL), let data = try? Data(contentsOf: URL) { cell.imageView?.image = UIImage.init(data: data) } cell.textLabel?.text = "sent by: \(name)" } else { let text = message[Constants.MessageFields.text] ?? "" cell.textLabel?.text = name + ": " + text cell.imageView?.image = UIImage(named: "ic_account_circle") if let photoURL = message[Constants.MessageFields.photoURL], let URL = URL(string: photoURL), let data = try? Data(contentsOf: URL) { cell.imageView?.image = UIImage(data: data) } } return cell } // UITextViewDelegate protocol methods func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let text = textField.text else { return true } textField.text = "" view.endEditing(true) let data = [Constants.MessageFields.text: text] sendMessage(withData: data) return true } func sendMessage(withData data: [String: String]) { var mdata = data mdata[Constants.MessageFields.name] = Auth.auth().currentUser?.displayName if let photoURL = Auth.auth().currentUser?.photoURL { mdata[Constants.MessageFields.photoURL] = photoURL.absoluteString } // Push data to Firebase Database self.ref.child("messages").childByAutoId().setValue(mdata) } // MARK: - Image Picker @IBAction func didTapAddPhoto(_ sender: AnyObject) { let picker = UIImagePickerController() picker.delegate = self if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) { picker.sourceType = .camera } else { picker.sourceType = .photoLibrary } present(picker, animated: true, completion:nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { picker.dismiss(animated: true, completion:nil) guard let uid = Auth.auth().currentUser?.uid else { return } // if it's a photo from the library, not an image from the camera if #available(iOS 8.0, *), let referenceURL = info[UIImagePickerControllerReferenceURL] as? URL { let assets = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil) let asset = assets.firstObject asset?.requestContentEditingInput(with: nil, completionHandler: { [weak self] (contentEditingInput, info) in let imageFile = contentEditingInput?.fullSizeImageURL let filePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000))/\((referenceURL as AnyObject).lastPathComponent!)" guard let strongSelf = self else { return } strongSelf.storageRef.child(filePath) .putFile(from: imageFile!, metadata: nil) { (metadata, error) in if let error = error { let nsError = error as NSError print("Error uploading: \(nsError.localizedDescription)") return } strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description]) } }) } else { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { return } let imageData = UIImageJPEGRepresentation(image, 0.8) let imagePath = "\(uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg" let metadata = StorageMetadata() metadata.contentType = "image/jpeg" self.storageRef.child(imagePath) .putData(imageData!, metadata: metadata) { [weak self] (metadata, error) in if let error = error { print("Error uploading: \(error)") return } guard let strongSelf = self else { return } strongSelf.sendMessage(withData: [Constants.MessageFields.imageURL: strongSelf.storageRef.child((metadata?.path)!).description]) } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion:nil) } @IBAction func signOut(_ sender: UIButton) { let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() dismiss(animated: true, completion: nil) } catch let signOutError as NSError { print ("Error signing out: \(signOutError.localizedDescription)") } } func showAlert(withTitle title: String, message: String) { DispatchQueue.main.async { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let dismissAction = UIAlertAction(title: "Dismiss", style: .destructive, handler: nil) alert.addAction(dismissAction) self.present(alert, animated: true, completion: nil) } } }
apache-2.0
2a914937c2e24aa9247ac2ff4c12e1ba
37.54375
140
0.693125
4.751156
false
true
false
false
Derek316x/MotionKit
MotionKit.swift
1
16253
// // MotionKit.swift // MotionKit // // Created by Haroon on 14/02/2015. // Launched under the Creative Commons License. You're free to use MotionKit. // // The original Github repository is https://github.com/MHaroonBaig/MotionKit // The official blog post and documentation is https://medium.com/@PyBaig/motionkit-the-missing-ios-coremotion-wrapper-written-in-swift-99fcb83355d0 // import Foundation import CoreMotion //_______________________________________________________________________________________________________________ // this helps retrieve values from the sensors. @objc protocol MotionKitDelegate { optional func retrieveAccelerometerValues (x: Double, y:Double, z:Double, absoluteValue: Double) optional func retrieveGyroscopeValues (x: Double, y:Double, z:Double, absoluteValue: Double) optional func retrieveDeviceMotionObject (deviceMotion: CMDeviceMotion) optional func retrieveMagnetometerValues (x: Double, y:Double, z:Double, absoluteValue: Double) optional func getAccelerationValFromDeviceMotion (x: Double, y:Double, z:Double) optional func getGravityAccelerationValFromDeviceMotion (x: Double, y:Double, z:Double) optional func getRotationRateFromDeviceMotion (x: Double, y:Double, z:Double) optional func getMagneticFieldFromDeviceMotion (x: Double, y:Double, z:Double) optional func getAttitudeFromDeviceMotion (attitude: CMAttitude) } class MotionKit { let manager = CMMotionManager() var delegate: MotionKitDelegate? /* * init:void: * * Discussion: * Initialises the MotionKit class and throw a Log with a timestamp. */ init(){ NSLog("MotionKit has been initialised successfully") } /* * getAccelerometerValues:interval:values: * * Discussion: * Starts accelerometer updates, providing data to the given handler through the given queue. * Note that when the updates are stopped, all operations in the * given NSOperationQueue will be cancelled. You can access the retrieved values either by a * Trailing Closure or through a Delgate. */ func getAccelerometerValues (interval: NSTimeInterval = 0.1, values: ((x: Double, y: Double, z: Double) -> ())? ){ var valX: Double! var valY: Double! var valZ: Double! if manager.accelerometerAvailable { manager.accelerometerUpdateInterval = interval manager.startAccelerometerUpdatesToQueue(NSOperationQueue()) { (data: CMAccelerometerData?, error: NSError?) in if let isError = error { NSLog("Error: %@", isError) } valX = data!.acceleration.x valY = data!.acceleration.y valZ = data!.acceleration.z if values != nil{ values!(x: valX,y: valY,z: valZ) } let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ) self.delegate?.retrieveAccelerometerValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal) } } else { NSLog("The Accelerometer is not available") } } /* * getGyroValues:interval:values: * * Discussion: * Starts gyro updates, providing data to the given handler through the given queue. * Note that when the updates are stopped, all operations in the * given NSOperationQueue will be cancelled. You can access the retrieved values either by a * Trailing Closure or through a Delegate. */ func getGyroValues (interval: NSTimeInterval = 0.1, values: ((x: Double, y: Double, z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.gyroAvailable{ manager.gyroUpdateInterval = interval manager.startGyroUpdatesToQueue(NSOperationQueue()) { (data: CMGyroData?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } valX = data!.rotationRate.x valY = data!.rotationRate.y valZ = data!.rotationRate.z if values != nil{ values!(x: valX, y: valY, z: valZ) } let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ) self.delegate?.retrieveGyroscopeValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal) } } else { NSLog("The Gyroscope is not available") } } /* * getMagnetometerValues:interval:values: * * Discussion: * Starts magnetometer updates, providing data to the given handler through the given queue. * You can access the retrieved values either by a Trailing Closure or through a Delegate. */ @available(iOS, introduced=5.0) func getMagnetometerValues (interval: NSTimeInterval = 0.1, values: ((x: Double, y:Double, z:Double) -> ())? ){ var valX: Double! var valY: Double! var valZ: Double! if manager.magnetometerAvailable { manager.magnetometerUpdateInterval = interval manager.startMagnetometerUpdatesToQueue(NSOperationQueue()){ (data: CMMagnetometerData?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } valX = data!.magneticField.x valY = data!.magneticField.y valZ = data!.magneticField.z if values != nil{ values!(x: valX, y: valY, z: valZ) } let absoluteVal = sqrt(valX * valX + valY * valY + valZ * valZ) self.delegate?.retrieveMagnetometerValues!(valX, y: valY, z: valZ, absoluteValue: absoluteVal) } } else { NSLog("Magnetometer is not available") } } /* MARK :- DEVICE MOTION APPROACH STARTS HERE */ /* * getDeviceMotionValues:interval:values: * * Discussion: * Starts device motion updates, providing data to the given handler through the given queue. * Uses the default reference frame for the device. Examine CMMotionManager's * attitudeReferenceFrame to determine this. You can access the retrieved values either by a * Trailing Closure or through a Delegate. */ func getDeviceMotionObject (interval: NSTimeInterval = 0.1, values: ((deviceMotion: CMDeviceMotion) -> ())? ) { if manager.deviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){ (data: CMDeviceMotion?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } if values != nil{ values!(deviceMotion: data!) } self.delegate?.retrieveDeviceMotionObject!(data!) } } else { NSLog("Device Motion is not available") } } /* * getAccelerationFromDeviceMotion:interval:values: * You can retrieve the processed user accelaration data from the device motion from this method. */ func getAccelerationFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.deviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){ (data: CMDeviceMotion?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } valX = data!.userAcceleration.x valY = data!.userAcceleration.y valZ = data!.userAcceleration.z if values != nil{ values!(x: valX, y: valY, z: valZ) } self.delegate?.getAccelerationValFromDeviceMotion!(valX, y: valY, z: valZ) } } else { NSLog("Device Motion is unavailable") } } /* * getGravityAccelerationFromDeviceMotion:interval:values: * You can retrieve the processed gravitational accelaration data from the device motion from this * method. */ func getGravityAccelerationFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.deviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){ (data: CMDeviceMotion?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } valX = data!.gravity.x valY = data!.gravity.y valZ = data!.gravity.z if values != nil{ values!(x: valX, y: valY, z: valZ) } self.delegate?.getGravityAccelerationValFromDeviceMotion!(valX, y: valY, z: valZ) } } else { NSLog("Device Motion is not available") } } /* * getAttitudeFromDeviceMotion:interval:values: * You can retrieve the processed attitude data from the device motion from this * method. */ func getAttitudeFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((attitude: CMAttitude) -> ())? ) { if manager.deviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){ (data: CMDeviceMotion?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } if values != nil{ values!(attitude: data!.attitude) } self.delegate?.getAttitudeFromDeviceMotion!(data!.attitude) } } else { NSLog("Device Motion is not available") } } /* * getRotationRateFromDeviceMotion:interval:values: * You can retrieve the processed rotation data from the device motion from this * method. */ func getRotationRateFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! if manager.deviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){ (data: CMDeviceMotion?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } valX = data!.rotationRate.x valY = data!.rotationRate.y valZ = data!.rotationRate.z if values != nil{ values!(x: valX, y: valY, z: valZ) } self.delegate?.getRotationRateFromDeviceMotion!(valX, y: valY, z: valZ) } } else { NSLog("Device Motion is not available") } } /* * getMagneticFieldFromDeviceMotion:interval:values: * You can retrieve the processed magnetic field data from the device motion from this * method. */ func getMagneticFieldFromDeviceMotion (interval: NSTimeInterval = 0.1, values: ((x:Double, y:Double, z:Double, accuracy: Int32) -> ())? ) { var valX: Double! var valY: Double! var valZ: Double! var valAccuracy: Int32! if manager.deviceMotionAvailable{ manager.deviceMotionUpdateInterval = interval manager.startDeviceMotionUpdatesToQueue(NSOperationQueue()){ (data: CMDeviceMotion?, error: NSError?) in if let isError = error{ NSLog("Error: %@", isError) } valX = data!.magneticField.field.x valY = data!.magneticField.field.y valZ = data!.magneticField.field.z valAccuracy = data!.magneticField.accuracy.rawValue if values != nil{ values!(x: valX, y: valY, z: valZ, accuracy: valAccuracy) } self.delegate?.getMagneticFieldFromDeviceMotion!(valX, y: valY, z: valZ) } } else { NSLog("Device Motion is not available") } } /* MARK :- DEVICE MOTION APPROACH ENDS HERE */ /* * From the methods hereafter, the sensor values could be retrieved at * a particular instant, whenever needed, through a trailing closure. */ /* MARK :- INSTANTANIOUS METHODS START HERE */ func getAccelerationAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){ self.getAccelerationFromDeviceMotion(0.5) { (x, y, z) -> () in values(x: x,y: y,z: z) self.stopDeviceMotionUpdates() } } func getGravitationalAccelerationAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){ self.getGravityAccelerationFromDeviceMotion(0.5) { (x, y, z) -> () in values(x: x,y: y,z: z) self.stopDeviceMotionUpdates() } } func getAttitudeAtCurrentInstant (values: (attitude: CMAttitude) -> ()){ self.getAttitudeFromDeviceMotion(0.5) { (attitude) -> () in values(attitude: attitude) self.stopDeviceMotionUpdates() } } func getMageticFieldAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){ self.getMagneticFieldFromDeviceMotion(0.5) { (x, y, z, accuracy) -> () in values(x: x,y: y,z: z) self.stopDeviceMotionUpdates() } } func getGyroValuesAtCurrentInstant (values: (x:Double, y:Double, z:Double) -> ()){ self.getRotationRateFromDeviceMotion(0.5) { (x, y, z) -> () in values(x: x,y: y,z: z) self.stopDeviceMotionUpdates() } } /* MARK :- INSTANTANIOUS METHODS END HERE */ /* * stopAccelerometerUpdates * * Discussion: * Stop accelerometer updates. */ func stopAccelerometerUpdates(){ self.manager.stopAccelerometerUpdates() NSLog("Accelaration Updates Status - Stopped") } /* * stopGyroUpdates * * Discussion: * Stops gyro updates. */ func stopGyroUpdates(){ self.manager.stopGyroUpdates() NSLog("Gyroscope Updates Status - Stopped") } /* * stopDeviceMotionUpdates * * Discussion: * Stops device motion updates. */ func stopDeviceMotionUpdates() { self.manager.stopDeviceMotionUpdates() NSLog("Device Motion Updates Status - Stopped") } /* * stopMagnetometerUpdates * * Discussion: * Stops magnetometer updates. */ @available(iOS, introduced=5.0) func stopmagnetometerUpdates() { self.manager.stopMagnetometerUpdates() NSLog("Magnetometer Updates Status - Stopped") } }
mit
3364b2f2e588248785e67e40962af9ac
34.801762
149
0.555344
5.106189
false
false
false
false
Spacerat/HexKeyboard
HexKeyboard/HexKey.swift
1
2358
// // HexKey.swift // HexKeyboard // // Created by Joseph Atkins-Turkish on 02/09/2014. // Copyright (c) 2014 Joseph Atkins-Turkish. All rights reserved. // import UIKit class HexKey : UILabel { let pressColour = UIColor(red: 255, green: 255, blue: 0, alpha: 0.4).CGColor var baseColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.4).CGColor let shape = CAShapeLayer() var held : Bool = false override init() { super.init() self.opaque = false self.layer.addSublayer(shape) } override init(frame: CGRect) { super.init(frame: frame) } override var frame : CGRect { get { return super.frame } set { super.frame = newValue let rect = CGRect(origin: CGPointZero, size: newValue.size) shape.path = UIBezierPath(hexagonWithSize: rect.size).CGPath let newbounds = CGPathGetBoundingBox(shape.path) shape.fillColor = baseColor } } override var text : String? { didSet { if text?.rangeOfString("#") != nil || text?.rangeOfString("b") != nil { baseColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4).CGColor } else { baseColor = UIColor(red: 255, green: 0, blue: 0, alpha: 0.4).CGColor } shape.fillColor = baseColor } } override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { return CGPathContainsPoint(shape.path, nil, point, true) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func doPressAnimation(#hold: Bool) { held = true if (!hold) { releaseAnimation() } else { shape.fillColor = pressColour } } func releaseAnimation() { if held { shape.fillColor = baseColor let animation = CABasicAnimation(keyPath: "fillColor") animation.duration = 0.5 animation.fromValue = pressColour animation.toValue = baseColor animation.repeatCount = 1 animation.autoreverses = false shape.addAnimation(animation, forKey: "fillColor") held = false } } }
gpl-2.0
3020b8d1ec81615934d2c2992939f222
27.071429
84
0.552587
4.474383
false
false
false
false
ray3132138/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRedPackertCell.swift
1
3844
// // CBRedPackertCell.swift // TestKitchen // // Created by qianfeng on 16/8/18. // Copyright © 2016年 ray. All rights reserved. // import UIKit class CBRedPackertCell: UITableViewCell { @IBOutlet weak var scrollView: UIScrollView! //显示数据 var model: CBRecommendWidgetListModel?{ didSet{ showData() } } //显示图片和文字 func showData(){ scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false //1.容器视图 let container = UIView.createView() scrollView.addSubview(container) container.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.scrollView) make.height.equalTo(self!.scrollView.snp_height) } //2.循环添加图片 let cnt = model?.widget_data?.count var lastView: UIView? = nil if cnt > 0{ for i in 0..<cnt! { let imageModel = model?.widget_data![i] if imageModel?.type == "image"{ let imageView = UIImageView.createImageView(nil) let url = NSURL(string: (imageModel?.content)!) imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) container.addSubview(imageView) imageView.tag = 400+i imageView.userInteractionEnabled = true //手势 let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:))) imageView.addGestureRecognizer(g) //约束 imageView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(container) make.width.equalTo(180) if i == 0{ make.left.equalTo(0) }else{ make.left.equalTo((lastView?.snp_right)!) } }) lastView = imageView } } //修改容器的大小 container.snp_makeConstraints(closure: { (make) in make.right.equalTo((lastView?.snp_right)!) }) } } func tapAction(g:UITapGestureRecognizer){ let index = (g.view?.tag)! - 400 print(index) } //创建cell的方法 class func createRedPackageCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel)->CBRedPackertCell{ let cellId = "redPackertCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRedPackertCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("CBRedPackertCell", owner: nil, options: nil).last as? CBRedPackertCell } cell?.model = listModel return cell! } 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 } }
mit
ba303d83cd09a658ce2b0394e672c5a4
23.782895
170
0.488983
5.876755
false
false
false
false
josherick/DailySpend
DailySpend/TodayViewController.swift
1
11537
// // TodayViewController.swift // DailySpend // // Created by Josh Sherick on 11/12/17. // Copyright © 2017 Josh Sherick. All rights reserved. // import UIKit import CoreData class TodayViewController: UIViewController, GoalPickerDelegate, TodayViewExpensesDelegate { let appDelegate = (UIApplication.shared.delegate as! AppDelegate) var context: NSManagedObjectContext { return appDelegate.persistentContainer.viewContext } private var summaryViewHidden: Bool = true private var summaryView: TodaySummaryView! private var neutralBarColor: UIColor! private var tableView: UITableView! private var expensesController: TodayViewExpensesController! private var cellCreator: TableViewCellHelper! var goalPicker: NavigationGoalPicker! var goal: Goal! let summaryViewHeightWithHint: CGFloat = 120 let summaryViewHeightWithoutHint: CGFloat = 97 var expenses = [(desc: String, amount: String)]() override func viewDidLoad() { super.viewDidLoad() view.tintColor = .tint NotificationCenter.default.addObserver( self, selector: #selector(updateBarTintColor), name: NSNotification.Name.init("ChangedSpendIndicationColor"), object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(dayChanged), name: NSNotification.Name.NSCalendarDayChanged, object: nil ) let width = view.frame.size.width let summaryFrame = CGRect( x: 0, y: -summaryViewHeightWithHint, width: width, height: summaryViewHeightWithHint ) summaryView = TodaySummaryView(frame: summaryFrame) // The border line hangs below the summary frame, so we'll use that one // so it slides out nicely. self.navigationController?.navigationBar.hideBorderLine() self.navigationController?.delegate = self let navHeight = navigationController?.navigationBar.frame.size.height ?? 0 let statusBarSize = UIApplication.shared.statusBarFrame.size let statusBarHeight = min(statusBarSize.width, statusBarSize.height) let tableHeight = view.frame.size.height - navHeight - statusBarHeight let tableFrame = CGRect(x: 0, y: 0, width: width, height: tableHeight) tableView = UITableView(frame: tableFrame, style: .grouped) tableView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubviews([tableView, summaryView]) tableView.topAnchor.constraint(equalTo: summaryView.bottomAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true expensesController = TodayViewExpensesController( tableView: tableView, present: self.present ) expensesController.delegate = self tableView.delegate = expensesController tableView.dataSource = expensesController goalPicker = goalPicker ?? NavigationGoalPicker() let infoButton = UIButton(type: .infoLight) infoButton.isEnabled = false infoButton.add(for: .touchUpInside, { let reviewController = ReviewViewController() reviewController.goalPicker = self.goalPicker reviewController.goal = self.goal self.navigationController?.pushViewController(reviewController, animated: true) }) let infoBBI = UIBarButtonItem(customView: infoButton) self.navigationItem.leftBarButtonItem = infoBBI } override func viewWillAppear(_ animated: Bool) { updateSummaryViewForGoal(self.goal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** * Implements TodayViewGoalsDelegate. * * Updates expenses and summary view to reflect the new goal, or if the new * goal is `nil`, puts those views into an appropriate state. */ func goalChanged(newGoal: Goal?) { self.navigationItem.leftBarButtonItem?.isEnabled = (newGoal != nil) self.goal = newGoal expensesController.loadExpensesForGoal(newGoal) updateSummaryViewForGoal(newGoal) } /** * Implements TodayViewExpensesDelegate. * * Updates the summary view to reflect any changes in data for this goal. */ func expensesChanged(goal: Goal) { if goal != self.goal { self.goal = goal goalPicker.setGoal(newGoal: goal) goalChanged(newGoal: goal) } else { updateSummaryViewForGoal(goal) } } /** * need to account fo the case where a goal has ended */ @objc func dayChanged() { } /** * Updates the summary view frame and displayed data to that of the passed * goal, or hides the summary view if the passed goal is `nil`. */ func updateSummaryViewForGoal(_ goal: Goal?) { guard let goal = goal else { animateSummaryViewFrameIfNecessary(show: false) summaryViewHidden = true return } animateSummaryViewFrameIfNecessary(show: true) summaryViewHidden = false // Update summary view with information from this goal for the // appropriate period. let newAmount = goal.balance(for: CalendarDay()).doubleValue let oldAmount = mostRecentlyUsedAmountForGoal(goal: goal) if oldAmount != newAmount { summaryView.countFrom(CGFloat(oldAmount), to: CGFloat(newAmount)) } else { summaryView.setAmount(value: CGFloat(newAmount)) } setMostRecentlyUsedAmountForGoal(goal: goal, amount: newAmount) // Determine what should be in the summary view hint and set it. var endDay: CalendarDay? if goal.isRecurring { guard let currentGoalPeriod = goal.periodInterval(for: CalendarDay().start) else { return } endDay = CalendarDay(dateInDay: currentGoalPeriod.end!).subtract(days: 1) } else if goal.end != nil { endDay = CalendarDay(dateInDay: goal.end!) } if let endDay = endDay { let dateFormatter = DateFormatter() if endDay.year == CalendarDay().year { dateFormatter.dateFormat = "M/d" } else { dateFormatter.dateFormat = "M/d/yy" } let formattedDate = endDay.string(formatter: dateFormatter) summaryView.setHint("Period End: \(formattedDate)") animateSummaryViewHeightIfNecessary(height: summaryViewHeightWithHint) } else { summaryView.setHint("") animateSummaryViewHeightIfNecessary(height: summaryViewHeightWithoutHint) } } /** * Animates sliding the summary view in or out based on the value of `show`. * * If the summary view is already believed to be in the correct state based * on the value of `summaryViewHidden`, it will not be animated. */ func animateSummaryViewFrameIfNecessary(show: Bool) { let offsetYMultiplier: CGFloat = show ? 1 : -1 let hiddenValueIndicatingSummaryViewPositionIsCorrect = show ? false : true if summaryViewHidden != hiddenValueIndicatingSummaryViewPositionIsCorrect { // Need to call layoutIfNeeded outside the animation block and // before changing the summary view frame, otherwise we could end // up animating subviews we don't mean to that haven't been // placed yet. self.view.layoutIfNeeded() UIView.animate( withDuration: 0.3, animations: { self.summaryView.frame = self.summaryView.frame.offsetBy( dx: 0, dy: self.summaryView.frame.height * offsetYMultiplier ) self.view.layoutIfNeeded() } ) } } /** * Animates changing the summary view to a certain height, if it isn't * already set to that height. */ func animateSummaryViewHeightIfNecessary(height: CGFloat) { if summaryView.frame.size.height != height { self.view.layoutIfNeeded() UIView.animate( withDuration: 0.3, animations: { var frame = self.summaryView.frame frame.size.height = height self.summaryView.frame = frame self.view.layoutIfNeeded() } ) } } /** * Returns a unique string associated with a particular goal. */ func keyForGoal(goal: Goal) -> String { let id = goal.objectID.uriRepresentation() return "mostRecentComputedAmount_\(id)" } /** * Retrieves the amount most recently displayed to the user in the summary * view, persisting across app termination. */ func mostRecentlyUsedAmountForGoal(goal: Goal) -> Double { return UserDefaults.standard.double(forKey: keyForGoal(goal: goal)) } /** * Set the amount most recently displayed to the user in the summary * view, persisting across app termination. */ func setMostRecentlyUsedAmountForGoal(goal: Goal, amount: Double) { UserDefaults.standard.set(amount, forKey: keyForGoal(goal: goal)) } /** * Updates the tint color of the navigation bar to the color specified * by the app delegate. */ @objc func updateBarTintColor() { let newColor = self.appDelegate.spendIndicationColor if self.summaryView.backgroundColor != newColor { UIView.animate(withDuration: 0.2) { self.summaryView.backgroundColor = newColor } } } } extension TodayViewController : UINavigationControllerDelegate { func navigationController( _ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController ) -> UIViewControllerAnimatedTransitioning? { let transition = ReverseNavigationAnimator() transition.forward = (operation == .push) return transition } func navigationController( _ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool ) { if viewController == self { goalPicker.delegate = self goalPicker.makeTitleView( view: navigationController.view, item: navigationItem, bar: navigationController.navigationBar, present: present, detailViewLanguage: false, buttonWidth: 50 // TODO: Make this a real number based on the button width ) self.goalChanged(newGoal: goalPicker.currentGoal) } } }
mit
dd30e5c6eb4592ec24dc870c407d989f
35.738854
94
0.626647
5.418506
false
false
false
false
LYM-mg/DemoTest
其他功能/SwiftyDemo/Pods/Alamofire/Source/ResponseSerialization.swift
41
29116
// // ResponseSerialization.swift // // Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The type in which all data response serializers must conform to in order to serialize a response. public protocol DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, data and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get } } // MARK: - /// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, data and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value> /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) { self.serializeResponse = serializeResponse } } // MARK: - /// The type in which all download response serializers must conform to in order to serialize a response. public protocol DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, url and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get } } // MARK: - /// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, url and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value> /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) { self.serializeResponse = serializeResponse } } // MARK: - Timeline extension Request { var timeline: Timeline { let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime return Timeline( requestStartTime: requestStartTime, initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) } } // MARK: - Default extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var dataResponse = DefaultDataResponse( request: self.request, response: self.response, data: self.delegate.data, error: self.delegate.error, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) completionHandler(dataResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response<T: DataResponseSerializerProtocol>( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) var dataResponse = DataResponse<T.SerializedObject>( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } } return self } } extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDownloadResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var downloadResponse = DefaultDownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, error: self.downloadDelegate.error, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) completionHandler(downloadResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data contained in the destination url. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response<T: DownloadResponseSerializerProtocol>( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.downloadDelegate.fileURL, self.downloadDelegate.error ) var downloadResponse = DownloadResponse<T.SerializedObject>( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, result: result, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } } return self } } // MARK: - Data extension Request { /// Returns a result data type that contains the response data as-is. /// /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } return .success(validData) } } extension DataRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DataResponseSerializer<Data> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseData(response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseData(response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DownloadResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } // MARK: - String extension Request { /// Returns a result string type initialized from the response data with the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseString( encoding: String.Encoding?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<String> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName)) ) } let actualEncoding = convertedEncoding ?? .isoLatin1 if let string = String(data: validData, encoding: actualEncoding) { return .success(string) } else { return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) } } } extension DataRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DataResponse<String>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DownloadResponse<String>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Any> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(json) } catch { return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DownloadResponseSerializer<Any> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DownloadResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /// Returns a plist object contained in a result type constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponsePropertyList( options: PropertyListSerialization.ReadOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Any> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) return .success(plist) } catch { return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DownloadResponseSerializer<Any> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DownloadResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set<Int> = [204, 205]
mit
812987fda189d32bfc683229bcfdf4ac
39.721678
126
0.64978
5.553309
false
false
false
false
joerocca/GitHawk
Classes/View Controllers/RootViewControllers.swift
1
2464
// // RootViewControllers.swift // Freetime // // Created by Ryan Nystrom on 5/17/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit func newSettingsRootViewController( sessionManager: GithubSessionManager, client: GithubClient, rootNavigationManager: RootNavigationManager ) -> UIViewController { guard let controller = UIStoryboard(name: "Settings", bundle: nil).instantiateInitialViewController() else { fatalError("Could not unpack settings storyboard") } if let nav = controller as? UINavigationController, let first = nav.viewControllers.first as? SettingsViewController { first.client = client first.sessionManager = sessionManager first.rootNavigationManager = rootNavigationManager nav.tabBarItem.title = NSLocalizedString("Settings", comment: "") nav.tabBarItem.image = UIImage(named: "tab-gear") nav.tabBarItem.selectedImage = UIImage(named: "tab-gear-selected") } return controller } func newNotificationsRootViewController(client: GithubClient) -> UIViewController { let controller = NotificationsViewController(client: NotificationClient(githubClient: client), showRead: false) let title = NSLocalizedString("Inbox", comment: "") controller.title = title let nav = UINavigationController(rootViewController: controller) nav.tabBarItem.title = title nav.tabBarItem.image = UIImage(named: "tab-inbox") nav.tabBarItem.selectedImage = UIImage(named: "tab-inbox-selected") return nav } func newSearchRootViewController(client: GithubClient) -> UIViewController { let controller = SearchViewController(client: client) let nav = UINavigationController(rootViewController: controller) nav.tabBarItem.title = Constants.Strings.search nav.tabBarItem.image = UIImage(named: "tab-search") nav.tabBarItem.selectedImage = UIImage(named: "tab-search-selected") return nav } func newBookmarksRootViewController(client: GithubClient) -> UIViewController { let title = Constants.Strings.bookmarks let controller = BookmarkViewController(client: client) controller.makeBackBarItemEmpty() controller.title = title let nav = UINavigationController(rootViewController: controller) nav.tabBarItem.image = UIImage(named: "tab-bookmark") nav.tabBarItem.selectedImage = UIImage(named: "tab-bookmark-selected") nav.tabBarItem.title = title return nav }
mit
09a20950cefb29bb61a9befef2f5cc89
38.725806
115
0.742996
4.877228
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/PresentControllerViewController.swift
1
1585
// // PresentControllerViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/25/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class PresentControllerViewController: UIViewController, SecondPresentControllerDelegate { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let button = UIButton(type: .system) button.setTitle("Present", for: UIControlState()) button.addTarget(self, action: #selector(PresentControllerViewController.doPresent(_:)), for: .touchUpInside) self.view.addSubview(button) button.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor) ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func doPresent(_ sender: UIButton) -> Void { let svc = SecondPresentViewController() svc.delegate = self // svc.modalTransitionStyle = .PartialCurl self.definesPresentationContext = true svc.modalPresentationStyle = .currentContext self.present(svc, animated: true, completion: nil) } func acceptData(_ data: AnyObject!) { // do nothing // self.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
9f0f7f6f76a749d5211d4dd7a24ed5c4
32
117
0.674242
5.176471
false
false
false
false
Johennes/firefox-ios
Sync/KeysPayload.swift
2
1712
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared public class KeysPayload: CleartextPayloadJSON { override public func isValid() -> Bool { // We should also call super.isValid(), but that'll fail: // Global is external, but doesn't have external or weak linkage! // Swift compiler bug #18422804. return !isError && self["default"].isArray } private func keyBundleFromPair(input: JSON) -> KeyBundle? { if let pair: [JSON] = input.asArray { if let encKey = pair[0].asString { if let hmacKey = pair[1].asString { return KeyBundle(encKeyB64: encKey, hmacKeyB64: hmacKey) } } } return nil } var defaultKeys: KeyBundle? { return self.keyBundleFromPair(self["default"]) } var collectionKeys: [String: KeyBundle] { if let collections: [String: JSON] = self["collections"].asDictionary { return optFilter(mapValues(collections, f: self.keyBundleFromPair)) } return [:] } override public func equalPayloads(obj: CleartextPayloadJSON) -> Bool { if !(obj is KeysPayload) { return false } if !super.equalPayloads(obj) { return false } let p = obj as! KeysPayload if p.defaultKeys != self.defaultKeys { return false } // TODO: check collections. return true } }
mpl-2.0
6d90a78fa75081df0b8546e676aece86
29.052632
79
0.575935
4.768802
false
false
false
false
shinobicontrols/adaptive-layout-workshop
AdaptiveWeaponry/AdaptiveWeaponry/MasterViewController.swift
1
2399
// // Copyright 2014 Scott Logic // // 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 MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil let weaponProvider = WeaponProvider() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "Weapons" } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { let indexPath = self.tableView.indexPathForSelectedRow() let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController let weapon = weaponProvider.weapons[indexPath!.row]; controller.weapon = weapon controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return weaponProvider.weapons.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let weapon = weaponProvider.weapons[indexPath.row] cell.textLabel?.text = weapon.name return cell } }
apache-2.0
37441ec7dcd41dc8eb1955e07c0a09d7
34.279412
124
0.739892
5.126068
false
false
false
false
nielubowicz/Particle-SDK
Source/Helpers/EventSource.swift
1
8009
// // EventSource.swift // ParticleSDK // // Created by Chris Nielubowicz on 12/17/15. // Copyright © 2015 Mobiquity, Inc. All rights reserved. // // ********************************************************************** // Original Header: // // EventSource.m // EventSource // // Created by Neil on 25/07/2013. // Copyright (c) 2013 Neil Cowburn. All rights reserved, // Heavily modified to match Spark event structure by Ido Kleinman, 2015 // Original codebase: // https://github.com/neilco/EventSource // ********************************************************************** import Foundation enum EventState: Int { case Connecting = 0, Open, Closed } class Event: NSObject, NSCopying { public static let MessageEvent = "message" public static let ErrorEvent = "error" public static let OpenEvent = "open" var name: String? var data: NSData? var readyState: EventState = .Connecting var error: NSError override init() { } override func description() -> String { let state: String switch self.readyState { case .Connecting: state = "CONNECTING" break case .Open: state = "OPEN" break case .Closed: state = "CLOSED" break } return "<Event: readyState: \(state), event: \(event), data: \(data)>" } func copyWithZone(zone: NSZone) -> AnyObject { let copy = self.dynamicType.initialize() as! Event copy.name = self.name copy.data = self.data copy.readyState = self.readyState copy.error = self.error return copy } } typealias EventSourceEventHandler = (event:Event) -> Void class EventSource: NSObject { static let ES_RETRY_INTERVAL = 1.0 static let ESKeyValueDelimiter = ": " static let ESEventSeparatorLFLF = "\n\n" static let ESEventSeparatorCRCR = "\r\r" static let ESEventSeparatorCRLFCRLF = "\r\n\r\n" static let ESEventKeyValuePairSeparator = "\n" static let ESEventDataKey = "data" static let ESEventEventKey = "event" private var wasClosed = false var eventURL: NSURL var eventSource: NSURLConnection? lazy var listeners: NSMutableDictionary = NSMutableDictionary() var timeoutInterval: NSTimeInterval var retryInterval: NSTimeInterval var lastEventID: AnyObject? var queue: dispatch_queue_t? var accessToken: String lazy var event: Event = Event() class func eventSource(withURL: NSURL, timeoutInterval: NSTimeInterval, queue:dispatch_queue_t, accessToken: String)->EventSource{ return EventSource(withURL: withURL, timeoutInterval: timeoutInterval, queue: queue, accessToken: accessToken) } init(withURL:NSURL, timeoutInterval: NSTimeInterval, queue:dispatch_queue_t, accessToken: String) { eventURL = withURL self.timeoutInterval = timeoutInterval retryInterval = EventSource.ES_RETRY_INTERVAL self.queue = queue self.accessToken = accessToken let popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)) dispatch_after(popTime, queue, { () -> Void in self.open() }) } func addEventListener(eventName:String, handler:EventSourceEventHandler) { guard self.listeners[eventName] != nil else { self.listeners[eventName] = () } if let listeners = self.listeners[eventName] { listeners.addObject(handler) } } func removeEventListener(eventName:String, handler:EventSourceEventHandler) { guard self.listeners[eventName] != nil else { return } if let listeners = self.listeners[eventName] { listeners.removeObject(handler) } } func onMessage(handler:EventSourceEventHandler) { addEventListener(Event.MessageEvent, handler: handler) } func onError(handler:EventSourceEventHandler) { addEventListener(Event.ErrorEvent, handler: handler) } func onOpen(handler:EventSourceEventHandler) { addEventListener(Event.OpenEvent, handler: handler) } func open() { wasClosed = false let request = NSMutableURLRequest(URL: eventURL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeoutInterval) if let lastEventID = lastEventID { request.setValue(lastEventID, forHTTPHeaderField: "Last-Event-ID") } request.addValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization") request.HTTPMethod = "GET" eventSource = NSURLConnection(request: request, delegate: self, startImmediately: true) if NSThread.isMainThread() == false { CFRunLoopRun() } } func close() { wasClosed = true eventSource?.cancel() queue = nil } } extension EventSource: NSURLConnectionDelegate, NSURLConnectionDataDelegate { func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { let httpResponse = response as NSHTTPURLResponse guard httpResponse.statusCode == 200 else { print("Error opening event stream, code \(httpResponse.statusCode)"); return } let e = Event() e.readyState = EventState.Open listeners[Event.OpenEvent].forEach({ dispatch_async(queue, { (handler) -> Void in handler(e) })}) } func connection(connection: NSURLConnection, didFailWithError error: NSError) { let e = Event() e.readyState = EventState.Closed e.error = error listeners[Event.ErrorEvent].forEach({ dispatch_async(queue, { (handler) -> Void in handler(e) })}) let popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)) dispatch_after(popTime, queue, { () -> Void in self.open() }) } func connection(connection: NSURLConnection, didReceiveData data: NSData) { let eventString = NSString(data: data, encoding: NSUTF8StringEncoding)? .stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) let components = eventString?.componentsSeparatedByString(EventSource.ESEventKeyValuePairSeparator) event.readyState = EventState.Open components?.forEach({ (component) -> () in guard component.characters.isEmpty == false else { continue } let index = component.rangeOfString(EventSource.ESKeyValueDelimiter)?.location guard index != NSNotFound && index != component.characters.count - 2 else { continue } let key = component.substringToIndex(index) let value = component.substringFromIndex(index + EventSource.ESKeyValueDelimiter.characters.count) if key == EventSource.ESEventEventKey { event.name = value } else if key == EventSource.ESEventDataKey { event.data = value.dataUsingEncoding(NSUTF8StringEncoding) } guard let name = event.name, data = event.data else { continue } let sendEvent = event.copy() listeners[Event.MessageEvent].forEach({ (handler) -> () in handler(sendEvent) }) event = Event() }) } func connectionDidFinishLoading(connection: NSURLConnection) { guard wasClosed == false else { return } e = Event() e.readyState = EventState.Closed e.error = NSError(domain: "", code: e.readyState, userInfo: [NSLocalizedDescriptionKey: "Connection with the event source was closed" ]) listeners[Event.ErrorEvent].forEach({ (handler) -> () in handler(e) }) open() } }
mit
8fa2e5d9817b441b7c12721f0a879843
32.651261
144
0.617258
4.983199
false
false
false
false
emiscience/SPUndoManager
SPUndoManager/SPUndoAction.swift
2
1837
import Foundation protocol SPUndoManagerAction { var done: Bool { get } func undo() func redo() var description: String { get } } class SPUndoManagerStandardAction : SPUndoManagerAction { /// Assumes action already performed init(description: String, forwards: Closure, backwards: Closure) { self.forwards = forwards self.backwards = backwards self.description = description self.done = true } var done: Bool var backwards: Closure var forwards: Closure var description: String func undo() { assert(done) backwards() done = false } func redo() { assert(!done) forwards() done = true } } class SPUndoManagerSuperDynamicAction : SPUndoManagerAction { var undoable: Undoable var description: String /// Assumes action performed, in 'done' state by default init(undoable: Undoable) { self.undoable = undoable self.description = undoable.description self.done = true } var done: Bool func undo() { assert(done) self.undoable = undoable.undo() done = false } func redo() { assert(!done) self.undoable = undoable.undo() done = true } } class SPUndoManagerGroupAction : SPUndoManagerAction { init(description: String) { self.description = description } var done: Bool = false var nestedActions = [SPUndoManagerAction]() func undo() { assert(done) self.nestedActions.eachBackwards { $0.undo() } done = false } func redo() { assert(!done) self.nestedActions.eachForwards { $0.redo() } done = true } var description: String }
mit
7ac9318ea0e61f8ec26b1e83ac7ca638
19.886364
70
0.581383
4.69821
false
false
false
false
peaks-cc/iOS11_samplecode
chapter_12/HomeKitSample/App/Code/Controller/CharacteristicWriteActionViewController.swift
1
2242
// // CharacteristicWriteActionViewController.swift // // Created by ToKoRo on 2017-08-22. // import UIKit import HomeKit class CharacteristicWriteActionViewController: UITableViewController, ContextHandler { typealias ContextType = HMAction @IBOutlet weak var typeLabel: UILabel? @IBOutlet weak var targetValueLabel: UILabel? @IBOutlet weak var characteristicLabel: UILabel? var action: HMAction { return context! } lazy var numberWriteAction: HMCharacteristicWriteAction<NSNumber>? = { action as? HMCharacteristicWriteAction<NSNumber> }() override func viewDidLoad() { super.viewDidLoad() refresh() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setToolbarHidden(false, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "Characteristic"?: if let numberWriteAction = numberWriteAction { sendContext(numberWriteAction.characteristic, to: segue.destination) } default: break } } private func refresh() { typeLabel?.text = { return String(describing: type(of: action)) }() targetValueLabel?.text = { guard let numberWriteAction = numberWriteAction else { return nil } return String(describing: numberWriteAction.targetValue) }() characteristicLabel?.text = { if let numberWriteAction = numberWriteAction { return CharacteristicType(typeString: numberWriteAction.characteristic.characteristicType).description } return nil }() } } // MARK: - Actions extension CharacteristicWriteActionViewController { @IBAction func removeButtonDidTap(sender: AnyObject) { ResponderChain(from: self).send(action, protocol: ActionActionHandler.self) { [weak self] action, handler in handler.handleRemove(action) DispatchQueue.main.async { self?.navigationController?.popViewController(animated: true) } } } }
mit
2822eddd564a1ba51a4401a875e6424e
28.5
127
0.648528
5.5086
false
false
false
false
pawan007/SmartZip
SmartZip/Controllers/Tutorial/TutorialVC.swift
1
5315
// // TutorialVC.swift // SmartZip // // Created by Narender Kumar on 17/07/16. // Copyright © 2016 Pawan Kumar. All rights reserved. // import Foundation import UIKit class TutorialVC: UIViewController, MYIntroductionDelegate { var introductionView:MYIntroductionView? = nil @IBOutlet weak var introView: UIView! @IBOutlet weak var btnSkip: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.showTutorial() } func showTutorial() { let panel: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut-1")!, description: "This is the home screen of SmartZip application. In this screen user has options to work with local files as well as cloud files. In local, user can explore, share, zip, unzip and delete files. In cloud, user user can download files and share with other devices.") let panel2: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut-2")!, description: "With Photos and Videos option in home screen user can select multiple photos or multiple videos for the creation of zip file.") let panel3: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut-3")!, description: "After selection, a zip will be created, having all selcted photos or videos. That zip can be unzipped, viewed or shared among other devices.") /*let panel4: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut_4.png")!, description: "Like Photos and Videos option in home screen, user can select songs from their device with Music option. A zip file will be created from selected songs. That zip file will perform operations as it performs in Photos and Videos.") let panel5: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut_5.png")!, description: "User can select their files from Dropbox. Selected files will download from Dropbox server. SmartZip will create zip file from downloaded file. Afterwords that zip file is ready to work") let panel6: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut_6.png")!, description: "User can select their files from Google Drive also. Selected files will download from Google Drive server. SmartZip will create zip file from downloaded file. Afterwords that zip file is ready to work") let panel7: MYIntroductionPanel = MYIntroductionPanel(image: UIImage(named: "tut_8.png")!, description: "All other options are in left menu/drawer. If you want to go on home screen, tap on Home. If you want to see this tutorial again tap on Tutorial. Want to get ad free app tap on Buy Pro. If you have done payment before, tap on Restore. If you want to share SmartZip, rate SmartZip or want to email us, options are given respectievely.")*/ if ( introductionView == nil) { introductionView = MYIntroductionView(frame: CGRectMake(0, 0, introView.frame.size.width, introView.frame.size.height), headerImage: UIImage(named: "SampleHeaderImage")!, panels: [panel, panel2, panel3]) introductionView!.setHeaderText("SmartZip") introductionView!.HeaderImageView.autoresizingMask = .FlexibleWidth introductionView!.HeaderLabel.autoresizingMask = .FlexibleWidth introductionView!.HeaderView.autoresizingMask = .FlexibleWidth introductionView!.PageControl.autoresizingMask = .FlexibleWidth introductionView!.SkipButton.autoresizingMask = .FlexibleWidth introductionView!.SkipButton.hidden = true introductionView!.delegate = self introductionView!.showInView(introView, animateDuration: 0.1) } } func introductionDidFinishWithType(finishType: MYFinishType) { // if(introductionView != nil) { introductionView?.removeFromSuperview() introductionView = nil self.showTutorial() } } func introductionDidChangeToPanel(panel: MYIntroductionPanel!, withIndex panelIndex: Int) { // print(panelIndex) if panelIndex == 6 { btnSkip.title = "Done" }else{ btnSkip.title = "Skip" } } @IBAction func menuButtonAction(sender: AnyObject) { if let container = SideMenuManager.sharedManager().container { container.toggleDrawerSide(.Left, animated: true) { (val) -> Void in } } } @IBAction func btnSkipTapped(sender: AnyObject) { if let container = SideMenuManager.sharedManager().container { container.toggleDrawerSide(.Left, animated: true) { (val) -> Void in let vc = container.leftDrawerViewController as! LeftMenuViewController vc.tableView(vc.topTableView, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0)) } } } }
mit
83e9a845004bd9186ff67f10253961b2
46.873874
451
0.665224
5.303393
false
false
false
false
lelandjansen/fatigue
ios/fatigue/YesNoQuestion.swift
1
2202
import Foundation class YesNoQuestion: Question, QuestionnaireItem { enum Answer: String { case none = "", yes = "Yes", no = "No" } var id: Questionnaire.QuestionId var question: String var details: String var description: String var options: [String] = [Answer.yes.rawValue, Answer.no.rawValue] var selection: String = Answer.none.rawValue { didSet { switch selection { case Answer.yes.rawValue: nextItem = nextItemIfYes case Answer.no.rawValue: nextItem = nextItemIfNo default: nextItem = nil } } } var nextItem: QuestionnaireItem? var nextItemIfYes: QuestionnaireItem? var nextItemIfNo: QuestionnaireItem? var riskScoreContribution: (String) -> Int32 init(id: Questionnaire.QuestionId, question: String, details: String = String(), description: String, riskScoreContribution: @escaping (String) -> Int32, nextItemIfYes: QuestionnaireItem, nextItemIfNo: QuestionnaireItem) { self.id = id self.question = question self.details = details self.description = description self.riskScoreContribution = riskScoreContribution self.nextItemIfYes = nextItemIfYes self.nextItemIfNo = nextItemIfNo } init(id: Questionnaire.QuestionId, question: String, details: String = String(), description: String, riskScoreContribution: @escaping (String) -> Int32, nextItem: QuestionnaireItem) { self.id = id self.question = question self.details = details self.description = description self.riskScoreContribution = riskScoreContribution self.nextItemIfYes = nextItem self.nextItemIfNo = nextItem } init(id: Questionnaire.QuestionId, question: String, riskScoreContribution: @escaping (String) -> Int32, details: String = String(), description: String) { self.id = id self.question = question self.details = details self.description = description self.description = description self.riskScoreContribution = riskScoreContribution } }
apache-2.0
5438813da2d8a6941dbcd05687bd7774
36.965517
226
0.652134
5.14486
false
false
false
false
Ben21hao/edx-app-ios-enterprise-new
Source/LiveObjectCache.swift
3
2280
// // LiveObjectCache.swift // edX // // Created by Akiva Leffert on 10/28/15. // Copyright © 2015 edX. All rights reserved. // import Foundation public protocol LifetimeTrackable : class { /// Lifetime should be associated with Self such that it gets deallocated when the object owning /// get deallocated var lifetimeToken : NSObject { get } } extension NSObject : LifetimeTrackable { public var lifetimeToken : NSObject { return self } } private struct Weak<A : AnyObject> { weak var value : A? init(_ value : A) { self.value = value } } /// Cache that doesn't clear an object as long as it has live pointers /// this way you don't end up with duplicated objects when the memory cache gets flushed. public class LiveObjectCache<A : LifetimeTrackable> : NSObject { private let dataCache = NSCache() private var activeObjects : [String : Weak<A>] = [:] private var deallocActionRemovers : [Removable] = [] override public init() { super.init() NSNotificationCenter.defaultCenter().oex_addObserver(self, name: UIApplicationDidReceiveMemoryWarningNotification) { (_, owner, _) -> Void in owner.dataCache.removeAllObjects() } } public func objectForKey(key : String, @noescape generator : () -> A) -> A { // first look in the active objects cache if let object = activeObjects[key]?.value { dataCache.setObject(Box(object), forKey: key) return object } else if let object = dataCache.objectForKey(key) as? Box<A> { return object.value } else { let object = generator() dataCache.setObject(Box(object), forKey: key) activeObjects[key] = Weak(object) let removable = object.lifetimeToken.oex_performActionOnDealloc {[weak self] in self?.activeObjects.removeValueForKey(key) } deallocActionRemovers.append(BlockRemovable{removable.remove()}) return object } } public func empty() { dataCache.removeAllObjects() activeObjects = [:] for actionRemover in deallocActionRemovers { actionRemover.remove() } } }
apache-2.0
1549e0391d38d4450a0893b6604cfedf
30.666667
149
0.627029
4.65102
false
false
false
false
eCrowdMedia/MooApi
Sources/helper/AccountData.swift
1
1710
import Foundation public struct AccountData { public let email: String public let password: String public let clientID: String public let clientSecret: String public let uuid: String public init(email: String, password: String, clientID: String, clientSecret: String, uuid: String) { self.email = email self.password = password self.clientID = clientID self.clientSecret = clientSecret self.uuid = uuid } public var base64Credentials: String? { return "\(clientID):\(clientSecret)" .data(using: .utf8)? .base64EncodedString(options: []) } public var scope: String? { return "reading highlight like comment me library" .addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) } public var encodingPassword: String? { return password.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved) } public var encodingEmail: String? { return email.addingPercentEncoding(withAllowedCharacters: .rfc3986Unreserved) } public func makeJsonData() -> Data? { guard let email = encodingEmail, let password = encodingPassword, let scope = scope else { return nil } let optionalBody = [ "grant_type": "password", "udid": uuid, "username": email, "password": password, "scope": scope ] .map({ "\($0)=\($1)" }) .joined(separator: "&") .data(using: .utf8) return optionalBody } public func makeAuthorization() -> Authorization? { guard let credentials = base64Credentials else { return nil } return Authorization.basic(credentials) } }
mit
414372228b3fbcce7b3dcb2cde3b741a
24.522388
84
0.64269
4.710744
false
false
false
false
sclark01/Swift_VIPER_Demo
VIPER_Demo/VIPER_DemoTests/EntitiesTests/PersonTests.swift
1
1919
import Foundation import Quick import Nimble @testable import VIPER_Demo class PersonTests : QuickSpec { override func spec() { describe("a person") { it("should be equal when they have the same value for phone, name, and age") { let person1 = Person(id: 0, name: "someName", phone: "somePhone", age: "someAge") let person2 = Person(id: 0, name: "someName", phone: "somePhone", age: "someAge") expect(person1) == person2 } it("should be equal when they have the same value for phone, name, and age, but a different ID") { let person1 = Person(id: 0, name: "someName", phone: "somePhone", age: "someAge") let person2 = Person(id: 1, name: "someName", phone: "somePhone", age: "someAge") expect(person1) == person2 } it("should not be equal when they have a different value for name") { let person1 = Person(id: 0, name: "someName", phone: "somePhone", age: "someAge") let person2 = Person(id: 1, name: "differentName", phone: "somePhone", age: "someAge") expect(person1) != person2 } it("should not be equal when they have a different value for phone") { let person1 = Person(id: 0, name: "someName", phone: "somePhone", age: "someAge") let person2 = Person(id: 1, name: "someName", phone: "differentPhone", age: "someAge") expect(person1) != person2 } it("should not be equal when they have a different value for age") { let person1 = Person(id: 0, name: "someName", phone: "somePhone", age: "someAge") let person2 = Person(id: 1, name: "someName", phone: "somePhone", age: "differentAge") expect(person1) != person2 } } } }
mit
090e2c1d8b5fcab6e167ac6966f6a2ce
40.73913
110
0.55654
4.180828
false
false
false
false
descorp/SwiftPlayground
General.playground/Pages/Reflections.xcplaygroundpage/Contents.swift
1
2344
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) public protocol OpenAirDTO: class { static var datatype: String { get } } public extension OpenAirDTO { static var datatype: String { return NSStringFromClass(self).components(separatedBy: ".").last! } } extension Array where Element == String { var xml: String { return self.reduce("\r") { (current, next) in return current + next + "\r" } } } func unwrap<T>(_ any: T) -> Any { let mirror = Mirror(reflecting: any) guard mirror.displayStyle == .optional, let first = mirror.children.first else { return any } return unwrap(first.value) } class Book: OpenAirDTO { let title: String let author: String? let published: Date let numberOfPages: Int let chapterCount: Int? let genres: [String] let stuff: String? = nil init(title: String, author: String?, published: Date, numberOfPages: Int, chapterCount: Int?, genres: [String]) { self.title = title self.author = author self.published = published self.numberOfPages = numberOfPages self.chapterCount = chapterCount self.genres = genres } var xml: String { let keys = Mirror(reflecting: self).children.flatMap { $0.label } let values = Mirror(reflecting: self).children.flatMap { unwrap($0.value) as! AnyObject } var dict = Dictionary(uniqueKeysWithValues: zip(keys, values)) var keysToRemove = dict.keys.filter{ dict[$0] is NSNull } for key in keysToRemove { dict.removeValue(forKey: key) } var parameters: [String] = [] let typename = type(of: self).datatype for (name, value) in dict { parameters.append("<\(name)>\(value)<\\\(name)>") } return "<\(typename)>\(parameters.xml)<\\\(typename)>" } } class SomeClass { var A: String var B: Int var C: Book init(a: String, b: Int, c: Book) { A = a B = b C = c } } let book = Book(title: "Harry Potter", author: "J.K. Rowling", published: Date(), numberOfPages: 450, chapterCount: 19, genres: ["Fantasy", "Best books ever"]) print(book.xml) print("✅")
mit
03994bb6088ef36c9f80eb5fe3048bcf
24.736264
159
0.587105
4.051903
false
false
false
false
steryokhin/AsciiArtPlayer
src/AsciiArtPlayer/Pods/R.swift.Library/Library/Core/ColorResource.swift
16
1081
// // ColorResource.swift // R.swift.Library // // Created by Tom Lokhorst on 2016-03-13. // From: https://github.com/mac-cain13/R.swift.Library // License: MIT License // import Foundation public protocol ColorResourceType { /// Name of the color var name: String { get } /// Red componenent of color var red: CGFloat { get } /// Green componenent of color var green: CGFloat { get } /// Blue componenent of color var blue: CGFloat { get } /// Alpha componenent of color var alpha: CGFloat { get } } public struct ColorResource: ColorResourceType { /// Name of the color public let name: String /// Red componenent of color public let red: CGFloat /// Green componenent of color public let green: CGFloat /// Blue componenent of color public let blue: CGFloat /// Alpha componenent of color public let alpha: CGFloat public init(name: String, red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { self.name = name self.red = red self.green = green self.blue = blue self.alpha = alpha } }
mit
1adbc9ae8bb21753a629d6b8329c9b8e
19.018519
90
0.670675
3.930909
false
false
false
false
tjw/swift
stdlib/public/core/ArrayBuffer.swift
1
17924
//===--- ArrayBuffer.swift - Dynamic storage for Swift Array --------------===// // // 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 // //===----------------------------------------------------------------------===// // // This is the class that implements the storage and object management for // Swift Array. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims internal typealias _ArrayBridgeStorage = _BridgeStorage<_ContiguousArrayStorageBase, _NSArrayCore> @usableFromInline @_fixed_layout internal struct _ArrayBuffer<Element> : _ArrayBufferProtocol { /// Create an empty buffer. @inlinable internal init() { _storage = _ArrayBridgeStorage(native: _emptyArrayStorage) } @inlinable internal init(nsArray: _NSArrayCore) { _sanityCheck(_isClassOrObjCExistential(Element.self)) _storage = _ArrayBridgeStorage(objC: nsArray) } /// Returns an `_ArrayBuffer<U>` containing the same elements. /// /// - Precondition: The elements actually have dynamic type `U`, and `U` /// is a class or `@objc` existential. @inlinable internal func cast<U>(toBufferOf _: U.Type) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) return _ArrayBuffer<U>(storage: _storage) } /// The spare bits that are set when a native array needs deferred /// element type checking. @inlinable internal var deferredTypeCheckMask: Int { return 1 } /// Returns an `_ArrayBuffer<U>` containing the same elements, /// deferring checking each element's `U`-ness until it is accessed. /// /// - Precondition: `U` is a class or `@objc` existential derived from /// `Element`. @inlinable internal func downcast<U>( toBufferWithDeferredTypeCheckOf _: U.Type ) -> _ArrayBuffer<U> { _sanityCheck(_isClassOrObjCExistential(Element.self)) _sanityCheck(_isClassOrObjCExistential(U.self)) // FIXME: can't check that U is derived from Element pending // <rdar://problem/20028320> generic metatype casting doesn't work // _sanityCheck(U.self is Element.Type) return _ArrayBuffer<U>( storage: _ArrayBridgeStorage( native: _native._storage, bits: deferredTypeCheckMask)) } @inlinable internal var needsElementTypeCheck: Bool { // NSArray's need an element typecheck when the element type isn't AnyObject return !_isNativeTypeChecked && !(AnyObject.self is Element.Type) } //===--- private --------------------------------------------------------===// @inlinable internal init(storage: _ArrayBridgeStorage) { _storage = storage } @usableFromInline internal var _storage: _ArrayBridgeStorage } extension _ArrayBuffer { /// Adopt the storage of `source`. @inlinable internal init(_buffer source: NativeBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") _storage = _ArrayBridgeStorage(native: source._storage) } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var arrayPropertyIsNativeTypeChecked: Bool { return _isNativeTypeChecked } /// Returns `true` iff this buffer's storage is uniquely-referenced. @inlinable internal mutating func isUniquelyReferenced() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferenced_native_noSpareBits() } // This is a performance optimization. This code used to be: // // return _storage.isUniquelyReferencedNative() && _isNative. // // SR-6437 if !_storage.isUniquelyReferencedNative() { return false } return _isNative } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. @inlinable internal mutating func isUniquelyReferencedOrPinned() -> Bool { if !_isClassOrObjCExistential(Element.self) { return _storage.isUniquelyReferencedOrPinned_native_noSpareBits() } // This is a performance optimization. This code used to be: // // return _storage.isUniquelyReferencedOrPinnedNative() && _isNative. // // SR-6437 if !_storage.isUniquelyReferencedOrPinnedNative() { return false } return _isNative } /// Convert to an NSArray. /// /// O(1) if the element type is bridged verbatim, O(*n*) otherwise. @inlinable internal func _asCocoaArray() -> _NSArrayCore { return _fastPath(_isNative) ? _native._asCocoaArray() : _nonNative } /// If this buffer is backed by a uniquely-referenced mutable /// `_ContiguousArrayBuffer` that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns `nil`. @inlinable internal mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> NativeBuffer? { if _fastPath(isUniquelyReferenced()) { let b = _native if _fastPath(b.capacity >= minimumCapacity) { return b } } return nil } @inlinable internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @inlinable internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @inlinable internal func requestNativeBuffer() -> NativeBuffer? { if !_isClassOrObjCExistential(Element.self) { return _native } return _fastPath(_storage.isNative) ? _native : nil } // We have two versions of type check: one that takes a range and the other // checks one element. The reason for this is that the ARC optimizer does not // handle loops atm. and so can get blocked by the presence of a loop (over // the range). This loop is not necessary for a single element access. @inlinable @inline(never) internal func _typeCheckSlowPath(_ index: Int) { if _fastPath(_isNative) { let element: AnyObject = cast(toBufferOf: AnyObject.self)._native[index] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { let ns = _nonNative _precondition( ns.objectAt(index) is Element, "NSArray element failed to match the Swift Array Element type") } } @inlinable internal func _typeCheck(_ subRange: Range<Int>) { if !_isClassOrObjCExistential(Element.self) { return } if _slowPath(needsElementTypeCheck) { // Could be sped up, e.g. by using // enumerateObjectsAtIndexes:options:usingBlock: in the // non-native case. for i in subRange.lowerBound ..< subRange.upperBound { _typeCheckSlowPath(i) } } } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @inlinable @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _typeCheck(bounds) if _fastPath(_isNative) { return _native._copyContents(subRange: bounds, initializing: target) } let nonNative = _nonNative let nsSubRange = SwiftShims._SwiftNSRange( location: bounds.lowerBound, length: bounds.upperBound - bounds.lowerBound) let buffer = UnsafeMutableRawPointer(target).assumingMemoryBound( to: AnyObject.self) // Copies the references out of the NSArray without retaining them nonNative.getObjects(buffer, range: nsSubRange) // Make another pass to retain the copied objects var result = target for _ in bounds { result.initialize(to: result.pointee) result += 1 } return result } /// Returns a `_SliceBuffer` containing the given sub-range of elements in /// `bounds` from this buffer. @inlinable internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { _typeCheck(bounds) if _fastPath(_isNative) { return _native[bounds] } let boundsCount = bounds.count if boundsCount == 0 { return _SliceBuffer( _buffer: _ContiguousArrayBuffer<Element>(), shiftedToStartIndex: bounds.lowerBound) } // Look for contiguous storage in the NSArray let nonNative = self._nonNative let cocoa = _CocoaArrayWrapper(nonNative) let cocoaStorageBaseAddress = cocoa.contiguousStorage(self.indices) if let cocoaStorageBaseAddress = cocoaStorageBaseAddress { let basePtr = UnsafeMutableRawPointer(cocoaStorageBaseAddress) .assumingMemoryBound(to: Element.self) return _SliceBuffer( owner: nonNative, subscriptBaseAddress: basePtr, indices: bounds, hasNativeBuffer: false) } // No contiguous storage found; we must allocate let result = _ContiguousArrayBuffer<Element>( _uninitializedCount: boundsCount, minimumCapacity: 0) // Tell Cocoa to copy the objects into our storage cocoa.buffer.getObjects( UnsafeMutableRawPointer(result.firstElementAddress) .assumingMemoryBound(to: AnyObject.self), range: _SwiftNSRange(location: bounds.lowerBound, length: boundsCount)) return _SliceBuffer( _buffer: result, shiftedToStartIndex: bounds.lowerBound) } set { fatalError("not implemented") } } /// A pointer to the first element. /// /// - Precondition: The elements are known to be stored contiguously. @inlinable internal var firstElementAddress: UnsafeMutablePointer<Element> { _sanityCheck(_isNative, "must be a native buffer") return _native.firstElementAddress } @inlinable internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return _fastPath(_isNative) ? firstElementAddress : nil } /// The number of elements the buffer stores. @inlinable internal var count: Int { @inline(__always) get { return _fastPath(_isNative) ? _native.count : _nonNative.count } set { _sanityCheck(_isNative, "attempting to update count of Cocoa array") _native.count = newValue } } /// Traps if an inout violation is detected or if the buffer is /// native and the subscript is out of range. /// /// wasNative == _isNative in the absence of inout violations. /// Because the optimizer can hoist the original check it might have /// been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeBounds(_ index: Int, wasNative: Bool) { _precondition( _isNative == wasNative, "inout rules were violated: the array was overwritten") if _fastPath(wasNative) { _native._checkValidSubscript(index) } } // TODO: gyb this /// Traps if an inout violation is detected or if the buffer is /// native and typechecked and the subscript is out of range. /// /// wasNativeTypeChecked == _isNativeTypeChecked in the absence of /// inout violations. Because the optimizer can hoist the original /// check it might have been invalidated by illegal user code. @inlinable internal func _checkInoutAndNativeTypeCheckedBounds( _ index: Int, wasNativeTypeChecked: Bool ) { _precondition( _isNativeTypeChecked == wasNativeTypeChecked, "inout rules were violated: the array was overwritten") if _fastPath(wasNativeTypeChecked) { _native._checkValidSubscript(index) } } /// The number of elements the buffer can store without reallocation. @inlinable internal var capacity: Int { return _fastPath(_isNative) ? _native.capacity : _nonNative.count } @inlinable @inline(__always) internal func getElement(_ i: Int, wasNativeTypeChecked: Bool) -> Element { if _fastPath(wasNativeTypeChecked) { return _nativeTypeChecked[i] } return unsafeBitCast(_getElementSlowPath(i), to: Element.self) } @inlinable @inline(never) internal func _getElementSlowPath(_ i: Int) -> AnyObject { _sanityCheck( _isClassOrObjCExistential(Element.self), "Only single reference elements can be indexed here.") let element: AnyObject if _isNative { // _checkInoutAndNativeTypeCheckedBounds does no subscript // checking for the native un-typechecked case. Therefore we // have to do it here. _native._checkValidSubscript(i) element = cast(toBufferOf: AnyObject.self)._native[i] _precondition( element is Element, "Down-casted Array element failed to match the target type") } else { // ObjC arrays do their own subscript checking. element = _nonNative.objectAt(i) _precondition( element is Element, "NSArray element failed to match the Swift Array Element type") } return element } /// Get or set the value of the ith element. @inlinable internal subscript(i: Int) -> Element { get { return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked) } nonmutating set { if _fastPath(_isNative) { _native[i] = newValue } else { var refCopy = self refCopy.replaceSubrange( i..<(i + 1), with: 1, elementsOf: CollectionOfOne(newValue)) } } } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. @inlinable internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { if _fastPath(_isNative) { defer { _fixLifetime(self) } return try body( UnsafeBufferPointer(start: firstElementAddress, count: count)) } return try ContiguousArray(self).withUnsafeBufferPointer(body) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. /// /// - Precondition: Such contiguous storage exists or the buffer is empty. @inlinable internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _sanityCheck( _isNative || count == 0, "Array is bridging an opaque NSArray; can't get a pointer to the elements" ) defer { _fixLifetime(self) } return try body(UnsafeMutableBufferPointer( start: firstElementAddressIfContiguous, count: count)) } /// An object that keeps the elements stored in this buffer alive. @inlinable internal var owner: AnyObject { return _fastPath(_isNative) ? _native._storage : _nonNative } /// An object that keeps the elements stored in this buffer alive. /// /// - Precondition: This buffer is backed by a `_ContiguousArrayBuffer`. @inlinable internal var nativeOwner: AnyObject { _sanityCheck(_isNative, "Expect a native array") return _native._storage } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. @inlinable internal var identity: UnsafeRawPointer { if _isNative { return _native.identity } else { return UnsafeRawPointer(Unmanaged.passUnretained(_nonNative).toOpaque()) } } //===--- Collection conformance -------------------------------------===// /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable internal 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 /// `index(after:)`. @inlinable internal var endIndex: Int { return count } internal typealias Indices = Range<Int> //===--- private --------------------------------------------------------===// internal typealias Storage = _ContiguousArrayStorage<Element> internal typealias NativeBuffer = _ContiguousArrayBuffer<Element> @inlinable internal var _isNative: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNative } } /// `true`, if the array is native and does not need a deferred type check. @inlinable internal var _isNativeTypeChecked: Bool { if !_isClassOrObjCExistential(Element.self) { return true } else { return _storage.isNativeWithClearedSpareBits(deferredTypeCheckMask) } } /// Our native representation. /// /// - Precondition: `_isNative`. @inlinable internal var _native: NativeBuffer { return NativeBuffer( _isClassOrObjCExistential(Element.self) ? _storage.nativeInstance : _storage.nativeInstance_noSpareBits) } /// Fast access to the native representation. /// /// - Precondition: `_isNativeTypeChecked`. @inlinable internal var _nativeTypeChecked: NativeBuffer { return NativeBuffer(_storage.nativeInstance_noSpareBits) } @inlinable internal var _nonNative: _NSArrayCore { @inline(__always) get { _sanityCheck(_isClassOrObjCExistential(Element.self)) return _storage.objCInstance } } } #endif
apache-2.0
0b9075d0dc060ffe0b1b250f3736c039
30.390543
80
0.668545
4.857453
false
false
false
false
merlos/iOS-Open-GPX-Tracker
Pods/CoreGPX/Classes/GPXWaypointProtocol.swift
1
4986
// // GPXWaypointProtocol.swift // Pods // // Created by Vincent Neo on 13/6/20. // import Foundation public protocol GPXWaypointProtocol: GPXElement { // MARK:- Attributes of a waypoint /// Elevation of current point /// /// Should be in unit **meters** (m) var elevation: Double? { get set } /// Date and time of current point /// /// Should be in **Coordinated Universal Time (UTC)**, without offsets, not local time. var time: Date? { get set } /// Magnetic Variation of current point /// /// Should be in unit **degrees** (º) var magneticVariation: Double? { get set } /// Geoid Height of current point /// /// Should be in unit **meters** (m). Height of geoid, or mean sea level, above WGS84 earth ellipsoid var geoidHeight: Double? { get set } /// Name of current point /// /// - Warning: /// - This attribute may not be useful, in schema context. /// - This is carried over from GPX schema, to be compliant with the schema. var name: String? { get set } /// Comment of current point /// /// - Warning: /// - This attribute may not be useful, in schema context. /// - This is carried over from GPX schema, to be compliant with the schema. var comment: String? { get set } /// Description of current point /// /// - Warning: /// - This attribute may not be useful, in schema context. /// - This is carried over from GPX schema, to be compliant with the schema. var desc: String? { get set } /// Source of data of current point /// /// For assurance that current point is reliable var source: String? { get set } /// Text of GPS symbol name /// /// - Warning: /// - This attribute does not appear to be useful due to `CoreLocation` API. /// - This is carried over from GPX schema, to be compliant with the schema. var symbol: String? { get set } /// Type of current point var type: String? { get set } /// Type of GPS fix of current point, represented as a number /// /// - **Supported Types:** (written in order) /// - **None**: No fix /// - **2D**: Position only /// - **3D**: Position and Elevation /// - **DGPS**: Differential GPS /// - **PPS**: Military Signal /// /// Unknown fix should leave fix attribute as `nil` /// - Warning: /// - This attribute may have limited usefulness due to `CoreLocation` API. /// - This is carried over from GPX schema, to be compliant with the schema. var fix: GPXFix? { get set } /// Number of satellites used to calculate GPS fix of current point var satellites: Int? { get set } /// Horizontal dilution of precision of current point var horizontalDilution: Double? { get set } /// Vertical dilution of precision of current point var verticalDilution: Double? { get set } /// Position dilution of precision of current point var positionDilution: Double? { get set } /// Age of DGPS Data /// /// Number of seconds since last DGPS update /// /// - Warning: /// - This attribute may not be useful. /// - This is carried over from GPX schema, to be compliant with the schema. var ageofDGPSData: Double? { get set } /// DGPS' ID /// /// ID of DGPS station used in differential correction. /// /// - Warning: /// - This attribute may not be useful. /// - This is carried over from GPX schema, to be compliant with the schema. var DGPSid: Int? { get set } /// Latitude of current point /// /// - Latitude value should be within range of **-90 to 90** /// - Should be in unit **degrees** (º) /// - Should conform to WGS 84 datum. /// var latitude: Double? { get set } /// Longitude of current point /// /// - Longitude value should be within range of **-180 to 180** /// - Should be in unit **degrees** (º) /// - Should conform to WGS 84 datum. /// var longitude: Double? { get set } } extension GPXWaypointProtocol { func convert<T: GPXWaypointProtocol>() -> T { let wpt = T() wpt.elevation = elevation wpt.time = time wpt.magneticVariation = magneticVariation wpt.geoidHeight = geoidHeight wpt.name = name wpt.comment = comment wpt.desc = desc wpt.source = source wpt.symbol = symbol wpt.type = type wpt.fix = fix wpt.satellites = satellites wpt.horizontalDilution = horizontalDilution wpt.verticalDilution = verticalDilution wpt.positionDilution = positionDilution wpt.ageofDGPSData = ageofDGPSData wpt.DGPSid = DGPSid wpt.latitude = latitude wpt.longitude = longitude return wpt } }
gpl-3.0
c0c5ef1fac1a89089da4d19b39733510
30.738854
105
0.5882
4.378735
false
false
false
false
wowiwj/WDayDayCook
WDayDayCook/WDayDayCook/Extension/WaterFlowLayout.swift
1
5616
// // WaterFlowLayout.swift // WDayDayCook // // Created by wangju on 16/8/19. // Copyright © 2016年 wangju. All rights reserved. // import UIKit @objc protocol UICollectionViewWaterFlowLayoutDelegate: NSObjectProtocol{ func waterFlowLayout(_ waterFlowLayout:WaterFlowlayout,heightForItemAtIndexpath indexpath:IndexPath,itemWidth:CGFloat)->CGFloat @objc optional func columnCountInwaterFlowLayout(_ waterFlowLayout:WaterFlowlayout)->Int @objc optional func columnMarginInwaterFlowLayout(_ waterFlowLayout:WaterFlowlayout)->CGFloat @objc optional func rowMarginInwaterFlowLayout(_ waterFlowLayout:WaterFlowlayout)->CGFloat @objc optional func edgeInsertInwaterFlowLayout(_ waterFlowLayout:WaterFlowlayout)->UIEdgeInsets } class WaterFlowlayout: UICollectionViewLayout { // MARK: 默认值属性 // 默认行数 fileprivate let DefaultColCount:Int = 3 // 默认每一列的间距 fileprivate let DefaultColMargin:CGFloat = 10 // 默认每一行的间距 fileprivate let DefaultRowMargin:CGFloat = 10 // 默认边缘间距 fileprivate let DefaultEdgeInsert:UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) // MARK: - 代理 weak var delegate:UICollectionViewWaterFlowLayoutDelegate? // MARK: - 数据处理 fileprivate var rowMargin:CGFloat{ if let delegate = delegate , delegate.responds(to: #selector(UICollectionViewWaterFlowLayoutDelegate.rowMarginInwaterFlowLayout(_:))) { return delegate.rowMarginInwaterFlowLayout!(self) } return DefaultRowMargin } fileprivate var colCount:Int{ if let delegate = delegate , delegate.responds(to: #selector(UICollectionViewWaterFlowLayoutDelegate.columnCountInwaterFlowLayout(_:))) { return delegate.columnCountInwaterFlowLayout!(self) } return DefaultColCount } fileprivate var colMargin:CGFloat{ if let delegate = delegate , delegate.responds(to: #selector(UICollectionViewWaterFlowLayoutDelegate.columnMarginInwaterFlowLayout(_:))) { return delegate.columnMarginInwaterFlowLayout!(self) } return DefaultColMargin } fileprivate var edgeInsert:UIEdgeInsets{ if let delegate = delegate , delegate.responds(to: #selector(UICollectionViewWaterFlowLayoutDelegate.edgeInsertInwaterFlowLayout(_:))) { return delegate.edgeInsertInwaterFlowLayout!(self) } return DefaultEdgeInsert } // 所有collectionView的布局属性 fileprivate var attrsArr:Array = [UICollectionViewLayoutAttributes]() /** 存放所有列的最大Y值 */ fileprivate var colHeights:Array = [CGFloat]() // MARK: - 瀑布流的核心计算 // 初始化 override func prepare() { super.prepare() // colHeights.removeAll() for _ in 0..<colCount { colHeights.append(edgeInsert.top) } attrsArr.removeAll() var attArr = [UICollectionViewLayoutAttributes]() let count = collectionView!.numberOfItems(inSection: 0) for i in 0..<count { let indexPath = IndexPath(item: i, section: 0) let attr = layoutAttributesForItem(at: indexPath) attArr.append(attr!) } attrsArr = attArr } // 决定cell的排布 override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return attrsArr } // 返回indexPath的cell对应的布局属性 override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attribute = UICollectionViewLayoutAttributes(forCellWith: indexPath) guard let delegate = delegate else { return attribute } if let collectionView = collectionView { let w:CGFloat = (collectionView.frame.size.width - self.edgeInsert.left - self.edgeInsert.right - CGFloat(colCount - 1) * colMargin) / CGFloat(colCount) let h:CGFloat = delegate.waterFlowLayout(self, heightForItemAtIndexpath: indexPath, itemWidth: w) var destColumn:NSInteger = 0 var minColHeight = colHeights[0] for i in 1..<colCount { let columnHeight = colHeights[i] if minColHeight > columnHeight { minColHeight = columnHeight destColumn = i } } let x = edgeInsert.left + (w + colMargin) * CGFloat(destColumn) var y = minColHeight if y != edgeInsert.top { y += rowMargin } attribute.frame = CGRect(x: x, y: y, width: w, height: h) self.colHeights[destColumn] = attribute.frame.maxY } return attribute } override var collectionViewContentSize : CGSize { var maxColHeight:CGFloat = colHeights[0] for i in 1..<colCount { let columnHeight = colHeights[i] if maxColHeight < columnHeight { maxColHeight = columnHeight } } return CGSize(width: 0, height: maxColHeight + edgeInsert.bottom) } }
mit
ecf8d6973004bba162864423a5c9906d
29.138122
164
0.613016
5.65285
false
false
false
false
Greenshire/Calibre
Calibre Example/ProductsListViewController.swift
1
4839
// // ProductsListViewController.swift // Calibre // // Created by Jeremy Tregunna on 9/6/16. // Copyright © 2016 Greenshire, Inc. All rights reserved. // import UIKit import Calibre class ProductsListViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let nib = UINib(nibName: NSStringFromClass(ProductsListCell.self), bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: ProductsListCell.identifier) self.clearsSelectionOnViewWillAppear = false self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) store.subscribe(self) tableView.reloadData() } override func viewDidDisappear(animated: Bool) { store.unsubscribe(self) super.viewDidDisappear(animated) } override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) let indexPath = NSIndexPath(forRow: store.state.products.count, inSection: 0) tableView.beginUpdates() if editing { tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else { tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } tableView.endUpdates() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let productCount = store.state.products.count guard editing else { return productCount } return productCount + 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(ProductsListCell.identifier, forIndexPath: indexPath) as! ProductsListCell if editing && indexPath.row == store.state.products.count { cell.titleLabel.text = "Add new product…" cell.priceLabel.text = "" cell.accessoryType = .DisclosureIndicator } else { let product = store.state.products[indexPath.row] cell.titleLabel.text = product.name cell.priceLabel.text = product.priceText } return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Can add, not edit return false } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { store.dispatch(AddProductAction(name: "test", price: "$1.22")) tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if editing && indexPath.row == tableView.numberOfRowsInSection(0) - 1 { showAddNewItem() } } private func showAddNewItem() { let alert = UIAlertController(title: "Add Product", message: "What's the product called?", preferredStyle: .Alert) alert.addTextFieldWithConfigurationHandler { (field) in field.placeholder = "Product name" } alert.addTextFieldWithConfigurationHandler { (field) in field.placeholder = "$1.99" } let done = UIAlertAction(title: "Done", style: .Default) { (action) in if let nameField = alert.textFields?.first, let name = nameField.text, let priceField = alert.textFields?.last, let price = priceField.text { let addAction = AddProductAction(name: name, price: price) store.dispatch(addAction) } } let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alert.addAction(done) alert.addAction(cancel) let present = PresentViewAction(fromView: self, toView: alert) store.dispatch(present) } } extension ProductsListViewController: Subscriber { func newState(state: AppState) { tableView.reloadData() } }
mit
0ecac120ba294a7f6065bd21ee977f77
33.791367
157
0.662324
5.233766
false
false
false
false
scamps88/ASCalendar
Example/Calendar/ASCalendarNamesM.swift
1
1539
// // ASCalendarNamesM.swift // Example // // Created by alberto.scampini on 19/05/2016. // Copyright © 2016 Alberto Scampini. All rights reserved. // import Foundation protocol ASCalendarNamesM { func getWeekNamesFromMonday() -> Array<String> func getWeekNamesFromSunday() -> Array<String> func getMonthNames() -> Array<String> } extension ASCalendarNamesM { func getWeekNamesFromMonday() -> Array<String> { //get day names let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() let fullWeekDays = formatter.weekdaySymbols var weekDays = Array<String>() for i in 1...6 { weekDays.append(String(fullWeekDays[i].characters.first!).uppercaseString) } //move sunday at the end of the week weekDays.append(String(fullWeekDays[0].characters.first!).uppercaseString) return weekDays } func getWeekNamesFromSunday() -> Array<String> { //get day names let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() let fullWeekDays = formatter.weekdaySymbols var weekDays = Array<String>() for i in 0...6 { weekDays.append(String(fullWeekDays[i].characters.first!).uppercaseString) } return weekDays } func getMonthNames() -> Array<String> { let formatter = NSDateFormatter() formatter.locale = NSLocale.currentLocale() return formatter.monthSymbols } }
mit
d0ebd593840291d9e531bc7d12da35ea
29.176471
86
0.646294
4.577381
false
false
false
false
BarTabs/bartabs
ios-application/Bar Tabs/UserTypeSelectionViewController.swift
1
2431
// // userTypeSelectionViewController.swift // Bar Tabs // // Created by Victor Lora on 2/26/17. // Copyright © 2017 muhlenberg. All rights reserved. /* This view controller checks to see if the person creating a new account chose owner or customer. If the owner was selected a 1 is passed and if customer is selected a 4 is passed. */ import UIKit class UserTypeSelectionViewController: UIViewController { @IBOutlet var customer: UIButton! @IBOutlet var owner: UIButton! @IBAction func customerSelected(_ sender: Any) { performSegue(withIdentifier: "customerViewController", sender: 4) } @IBAction func ownerSelected(_ sender: Any) { performSegue(withIdentifier: "customerViewController", sender: 1) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Create Account" // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.black } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "customerViewController") { let userCreateViewController = segue.destination as! UserCreateViewController userCreateViewController.userType = sender as? Int } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) customer.layer.backgroundColor = UIColor(red: 0, green: 0.8392, blue: 0.0275, alpha: 1.0).cgColor customer.tintColor = UIColor.white customer.layer.cornerRadius = 5 owner.layer.backgroundColor = UIColor(red: 0, green: 0.4941, blue: 0.9647, alpha: 1.0).cgColor owner.tintColor = UIColor.white owner.layer.cornerRadius = 5 self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] self.navigationController?.navigationBar.barTintColor = UIColor.black self.navigationController?.navigationBar.tintColor = UIColor.white } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.black] } }
gpl-3.0
0d4cad10c01fc9ccae10a0f051ddb7d1
35.268657
117
0.68642
5.020661
false
false
false
false
ileitch/SwiftState
SwiftState/StateTransition.swift
2
1779
// // StateTransition.swift // SwiftState // // Created by Yasuhiro Inami on 2014/08/03. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // public struct StateTransition<S: StateType>: Hashable { public typealias State = S public let fromState: State public let toState: State public init(fromState: State, toState: State) { self.fromState = fromState self.toState = toState } public var hashValue: Int { return self.fromState.hashValue &+ self.toState.hashValue.byteSwapped } public func toTransitionChain() -> StateTransitionChain<State> { return StateTransitionChain(transition: self) } public func toRoute() -> StateRoute<State> { return StateRoute(transition: self, condition: nil) } } // for StateTransition Equatable public func == <S: StateType>(left: StateTransition<S>, right: StateTransition<S>) -> Bool { return left.hashValue == right.hashValue } //-------------------------------------------------- // MARK: - Custom Operators //-------------------------------------------------- infix operator => { associativity left } /// e.g. .State0 => .State1 // NOTE: argument types (S) don't need to be optional because it automatically converts nil to Any via NilLiteralConvertible public func => <S: StateType>(left: S, right: S) -> StateTransition<S> { return StateTransition(fromState: left, toState: right) } //-------------------------------------------------- // MARK: - Printable //-------------------------------------------------- extension StateTransition: CustomStringConvertible { public var description: String { return "\(self.fromState) => \(self.toState) (\(self.hashValue))" } }
mit
1baf2ca786caddda38a63ee0a01f047b
25.537313
124
0.590321
4.738667
false
false
false
false
crazypoo/PTools
Pods/FloatingPanel/Sources/Layout.swift
1
33542
// Copyright 2018-Present Shin Yamamoto. All rights reserved. MIT license. import UIKit /// An interface for generating layout information for a panel. @objc public protocol FloatingPanelLayout { /// Returns the position of a panel in a `FloatingPanelController` view . @objc var position: FloatingPanelPosition { get } /// Returns the initial state when a panel is presented. @objc var initialState: FloatingPanelState { get } /// Returns the layout anchors to specify the snapping locations for each state. @objc var anchors: [FloatingPanelState: FloatingPanelLayoutAnchoring] { get } /// Returns layout constraints to determine the cross dimension of a panel. @objc optional func prepareLayout(surfaceView: UIView, in view: UIView) -> [NSLayoutConstraint] /// Returns the alpha value of the backdrop of a panel for each state. @objc optional func backdropAlpha(for state: FloatingPanelState) -> CGFloat } /// A layout object that lays out a panel in bottom sheet style. @objcMembers open class FloatingPanelBottomLayout: NSObject, FloatingPanelLayout { public override init() { super.init() } open var initialState: FloatingPanelState { return .half } open var anchors: [FloatingPanelState: FloatingPanelLayoutAnchoring] { return [ .full: FloatingPanelLayoutAnchor(absoluteInset: 18.0, edge: .top, referenceGuide: .safeArea), .half: FloatingPanelLayoutAnchor(fractionalInset: 0.5, edge: .bottom, referenceGuide: .safeArea), .tip: FloatingPanelLayoutAnchor(absoluteInset: 69.0, edge: .bottom, referenceGuide: .safeArea), ] } open var position: FloatingPanelPosition { return .bottom } open func prepareLayout(surfaceView: UIView, in view: UIView) -> [NSLayoutConstraint] { return [ surfaceView.leftAnchor.constraint(equalTo: view.fp_safeAreaLayoutGuide.leftAnchor, constant: 0.0), surfaceView.rightAnchor.constraint(equalTo: view.fp_safeAreaLayoutGuide.rightAnchor, constant: 0.0), ] } open func backdropAlpha(for state: FloatingPanelState) -> CGFloat { return state == .full ? 0.3 : 0.0 } } struct LayoutSegment { let lower: FloatingPanelState? let upper: FloatingPanelState? } class LayoutAdapter { private unowned var vc: FloatingPanelController private let defaultLayout = FloatingPanelBottomLayout() fileprivate var layout: FloatingPanelLayout { didSet { surfaceView.position = position } } private var surfaceView: SurfaceView { return vc.surfaceView } private var backdropView: BackdropView { return vc.backdropView } private var safeAreaInsets: UIEdgeInsets { return vc.fp_safeAreaInsets } private var initialConst: CGFloat = 0.0 private var fixedConstraints: [NSLayoutConstraint] = [] private var stateConstraints: [FloatingPanelState: [NSLayoutConstraint]] = [:] private var offConstraints: [NSLayoutConstraint] = [] private var fitToBoundsConstraint: NSLayoutConstraint? private(set) var interactionConstraint: NSLayoutConstraint? private(set) var attractionConstraint: NSLayoutConstraint? private var staticConstraint: NSLayoutConstraint? private var anchorStates: Set<FloatingPanelState> { return Set(layout.anchors.keys) } private var sortedAnchorStates: [FloatingPanelState] { return anchorStates.sorted(by: { return $0.order < $1.order }) } var initialState: FloatingPanelState { layout.initialState } var position: FloatingPanelPosition { layout.position } var validStates: Set<FloatingPanelState> { return anchorStates.union([.hidden]) } var sortedAnchorStatesByCoordinate: [FloatingPanelState] { return anchorStates.sorted(by: { switch position { case .top, .left: return $0.order < $1.order case .bottom, .right: return $0.order > $1.order } }) } private var leastCoordinateState: FloatingPanelState { return sortedAnchorStatesByCoordinate.first ?? .hidden } private var mostCoordinateState: FloatingPanelState { return sortedAnchorStatesByCoordinate.last ?? .hidden } var leastExpandedState: FloatingPanelState { if sortedAnchorStates.count == 1 { return .hidden } return sortedAnchorStates.first ?? .hidden } var mostExpandedState: FloatingPanelState { if sortedAnchorStates.count == 1 { return sortedAnchorStates[0] } return sortedAnchorStates.last ?? .hidden } var adjustedContentInsets: UIEdgeInsets { switch position { case .top: return UIEdgeInsets(top: safeAreaInsets.top, left: 0.0, bottom: 0.0, right: 0.0) case .left: return UIEdgeInsets(top: 0.0, left: safeAreaInsets.left, bottom: 0.0, right: 0.0) case .bottom: return UIEdgeInsets(top: 0.0, left: 0.0, bottom: safeAreaInsets.bottom, right: 0.0) case .right: return UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: safeAreaInsets.right) } } /* Returns a constraint based value in the interaction and animation. So that it doesn't need to call `surfaceView.layoutIfNeeded()` after every interaction and animation update. It has an effect on the smooth interaction because the content view doesn't need to update its layout frequently. */ var surfaceLocation: CGPoint { get { var pos: CGFloat if let constraint = interactionConstraint { pos = constraint.constant } else if let animationConstraint = attractionConstraint, let anchor = layout.anchors[vc.state] { switch position { case .top, .bottom: switch referenceEdge(of: anchor) { case .top: pos = animationConstraint.constant if anchor.referenceGuide == .safeArea { pos += safeAreaInsets.top } case .bottom: pos = vc.view.bounds.height + animationConstraint.constant if anchor.referenceGuide == .safeArea { pos -= safeAreaInsets.bottom } default: fatalError("Unsupported reference edges") } case .left, .right: switch referenceEdge(of: anchor) { case .left: pos = animationConstraint.constant if anchor.referenceGuide == .safeArea { pos += safeAreaInsets.left } case .right: pos = vc.view.bounds.width + animationConstraint.constant if anchor.referenceGuide == .safeArea { pos -= safeAreaInsets.right } default: fatalError("Unsupported reference edges") } } } else { pos = edgePosition(surfaceView.frame).rounded(by: surfaceView.fp_displayScale) } switch position { case .top, .bottom: return CGPoint(x: 0.0, y: pos) case .left, .right: return CGPoint(x: pos, y: 0.0) } } set { let pos = position.mainLocation(newValue) if let constraint = interactionConstraint { constraint.constant = pos } else if let animationConstraint = attractionConstraint, let anchor = layout.anchors[vc.state] { let refEdge = referenceEdge(of: anchor) switch refEdge { case .top, .left: animationConstraint.constant = pos if anchor.referenceGuide == .safeArea { animationConstraint.constant -= refEdge.inset(of: safeAreaInsets) } case .bottom, .right: animationConstraint.constant = pos - position.mainDimension(vc.view.bounds.size) if anchor.referenceGuide == .safeArea { animationConstraint.constant += refEdge.inset(of: safeAreaInsets) } } } else { switch position { case .top: return surfaceView.frame.origin.y = pos - surfaceView.bounds.height case .left: return surfaceView.frame.origin.x = pos - surfaceView.bounds.width case .bottom: return surfaceView.frame.origin.y = pos case .right: return surfaceView.frame.origin.x = pos } } } } var offsetFromMostExpandedAnchor: CGFloat { switch position { case .top, .left: return edgePosition(surfaceView.presentationFrame) - position(for: mostExpandedState) case .bottom, .right: return position(for: mostExpandedState) - edgePosition(surfaceView.presentationFrame) } } private var hiddenAnchor: FloatingPanelLayoutAnchoring { switch position { case .top: return FloatingPanelLayoutAnchor(absoluteInset: -100, edge: .top, referenceGuide: .superview) case .left: return FloatingPanelLayoutAnchor(absoluteInset: -100, edge: .left, referenceGuide: .superview) case .bottom: return FloatingPanelLayoutAnchor(absoluteInset: -100, edge: .bottom, referenceGuide: .superview) case .right: return FloatingPanelLayoutAnchor(absoluteInset: -100, edge: .right, referenceGuide: .superview) } } init(vc: FloatingPanelController, layout: FloatingPanelLayout) { self.vc = vc self.layout = layout } func surfaceLocation(for state: FloatingPanelState) -> CGPoint { let pos = position(for: state).rounded(by: surfaceView.fp_displayScale) switch layout.position { case .top, .bottom: return CGPoint(x: 0.0, y: pos) case .left, .right: return CGPoint(x: pos, y: 0.0) } } func position(for state: FloatingPanelState) -> CGFloat { let bounds = vc.view.bounds let anchor = layout.anchors[state] ?? self.hiddenAnchor switch anchor { case let anchor as FloatingPanelIntrinsicLayoutAnchor: let intrinsicLength = position.mainDimension(surfaceView.intrinsicContentSize) let diff = anchor.isAbsolute ? anchor.offset : intrinsicLength * anchor.offset switch position { case .top, .left: var base: CGFloat = 0.0 if anchor.referenceGuide == .safeArea { base += position.inset(safeAreaInsets) } return base + intrinsicLength - diff case .bottom, .right: var base = position.mainDimension(bounds.size) if anchor.referenceGuide == .safeArea { base -= position.inset(safeAreaInsets) } return base - intrinsicLength + diff } case let anchor as FloatingPanelAdaptiveLayoutAnchor: let dimension = layout.position.mainDimension(anchor.contentLayoutGuide.layoutFrame.size) let diff = anchor.distance(from: dimension) var referenceBoundsLength = layout.position.mainDimension(bounds.size) switch layout.position { case .top, .left: if anchor.referenceGuide == .safeArea { referenceBoundsLength += position.inset(safeAreaInsets) } return dimension - diff case .bottom, .right: if anchor.referenceGuide == .safeArea { referenceBoundsLength -= position.inset(safeAreaInsets) } return referenceBoundsLength - dimension + diff } case let anchor as FloatingPanelLayoutAnchor: let referenceBounds = anchor.referenceGuide == .safeArea ? bounds.inset(by: safeAreaInsets) : bounds let diff = anchor.isAbsolute ? anchor.inset : position.mainDimension(referenceBounds.size) * anchor.inset switch anchor.referenceEdge { case .top: return referenceBounds.minY + diff case .left: return referenceBounds.minX + diff case .bottom: return referenceBounds.maxY - diff case .right: return referenceBounds.maxX - diff } default: fatalError("Unsupported a FloatingPanelLayoutAnchoring object") } } func isIntrinsicAnchor(state: FloatingPanelState) -> Bool { return layout.anchors[state] is FloatingPanelIntrinsicLayoutAnchor } private func edgePosition(_ frame: CGRect) -> CGFloat { switch position { case .top: return frame.maxY case .left: return frame.maxX case .bottom: return frame.minY case .right: return frame.minX } } private func referenceEdge(of anchor: FloatingPanelLayoutAnchoring) -> FloatingPanelReferenceEdge { switch anchor { case is FloatingPanelIntrinsicLayoutAnchor, is FloatingPanelAdaptiveLayoutAnchor: switch position { case .top: return .top case .left: return .left case .bottom: return .bottom case .right: return .right } case let anchor as FloatingPanelLayoutAnchor: return anchor.referenceEdge default: fatalError("Unsupported a FloatingPanelLayoutAnchoring object") } } func prepareLayout() { NSLayoutConstraint.deactivate(fixedConstraints) surfaceView.translatesAutoresizingMaskIntoConstraints = false backdropView.translatesAutoresizingMaskIntoConstraints = false // Fixed constraints of surface and backdrop views let surfaceConstraints: [NSLayoutConstraint] if let constraints = layout.prepareLayout?(surfaceView: surfaceView, in: vc.view) { surfaceConstraints = constraints } else { switch position { case .top, .bottom: surfaceConstraints = [ surfaceView.leftAnchor.constraint(equalTo: vc.fp_safeAreaLayoutGuide.leftAnchor, constant: 0.0), surfaceView.rightAnchor.constraint(equalTo: vc.fp_safeAreaLayoutGuide.rightAnchor, constant: 0.0), ] case .left, .right: surfaceConstraints = [ surfaceView.topAnchor.constraint(equalTo: vc.fp_safeAreaLayoutGuide.topAnchor, constant: 0.0), surfaceView.bottomAnchor.constraint(equalTo: vc.fp_safeAreaLayoutGuide.bottomAnchor, constant: 0.0), ] } } let backdropConstraints = [ backdropView.topAnchor.constraint(equalTo: vc.view.topAnchor, constant: 0.0), backdropView.leftAnchor.constraint(equalTo: vc.view.leftAnchor,constant: 0.0), backdropView.rightAnchor.constraint(equalTo: vc.view.rightAnchor, constant: 0.0), backdropView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 0.0), ] fixedConstraints = surfaceConstraints + backdropConstraints NSLayoutConstraint.deactivate(constraint: self.fitToBoundsConstraint) self.fitToBoundsConstraint = nil if vc.contentMode == .fitToBounds { switch position { case .top: fitToBoundsConstraint = surfaceView.topAnchor.constraint(equalTo: vc.view.topAnchor, constant: 0.0) fitToBoundsConstraint?.identifier = "FloatingPanel-fit-to-top" case .left: fitToBoundsConstraint = surfaceView.leftAnchor.constraint(equalTo: vc.view.leftAnchor, constant: 0.0) fitToBoundsConstraint?.identifier = "FloatingPanel-fit-to-left" case .bottom: fitToBoundsConstraint = surfaceView.bottomAnchor.constraint(equalTo: vc.view.bottomAnchor, constant: 0.0) fitToBoundsConstraint?.identifier = "FloatingPanel-fit-to-bottom" case .right: fitToBoundsConstraint = surfaceView.rightAnchor.constraint(equalTo: vc.view.rightAnchor, constant: 0.0) fitToBoundsConstraint?.identifier = "FloatingPanel-fit-to-right" } fitToBoundsConstraint?.priority = .defaultHigh } updateStateConstraints() } private func updateStateConstraints() { let allStateConstraints = stateConstraints.flatMap { $1 } NSLayoutConstraint.deactivate(allStateConstraints + offConstraints) stateConstraints.removeAll() for state in layout.anchors.keys { stateConstraints[state] = layout.anchors[state]? .layoutConstraints(vc, for: position) .map{ $0.identifier = "FloatingPanel-\(state)-constraint"; return $0 } } let hiddenAnchor = layout.anchors[.hidden] ?? self.hiddenAnchor offConstraints = hiddenAnchor.layoutConstraints(vc, for: position) offConstraints.forEach { $0.identifier = "FloatingPanel-hidden-constraint" } } func startInteraction(at state: FloatingPanelState, offset: CGPoint = .zero) { if let constraint = interactionConstraint { initialConst = constraint.constant return } tearDownAttraction() NSLayoutConstraint.deactivate(stateConstraints.flatMap { $1 } + offConstraints) initialConst = edgePosition(surfaceView.frame) + offset.y let constraint: NSLayoutConstraint switch position { case .top: constraint = surfaceView.bottomAnchor.constraint(equalTo: vc.view.topAnchor, constant: initialConst) case .left: constraint = surfaceView.rightAnchor.constraint(equalTo: vc.view.leftAnchor, constant: initialConst) case .bottom: constraint = surfaceView.topAnchor.constraint(equalTo: vc.view.topAnchor, constant: initialConst) case .right: constraint = surfaceView.leftAnchor.constraint(equalTo: vc.view.leftAnchor, constant: initialConst) } constraint.priority = .required constraint.identifier = "FloatingPanel-interaction" NSLayoutConstraint.activate([constraint]) self.interactionConstraint = constraint } func endInteraction(at state: FloatingPanelState) { // Don't deactivate `interactiveTopConstraint` here because it leads to // unsatisfiable constraints if self.interactionConstraint == nil { // Activate `interactiveTopConstraint` for `fitToBounds` mode. // It goes through this path when the pan gesture state jumps // from .begin to .end. startInteraction(at: state) } } func setUpAttraction(to state: FloatingPanelState) -> (NSLayoutConstraint, CGFloat) { NSLayoutConstraint.deactivate(constraint: attractionConstraint) let anchor = layout.anchors[state] ?? self.hiddenAnchor NSLayoutConstraint.deactivate(stateConstraints.flatMap { $1 } + offConstraints) NSLayoutConstraint.deactivate(constraint: interactionConstraint) interactionConstraint = nil let layoutGuideProvider: LayoutGuideProvider switch anchor.referenceGuide { case .safeArea: layoutGuideProvider = vc.fp_safeAreaLayoutGuide case .superview: layoutGuideProvider = vc.view } let currentY = position.mainLocation(surfaceLocation) let baseHeight = position.mainDimension(vc.view.bounds.size) let animationConstraint: NSLayoutConstraint var targetY = position(for: state) switch position { case .top: switch referenceEdge(of: anchor) { case .top: animationConstraint = surfaceView.bottomAnchor.constraint(equalTo: layoutGuideProvider.topAnchor, constant: currentY) if anchor.referenceGuide == .safeArea { animationConstraint.constant -= safeAreaInsets.top targetY -= safeAreaInsets.top } case .bottom: let baseHeight = vc.view.bounds.height targetY = -(baseHeight - targetY) animationConstraint = surfaceView.bottomAnchor.constraint(equalTo: layoutGuideProvider.bottomAnchor, constant: -(baseHeight - currentY)) if anchor.referenceGuide == .safeArea { animationConstraint.constant += safeAreaInsets.bottom targetY += safeAreaInsets.bottom } default: fatalError("Unsupported reference edges") } case .left: switch referenceEdge(of: anchor) { case .left: animationConstraint = surfaceView.rightAnchor.constraint(equalTo: layoutGuideProvider.leftAnchor, constant: currentY) if anchor.referenceGuide == .safeArea { animationConstraint.constant -= safeAreaInsets.right targetY -= safeAreaInsets.right } case .right: targetY = -(baseHeight - targetY) animationConstraint = surfaceView.rightAnchor.constraint(equalTo: layoutGuideProvider.rightAnchor, constant: -(baseHeight - currentY)) if anchor.referenceGuide == .safeArea { animationConstraint.constant += safeAreaInsets.left targetY += safeAreaInsets.left } default: fatalError("Unsupported reference edges") } case .bottom: switch referenceEdge(of: anchor) { case .top: animationConstraint = surfaceView.topAnchor.constraint(equalTo: layoutGuideProvider.topAnchor, constant: currentY) if anchor.referenceGuide == .safeArea { animationConstraint.constant -= safeAreaInsets.top targetY -= safeAreaInsets.top } case .bottom: targetY = -(baseHeight - targetY) animationConstraint = surfaceView.topAnchor.constraint(equalTo: layoutGuideProvider.bottomAnchor, constant: -(baseHeight - currentY)) if anchor.referenceGuide == .safeArea { animationConstraint.constant += safeAreaInsets.bottom targetY += safeAreaInsets.bottom } default: fatalError("Unsupported reference edges") } case .right: switch referenceEdge(of: anchor) { case .left: animationConstraint = surfaceView.leftAnchor.constraint(equalTo: layoutGuideProvider.leftAnchor, constant: currentY) if anchor.referenceGuide == .safeArea { animationConstraint.constant -= safeAreaInsets.left targetY -= safeAreaInsets.left } case .right: targetY = -(baseHeight - targetY) animationConstraint = surfaceView.leftAnchor.constraint(equalTo: layoutGuideProvider.rightAnchor, constant: -(baseHeight - currentY)) if anchor.referenceGuide == .safeArea { animationConstraint.constant += safeAreaInsets.right targetY += safeAreaInsets.right } default: fatalError("Unsupported reference edges") } } animationConstraint.priority = .defaultHigh animationConstraint.identifier = "FloatingPanel-attraction" NSLayoutConstraint.activate([animationConstraint]) self.attractionConstraint = animationConstraint return (animationConstraint, targetY) } private func tearDownAttraction() { NSLayoutConstraint.deactivate(constraint: attractionConstraint) attractionConstraint = nil } // The method is separated from prepareLayout(to:) for the rotation support // It must be called in FloatingPanelController.traitCollectionDidChange(_:) func updateStaticConstraint() { NSLayoutConstraint.deactivate(constraint: staticConstraint) staticConstraint = nil if vc.contentMode == .fitToBounds { surfaceView.containerOverflow = 0 return } let anchor = layout.anchors[self.mostExpandedState]! let surfaceAnchor = position.mainDimensionAnchor(surfaceView) switch anchor { case let anchor as FloatingPanelIntrinsicLayoutAnchor: var constant = position.mainDimension(surfaceView.intrinsicContentSize) if anchor.referenceGuide == .safeArea { constant += position.inset(safeAreaInsets) } staticConstraint = surfaceAnchor.constraint(equalToConstant: constant) case let anchor as FloatingPanelAdaptiveLayoutAnchor: let constant: CGFloat if anchor.referenceGuide == .safeArea { constant = position.inset(safeAreaInsets) } else { constant = 0.0 } let baseAnchor = position.mainDimensionAnchor(anchor.contentLayoutGuide) staticConstraint = surfaceAnchor.constraint(equalTo: baseAnchor, constant: constant) default: switch position { case .top, .left: staticConstraint = surfaceAnchor.constraint(equalToConstant: position(for: self.mostCoordinateState)) case .bottom, .right: let rootViewAnchor = position.mainDimensionAnchor(vc.view) staticConstraint = rootViewAnchor.constraint(equalTo: surfaceAnchor, constant: position(for: self.leastCoordinateState)) } } switch position { case .top, .bottom: staticConstraint?.identifier = "FloatingPanel-static-height" case .left, .right: staticConstraint?.identifier = "FloatingPanel-static-width" } NSLayoutConstraint.activate(constraint: staticConstraint) surfaceView.containerOverflow = position.mainDimension(vc.view.bounds.size) } func updateInteractiveEdgeConstraint(diff: CGFloat, scrollingContent: Bool, allowsRubberBanding: (UIRectEdge) -> Bool) { defer { log.debug("update surface location = \(surfaceLocation)") } let minConst: CGFloat = position(for: leastCoordinateState) let maxConst: CGFloat = position(for: mostCoordinateState) var const = initialConst + diff let base = position.mainDimension(vc.view.bounds.size) // Rubber-banding top buffer if allowsRubberBanding(.top), const < minConst { let buffer = minConst - const const = minConst - rubberBandEffect(for: buffer, base: base) } // Rubber-banding bottom buffer if allowsRubberBanding(.bottom), const > maxConst { let buffer = const - maxConst const = maxConst + rubberBandEffect(for: buffer, base: base) } if scrollingContent { const = min(max(const, minConst), maxConst) } interactionConstraint?.constant = const } // According to @chpwn's tweet: https://twitter.com/chpwn/status/285540192096497664 // x = distance from the edge // c = constant value, UIScrollView uses 0.55 // d = dimension, either width or height private func rubberBandEffect(for buffer: CGFloat, base: CGFloat) -> CGFloat { return (1.0 - (1.0 / ((buffer * 0.55 / base) + 1.0))) * base } func activateLayout(for state: FloatingPanelState, forceLayout: Bool = false) { defer { if forceLayout { layoutSurfaceIfNeeded() log.debug("activateLayout for \(state) -- surface.presentation = \(self.surfaceView.presentationFrame) surface.frame = \(self.surfaceView.frame)") } else { log.debug("activateLayout for \(state)") } } // Must deactivate `interactiveTopConstraint` here NSLayoutConstraint.deactivate(constraint: self.interactionConstraint) self.interactionConstraint = nil tearDownAttraction() NSLayoutConstraint.activate(fixedConstraints) if vc.contentMode == .fitToBounds { NSLayoutConstraint.activate(constraint: self.fitToBoundsConstraint) } var state = state if validStates.contains(state) == false { state = layout.initialState } // Recalculate the intrinsic size of a content view. This is because // UIView.systemLayoutSizeFitting() returns a different size between an // on-screen and off-screen view which includes // UIStackView(i.e. Settings view in Samples.app) updateStateConstraints() switch state { case .hidden: NSLayoutConstraint.activate(offConstraints) default: if let constraints = stateConstraints[state] { NSLayoutConstraint.activate(constraints) } else { log.error("Couldn't find any constraints for \(state)") } } } private func layoutSurfaceIfNeeded() { #if !TEST guard surfaceView.window != nil else { return } #endif surfaceView.superview?.layoutIfNeeded() } func backdropAlpha(for state: FloatingPanelState) -> CGFloat { return layout.backdropAlpha?(for: state) ?? defaultLayout.backdropAlpha(for: state) } fileprivate func checkLayout() { // Verify layout configurations assert(anchorStates.count > 0) assert(validStates.contains(layout.initialState), "Does not include an initial state (\(layout.initialState)) in (\(validStates))") /* This assertion does not work in a device rotating let statePosOrder = activeStates.sorted(by: { position(for: $0) < position(for: $1) }) assert(sortedDirectionalStates == statePosOrder, "Check your layout anchors because the state order(\(statePosOrder)) must be (\(sortedDirectionalStates))).") */ } } extension LayoutAdapter { func segment(at pos: CGFloat, forward: Bool) -> LayoutSegment { /// ----------------------->Y /// --> forward <-- backward /// |-------|===o===|-------| |-------|-------|===o===| /// |-------|-------x=======| |-------|=======x-------| /// |-------|-------|===o===| |-------|===o===|-------| /// pos: o/x, segment: = let sortedStates = sortedAnchorStatesByCoordinate let upperIndex: Int? if forward { upperIndex = sortedStates.firstIndex(where: { pos < position(for: $0) }) } else { upperIndex = sortedStates.firstIndex(where: { pos <= position(for: $0) }) } switch upperIndex { case 0: return LayoutSegment(lower: nil, upper: sortedStates.first) case let upperIndex?: return LayoutSegment(lower: sortedStates[upperIndex - 1], upper: sortedStates[upperIndex]) default: return LayoutSegment(lower: sortedStates[sortedStates.endIndex - 1], upper: nil) } } } extension FloatingPanelController { var _layout: FloatingPanelLayout { get { floatingPanel.layoutAdapter.layout } set { floatingPanel.layoutAdapter.layout = newValue floatingPanel.layoutAdapter.checkLayout() } } }
mit
603d00c192438fe5809b2e960484b22a
39.509662
162
0.590066
5.726823
false
false
false
false
haranicle/AlcatrazTour
Pods/OAuthSwift/OAuthSwift/OAuth2Swift.swift
1
9920
// // OAuth2Swift.swift // OAuthSwift // // Created by Dongri Jin on 6/22/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import Foundation public class OAuth2Swift: NSObject { public var client: OAuthSwiftClient public var version: OAuthSwiftCredential.Version { return self.client.credential.version } public var authorize_url_handler: OAuthSwiftURLHandlerType = OAuthSwiftOpenURLExternally.sharedInstance public var accessTokenBasicAuthentification = false var consumer_key: String var consumer_secret: String var authorize_url: String var access_token_url: String? var response_type: String var observer: AnyObject? var content_type: String? public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String){ self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType) self.access_token_url = accessTokenUrl } public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String, contentType: String){ self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType) self.access_token_url = accessTokenUrl self.content_type = contentType } public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String){ self.consumer_key = consumerKey self.consumer_secret = consumerSecret self.authorize_url = authorizeUrl self.response_type = responseType self.client = OAuthSwiftClient(consumerKey: consumerKey, consumerSecret: consumerSecret) self.client.credential.version = .OAuth2 } public convenience init?(parameters: [String:String]){ guard let consumerKey = parameters["consumerKey"], consumerSecret = parameters["consumerSecret"], responseType = parameters["responseType"], authorizeUrl = parameters["authorizeUrl"] else { return nil } if let accessTokenUrl = parameters["accessTokenUrl"] { self.init(consumerKey:consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl, responseType: responseType) } else { self.init(consumerKey:consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType) } } struct CallbackNotification { static let notificationName = "OAuthSwiftCallbackNotificationName" static let optionsURLKey = "OAuthSwiftCallbackNotificationOptionsURLKey" } struct OAuthSwiftError { static let domain = "OAuthSwiftErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } public typealias TokenSuccessHandler = (credential: OAuthSwiftCredential, response: NSURLResponse?, parameters: NSDictionary) -> Void public typealias FailureHandler = (error: NSError) -> Void public func authorizeWithCallbackURL(callbackURL: NSURL, scope: String, state: String, params: Dictionary<String, String> = Dictionary<String, String>(), success: TokenSuccessHandler, failure: ((error: NSError) -> Void)) { self.observer = NSNotificationCenter.defaultCenter().addObserverForName(CallbackNotification.notificationName, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock:{ notification in NSNotificationCenter.defaultCenter().removeObserver(self.observer!) let url = notification.userInfo![CallbackNotification.optionsURLKey] as! NSURL var responseParameters: Dictionary<String, String> = Dictionary() if let query = url.query { responseParameters += query.parametersFromQueryString() } if let fragment = url.fragment where !fragment.isEmpty { responseParameters += fragment.parametersFromQueryString() } if let accessToken = responseParameters["access_token"] { self.client.credential.oauth_token = accessToken success(credential: self.client.credential, response: nil, parameters: responseParameters) } else if let code = responseParameters["code"] { self.postOAuthAccessTokenWithRequestTokenByCode(code.safeStringByRemovingPercentEncoding, callbackURL:callbackURL, success: success, failure: failure) } else if let error = responseParameters["error"], error_description = responseParameters["error_description"] { let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString(error, comment: error_description)] failure(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: errorInfo)) } else { let errorInfo = [NSLocalizedDescriptionKey: "No access_token, no code and no error provided by server"] failure(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: errorInfo)) } }) //let authorizeURL = NSURL(string: ) var urlString = String() urlString += self.authorize_url urlString += (self.authorize_url.has("?") ? "&" : "?") + "client_id=\(self.consumer_key)" urlString += "&redirect_uri=\(callbackURL.absoluteString)" urlString += "&response_type=\(self.response_type)" if (scope != "") { urlString += "&scope=\(scope)" } if (state != "") { urlString += "&state=\(state)" } for param in params { urlString += "&\(param.0)=\(param.1)" } if let queryURL = NSURL(string: urlString) { self.authorize_url_handler.handle(queryURL) } } func postOAuthAccessTokenWithRequestTokenByCode(code: String, callbackURL: NSURL, success: TokenSuccessHandler, failure: FailureHandler?) { var parameters = Dictionary<String, AnyObject>() parameters["client_id"] = self.consumer_key parameters["client_secret"] = self.consumer_secret parameters["code"] = code parameters["grant_type"] = "authorization_code" parameters["redirect_uri"] = callbackURL.absoluteString.safeStringByRemovingPercentEncoding if self.content_type == "multipart/form-data" { self.client.postMultiPartRequest(self.access_token_url!, method: .POST, parameters: parameters, success: { data, response in let responseJSON: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) let responseParameters: NSDictionary if responseJSON != nil { responseParameters = responseJSON as! NSDictionary } else { let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String! responseParameters = responseString.parametersFromQueryString() } let accessToken = responseParameters["access_token"] as! String self.client.credential.oauth_token = accessToken success(credential: self.client.credential, response: response, parameters: responseParameters) }, failure: failure) } else { // special headers var headers: [String:String]? = nil if accessTokenBasicAuthentification { let authentification = "\(self.consumer_key):\(self.consumer_secret)".dataUsingEncoding(NSUTF8StringEncoding) if let base64Encoded = authentification?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) { headers = ["Authorization": "Basic \(base64Encoded)"] } } self.client.request(self.access_token_url!, method: .POST, parameters: parameters, headers: headers, success: { data, response in let responseJSON: AnyObject? = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) let responseParameters: NSDictionary if responseJSON != nil { responseParameters = responseJSON as! NSDictionary } else { let responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as String! responseParameters = responseString.parametersFromQueryString() } guard let accessToken = responseParameters["access_token"] as? String else { if let failure = failure { let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")] failure(error: NSError(domain: OAuthSwiftErrorDomain, code: -1, userInfo: errorInfo)) } return } self.client.credential.oauth_token = accessToken success(credential: self.client.credential, response: response, parameters: responseParameters) }, failure: failure) } } public class func handleOpenURL(url: NSURL) { let notification = NSNotification(name: CallbackNotification.notificationName, object: nil, userInfo: [CallbackNotification.optionsURLKey: url]) NSNotificationCenter.defaultCenter().postNotification(notification) } }
mit
c35844dbfd34f464231011a77e11c258
49.35533
226
0.650302
5.740741
false
false
false
false
wwu-pi/md2-framework
de.wwu.md2.framework/res/resources/ios/lib/controller/MD2DataMapper.swift
1
5679
// // MD2DataMapper.swift // md2-ios-library // // Created by Christoph Rieger on 22.07.15. // Copyright (c) 2015 Christoph Rieger. All rights reserved. // /** A data mapping mechanism for two-way synchronization of changes between input fields and content providers. *Notice* The class may bypass the event/action construct and use a direct form synchronization instead. */ class MD2DataMapper { /// Singleton instance of the REST client static let instance = MD2DataMapper() /// Private initializer for the singleton instance private init() { // Nothing to initialize } /** Content provider and attribute to widget association. *Notice* There is no native bidirectional data structure available and the overhead is acceptable because only object references are stored. */ var contentProviderToWidgetMapping: Dictionary<MD2ContentProviderAttributeIdentity, MD2WidgetWrapper> = [:] /** Widget to content provider and attribute association. *Notice* There is no native bidirectional data structure available and the overhead is acceptable because only object references are stored. */ var widgetToContentProviderMapping: Dictionary<MD2WidgetWrapper, MD2ContentProviderAttributeIdentity> = [:] /** Install the binding between a widget wrapper and a content provider and attribute combination. On change of the input field or the content provider a respective event is fired to update the mapping partner. :param: widget The widget wrapper of the input field. :param: contentProvider The content provider for data storage. :param: attribute The attribute to specify the field of the content provider. */ func map(widget: MD2WidgetWrapper, contentProvider: MD2ContentProvider, attribute: String) { // Add mapping contentProviderToWidgetMapping[MD2ContentProviderAttributeIdentity(contentProvider, attribute)] = widget widgetToContentProviderMapping[widget] = MD2ContentProviderAttributeIdentity(contentProvider, attribute) // Add respective action on change let providerChangeAction = MD2UpdateWidgetAction( actionSignature: MD2Util.getClassName(contentProvider) + "__" + attribute + "__" + widget.widgetId.description, viewElement: widget, contentProvider: contentProvider, attribute: attribute) MD2OnContentChangeHandler.instance.registerAction(providerChangeAction, contentProvider: contentProvider, attribute: attribute) let fieldChangeAction = MD2UpdateContentProviderAction( actionSignature: MD2Util.getClassName(contentProvider) + "__" + attribute + "__" + widget.widgetId.description, viewElement: widget, contentProvider: contentProvider, attribute: attribute) MD2OnWidgetChangeHandler.instance.registerAction(fieldChangeAction, widget: widget) // Add content provider observer and trigger first value update contentProvider.registerObservedOnChange(attribute) } /** Revoke the binding between a widget wrapper and a content provider and attribute combination. :param: widget The widget wrapper of the input field. :param: contentProvider The content provider for data storage. :param: attribute The attribute to specify the field of the content provider. */ func unmap(widget: MD2WidgetWrapper, contentProvider: MD2ContentProvider, attribute: String) { // Remove mapping contentProviderToWidgetMapping.removeValueForKey(MD2ContentProviderAttributeIdentity(contentProvider, attribute)) widgetToContentProviderMapping.removeValueForKey(widget) // Remove content provider observer contentProvider.unregisterObservedOnChange(attribute) // Remove onChange action let action = MD2UpdateWidgetAction(actionSignature: MD2Util.getClassName(contentProvider), viewElement: widget, contentProvider: contentProvider, attribute: attribute) MD2OnContentChangeHandler.instance.unregisterAction(action, contentProvider: contentProvider, attribute: attribute) let fieldChangeAction = MD2UpdateContentProviderAction(actionSignature: MD2Util.getClassName(contentProvider), viewElement: widget, contentProvider: contentProvider, attribute: attribute) MD2OnWidgetChangeHandler.instance.unregisterAction(fieldChangeAction, widget: widget) // Remove mapping widgetToContentProviderMapping.removeValueForKey(widget) } /** Retrieve the widget wrapper for a content provider and attribute combination. :param: contentProvider The content provider for data storage. :param: attribute The attribute to specify the field of the content provider. :returns: The respective widget wrapper if found. */ func getWidgetForContentProvider(contentProvider: MD2ContentProvider, attribute: String) -> MD2WidgetWrapper? { return contentProviderToWidgetMapping[MD2ContentProviderAttributeIdentity(contentProvider, attribute)] } /** Retrieve the content provider for a widget wrapper. :param: widget The widget wrapper of the input field. :returns: The respective content provider and attribute combination if found. */ func getContentProviderForWidget(widget: MD2WidgetWrapper) -> MD2ContentProviderAttributeIdentity? { return widgetToContentProviderMapping[widget] } }
apache-2.0
08697c380e1154706f6bf0c49ec20ea3
46.731092
195
0.721078
5.824615
false
false
false
false
BronxDupaix/WaffleLuv
WaffleLuv/Datastore.swift
1
2013
// // Datastore.swift // WaffleLuv // // Created by Bronson Dupaix on 4/7/16. // Copyright © 2016 Bronson Dupaix. All rights reserved. // import Foundation import CoreLocation class DataStore: NSObject { static let sharedInstance = DataStore() private override init() {} var currentEvents = [CalendarEvent]() var instaPhotos = [InstaPhoto]() var currentTime = NSDate() //MARK: - Events Functions func numberOFEvents() { print("Number of events in datastore \(currentEvents.count)") } func geocodeLocations() { for event in currentEvents { geocoding(event.location) { (latitude: Double, longitude: Double) in let lat: Double = latitude event.latitiude = lat let long: Double = longitude event.longitude = long print(" Calling notification event") NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEventGeocode, object: nil) } } } func geocoding(location: String, completion: (Double, Double) -> ()) { CLGeocoder().geocodeAddressString(location) { (placemarks, error) in if placemarks?.count > 0 { let placemark = placemarks?[0] let location = placemark!.location let coordinate = location?.coordinate completion((coordinate?.latitude)!, (coordinate?.longitude)!) } } } func removeOldEvents(){ let time = currentTime.timeIntervalSince1970 for event in currentEvents{ let eventEnd = event.endDate.timeIntervalSince1970 if eventEnd <= time { } } } }
apache-2.0
4d49171e131743376c48263952d3b90b
22.964286
113
0.515905
5.683616
false
false
false
false
callam/Moya
Source/RxSwift/Moya+RxSwift.swift
9
1544
import Foundation import RxSwift /// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures. public class RxMoyaProvider<Target where Target: TargetType>: MoyaProvider<Target> { /// Initializes a reactive provider. override public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = RxMoyaProvider<Target>.DefaultAlamofireManager(), plugins: [PluginType] = []) { super.init(endpointClosure: endpointClosure, requestClosure: requestClosure, stubClosure: stubClosure, manager: manager, plugins: plugins) } /// Designated request-making method. public func request(token: Target) -> Observable<Response> { // Creates an observable that starts a request each time it's subscribed to. return Observable.create { [weak self] observer in let cancellableToken = self?.request(token) { result in switch result { case let .Success(response): observer.onNext(response) observer.onCompleted() break case let .Failure(error): observer.onError(error) } } return AnonymousDisposable { cancellableToken?.cancel() } } } }
mit
1d393f0354041e2cb50c2c63fdf17db8
41.888889
150
0.645078
5.96139
false
false
false
false
neoneye/SwiftyFORM
Example/TextView/TextViewViewController.swift
1
2249
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM class TextViewViewController: FormViewController { override func populate(_ builder: FormBuilder) { builder.navigationTitle = "TextViews" builder += longSummary builder += notes builder += commentArea builder += userDescription builder += SectionHeaderTitleFormItem().title("Buttons") builder += randomizeButton builder += clearButton } lazy var longSummary: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Long summary").placeholder("placeholder") instance.value = "Lorem ipsum" return instance }() lazy var notes: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Notes").placeholder("I'm a placeholder") return instance }() lazy var commentArea: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Comments").placeholder("I'm also a placeholder") return instance }() lazy var userDescription: TextViewFormItem = { let instance = TextViewFormItem() instance.title("Description").placeholder("Yet another placeholder") return instance }() lazy var randomizeButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Randomize" instance.action = { [weak self] in self?.randomize() } return instance }() lazy var clearButton: ButtonFormItem = { let instance = ButtonFormItem() instance.title = "Clear" instance.action = { [weak self] in self?.clear() } return instance }() func pickRandom(_ strings: [String]) -> String { return strings.randomElement() ?? "" } func appendRandom(_ textView: TextViewFormItem, strings: [String]) { let notEmpty = textView.value.utf8.count != 0 var s = "" if notEmpty { s = " " } textView.value += s + pickRandom(strings) } func randomize() { appendRandom(longSummary, strings: ["Hello", "World", "Cat", "Water", "Fish", "Hund"]) appendRandom(notes, strings: ["Hat", "Ham", "Has"]) commentArea.value += pickRandom(["a", "b", "c"]) userDescription.value += pickRandom(["x", "y", "z", "w"]) } func clear() { longSummary.value = "" notes.value = "" commentArea.value = "" userDescription.value = "" } }
mit
66e887105bd52c3f0d8062ab265ee45c
24.850575
88
0.687861
3.786195
false
false
false
false
natecook1000/swift
test/SILGen/guaranteed_closure_context.swift
3
3731
// RUN: %target-swift-emit-silgen -parse-as-library -enable-sil-ownership %s | %FileCheck %s func use<T>(_: T) {} func escape(_ f: () -> ()) {} protocol P {} class C: P {} struct S {} // CHECK-LABEL: sil hidden @$S26guaranteed_closure_context0A9_capturesyyF func guaranteed_captures() { // CHECK: [[MUTABLE_TRIVIAL_BOX:%.*]] = alloc_box ${ var S } var mutableTrivial = S() // CHECK: [[MUTABLE_RETAINABLE_BOX:%.*]] = alloc_box ${ var C } var mutableRetainable = C() // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX:%.*]] = alloc_box ${ var P } var mutableAddressOnly: P = C() // CHECK: [[IMMUTABLE_TRIVIAL:%.*]] = apply {{.*}} -> S let immutableTrivial = S() // CHECK: [[IMMUTABLE_RETAINABLE:%.*]] = apply {{.*}} -> @owned C let immutableRetainable = C() // CHECK: [[IMMUTABLE_ADDRESS_ONLY:%.*]] = alloc_stack $P let immutableAddressOnly: P = C() func captureEverything() { use((mutableTrivial, mutableRetainable, mutableAddressOnly, immutableTrivial, immutableRetainable, immutableAddressOnly)) } // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[B_MUTABLE_TRIVIAL_BOX:%.*]] = begin_borrow [[MUTABLE_TRIVIAL_BOX]] : ${ var S } // CHECK: [[B_MUTABLE_RETAINABLE_BOX:%.*]] = begin_borrow [[MUTABLE_RETAINABLE_BOX]] : ${ var C } // CHECK: [[B_MUTABLE_ADDRESS_ONLY_BOX:%.*]] = begin_borrow [[MUTABLE_ADDRESS_ONLY_BOX]] : ${ var P } // CHECK: [[B_IMMUTABLE_RETAINABLE:%.*]] = begin_borrow [[IMMUTABLE_RETAINABLE]] : $C // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[B_IMMUTABLE_AO_BOX:%.*]] = begin_borrow [[IMMUTABLE_AO_BOX]] : ${ var P } // CHECK: [[FN:%.*]] = function_ref [[FN_NAME:@\$S26guaranteed_closure_context0A9_capturesyyF17captureEverythingL_yyF]] // CHECK: apply [[FN]]([[B_MUTABLE_TRIVIAL_BOX]], [[B_MUTABLE_RETAINABLE_BOX]], [[B_MUTABLE_ADDRESS_ONLY_BOX]], [[IMMUTABLE_TRIVIAL]], [[B_IMMUTABLE_RETAINABLE]], [[B_IMMUTABLE_AO_BOX]]) captureEverything() // CHECK: destroy_value [[IMMUTABLE_AO_BOX]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // -- partial_apply still takes ownership of its arguments. // CHECK: [[FN:%.*]] = function_ref [[FN_NAME]] // CHECK: [[MUTABLE_TRIVIAL_BOX_COPY:%.*]] = copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK: [[MUTABLE_RETAINABLE_BOX_COPY:%.*]] = copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK: [[MUTABLE_ADDRESS_ONLY_BOX_COPY:%.*]] = copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK: [[IMMUTABLE_RETAINABLE_COPY:%.*]] = copy_value [[IMMUTABLE_RETAINABLE]] // CHECK: [[IMMUTABLE_AO_BOX:%.*]] = alloc_box ${ var P } // CHECK: [[CLOSURE:%.*]] = partial_apply {{.*}}([[MUTABLE_TRIVIAL_BOX_COPY]], [[MUTABLE_RETAINABLE_BOX_COPY]], [[MUTABLE_ADDRESS_ONLY_BOX_COPY]], [[IMMUTABLE_TRIVIAL]], [[IMMUTABLE_RETAINABLE_COPY]], [[IMMUTABLE_AO_BOX]]) // CHECK: [[CONVERT:%.*]] = convert_escape_to_noescape [not_guaranteed] [[CLOSURE]] // CHECK: apply {{.*}}[[CONVERT]] // CHECK-NOT: copy_value [[MUTABLE_TRIVIAL_BOX]] // CHECK-NOT: copy_value [[MUTABLE_RETAINABLE_BOX]] // CHECK-NOT: copy_value [[MUTABLE_ADDRESS_ONLY_BOX]] // CHECK-NOT: copy_value [[IMMUTABLE_RETAINABLE]] // CHECK-NOT: destroy_value [[IMMUTABLE_AO_BOX]] escape(captureEverything) } // CHECK: sil private [[FN_NAME]] : $@convention(thin) (@guaranteed { var S }, @guaranteed { var C }, @guaranteed { var P }, S, @guaranteed C, @guaranteed { var P })
apache-2.0
344667ffb509a43f9688e7a459cee3ce
48.746667
224
0.635754
3.513183
false
false
false
false
brentsimmons/Evergreen
Shared/Extensions/ArticleStringFormatter.swift
1
2860
// // ArticleStringFormatter.swift // NetNewsWire // // Created by Brent Simmons on 8/31/15. // Copyright © 2015 Ranchero Software, LLC. All rights reserved. // import Foundation import Articles import RSParser struct ArticleStringFormatter { private static var feedNameCache = [String: String]() private static var titleCache = [String: String]() private static var summaryCache = [String: String]() private static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .none return formatter }() private static let timeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .none formatter.timeStyle = .short return formatter }() static func emptyCaches() { feedNameCache = [String: String]() titleCache = [String: String]() summaryCache = [String: String]() } static func truncatedFeedName(_ feedName: String) -> String { if let cachedFeedName = feedNameCache[feedName] { return cachedFeedName } let maxFeedNameLength = 100 if feedName.count < maxFeedNameLength { feedNameCache[feedName] = feedName return feedName } let s = (feedName as NSString).substring(to: maxFeedNameLength) feedNameCache[feedName] = s return s } static func truncatedTitle(_ article: Article, forHTML: Bool = false) -> String { guard let title = article.sanitizedTitle(forHTML: forHTML) else { return "" } if let cachedTitle = titleCache[title] { return cachedTitle } var s = title.replacingOccurrences(of: "\n", with: "") s = s.replacingOccurrences(of: "\r", with: "") s = s.replacingOccurrences(of: "\t", with: "") if !forHTML { s = s.rsparser_stringByDecodingHTMLEntities() } s = s.trimmingWhitespace s = s.collapsingWhitespace let maxLength = 1000 if s.count < maxLength { titleCache[title] = s return s } s = (s as NSString).substring(to: maxLength) titleCache[title] = s return s } static func attributedTruncatedTitle(_ article: Article) -> NSAttributedString { let title = truncatedTitle(article, forHTML: true) let attributed = NSAttributedString(html: title) return attributed } static func truncatedSummary(_ article: Article) -> String { guard let body = article.body else { return "" } let key = article.articleID + article.accountID if let cachedBody = summaryCache[key] { return cachedBody } var s = body.rsparser_stringByDecodingHTMLEntities() s = s.strippingHTML(maxCharacters: 250) s = s.trimmingWhitespace s = s.collapsingWhitespace if s == "Comments" { // Hacker News. s = "" } summaryCache[key] = s return s } static func dateString(_ date: Date) -> String { if Calendar.dateIsToday(date) { return timeFormatter.string(from: date) } return dateFormatter.string(from: date) } }
mit
cc5dfddd6262046b75dad13d0bf42632
23.02521
82
0.702693
3.560399
false
false
false
false
magicien/MMDSceneKit
Sample_swift/Common/MMDSceneViewController.swift
1
1615
// // MMDSceneViewController.swift // MMDSceneKit // // Created by magicien on 2/13/16. // Copyright © 2016 DarkHorse. All rights reserved. // import SceneKit #if os(OSX) import MMDSceneKit_macOS public typealias SuperViewController = NSViewController public typealias MMDView = SCNView #elseif os(tvOS) import MMDSceneKit_tvOS public typealias SuperViewController = UIViewController public typealias MMDView = SCNView #elseif os(iOS) import MMDSceneKit_iOS public typealias SuperViewController = UIViewController public typealias MMDView = SCNView #elseif os(watchOS) import MMDSceneKit_watchOS public typealias SuperViewController = WKInterfaceController public typealias MMDView = WKInterfaceSCNScene #endif var mikuNode: MMDNode! = nil public class MMDSceneViewController: SuperViewController { /** * setup game scene */ public func setupGameScene(_ scene: SCNScene, view: MMDView) { // set the scene to the view view.scene = MMDSceneSource(named: "art.scnassets/サンプル(きしめんAllStar).pmm")!.getScene()! // show statistics such as fps and timing information view.showsStatistics = true #if !os(watchOS) // set the delegate to update IK for each frame view.delegate = MMDIKController.sharedController #endif // configure the view #if os(macOS) view.backgroundColor = NSColor.white #elseif os(iOS) || os(tvOS) view.backgroundColor = UIColor.white #endif } }
mit
f7882b5b594628b2c11a4836b06e55d5
28.518519
95
0.675031
4.786787
false
false
false
false