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
Nana-Muthuswamy/AadhuEats
AadhuEats/Controller/LogDetailsViewController.swift
1
8955
// // LogDetailsViewController.swift // AadhuEats // // Created by Nana on 10/26/17. // Copyright © 2017 Nana. All rights reserved. // import UIKit class LogDetailsViewController: UIViewController { @IBOutlet weak var logTypeControl: UISegmentedControl! @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var durationPicker: UIPickerView! @IBOutlet weak var volumePicker: UIPickerView! @IBOutlet weak var milkTypeControl: UISegmentedControl! @IBOutlet weak var breastOrientationControl: UISegmentedControl! @IBOutlet weak var durationPickerHeight: NSLayoutConstraint! @IBOutlet weak var volumePickerHeight: NSLayoutConstraint! @IBOutlet weak var milkTypeControlHeight: NSLayoutConstraint! @IBOutlet weak var breastOrientationControlHeight: NSLayoutConstraint! // To store the default storyboard height constraint constants for fallback var defaultHeights = [NSLayoutConstraint:CGFloat]() // Log Model var model = Log(date: Date(), type: .pumpSession, milkType: .breast, breastOrientation: .none, volume: 0, duration: 0) // Selected Log index, if editing existing log var selectedLogIndexPath: IndexPath? // MARK: View Controller Life Cycle override func viewDidLoad() { super.viewDidLoad() // Keep track of default constant values of all height constaints defaultHeights.updateValue(durationPickerHeight.constant, forKey: durationPickerHeight) defaultHeights.updateValue(volumePickerHeight.constant, forKey: volumePickerHeight) defaultHeights.updateValue(milkTypeControlHeight.constant, forKey: milkTypeControlHeight) defaultHeights.updateValue(breastOrientationControlHeight.constant, forKey: breastOrientationControlHeight) // Setup Log Date picker setupDatePicker() // Refresh UI with model data refreshUIData() // Display default Pump session log details logTypeSelected(logTypeControl) } // MARK: Util Methods func saveModel() { if let pathToReplaceLog = selectedLogIndexPath { if (DataManager.shared.replaceLog(at: pathToReplaceLog, with: model) == false) { let alert = UIAlertController(title: "Operation Failed", message: "Unable to create new log.", preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) show(alert, sender: self) } } else { if (DataManager.shared.addLog(model) == false) { let alert = UIAlertController(title: "Operation Failed", message: "Unable to create new log.", preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (action) in self.dismiss(animated: true, completion: nil) })) show(alert, sender: self) } } } func updateModel(for logType: LogType) { model.type = logType model.date = datePicker.date switch logType { case .pumpSession: model.duration = durationPicker.selectedRow(inComponent: 0) model.volume = volumePicker.selectedRow(inComponent: 0) // set defaults for rest model.breastOrientation = .both model.milkType = .breast case .bottleFeed: model.milkType = MilkType(rawValue: milkTypeControl.selectedSegmentIndex) ?? .breast model.volume = volumePicker.selectedRow(inComponent: 0) // set defaults for rest model.breastOrientation = .none model.duration = 0 case .breastFeed: model.duration = durationPicker.selectedRow(inComponent: 0) model.breastOrientation = BreastOrientation(rawValue: breastOrientationControl.selectedSegmentIndex) ?? .both // set defaults for rest model.milkType = .breast model.volume = 0 } } func updateUILayout(for logType: LogType) { switch logType { case .pumpSession: // Remove irrelevant fields self.milkTypeControl.alpha = 0 self.breastOrientationControl.alpha = 0 self.milkTypeControlHeight.constant = 0 self.breastOrientationControlHeight.constant = 0 UIView.animate(withDuration: 1.0, animations: { // Display relevant fields self.durationPicker.alpha = 1 self.volumePicker.alpha = 1 self.durationPickerHeight.constant = self.defaultHeights[self.durationPickerHeight]! self.volumePickerHeight.constant = self.defaultHeights[self.volumePickerHeight]! }) case .bottleFeed: // Remove irrelevant fields self.durationPicker.alpha = 0 self.breastOrientationControl.alpha = 0 self.durationPickerHeight.constant = 0 self.breastOrientationControlHeight.constant = 0 UIView.animate(withDuration: 1.0, animations: { // Display relevant fields self.volumePicker.alpha = 1 self.milkTypeControl.alpha = 1 self.volumePickerHeight.constant = self.defaultHeights[self.volumePickerHeight]! self.milkTypeControlHeight.constant = self.defaultHeights[self.milkTypeControlHeight]! }) case .breastFeed: // Remove irrelevant fields self.volumePicker.alpha = 0 self.milkTypeControl.alpha = 0 self.volumePickerHeight.constant = 0 self.milkTypeControlHeight.constant = 0 UIView.animate(withDuration: 1.0, animations: { // Display relevant fields self.durationPickerHeight.constant = self.defaultHeights[self.durationPickerHeight]! self.breastOrientationControlHeight.constant = self.defaultHeights[self.breastOrientationControlHeight]! self.durationPicker.alpha = 1 self.breastOrientationControl.alpha = 1 }) } } func refreshUIData() { datePicker.setDate(model.date, animated: true) logTypeControl.selectedSegmentIndex = model.type.rawValue milkTypeControl.selectedSegmentIndex = model.milkType.rawValue breastOrientationControl.selectedSegmentIndex = model.breastOrientation.rawValue durationPicker.selectRow(model.duration, inComponent: 0, animated: true) volumePicker.selectRow(model.volume, inComponent: 0, animated: true) } func setupDatePicker() { datePicker.calendar = Calendar.autoupdatingCurrent datePicker.locale = Locale.autoupdatingCurrent datePicker.timeZone = TimeZone.autoupdatingCurrent datePicker.setDate(model.date, animated: false) datePicker.maximumDate = Date().endOfDay() } // MARK: Action Methods @IBAction func logTypeSelected(_ sender: UISegmentedControl) { guard let logType = LogType(rawValue: sender.selectedSegmentIndex) else {return} // Update UI and Model for selected log type updateUILayout(for: logType) } @IBAction func saveLog(_ sender: Any) { updateModel(for: (LogType(rawValue: logTypeControl.selectedSegmentIndex) ?? .pumpSession)) saveModel() dismiss(animated: true, completion: nil) } @IBAction func discardLog(_ sender: Any) { dismiss(animated: true, completion: nil) } } // MARK: Picker View Extension extension LogDetailsViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: if pickerView == durationPicker { return 61 } else if pickerView == volumePicker { return 1000 } else { return 0 } default: return 1 } } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 32.0 } func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 60.0 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch component { case 0: return String(row) default: if pickerView == durationPicker { return "mins" } else if pickerView == volumePicker { return "ml" } else { return "" } } } }
mit
a1b95b419cb297cf878d6ee1a87e32f9
37.594828
140
0.642059
5.033165
false
false
false
false
KYawn/myiOS
scrowllView/scrowllView/RootViewController.swift
1
3227
// // RootViewController.swift // scrowllView // // Created by K.Yawn Xoan on 3/22/15. // Copyright (c) 2015 K.Yawn Xoan. All rights reserved. // import UIKit class RootViewController: UIViewController, UIPageViewControllerDelegate { var pageViewController: UIPageViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Configure the page view controller and add it as a child view controller. self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil) self.pageViewController!.delegate = self let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)! let viewControllers: NSArray = [startingViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in }) self.pageViewController!.dataSource = self.modelController self.addChildViewController(self.pageViewController!) self.view.addSubview(self.pageViewController!.view) // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. var pageViewRect = self.view.bounds self.pageViewController!.view.frame = pageViewRect self.pageViewController!.didMoveToParentViewController(self) // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var modelController: ModelController { // Return the model controller object, creating it if necessary. // In more complex implementations, the model controller may be passed to the view controller. if _modelController == nil { _modelController = ModelController() } return _modelController! } var _modelController: ModelController? = nil // MARK: - UIPageViewController delegate methods func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation { // Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here. let currentViewController = self.pageViewController!.viewControllers[0] as UIViewController let viewControllers: NSArray = [currentViewController] self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in }) self.pageViewController!.doubleSided = false return .Min } }
apache-2.0
f702f2b4309eea3ac588cf6eeca322fa
43.819444
291
0.737837
5.691358
false
false
false
false
aichamorro/fitness-tracker
Clients/Apple/UIGraphView/UIGraphView/GraphStyles/UIGraphViewDrawingStyles.swift
1
2852
// // UIGraphViewDrawingStyles.swift // UIGraphView // // Created by Alberto Chamorro on 29/01/2017. // Copyright © 2017 OnsetBits. All rights reserved. // import QuartzCore internal typealias UIGraphViewDrawingStyle = (_ context: CGContext, _ rect: CGRect, _ iterator: UIGraphViewValuesIterator, _ didDrawPoint: ((CGPoint, Int)->Void)?) -> Void internal typealias UIGraphViewValuesIterator = (_ rect: CGRect, (_ point: CGPoint) -> Void) -> Void struct UIGraphViewDrawingStyles { static func bars(barWidth: CGFloat, barColor: CGColor) -> UIGraphViewDrawingStyle { return { context, rect, iterator, didDrawPoint in let fillColor = barColor context.setFillColor(fillColor) context.setLineWidth(barWidth) context.setStrokeColor(fillColor) var index = 0 iterator(rect) { point in context.strokeLineSegments(between: [point, CGPoint(x: point.x, y: rect.maxY)]) context.fillCircle(center: point, radius: barWidth) didDrawPoint?(point, index) index += 1 } context.strokePath() context.fillPath() } } static func points(pointRadius: CGFloat, color: UIColor, didDrawPoint: ((CGPoint) -> Void)? = nil) -> UIGraphViewDrawingStyle { return { context, rect, iterator, didDrawPoint in context.executeBatch { (context) in context.setFillColor(color.cgColor) // Graph let path = CGMutablePath() var isFirst = true var index = 0 iterator(rect) { point in if isFirst { isFirst = false path.move(to: point) } else { path.addLine(to: point) } context.addCircle(center: point, radius: pointRadius) didDrawPoint?(point, index) index += 1 } context.fillPath() context.addPath(path) context.setStrokeColor(color.cgColor) context.strokePath() // Gradients path.addLine(to: CGPoint(x: path.currentPoint.x, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.origin.x, y: rect.maxY)) context.addPath(path) context.clip() let startColor = color.withAlphaComponent(0.5).cgColor let endColor = color.withAlphaComponent(0).cgColor context.drawLinearGradient(rect: rect, startColor: startColor, endColor: endColor) } } } }
gpl-3.0
0393cc2f00b7ae2d207505424c76b326
37.013333
171
0.531743
5.155515
false
false
false
false
benlangmuir/swift
test/SILOptimizer/definite_init_actor.swift
4
13783
// RUN: %target-swift-frontend -module-name test -disable-availability-checking -swift-version 5 -sil-verify-all -emit-sil %s | %FileCheck --enable-var-scope --implicit-check-not='hop_to_executor' %s // REQUIRES: concurrency enum ActingError<T> : Error { case forgotLine case smuggledValue(T) } func neverReturn() -> Never { fatalError("quit!") } func arbitraryAsync() async {} actor BoringActor { // CHECK-LABEL: sil hidden @$s4test11BoringActorCACyYacfc : $@convention(method) @async (@owned BoringActor) -> @owned BoringActor { // CHECK: bb0([[SELF:%[0-9]+]] : $BoringActor): // CHECK: initializeDefaultActor // CHECK-NEXT: hop_to_executor [[SELF]] // CHECK: } // end sil function '$s4test11BoringActorCACyYacfc' init() async {} // CHECK-LABEL: sil hidden @$s4test11BoringActorC4sizeACSi_tYacfc : $@convention(method) @async (Int, @owned BoringActor) -> @owned BoringActor { // CHECK: bb0({{%[0-9]+}} : $Int, [[SELF:%[0-9]+]] : $BoringActor): // CHECK: initializeDefaultActor // CHECK-NEXT: hop_to_executor [[SELF]] // CHECK: } // end sil function '$s4test11BoringActorC4sizeACSi_tYacfc' init(size: Int) async { var sz = size while sz > 0 { print(".") sz -= 1 } print("done!") } // CHECK-LABEL: sil hidden @$s4test11BoringActorC04mainC0ACyt_tYacfc : $@convention(method) @async (@owned BoringActor) -> @owned BoringActor { // CHECK: hop_to_executor {{%[0-9]+}} : $MainActor // CHECK: builtin "initializeDefaultActor" // CHECK: [[FN:%[0-9]+]] = function_ref @$s4test14arbitraryAsyncyyYaF : $@convention(thin) @async () -> () // CHECK: = apply [[FN]]() : $@convention(thin) @async () -> () // CHECK-NEXT: hop_to_executor {{%[0-9]+}} : $MainActor @MainActor init(mainActor: Void) async { await arbitraryAsync() } // CHECK-LABEL: sil hidden @$s4test11BoringActorC6crashyACSgyt_tYacfc : $@convention(method) @async (@owned BoringActor) -> @owned Optional<BoringActor> { // CHECK: bb0([[SELF:%[0-9]+]] : $BoringActor): // CHECK: initializeDefaultActor // CHECK-NEXT: hop_to_executor [[SELF]] // CHECK: } // end sil function '$s4test11BoringActorC6crashyACSgyt_tYacfc' init!(crashy: Void) async { return nil } // CHECK-LABEL: sil hidden @$s4test11BoringActorC5nillyACSgSi_tYacfc : $@convention(method) @async (Int, @owned BoringActor) -> @owned Optional<BoringActor> { // CHECK: bb0({{%[0-9]+}} : $Int, [[SELF:%[0-9]+]] : $BoringActor): // CHECK: initializeDefaultActor // CHECK-NEXT: hop_to_executor [[SELF]] // CHECK: } // end sil function '$s4test11BoringActorC5nillyACSgSi_tYacfc' init?(nilly: Int) async { guard nilly > 0 else { return nil } } } actor SingleVarActor { var myVar: Int init(sync: Void) { myVar = 0 } // CHECK-LABEL: sil hidden @$s4test14SingleVarActorCACyYacfc : $@convention(method) @async (@owned SingleVarActor) -> @owned SingleVarActor { // CHECK: bb0([[SELF:%[0-9]+]] : $SingleVarActor): // CHECK: store {{%[0-9]+}} to [[ACCESS:%[0-9]+]] // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: hop_to_executor [[SELF]] : $SingleVarActor // CHECK: store {{%[0-9]+}} to {{%[0-9]+}} // CHECK: } // end sil function '$s4test14SingleVarActorCACyYacfc' init() async { myVar = 0 myVar = 1 } // CHECK-LABEL: sil hidden @$s4test14SingleVarActorC10iterationsACSi_tYacfc : $@convention(method) @async (Int, @owned SingleVarActor) -> @owned SingleVarActor { // CHECK: bb0({{%[0-9]+}} : $Int, [[SELF:%[0-9]+]] : $SingleVarActor): // CHECK: [[MYVAR_REF:%[0-9]+]] = ref_element_addr [[SELF]] : $SingleVarActor, #SingleVarActor.myVar // CHECK: [[MYVAR:%[0-9]+]] = begin_access [modify] [dynamic] [[MYVAR_REF]] : $*Int // CHECK: store {{%[0-9]+}} to [[MYVAR]] : $*Int // CHECK-NEXT: end_access [[MYVAR]] // CHECK-NEXT: hop_to_executor [[SELF]] : $SingleVarActor // CHECK: } // end sil function '$s4test14SingleVarActorC10iterationsACSi_tYacfc' init(iterations: Int) async { var iter = iterations repeat { myVar = 0 iter -= 1 } while iter > 0 } // CHECK-LABEL: sil hidden @$s4test14SingleVarActorC2b12b2ACSb_SbtYacfc : $@convention(method) @async (Bool, Bool, @owned SingleVarActor) -> @owned SingleVarActor { // CHECK: bb0({{%[0-9]+}} : $Bool, {{%[0-9]+}} : $Bool, [[SELF:%[0-9]+]] : $SingleVarActor): // CHECK: store {{%[0-9]+}} to [[A1:%[0-9]+]] : $*Int // CHECK-NEXT: end_access [[A1]] // CHECK-NEXT: hop_to_executor [[SELF]] : $SingleVarActor // CHECK: store {{%[0-9]+}} to [[A2:%[0-9]+]] : $*Int // CHECK-NEXT: end_access [[A2]] // CHECK-NEXT: hop_to_executor [[SELF]] : $SingleVarActor // CHECK: store {{%[0-9]+}} to [[A3:%[0-9]+]] : $*Int // CHECK-NEXT: end_access [[A3]] // CHECK-NEXT: hop_to_executor [[SELF]] : $SingleVarActor // CHECK: } // end sil function '$s4test14SingleVarActorC2b12b2ACSb_SbtYacfc' init(b1: Bool, b2: Bool) async { if b1 { if b2 { myVar = 0 } myVar = 1 } myVar = 2 } // CHECK-LABEL: sil hidden @$s4test14SingleVarActorC14failable_asyncACSgSb_tYacfc : $@convention(method) @async (Bool, @owned SingleVarActor) -> @owned Optional<SingleVarActor> { // CHECK: bb0({{%[0-9]+}} : $Bool, {{%[0-9]+}} : $SingleVarActor): // CHECK: cond_br {{%[0-9]+}}, [[SUCCESS_BB:bb[0-9]+]], {{bb[0-9]+}} // // CHECK: [[SUCCESS_BB]]: // CHECK: store {{%[0-9]+}} to {{%[0-9]+}} : $*Int // CHECK: hop_to_executor {{%[0-9]+}} // CHECK: enum $Optional<SingleVarActor>, #Optional.some!enumelt // // CHECK: } // end sil function '$s4test14SingleVarActorC14failable_asyncACSgSb_tYacfc' init?(failable_async cond: Bool) async { guard cond else { return nil } myVar = 1 } // FIXME: the convenience init below is missing a hop after the call to arbitraryAsync (rdar://87485045) // CHECK-LABEL: sil hidden @$s4test14SingleVarActorC10delegatingACSb_tYacfC : $@convention(method) @async (Bool, @thick SingleVarActor.Type) -> @owned SingleVarActor { // CHECK: [[SELF_ALLOC:%[0-9]+]] = alloc_stack [lexical] $SingleVarActor, let, name "self", implicit // ** first hop is after the call to the synchronous init, right after initializing the allocation. // CHECK: [[SYNC_FN:%[0-9]+]] = function_ref @$s4test14SingleVarActorC4syncACyt_tcfC : $@convention(method) (@thick SingleVarActor.Type) -> @owned SingleVarActor // CHECK: [[INIT1:%[0-9]+]] = apply [[SYNC_FN]]({{%[0-9]+}}) : $@convention(method) (@thick SingleVarActor.Type) -> @owned SingleVarActor // CHECK: store [[INIT1]] to [[SELF_ALLOC]] : $*SingleVarActor // CHECK-NEXT: hop_to_executor [[INIT1]] : $SingleVarActor // ** second hop is after the call to async init // CHECK: [[ASYNC_FN:%[0-9]+]] = function_ref @$s4test14SingleVarActorCACyYacfC : $@convention(method) @async (@thick SingleVarActor.Type) -> @owned SingleVarActor // CHECK: [[INIT2:%[0-9]+]] = apply [[ASYNC_FN]]({{%[0-9]+}}) : $@convention(method) @async (@thick SingleVarActor.Type) -> @owned SingleVarActor // CHECK: store [[INIT2]] to [[SELF_ALLOC]] : $*SingleVarActor // CHECK-NEXT: hop_to_executor [[INIT2]] : $SingleVarActor // CHECK: } // end sil function '$s4test14SingleVarActorC10delegatingACSb_tYacfC' convenience init(delegating c: Bool) async { if c { self.init(sync: ()) } else { await self.init() } await arbitraryAsync() } } actor DefaultInit { var x: DefaultInit? var y: String = "" var z: ActingError<Int> = .smuggledValue(5) // CHECK-LABEL: sil hidden @$s4test11DefaultInitCACyYacfc : $@convention(method) @async (@owned DefaultInit) -> @owned DefaultInit { // CHECK: bb0([[SELF:%[0-9]+]] : $DefaultInit): // CHECK: store {{%[0-9]+}} to {{%[0-9]+}} : $*ActingError<Int> // CHECK-NEXT: hop_to_executor [[SELF]] : $DefaultInit // CHECK: } // end sil function '$s4test11DefaultInitCACyYacfc' init() async {} // CHECK-LABEL: sil hidden @$s4test11DefaultInitC5nillyACSgSb_tYacfc : $@convention(method) @async (Bool, @owned DefaultInit) -> @owned Optional<DefaultInit> { // CHECK: bb0({{%[0-9]+}} : $Bool, [[SELF:%[0-9]+]] : $DefaultInit): // CHECK: store {{%[0-9]+}} to {{%[0-9]+}} : $*ActingError<Int> // CHECK-NEXT: hop_to_executor [[SELF]] : $DefaultInit // CHECK: } // end sil function '$s4test11DefaultInitC5nillyACSgSb_tYacfc' init?(nilly: Bool) async { guard nilly else { return nil } } init(sync: Void) {} @MainActor init(mainActorSync: Void) {} } actor MultiVarActor { var firstVar: Int var secondVar: Float // CHECK-LABEL: sil hidden @$s4test13MultiVarActorC10doNotThrowACSb_tYaKcfc : $@convention(method) @async (Bool, @owned MultiVarActor) -> (@owned MultiVarActor, @error any Error) { // CHECK: bb0({{%[0-9]+}} : $Bool, [[SELF:%[0-9]+]] : $MultiVarActor): // CHECK: [[REF:%[0-9]+]] = ref_element_addr [[SELF]] : $MultiVarActor, #MultiVarActor.firstVar // CHECK: [[VAR:%[0-9]+]] = begin_access [modify] [dynamic] [[REF]] : $*Int // CHECK: store {{%[0-9]+}} to [[VAR]] : $*Int // CHECK-NEXT: end_access [[VAR]] // CHECK-NEXT: hop_to_executor %1 : $MultiVarActor // CHECK: } // end sil function '$s4test13MultiVarActorC10doNotThrowACSb_tYaKcfc' init(doNotThrow: Bool) async throws { secondVar = 0 guard doNotThrow else { throw ActingError<Any>.forgotLine } firstVar = 1 } // CHECK-LABEL: sil hidden @$s4test13MultiVarActorC10noSuccCaseACSb_tYacfc : $@convention(method) @async (Bool, @owned MultiVarActor) -> @owned MultiVarActor { // CHECK: store {{%[0-9]+}} to [[A1:%[0-9]+]] : $*Int // CHECK-NEXT: end_access [[A1]] // CHECK-NEXT: hop_to_executor {{%[0-9]+}} : $MultiVarActor // CHECK: store {{%[0-9]+}} to [[A2:%[0-9]+]] : $*Int // CHECK-NEXT: end_access [[A2]] // CHECK-NEXT: hop_to_executor {{%[0-9]+}} : $MultiVarActor // CHECK: } // end sil function '$s4test13MultiVarActorC10noSuccCaseACSb_tYacfc' init(noSuccCase: Bool) async { secondVar = 0 if noSuccCase { firstVar = 1 } firstVar = 2 } // CHECK-LABEL: sil hidden @$s4test13MultiVarActorC10noPredCaseACSb_tYacfc : $@convention(method) @async (Bool, @owned MultiVarActor) -> @owned MultiVarActor { // CHECK: store {{%[0-9]+}} to [[ACCESS:%[0-9]+]] : $*Int // CHECK-NEXT: end_access [[ACCESS]] // CHECK-NEXT: hop_to_executor {{%[0-9]+}} : $MultiVarActor // CHECK: } // end sil function '$s4test13MultiVarActorC10noPredCaseACSb_tYacfc' init(noPredCase: Bool) async { secondVar = 0 firstVar = 1 if noPredCase { print("hello") } print("hi") } // Some cases where we do NOT expect a hop to be emitted because they do // not fully-initialize `self`. The implicit check-not flag on this test // ensures that any unexpected hops are caught. init?(doesNotFullyInit1: Bool) async { firstVar = 1 return nil } init(doesNotFullyInit2: Bool) async { firstVar = 1 fatalError("I give up!") } init(doesNotFullyInit3: Bool) async throws { firstVar = 1 throw ActingError<Any>.forgotLine } init?(doesNotFullyInit4: Bool) async { firstVar = 1 neverReturn() } } @available(SwiftStdlib 5.1, *) actor TaskMaster { var task: Task<Void, Never>? func sayHello() { print("hello") } ////// for the initializer // CHECK-LABEL: @$s4test10TaskMasterCACyYacfc : $@convention(method) @async (@owned TaskMaster) -> @owned TaskMaster { // CHECK: [[ELM:%[0-9]+]] = ref_element_addr [[SELF:%[0-9]+]] : $TaskMaster, #TaskMaster.task // CHECK: [[NIL:%[0-9]+]] = enum $Optional<Task<(), Never>>, #Optional.none!enumelt // CHECK: store [[NIL]] to [[ELM]] : $*Optional<Task<(), Never>> // CHECK-NEXT: hop_to_executor [[SELF]] : $TaskMaster // CHECK: } // end sil function '$s4test10TaskMasterCACyYacfc' init() async { ////// for the closure // CHECK-LABEL: sil private @$s4test10TaskMasterCACyYacfcyyYaYbcfU_ : // CHECK: hop_to_executor {{%[0-9]+}} : $TaskMaster // CHECK: } // end sil function '$s4test10TaskMasterCACyYacfcyyYaYbcfU_' task = Task.detached { await self.sayHello() } } } actor SomeActor { var x: Int = 0 // CHECK-LABEL: sil hidden @$s4test9SomeActorCACyYacfc : $@convention(method) @async (@owned SomeActor) -> @owned SomeActor { // CHECK-NOT: begin_access // CHECK: store {{%[0-9]+}} to {{%[0-9]+}} : $*Int // CHECK-NEXT: hop_to_executor {{%[0-9]+}} : $SomeActor // CHECK: } // end sil function '$s4test9SomeActorCACyYacfc' init() async {} } actor Ahmad { var x: Int = 0 // CHECK-LABEL: sil hidden @$s4test5AhmadCACyYacfc : $@convention(method) @async (@owned Ahmad) -> @owned Ahmad { // CHECK: bb0{{.*}}: // CHECK-NEXT: [[GENERIC:%[0-9]+]] = enum $Optional<Builtin.Executor>, #Optional.none!enumelt // CHECK-NEXT: hop_to_executor [[GENERIC]] // CHECK: store {{%[0-9]+}} to {{%[0-9]+}} : $*Int // CHECK: } // end sil function '$s4test5AhmadCACyYacfc' nonisolated init() async {} }
apache-2.0
c28df04632589ab61b0669c5190631f3
43.318328
199
0.591236
3.344577
false
true
false
false
accepton/accepton-apple
Example/Tests/Spy.swift
1
4031
import Nimble //Useful for mocking delegates by keeping track of incomming calls protocol Spy: class { var callLog: [(name: String, args: [String:AnyObject])] { get set } var callLogNames: [String] { get } func logCall(name: String, withArgs args: [String:AnyObject]) } extension Spy { func logCall(name: String, withArgs args: [String:AnyObject]) { callLog.append(name: name, args: args) } var callLogNames: [String] { return callLog.map { $0.name } } } struct SpyCallLogSlice { let callLog: [(name: String, args: [String:AnyObject])] var count: Int { return callLog.count } } func haveInvoked(selector: String) -> NonNilMatcherFunc<Spy> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "have invoked \(selector)." if let spy = try actualExpression.evaluate() { //Match the call, check if it existed in the log let possibleResult = spy.callLog.filter { $0.name == selector }.first if possibleResult != nil { return true } else { failureMessage.postfixMessage += " The \(selector) did not exist in the log which contained: \(spy.callLogNames)" return false } } else { return false } } } func haveInvoked(selector: String, withMatchingArgExpression argExp: (args: [String:AnyObject])->(Bool)) -> NonNilMatcherFunc<Spy> { return NonNilMatcherFunc { actualExpression, failureMessage in failureMessage.postfixMessage = "have invoked \(selector)." if let spy = try actualExpression.evaluate() { //Match the call, check if it existed in the log let possibleResult = spy.callLog.filter { $0.name == selector }.first if let result = possibleResult { if argExp(args: result.args) { return true } else { failureMessage.postfixMessage += " The \(selector) *did* exist in log! (but) the argument expression failed to match \(result.args) for \(result.name)" return false } } else { failureMessage.postfixMessage += " The \(selector) did not exist in the log which contained: \(spy.callLogNames)" return false } } else { return false } } } //Matcher helpers for Spy //func haveTheCall(card: AcceptOnAPICreditCardParams) -> NonNilMatcherFunc<[String:AnyObject]> { // return NonNilMatcherFunc { actualExpression, failureMessage in // failureMessage.postfixMessage = "represent complaint 'card' field for AcceptOn /v1/Charges endpoint for given raw credit-card parameters." // // if let cardInfo = try actualExpression.evaluate() { // guard let number = cardInfo["number"] as? String where number == card.number else { // failureMessage.postfixMessage += " The cardInfo field 'number' was non-existant" // return false // } // // guard let expMonth = cardInfo["exp_month"] as? String where expMonth == card.expMonth else { // failureMessage.postfixMessage += " The cardInfo field 'expMonth' was non-existant" // return false // } // // guard let expYear = cardInfo["exp_year"] as? String where expYear == card.expYear else { // failureMessage.postfixMessage += " The cardInfo field 'expYear' was non-existant" // return false // } // // guard let security = cardInfo["security_code"] as? String where security == card.cvc else { // failureMessage.postfixMessage += " The cardInfo field 'security_code' was non-existant" // return false // } // // return true // } else { return false } // } //}
mit
4ac2369d8708bcfaa06888d1892d9fcb
39.727273
171
0.588192
4.649366
false
false
false
false
terikon/cordova-plugin-photo-library
src/ios/PhotoLibrary.swift
1
12397
import Foundation @objc(PhotoLibrary) class PhotoLibrary : CDVPlugin { lazy var concurrentQueue: DispatchQueue = DispatchQueue(label: "photo-library.queue.plugin", qos: DispatchQoS.utility, attributes: [.concurrent]) override func pluginInitialize() { // Do not call PhotoLibraryService here, as it will cause permission prompt to appear on app start. URLProtocol.registerClass(PhotoLibraryProtocol.self) } override func onMemoryWarning() { // self.service.stopCaching() NSLog("-- MEMORY WARNING --") } // Will sort by creation date @objc func getLibrary(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let options = command.arguments[0] as! NSDictionary let thumbnailWidth = options["thumbnailWidth"] as! Int let thumbnailHeight = options["thumbnailHeight"] as! Int let itemsInChunk = options["itemsInChunk"] as! Int let chunkTimeSec = options["chunkTimeSec"] as! Double let useOriginalFileNames = options["useOriginalFileNames"] as! Bool let includeAlbumData = options["includeAlbumData"] as! Bool let includeCloudData = options["includeCloudData"] as! Bool let includeVideos = options["includeVideos"] as! Bool let includeImages = options["includeImages"] as! Bool let maxItems = options["maxItems"] as! Int func createResult (library: [NSDictionary], chunkNum: Int, isLastChunk: Bool) -> [String: AnyObject] { let result: NSDictionary = [ "chunkNum": chunkNum, "isLastChunk": isLastChunk, "library": library ] return result as! [String: AnyObject] } let getLibraryOptions = PhotoLibraryGetLibraryOptions(thumbnailWidth: thumbnailWidth, thumbnailHeight: thumbnailHeight, itemsInChunk: itemsInChunk, chunkTimeSec: chunkTimeSec, useOriginalFileNames: useOriginalFileNames, includeImages: includeImages, includeAlbumData: includeAlbumData, includeCloudData: includeCloudData, includeVideos: includeVideos, maxItems: maxItems) service.getLibrary(getLibraryOptions, completion: { (library, chunkNum, isLastChunk) in let result = createResult(library: library, chunkNum: chunkNum, isLastChunk: isLastChunk) let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: result) pluginResult!.setKeepCallbackAs(!isLastChunk) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) } ) } } @objc func getAlbums(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let albums = service.getAlbums() let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: albums) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) } } @objc func isAuthorized(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: PhotoLibraryService.hasPermission()) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) } } @objc func getThumbnail(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let photoId = command.arguments[0] as! String let options = command.arguments[1] as! NSDictionary let thumbnailWidth = options["thumbnailWidth"] as! Int let thumbnailHeight = options["thumbnailHeight"] as! Int let quality = options["quality"] as! Float service.getThumbnail(photoId, thumbnailWidth: thumbnailWidth, thumbnailHeight: thumbnailHeight, quality: quality) { (imageData) in let pluginResult = imageData != nil ? CDVPluginResult( status: CDVCommandStatus_OK, messageAsMultipart: [imageData!.data, imageData!.mimeType]) : CDVPluginResult( status: CDVCommandStatus_ERROR, messageAs: "Could not fetch the thumbnail") self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) } } } @objc func getPhoto(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let photoId = command.arguments[0] as! String service.getPhoto(photoId) { (imageData) in let pluginResult = imageData != nil ? CDVPluginResult( status: CDVCommandStatus_OK, messageAsMultipart: [imageData!.data, imageData!.mimeType]) : CDVPluginResult( status: CDVCommandStatus_ERROR, messageAs: "Could not fetch the image") self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) } } } @objc func getLibraryItem(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let info = command.arguments[0] as! NSDictionary let mime_type = info["mimeType"] as! String service.getLibraryItem(info["id"] as! String, mimeType: mime_type, completion: { (base64: String?) in self.returnPictureData(callbackId: command.callbackId, base64: base64, mimeType: mime_type) }) } } @objc func returnPictureData(callbackId : String, base64: String?, mimeType: String?) { let pluginResult = (base64 != nil) ? CDVPluginResult( status: CDVCommandStatus_OK, messageAsMultipart: [base64!, mimeType!]) : CDVPluginResult( status: CDVCommandStatus_ERROR, messageAs: "Could not fetch the image") self.commandDelegate!.send(pluginResult, callbackId: callbackId) } @objc func stopCaching(_ command: CDVInvokedUrlCommand) { let service = PhotoLibraryService.instance service.stopCaching() let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) } @objc func requestAuthorization(_ command: CDVInvokedUrlCommand) { let service = PhotoLibraryService.instance service.requestAuthorization({ let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) }, failure: { (err) in let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: err) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) }) } @objc func saveImage(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let url = command.arguments[0] as! String let album = command.arguments[1] as! String service.saveImage(url, album: album) { (libraryItem: NSDictionary?, error: String?) in if (error != nil) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) } else { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: libraryItem as! [String: AnyObject]?) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) } } } } @objc func saveVideo(_ command: CDVInvokedUrlCommand) { concurrentQueue.async { if !PhotoLibraryService.hasPermission() { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: PhotoLibraryService.PERMISSION_ERROR) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) return } let service = PhotoLibraryService.instance let url = command.arguments[0] as! String let album = command.arguments[1] as! String service.saveVideo(url, album: album) { (_ libraryItem: NSDictionary?, error: String?) in if (error != nil) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: error) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) } else { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: libraryItem as! [String: AnyObject]?) self.commandDelegate!.send(pluginResult, callbackId: command.callbackId ) } } } } }
mit
a18b03348a9f9f5035b05dc177012e10
41.346154
149
0.569493
6.053223
false
false
false
false
DKJone/DKLoginButton
loginbutton/DKButton/CGRectEx.swift
1
2229
import UIKit extension CGRect { var x: CGFloat { get { return self.origin.x } set { self = CGRect(x: newValue, y: self.y, width: self.width, height: self.height) } } var y: CGFloat { get { return self.origin.y } set { self = CGRect(x: self.x, y: newValue, width: self.width, height: self.height) } } var width: CGFloat { get { return self.size.width } set { self = CGRect(x: self.x, y: self.y, width: newValue, height: self.height) } } var height: CGFloat { get { return self.size.height } set { self = CGRect(x: self.x, y: self.y, width: self.width, height: newValue) } } var top: CGFloat { get { return self.origin.y } set { y = newValue } } var bottom: CGFloat { get { return self.origin.y + self.size.height } set { self = CGRect(x: x, y: newValue - height, width: width, height: height) } } var left: CGFloat { get { return self.origin.x } set { self.x = newValue } } var right: CGFloat { get { return x + width } set { self = CGRect(x: newValue - width, y: y, width: width, height: height) } } var midX: CGFloat { get { return self.x + self.width / 2 } set { self = CGRect(x: newValue - width / 2, y: y, width: width, height: height) } } var midY: CGFloat { get { return self.y + self.height / 2 } set { self = CGRect(x: x, y: newValue - height / 2, width: width, height: height) } } var center: CGPoint { get { return CGPoint(x: self.midX, y: self.midY) } set { self = CGRect(x: newValue.x - width / 2, y: newValue.y - height / 2, width: width, height: height) } } }
mit
97412e56af753bfa795ee6cb58133b12
20.852941
110
0.43293
4.030741
false
false
false
false
codescv/DQuery
TodoDemoSwift/TodoItemCell.swift
1
1492
// // Copyright 2016 DQuery // // 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. // // TodoItemCell.swift // // Created by chi on 16/1/10. // import UIKit class TodoItemCell: UITableViewCell { enum Action { case MarkAsDone } var actionTriggered: ((TodoItemCell, Action)->())? @IBOutlet weak var cardBackgroundView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBAction func markAsDone(sender: AnyObject) { self.actionTriggered?(self, .MarkAsDone) } func configureWithViewModel(todoItemViewModel: TodoItemViewModel) { self.titleLabel.text = todoItemViewModel.title } override func awakeFromNib() { // set background colors so the cell background can show self.backgroundColor = UIColor.clearColor() self.contentView.backgroundColor = UIColor.clearColor() self.cardBackgroundView.layer.cornerRadius = 5.0 self.cardBackgroundView.clipsToBounds = true } }
apache-2.0
8347d34519590c9dd74ff57049940153
30.104167
75
0.701743
4.521212
false
false
false
false
aatalyk/swift-algorithm-club
Knuth-Morris-Pratt/KnuthMorrisPratt.playground/Contents.swift
3
3678
//: Playground - noun: a place where people can play func ZetaAlgorithm(ptnr: String) -> [Int]? { let pattern = Array(ptnr.characters) let patternLength: Int = pattern.count guard patternLength > 0 else { return nil } var zeta: [Int] = [Int](repeating: 0, count: patternLength) var left: Int = 0 var right: Int = 0 var k_1: Int = 0 var betaLength: Int = 0 var textIndex: Int = 0 var patternIndex: Int = 0 for k in 1 ..< patternLength { if k > right { patternIndex = 0 while k + patternIndex < patternLength && pattern[k + patternIndex] == pattern[patternIndex] { patternIndex = patternIndex + 1 } zeta[k] = patternIndex if zeta[k] > 0 { left = k right = k + zeta[k] - 1 } } else { k_1 = k - left + 1 betaLength = right - k + 1 if zeta[k_1 - 1] < betaLength { zeta[k] = zeta[k_1 - 1] } else if zeta[k_1 - 1] >= betaLength { textIndex = betaLength patternIndex = right + 1 while patternIndex < patternLength && pattern[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } zeta[k] = patternIndex - k left = k right = patternIndex - 1 } } } return zeta } extension String { func indexesOf(ptnr: String) -> [Int]? { let text = Array(self.characters) let pattern = Array(ptnr.characters) let textLength: Int = text.count let patternLength: Int = pattern.count guard patternLength > 0 else { return nil } var suffixPrefix: [Int] = [Int](repeating: 0, count: patternLength) var textIndex: Int = 0 var patternIndex: Int = 0 var indexes: [Int] = [Int]() /* Pre-processing stage: computing the table for the shifts (through Z-Algorithm) */ let zeta = ZetaAlgorithm(ptnr: ptnr) for patternIndex in (1 ..< patternLength).reversed() { textIndex = patternIndex + zeta![patternIndex] - 1 suffixPrefix[textIndex] = zeta![patternIndex] } /* Search stage: scanning the text for pattern matching */ textIndex = 0 patternIndex = 0 while textIndex + (patternLength - patternIndex - 1) < textLength { while patternIndex < patternLength && text[textIndex] == pattern[patternIndex] { textIndex = textIndex + 1 patternIndex = patternIndex + 1 } if patternIndex == patternLength { indexes.append(textIndex - patternIndex) } if patternIndex == 0 { textIndex = textIndex + 1 } else { patternIndex = suffixPrefix[patternIndex - 1] } } guard !indexes.isEmpty else { return nil } return indexes } } /* Examples */ let dna = "ACCCGGTTTTAAAGAACCACCATAAGATATAGACAGATATAGGACAGATATAGAGACAAAACCCCATACCCCAATATTTTTTTGGGGAGAAAAACACCACAGATAGATACACAGACTACACGAGATACGACATACAGCAGCATAACGACAACAGCAGATAGACGATCATAACAGCAATCAGACCGAGCGCAGCAGCTTTTAAGCACCAGCCCCACAAAAAACGACAATFATCATCATATACAGACGACGACACGACATATCACACGACAGCATA" dna.indexesOf(ptnr: "CATA") // [20, 64, 130, 140, 166, 234, 255, 270] let concert = "🎼🎹🎹🎸🎸🎻🎻🎷🎺🎤👏👏👏" concert.indexesOf(ptnr: "🎻🎷") // [6]
mit
28ea3e03ff7f3eb707ba976c27afcbb9
28.778689
286
0.549959
3.840381
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Explorer/BlockDetailViewController.swift
1
5532
// Copyright (c) 2016 Ark // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import SwiftyArk class BlockDetailViewController: ArkViewController { fileprivate let block : Block fileprivate var tableView : ArkTableView! init(_ block: Block) { self.block = block super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Block Detail" tableView = ArkTableView(CGRect.zero) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview() } } } // MARK: UITableViewDelegate extension BlockDetailViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: _screenWidth, height: 35.0)) headerView.backgroundColor = ArkPalette.secondaryBackgroundColor let headerLabel = UILabel(frame: CGRect(x: 12.5, y: 0.0, width: _screenWidth - 12.5, height: 35.0)) headerLabel.textColor = ArkPalette.highlightedTextColor headerLabel.textAlignment = .center headerLabel.font = UIFont.systemFont(ofSize: 15.0, weight: .semibold) switch section { case 0: headerLabel.text = "Block ID" case 1: headerLabel.text = "Height" case 2: headerLabel.text = "Previous Block" case 3: headerLabel.text = "Number of Transactions" case 4: headerLabel.text = "Total Amount" case 5: headerLabel.text = "Total Fee" case 6: headerLabel.text = "Rewards Fee" case 7: headerLabel.text = "Payload Length" case 8: headerLabel.text = "Generator Public Key" case 9: headerLabel.text = "Block Signature" default: headerLabel.text = "Confirmations" } headerView.addSubview(headerLabel) return headerView } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 8 { return 60.0 } else if indexPath.section == 9 { return 90.0 } return 40.0 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } } // MARK: UITableViewDelegate extension BlockDetailViewController : UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 11 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var titleString = "" var numberOfLines = 1 switch indexPath.section { case 0: titleString = String(block.id) case 1: titleString = String(block.height) case 2: titleString = block.previousBlock case 3: titleString = String(block.numberOfTransactions) case 4: titleString = String(block.totalAmount) case 5: titleString = String(block.totalFee) case 6: titleString = String(block.reward) case 7: titleString = String(block.payloadLength) case 8: titleString = block.generatorPublicKey numberOfLines = 2 case 9: titleString = block.blockSignature numberOfLines = 4 default: titleString = String(block.confirmations) } let cell = ArkDetailTableViewCell(titleString, numberOfLines: numberOfLines) return cell } }
mit
13a537c317adac4289ef7977840ccba6
33.360248
137
0.629067
5.131725
false
false
false
false
danielbreves/MusicTheory
Sources/NoteWithIntervals.swift
1
1465
// // NoteWithIntervals.swift // MusicTheory // // Created by Daniel Breves Ribeiro on 2/04/2015. // Copyright (c) 2015 Daniel Breves. All rights reserved. // import Foundation /** A root note with intervals (or a scale). */ open class RootWithIntervals { internal(set) open var notes: [Note] /** Initializes the scale with a root note and intervals. - parameter root:The root note of the scale. - parameter intervals:an array of interval symbols for the scale. - returns: The new RootWithIntervals instance. */ public init(root: Note, intervals: [String]) { var currentNote = root var notes = [currentNote] for interval in intervals { currentNote = root.add(interval) notes.append(currentNote) } self.notes = notes } internal init(notes: [Note]) { self.notes = notes } fileprivate(set) open lazy var names: [String] = { return self.notes.map { (note) -> String in return note.name } }() fileprivate(set) open lazy var values: [Int8] = { return self.notes.map { (note) -> Int8 in return note.value } }() /** The root note. - returns: the root note. */ open func root() -> Note { return notes[0] } /** Copies the scale. - returns: the copy of the scale. */ open func copy() -> RootWithIntervals { let copiedNotes = notes.map { $0.copy() } return RootWithIntervals(notes: copiedNotes) } }
mit
87680bd8fb82b356ce8158ff7555ba8d
19.068493
69
0.626621
3.690176
false
false
false
false
AaronBratcher/ALBPeerConnection
ALBPeerConnection/ALBPeerConnection/ALBPeerConnection.swift
1
11853
// // ALBPeerConnection.swift // ALBPeerConnection // // Created by Aaron Bratcher on 3/13/15. // Copyright (c) 2015 Aaron Bratcher. All rights reserved. // import Foundation public protocol ALBPeerConnectionDelegate { /** Called when the connection to the remote has been broken. - parameter connection: The connection that has been disconnected. - parameter byRequest: Is true if the disconnect was by request. */ func disconnected(_ connection: ALBPeerConnection, byRequest: Bool) /** Called when text has been received from the remote. - parameter connection: The connection that received the text. - parameter text: The text that was received. */ func textReceived(_ connection: ALBPeerConnection, text: String) /** Called when data has been received from the remote. - parameter connection: The connection that received the data. - parameter data: The data that was received. */ func dataReceived(_ connection: ALBPeerConnection, data: Data) /** Called when this connection has started to receive a resource from the remote. - parameter connection: The connection that is receiving the resource. - parameter atURL: The location of the resource. - parameter name: The given name of the resource. - parameter resourceID: The unique identifier of the resource - parameter progress: An NSProgress object that is updated as the file is received. This cannot be canceled at this time. */ func startedReceivingResource(_ connection: ALBPeerConnection, atURL: URL, name: String, resourceID: String, progress: Progress) /** Called when this connection has finished receiving a resource from the remote. - parameter connection: The connection that is receiving the resource. - parameter atURL: The location of the resource. - parameter name: The given name of the resource. - parameter resourceID: The unique identifier of the resource */ func resourceReceived(_ connection: ALBPeerConnection, atURL: URL, name: String, resourceID: String) } let ALBPeerConnectionQueue = DispatchQueue(label: "com.AaronLBratcher.ALBPeerConnectionQueue") let ALBPeerPacketDelimiter = Data(bytes: UnsafePointer<UInt8>([0x0B, 0x1B, 0x1B] as [UInt8]), count: 3) // VerticalTab Esc Esc let ALBPeerMaxDataSize = 65536 let ALBPeerWriteTimeout = TimeInterval(60) public final class ALBPeerConnection: NSObject, GCDAsyncSocketDelegate { public var delegate: ALBPeerConnectionDelegate? { didSet { _socket.readData(to: ALBPeerPacketDelimiter, withTimeout: -1, tag: 0) } } public var delegateQueue = DispatchQueue.main public var remotNode: ALBPeer fileprivate var _socket: GCDAsyncSocket fileprivate var _disconnecting = false fileprivate var _pendingPackets = [Int: ALBPeerPacket]() fileprivate var _lastTag = 0 fileprivate var _cachedData: Data? fileprivate var _resourceFiles = [String: Resource]() class Resource { var handle: FileHandle var path: String var name: String var progress = Progress() init(handle: FileHandle, path: String, name: String) { self.handle = handle self.path = path self.name = name self.progress.isCancellable = false } } // MARK: - Initializers /* this is called by the client or server class. Do not call this directly. */ public init(socket: GCDAsyncSocket, remoteNode: ALBPeer) { _socket = socket self.remotNode = remoteNode super.init() socket.delegate = self } // MARK: - Public Methods /* Disconnect from the remote. If there are pending packets to be sent, they will be sent before disconnecting. */ public func disconnect() { _disconnecting = true if _pendingPackets.count == 0 { _socket.disconnect() } } /** Send a text string to the remote. - parameter text: The text to send. */ public func sendText(_ text: String) { let packet = ALBPeerPacket(type: .text) let data = text.data(using: String.Encoding.utf8, allowLossyConversion: false) _pendingPackets[_lastTag] = packet _socket.write(packet.packetDataUsingData(data), withTimeout: ALBPeerWriteTimeout, tag: _lastTag) _lastTag += 1 } /** Send data to the remote. - parameter data: The data to send. */ public func sendData(_ data: Data) { let packet = ALBPeerPacket(type: .data) _pendingPackets[_lastTag] = packet _socket.write(packet.packetDataUsingData(data), withTimeout: ALBPeerWriteTimeout, tag: _lastTag) _lastTag += 1 } /** Send a file to the remote. - parameter url: The URL path to the file. - parameter name: The name of the file. - parameter resourceID: A unique string identifier to this resource. - parameter onCompletion: A block of code that will be called when the resource has been sent - returns: NSProgress This will be updated as the file is sent. Currently, a send cannot be canceled. */ public func sendResourceAtURL(_ url: URL, name: String, resourceID: String, onCompletion: @escaping completionHandler) -> Progress { let data = try! Data(contentsOf: url, options: NSData.ReadingOptions.mappedRead) var resource = ALBPeerResource(identity: resourceID, name: name, url: url, data: data) resource.onCompletion = onCompletion resource.progress = Progress(totalUnitCount: Int64(resource.length)) resource.progress?.isCancellable = false sendResourcePacket(resource) return resource.progress! } private func sendResourcePacket(_ resource: ALBPeerResource) { var resource = resource var packet = ALBPeerPacket(type: .resource) let dataSize = max(ALBPeerMaxDataSize, resource.length - resource.offset) resource.offset += dataSize if resource.offset >= resource.length { packet.isFinal = true } if let progress = resource.progress { progress.completedUnitCount = Int64(resource.offset) } packet.resource = resource let range = 0..<resource.offset + dataSize let subData = resource.mappedData!.subdata(in: range) _pendingPackets[_lastTag] = packet _socket.write(packet.packetDataUsingData(subData), withTimeout: ALBPeerWriteTimeout, tag: _lastTag) _lastTag += 1 } // MARK: - Socket Delegate /** This is for internal use only **/ public func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { if let packet = _pendingPackets[tag] { _pendingPackets.removeValue(forKey: tag) if _disconnecting && _pendingPackets.count == 0 && (packet.type == .data || packet.isFinal) { _socket.disconnectAfterWriting() return } // if this is a resource packet... send next packet if packet.type == .resource { if !packet.isFinal { sendResourcePacket(packet.resource!) } else { if let resource = packet.resource, let completionHandler = resource.onCompletion { completionHandler(true) } } } } } /** This is for internal use only **/ public func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) { if let packet = ALBPeerPacket(packetData: data) { processPacket(packet) } else { // store data from this read and append to it with data from next read if _cachedData == nil { _cachedData = Data() } _cachedData!.append(data) if _cachedData!.count > ALBPeerMaxDataSize * 4 { _socket.disconnect() return } if let packet = ALBPeerPacket(packetData: _cachedData!) { processPacket(packet) } } _socket.readData(to: ALBPeerPacketDelimiter, withTimeout: -1, tag: 0) } private func processPacket(_ packet: ALBPeerPacket) { _cachedData = nil switch packet.type { case .text: delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { guard let data = packet.data , let text = String(data: data, encoding: .utf8) else { return } delegate.textReceived(self, text: text) } else { print("Connection delegate is not assigned") } }) case .data: delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.dataReceived(self, data: packet.data! as Data) } else { print("Connection delegate is not assigned") } }) case .resource: if let resourceID = packet.resource?.identity, let name = packet.resource?.name, let resourceLength = packet.resource?.length, let packetLength = packet.data?.count { let handle: FileHandle var resourcePath: String var resource = _resourceFiles[packet.resource!.identity] if let resource = resource { handle = resource.handle resourcePath = resource.path } else { // create file let searchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentFolderPath = searchPaths[0] resourcePath = "\(documentFolderPath)/\(name)" var nameIndex = 1 while FileManager.default.fileExists(atPath: resourcePath) { let parts = resourcePath.components(separatedBy: ".") resourcePath = "" if parts.count > 1 { let partCount = parts.count - 1 for partIndex in 0..<partCount { resourcePath = "\(resourcePath).\(parts[partIndex])" } resourcePath = "\(resourcePath)-\(nameIndex)" resourcePath = "\(resourcePath).\(parts[parts.count-1])" } else { resourcePath = "\(resourcePath)\(nameIndex)" } nameIndex = nameIndex + 1 } FileManager.default.createFile(atPath: resourcePath, contents: nil, attributes: nil) if let fileHandle = FileHandle(forWritingAtPath: resourcePath) { resource = Resource(handle: fileHandle, path: resourcePath, name: name) let progress = Progress(totalUnitCount: Int64(resourceLength)) resource?.progress = progress _resourceFiles[resourceID] = resource handle = fileHandle } else { resourceCopyError(resourceID, name: name) return } delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.startedReceivingResource(self, atURL: URL(fileURLWithPath: resourcePath), name: packet.resource!.name, resourceID: resourceID, progress: resource!.progress) } else { print("Connection delegate is not assigned") } }) } if let progress = resource?.progress { progress.completedUnitCount = progress.completedUnitCount + Int64(packetLength) } handle.write(packet.data! as Data) if packet.isFinal { handle.closeFile() let resource = _resourceFiles[resourceID]! _resourceFiles.removeValue(forKey: resourceID) delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.resourceReceived(self, atURL: URL(fileURLWithPath: resourcePath), name: resource.name, resourceID: resourceID) } else { print("Connection delegate is not assigned") } }) } } else { resourceCopyError("**Unknown**", name: "**Unknown**") return } case .resourceError: if let resource = packet.resource, let completionHandler = resource.onCompletion { completionHandler(false) } default: // other cases handled elsewhere break } } private func resourceCopyError(_ resourceID: String, name: String) { let resource = ALBPeerResource(identity: resourceID, name: name) var packet = ALBPeerPacket(type: .resourceError) packet.resource = resource _socket.write(packet.packetDataUsingData(nil), withTimeout: ALBPeerWriteTimeout, tag: 0) } /** This is for internal use only **/ public func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { delegateQueue.async(execute: {[unowned self]() -> Void in if let delegate = self.delegate { delegate.disconnected(self, byRequest: self._disconnecting) } else { print("Connection delegate is not assigned") } }) } }
mit
c2e5cdbbeacfcb6bf1f4440941b6a2bd
31.385246
173
0.698642
3.920939
false
false
false
false
Hoodps/WZSJM
WZSJM/ViewController.swift
1
2279
// // ViewController.swift // WZSJM // // Created by xiexz on 15/12/18. // Copyright © 2015年 xiexz. All rights reserved. // import UIKit class ViewController: UIViewController { var allButtonImage = [[UIButton]]() override func viewDidLoad() { super.viewDidLoad() let backgroundImage = UIImageView() backgroundImage.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height) backgroundImage.image = UIImage(named: "background1.png") self.view.addSubview(backgroundImage) self.produceDie() self.produceCat() } func produceCat(){ let catImage = UIImageView() catImage.frame = CGRectMake(CGFloat(25+28*4), CGFloat(220+28*3), 28, 56) let leftImage = UIImage(named: "left2.png") let rightImage = UIImage(named: "right2.png") let middleImage = UIImage(named: "middle2.png") catImage.animationImages = [leftImage!,rightImage!, middleImage!] catImage.animationDuration = 1.0 catImage.startAnimating() self.view.addSubview(catImage) } func produceDie(){ for var i=0; i < 9; i++ { var rowButtons = [UIButton]() for var j = 0; j < 9; j++ { let btn = UIButton() rowButtons.append(btn) if j % 2 == 0{ btn.frame = CGRectMake(CGFloat(25+28*i), CGFloat(220+28*j), 28, 28) }else{ btn.frame = CGRectMake(CGFloat(39+28*i), CGFloat(220+28*j), 28, 28) } btn.setImage(UIImage(named: "gray.png"), forState: UIControlState.Normal) btn.addTarget(self, action: "clickMe:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(btn) } allButtonImage.append(rowButtons) } } func clickMe(btn:UIButton){ btn.setImage(UIImage(named: "yellow2.png"), forState: UIControlState.Normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
5714f5524b25b0e5aa208db836e6fee1
29.346667
121
0.569859
4.393822
false
false
false
false
ryanipete/AmericanChronicle
AmericanChronicle/Code/AppWide/Views/TitleButton.swift
1
854
import UIKit final class TitleButton: UIButton { init(title: String) { super.init(frame: .zero) layer.shadowColor = AMCColor.darkGray.cgColor layer.shadowOffset = .zero layer.shadowRadius = 0.5 layer.shadowOpacity = 0.4 titleLabel?.font = AMCFont.mediumRegular setTitleColor(AMCColor.brightBlue, for: .normal) setTitleColor(.white, for: .highlighted) setBackgroundImage(.imageWithFillColor(.white), for: .normal) setBackgroundImage(.imageWithFillColor(AMCColor.brightBlue), for: .highlighted) setTitle(title, for: .normal) } override convenience init(frame: CGRect) { self.init(title: "") } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
2915dcc233fe4f19c5137edf4e6a59a5
28.448276
87
0.652225
4.447917
false
false
false
false
swilliams/Lattice
Lattice/Extensions/NumberMasker.swift
1
2199
// // StringMask.swift // Lattice // // Created by Scott Williams on 7/29/15. // Copyright (c) 2015 Tallwave. All rights reserved. // // NSMatchingOptions.WithoutAnchoringBounds 1 << 4 (16) // NSRegularExpressionOptions.AnchorsMatchLines (16) import UIKit /** Masks a numeric string according to a pattern defined. The pattern should resemble a string of #'s with the punctuation and spacing at appropriate positions. For example a phone number's pattern would look like `(###) ###-####`. The masker will skip over any characters that are not numbers. If a string is shorter than the pattern, it will be masked to the pattern for as much as it can. For example, `12345` masked against the phone number mask will be `(123) 45`. */ struct NumberMasker { /** Formats the string with the provided pattern. */ func mask(string: String, withPattern pattern: String) -> String { var stringIndex = 0 var patternIndex = 0 let stringCount = count(string) let patternCount = count(pattern) var formattedString = "" while stringIndex < stringCount && patternIndex < patternCount { let currentStringChar = character(inString: string, atIndex: stringIndex) let currentPatternChar = character(inString: pattern, atIndex: patternIndex) switch currentPatternChar { case "#": if currentStringChar.isDigit() { formattedString += currentStringChar patternIndex += 1 } stringIndex += 1 default: formattedString += currentPatternChar if currentStringChar == currentPatternChar { stringIndex += 1 } patternIndex += 1 } } return formattedString } private func character(inString string: String, atIndex index: Int) -> String { let startStringIndex = advance(string.startIndex, index) let endStringIndex = advance(string.startIndex, index + 1) return string.substringWithRange(Range<String.Index>(start: startStringIndex, end: endStringIndex)) } }
mit
89b637e8edbb197e9095b251e221f091
33.375
107
0.635744
4.832967
false
false
false
false
arikis/Overdrive
Sources/Overdrive/Result.swift
1
2849
// // Result.swift // Overdrive // // Created by Said Sikira on 6/19/16. // Copyright © 2016 Said Sikira. All rights reserved. // /** Task result definition. `Result<T>` is one of the fundamental concepts in Task execution. To finish execution of any task, you need to pass the Result to the `finish(_:)` method. `Result<T>` enum definition defines two cases: * `Value(T)` * `Error(ErrorType)` **Example** ```swift var intResult: Result<Int> = .Value(10) intResult = .Error(someError) ``` */ public enum Result<T> { /// Value with associated type `T` case value(T) /// Error case with associated `ErrorType` case error(Error) // MARK: Init methods public init(_ value: T) { self = .value(value) } public init(_ error: Error) { self = .error(error) } // MARK: Associated values /// Returns value `T` public var value: T? { if case .value(let value) = self { return value } return nil } /// Returns error value public var error: Error? { if case .error(let error) = self { return error } return nil } } extension Result { /// Flat map over the result value /// /// - Parameter transform: transform block /// /// - Returns: `Result<U>` public func flatMap<U>(_ transform: (T) throws -> Result<U>) rethrows -> Result<U> { switch self { case let .value(value): return try transform(value) case let .error(error): return Result<U>.error(error) } } /// Flat map over result error /// /// - Parameter transform: Transform block /// - Returns: `Result` public func flatMapError(_ transform: (Error) throws -> Result) rethrows -> Result { switch self { case let .value(current): return .value(current) case let .error(error): return try transform(error) } } /// Maps over result /// /// - Parameter transform: Transform block /// - Returns: `Result<U>` public func map<U>(_ transform: (T) throws -> U) rethrows -> Result<U> { return try flatMap { .value(try transform($0)) } } /// Map over task error /// /// - Parameter transform: Transform block /// - Returns: `Result` public func mapError<O: Error>(_ transform: (Error) throws -> O) rethrows -> Result { return try flatMapError{ .error(try transform($0)) } } } extension Result: CustomStringConvertible { /// Returns textual representation of `self` public var description: String { switch self { case .value(let value): return "\(value)" case .error(let error): return "\(error)" } } }
mit
a9fe600c105ff9a754d67741aaf7079e
22.932773
89
0.561096
4.20059
false
false
false
false
alexito4/RACPhotos
Example/Tests/Tests.swift
1
1176
// https://github.com/Quick/Quick import Quick import Nimble import RACPhotos class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
b7d6f16940e4aeef133341616aa4c99a
22.4
63
0.363248
5.46729
false
false
false
false
idapgroup/IDPDesign
Tests/iOS/iOSTests/Specs/Lens+UIButtonSpec.swift
1
7981
// // Lens+UIButtonSpec.swift // iOSTests // // Created by Oleksa 'trimm' Korin on 9/2/17. // Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved. // import Quick import Nimble import UIKit @testable import IDPDesign extension UIButton: UIButtonProtocol { } class LensUIButtonSpec: QuickSpec { override func spec() { describe("Lens+UIButtonSpec") { context("backgroundImage(for:)") { it("should get and set") { let state = UIControl.State.disabled let lens: Lens<UIButton, UIImage?> = backgroundImage(for: state) let object = UIButton() let value = UIImage.default let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.backgroundImage(for: state)).to(equal(value)) } } context("title(for:)") { it("should get and set") { let state = UIControl.State.disabled let lens: Lens<UIButton, String?> = title(for: state) let object = UIButton() let value = "mama" let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.title(for: state)).to(equal(value)) } } context("image(for:)") { it("should get and set") { let state = UIControl.State.disabled let lens: Lens<UIButton, UIImage?> = image(for: state) let object = UIButton() let value = UIImage.default let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.image(for: state)).to(equal(value)) } } context("title(for:)") { it("should get and set") { let state = UIControl.State.disabled let lens: Lens<UIButton, NSAttributedString?> = attributedTitle(for: state) let object = UIButton() let value = NSAttributedString(string: "mama") let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.attributedTitle(for: state)).to(equal(value)) } } context("titleColor(for:)") { it("should get and set") { let state = UIControl.State.disabled let lens: Lens<UIButton, UIColor?> = titleColor(for: state) let object = UIButton() let value = UIColor.red let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.titleColor(for: state)).to(equal(value)) } } context("adjustsImageWhenDisabled") { it("should get and set") { let lens: Lens<UIButton, Bool> = adjustsImageWhenDisabled() let object = UIButton() let value: Bool = !object.adjustsImageWhenDisabled let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.adjustsImageWhenDisabled).to(equal(value)) } } context("adjustsImageWhenHighlighted") { it("should get and set") { let lens: Lens<UIButton, Bool> = adjustsImageWhenHighlighted() let object = UIButton() let value: Bool = !object.adjustsImageWhenHighlighted let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.adjustsImageWhenHighlighted).to(equal(value)) } } context("contentEdgeInsets") { it("should get and set") { let lens: Lens<UIButton, UIEdgeInsets> = contentEdgeInsets() let object = UIButton() let value: UIEdgeInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.contentEdgeInsets).to(equal(value)) } } context("imageEdgeInsets") { it("should get and set") { let lens: Lens<UIButton, UIEdgeInsets> = imageEdgeInsets() let object = UIButton() let value: UIEdgeInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.imageEdgeInsets).to(equal(value)) } } context("imageView") { it("should get and set") { let lens: Lens<UIButton, UIImageView?> = imageView() let object = UIButton() let value: UIImageView = UIImageView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.imageView).to(equal(resultValue)) } } context("titleEdgeInsets") { it("should get and set") { let lens: Lens<UIButton, UIEdgeInsets> = titleEdgeInsets() let object = UIButton() let value: UIEdgeInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.titleEdgeInsets).to(equal(value)) } } context("titleLabel") { it("should get and set") { let lens: Lens<UIButton, UILabel?> = titleLabel() let object = UIButton() let value: UILabel = UILabel() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.titleLabel).to(equal(resultValue)) } } } } }
bsd-3-clause
090f512541c902374c96babe67f7edca
36.464789
96
0.470927
5.841874
false
false
false
false
emilstahl/swift
test/attr/attr_nonobjc.swift
14
3502
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop import Foundation @objc class LightSaber { init() { caloriesBurned = 5 } func defeatEnemy(b: Bool) -> Bool { // expected-note {{'defeatEnemy' previously declared here}} return !b } // Make sure we can overload a method with @nonobjc methods @nonobjc func defeatEnemy(i: Int) -> Bool { return (i > 0) } // This is not allowed, though func defeatEnemy(s: String) -> Bool { // expected-error {{method 'defeatEnemy' with Objective-C selector 'defeatEnemy:' conflicts with previous declaration with the same Objective-C selector}} return s != "" } @nonobjc subscript(index: Int) -> Int { return index } @nonobjc var caloriesBurned: Float } class BlueLightSaber : LightSaber { @nonobjc override func defeatEnemy(b: Bool) -> Bool { } } @objc class InchoateToad { init(x: Int) {} // expected-note {{previously declared}} @nonobjc init(x: Float) {} init(x: String) {} // expected-error {{conflicts with previous declaration with the same Objective-C selector}} } @nonobjc class NonObjCClassNotAllowed { } // expected-error {{@nonobjc cannot be applied to this declaration}} {{1-10=}} class NonObjCDeallocNotAllowed { @nonobjc deinit { // expected-error {{@nonobjc cannot be applied to this declaration}} {{3-12=}} } } @objc protocol ObjCProtocol { func protocolMethod() // expected-note {{}} @nonobjc func nonObjCProtocolMethodNotAllowed() // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} @nonobjc subscript(index: Int) -> Int { get } // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} var surfaceArea: Float { @nonobjc get } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} var displacement: Float { get } } class SillyClass { @objc var description: String { @nonobjc get { return "" } } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} } class ObjCAndNonObjCNotAllowed { @objc @nonobjc func redundantAttributes() { } // expected-error {{declaration is marked @objc, and cannot be marked @nonobjc}} } class DynamicAndNonObjCNotAllowed { @nonobjc dynamic func redundantAttributes() { } // expected-error {{declaration is marked dynamic, and cannot be marked @nonobjc}} } class IBOutletAndNonObjCNotAllowed { @nonobjc @IBOutlet var leeloo : String? = "Hello world" // expected-error {{declaration is marked @IBOutlet, and cannot be marked @nonobjc}} } class NSManagedAndNonObjCNotAllowed { @nonobjc @NSManaged var rosie : NSObject // expected-error {{declaration is marked @NSManaged, and cannot be marked @nonobjc}} } @nonobjc func nonObjCTopLevelFuncNotAllowed() { } // expected-error {{only methods, initializers, properties and subscript declarations can be declared @nonobjc}} {{1-10=}} @objc class NonObjCPropertyObjCProtocolNotAllowed : ObjCProtocol { // expected-error {{does not conform to protocol}} @nonobjc func protocolMethod() { } // expected-note {{candidate is not '@objc', but protocol requires it}} {{3-3=@objc }} func nonObjCProtocolMethodNotAllowed() { } subscript(index: Int) -> Int { return index } var displacement: Float { @nonobjc get { // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} return Float(self[10]) } } var surfaceArea: Float { get { return Float(100) } } }
apache-2.0
d2fbd5b9a31c0191254a31e1934dc3f3
32.673077
194
0.705882
4.115159
false
false
false
false
ben-ng/swift
test/stdlib/StringReallocation.swift
21
1009
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // CHECK-NOT: Reallocations exceeded 30 func testReallocation() { var x = "The quick brown fox jumped over the lazy dog\n"._split(separator: " ") var story = "Let me tell you a story:" var laps = 1000 var reallocations = 0 for i in 0..<laps { for s in x { var lastBase = story._core._baseAddress story += " " story += s if lastBase != story._core._baseAddress { reallocations += 1 // To avoid dumping a vast string here, just write the first // part of the story out each time there's a reallocation. var intro = story._split(separator: ":")[0] print("reallocation \(reallocations), with intro \(intro)") if reallocations >= 30 { print("Reallocations exceeded 30") return } } } story += "." } print("total reallocations = \(reallocations)") } testReallocation() print("done!")
apache-2.0
2bbed1c20d43fc1a6d291880c5004cb5
26.27027
81
0.592666
4.118367
false
true
false
false
wesj/firefox-ios-1
Storage/Site.swift
4
1186
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit protocol Identifiable { var id: Int? { get set } } public enum IconType: Int { case Icon = 0 case AppleIcon = 1 case AppleIconPrecomposed = 2 case Guess = 3 case Local = 4 } public class Favicon : Identifiable { var id: Int? = nil var img: UIImage? = nil public let url: String public let date: NSDate public var width: Int? public var height: Int? public let type: IconType public init(url: String, date: NSDate = NSDate(), type: IconType) { self.url = url self.date = date self.type = type } } public class Site : Identifiable { var id: Int? = nil var guid: String? = nil public let url: String public let title: String // Sites may have multiple favicons. We'll return the largest. public var icon: Favicon? public var latestVisit: Visit? public init(url: String, title: String) { self.url = url self.title = title } }
mpl-2.0
2e06602eaad048d9c10829f5a93d566f
22.72
71
0.631535
3.838188
false
false
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Collection/Cells/NTFormActionCell.swift
1
2402
// // NTFormActionCell.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 6/23/17. // open class NTFormActionCell: NTFormCell { open override var datasourceItem: Any? { get { return self } set { guard let cell = newValue as? NTFormActionCell else { return } self.button.removeFromSuperview() self.button = cell.button self.onTap = cell.onTap self.setupViews() } } open var title: String? { get { return button.title } set { button.title = newValue } } open var button: NTButton = { let button = NTButton() button.backgroundColor = .white return button }() open var onTap: (() -> Void)? @discardableResult open func onTap(_ handler: @escaping (() -> Void)) -> Self { onTap = handler return self } open override func setupViews() { super.setupViews() addSubview(button) button.fillSuperview() button.addTarget(self, action: #selector(didTap(_:)), for: .touchUpInside) } @objc open func didTap(_ sender: AnyObject) { onTap?() } }
mit
e8676b970085a2a83f198e63524246d0
30.181818
82
0.63307
4.582061
false
false
false
false
varkor/firefox-ios
Storage/SQL/SQLiteHistory.swift
1
52393
/* 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 XCGLogger import Deferred private let log = Logger.syncLogger class NoSuchRecordError: MaybeErrorType { let guid: GUID init(guid: GUID) { self.guid = guid } var description: String { return "No such record: \(guid)." } } func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Maybe<T>> { if let err = err { log.debug("\(op) failed: \(err.localizedDescription)") return deferMaybe(DatabaseError(err: err)) } return deferMaybe(val) } func failOrSucceed(err: NSError?, op: String) -> Success { return failOrSucceed(err, op: op, val: ()) } private var ignoredSchemes = ["about"] public func isIgnoredURL(url: NSURL) -> Bool { let scheme = url.scheme if let _ = ignoredSchemes.indexOf(scheme) { return true } if url.host == "localhost" { return true } return false } public func isIgnoredURL(url: String) -> Bool { if let url = NSURL(string: url) { return isIgnoredURL(url) } return false } /* // Here's the Swift equivalent of the below. func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double { let ageMicroseconds = (now - then) let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion. let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225) return Double(visitCount) * max(1.0, f) } */ // The constants in these functions were arrived at by utterly unscientific experimentation. func getRemoteFrecencySQL() -> String { let visitCountExpression = "remoteVisitCount" let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))" } func getLocalFrecencySQL() -> String { let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))" let now = NSDate.nowMicroseconds() let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24 let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))" return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))" } extension SDRow { func getTimestamp(column: String) -> Timestamp? { return (self[column] as? NSNumber)?.unsignedLongLongValue } func getBoolean(column: String) -> Bool { if let val = self[column] as? Int { return val != 0 } return false } } /** * The sqlite-backed implementation of the history protocol. */ public class SQLiteHistory { let db: BrowserDB let favicons: FaviconsTable<Favicon> let prefs: Prefs required public init?(db: BrowserDB, prefs: Prefs) { self.db = db self.favicons = FaviconsTable<Favicon>() self.prefs = prefs // BrowserTable exists only to perform create/update etc. operations -- it's not // a queryable thing that needs to stick around. if !db.createOrUpdate(BrowserTable()) { return nil } } } private let topSitesQuery = "SELECT * FROM \(TableCachedTopSites) ORDER BY frecencies DESC LIMIT (?)" extension SQLiteHistory: BrowserHistory { public func removeSiteFromTopSites(site: Site) -> Success { if let host = site.url.asURL?.normalizedHost() { return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])]) >>> { return self.refreshTopSitesCache() } } return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)")) } public func removeHistoryForURL(url: String) -> Success { let visitArgs: Args = [url] let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)" let markArgs: Args = [NSDate.nowNumber(), url] let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?" return db.run([(deleteVisits, visitArgs), (markDeleted, markArgs), favicons.getCleanupCommands()]) } // Note: clearing history isn't really a sane concept in the presence of Sync. // This method should be split to do something else. // Bug 1162778. public func clearHistory() -> Success { return self.db.run([ ("DELETE FROM \(TableVisits)", nil), ("DELETE FROM \(TableHistory)", nil), ("DELETE FROM \(TableDomains)", nil), self.favicons.getCleanupCommands(), ]) // We've probably deleted a lot of stuff. Vacuum now to recover the space. >>> effect(self.db.vacuum) } func recordVisitedSite(site: Site) -> Success { var error: NSError? = nil // Don't store visits to sites with about: protocols if isIgnoredURL(site.url) { return deferMaybe(IgnoredSiteError()) } db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in let now = NSDate.nowNumber() let i = self.updateSite(site, atTime: now, withConnection: conn) if i > 0 { return i } // Insert instead. return self.insertSite(site, atTime: now, withConnection: conn) } return failOrSucceed(error, op: "Record site") } func updateSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int { // We know we're adding a new visit, so we'll need to upload this record. // If we ever switch to per-visit change flags, this should turn into a CASE statement like // CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END // so that we don't flag this as changed unless the title changed. // // Note that we will never match against a deleted item, because deleted items have no URL, // so we don't need to unset is_deleted here. if let host = site.url.asURL?.normalizedHost() { let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?" let updateArgs: Args? = [site.title, time, host, site.url] if Logger.logPII { log.debug("Setting title to \(site.title) for URL \(site.url)") } let error = conn.executeChange(update, withArgs: updateArgs) if error != nil { log.warning("Update failed with \(error?.localizedDescription)") return 0 } return conn.numberOfRowsModified } return 0 } private func insertSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int { if let host = site.url.asURL?.normalizedHost() { if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) { log.warning("Domain insertion failed with \(error.localizedDescription)") return 0 } let insert = "INSERT INTO \(TableHistory) " + "(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " + "SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?" let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host] if let error = conn.executeChange(insert, withArgs: insertArgs) { log.warning("Site insertion failed with \(error.localizedDescription)") return 0 } return 1 } if Logger.logPII { log.warning("Invalid URL \(site.url). Not stored in history.") } return 0 } // TODO: thread siteID into this to avoid the need to do the lookup. func addLocalVisitForExistingSite(visit: SiteVisit) -> Success { var error: NSError? = nil db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in // INSERT OR IGNORE because we *might* have a clock error that causes a timestamp // collision with an existing visit, and it would really suck to error out for that reason. let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" + "(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)" let realDate = NSNumber(unsignedLongLong: visit.date) let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue] error = conn.executeChange(insert, withArgs: insertArgs) if error != nil { log.warning("Visit insertion failed with \(err?.localizedDescription)") return 0 } return 1 } return failOrSucceed(error, op: "Record visit") } public func addLocalVisit(visit: SiteVisit) -> Success { return recordVisitedSite(visit.site) >>> { self.addLocalVisitForExistingSite(visit) } } public func getSitesByFrecencyWithHistoryLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.getSitesByFrecencyWithHistoryLimit(limit, includeIcon: true) } public func getSitesByFrecencyWithHistoryLimit(limit: Int, includeIcon: Bool) -> Deferred<Maybe<Cursor<Site>>> { // Exclude redirect domains. Bug 1194852. let (whereData, groupBy) = self.topSiteClauses() return self.getFilteredSitesByFrecencyWithHistoryLimit(limit, bookmarksLimit: 0, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon) } public func getTopSitesWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.db.runQuery(topSitesQuery, args: [limit], factory: SQLiteHistory.iconHistoryColumnFactory) } public func setTopSitesNeedsInvalidation() { prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid) } public func updateTopSitesCacheIfInvalidated() -> Deferred<Maybe<Bool>> { if prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false { return deferMaybe(false) } return refreshTopSitesCache() >>> always(true) } public func setTopSitesCacheSize(size: Int32) { let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0 if oldValue != size { prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize) setTopSitesNeedsInvalidation() } } public func refreshTopSitesCache() -> Success { let cacheSize = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0) return updateTopSitesCacheWithLimit(cacheSize) } //swiftlint:disable opening_brace public func areTopSitesDirty(withLimit limit: Int) -> Deferred<Maybe<Bool>> { let (whereData, groupBy) = self.topSiteClauses() let (query, args) = self.filteredSitesByFrecencyQueryWithHistoryLimit(limit, bookmarksLimit: 0, groupClause: groupBy, whereData: whereData) let cacheArgs: Args = [limit] return accumulate([ { self.db.runQuery(query, args: args, factory: SQLiteHistory.iconHistoryColumnFactory) }, { self.db.runQuery(topSitesQuery, args: cacheArgs, factory: SQLiteHistory.iconHistoryColumnFactory) } ]).bind { results in guard let results = results.successValue else { // Something weird happened - default to dirty. return deferMaybe(true) } let frecencyResults = results[0] let cacheResults = results[1] // Counts don't match? Exit early and say we're dirty. if frecencyResults.count != cacheResults.count { return deferMaybe(true) } var isDirty = false // Check step-wise that the ordering and entries are the same (0..<frecencyResults.count).forEach { index in guard let frecencyID = frecencyResults[index]?.id, let cacheID = cacheResults[index]?.id where frecencyID == cacheID else { // It only takes one difference to make everything dirty isDirty = true return } } return deferMaybe(isDirty) } } //swiftlint:enable opening_brace private func updateTopSitesCacheWithLimit(limit: Int) -> Success { let (whereData, groupBy) = self.topSiteClauses() let (query, args) = self.filteredSitesByFrecencyQueryWithHistoryLimit(limit, bookmarksLimit: 0, groupClause: groupBy, whereData: whereData) // We must project, because we get bookmarks in these results. let insertQuery = [ "INSERT INTO \(TableCachedTopSites)", "SELECT historyID, url, title, guid, domain_id, domain,", "localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount,", "iconID, iconURL, iconDate, iconType, iconWidth, frecencies", "FROM (", query, ")" ].joinWithSeparator(" ") return self.clearTopSitesCache() >>> { return self.db.run(insertQuery, withArgs: args) } >>> { self.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } public func clearTopSitesCache() -> Success { let deleteQuery = "DELETE FROM \(TableCachedTopSites)" return self.db.run(deleteQuery, withArgs: nil) >>> { self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid) return succeed() } } public func getSitesByFrecencyWithHistoryLimit(limit: Int, bookmarksLimit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByFrecencyWithHistoryLimit(limit, bookmarksLimit: bookmarksLimit, whereURLContains: filter, includeIcon: true) } public func getSitesByFrecencyWithHistoryLimit(limit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByFrecencyWithHistoryLimit(limit, bookmarksLimit: 0, whereURLContains: filter, includeIcon: true) } public func getSitesByLastVisit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> { return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true) } private class func basicHistoryColumnFactory(row: SDRow) -> Site { let id = row["historyID"] as! Int let url = row["url"] as! String let title = row["title"] as! String let guid = row["guid"] as! String // Extract a boolean from the row if it's present. let iB = row["is_bookmarked"] as? Int let isBookmarked: Bool? = (iB == nil) ? nil : (iB! != 0) let site = Site(url: url, title: title, bookmarked: isBookmarked) site.guid = guid site.id = id // Find the most recent visit, regardless of which column it might be in. let local = row.getTimestamp("localVisitDate") ?? 0 let remote = row.getTimestamp("remoteVisitDate") ?? 0 let either = row.getTimestamp("visitDate") ?? 0 let latest = max(local, remote, either) if latest > 0 { site.latestVisit = Visit(date: latest, type: VisitType.Unknown) } return site } private class func iconColumnFactory(row: SDRow) -> Favicon? { if let iconType = row["iconType"] as? Int, let iconURL = row["iconURL"] as? String, let iconDate = row["iconDate"] as? Double, let _ = row["iconID"] as? Int { let date = NSDate(timeIntervalSince1970: iconDate) return Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!) } return nil } private class func iconHistoryColumnFactory(row: SDRow) -> Site { let site = basicHistoryColumnFactory(row) site.icon = iconColumnFactory(row) return site } private func topSiteClauses() -> (String, String) { let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') " let groupBy = "GROUP BY domain_id " return (whereData, groupBy) } private func computeWordsWithFilter(filter: String) -> [String] { // Split filter on whitespace. let words = filter.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) // Remove substrings and duplicates. // TODO: this can probably be improved. return words.enumerate().filter({ (index: Int, word: String) in if word.isEmpty { return false } for i in words.indices where i != index { if words[i].rangeOfString(word) != nil && (words[i].characters.count != word.characters.count || i < index) { return false } } return true }).map({ $0.1 }) } /** * Take input like "foo bar" and a template fragment and produce output like * * ((x.y LIKE ?) OR (x.z LIKE ?)) AND ((x.y LIKE ?) OR (x.z LIKE ?)) * * with args ["foo", "foo", "bar", "bar"]. */ internal func computeWhereFragmentWithFilter(filter: String, perWordFragment: String, perWordArgs: String -> Args) -> (fragment: String, args: Args) { precondition(!filter.isEmpty) let words = computeWordsWithFilter(filter) return self.computeWhereFragmentForWords(words, perWordFragment: perWordFragment, perWordArgs: perWordArgs) } internal func computeWhereFragmentForWords(words: [String], perWordFragment: String, perWordArgs: String -> Args) -> (fragment: String, args: Args) { assert(!words.isEmpty) let fragment = Array(count: words.count, repeatedValue: perWordFragment).joinWithSeparator(" AND ") let args = words.flatMap(perWordArgs) return (fragment, args) } private func getFilteredSitesByVisitDateWithLimit(limit: Int, whereURLContains filter: String? = nil, includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> { let args: Args? let whereClause: String if let filter = filter?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) where !filter.isEmpty { let perWordFragment = "((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?))" let perWordArgs: String -> Args = { ["%\($0)%", "%\($0)%"] } let (filterFragment, filterArgs) = computeWhereFragmentWithFilter(filter, perWordFragment: perWordFragment, perWordArgs: perWordArgs) // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = "WHERE (\(filterFragment))" args = filterArgs } else { whereClause = "WHERE (\(TableHistory).is_deleted = 0)" args = [] } let ungroupedSQL = [ "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain,", "COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate,", "COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate,", "COALESCE(count(\(TableVisits).is_local), 0) AS visitCount", "FROM \(TableHistory)", "INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id", "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id", whereClause, "GROUP BY historyID", ].joinWithSeparator(" ") let historySQL = [ "SELECT historyID, url, title, guid, domain_id, domain, visitCount,", "max(localVisitDate) AS localVisitDate,", "max(remoteVisitDate) AS remoteVisitDate", "FROM (", ungroupedSQL, ")", "WHERE (visitCount > 0)", // Eliminate dead rows from coalescing. "GROUP BY historyID", "ORDER BY max(localVisitDate, remoteVisitDate) DESC", "LIMIT \(limit)", ].joinWithSeparator(" ") if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let sql = [ "SELECT", "historyID, url, title, guid, domain_id, domain,", "localVisitDate, remoteVisitDate, visitCount, ", "iconID, iconURL, iconDate, iconType, iconWidth ", "FROM (", historySQL, ") LEFT OUTER JOIN ", "view_history_id_favicon ON historyID = view_history_id_favicon.id", ].joinWithSeparator(" ") let factory = SQLiteHistory.iconHistoryColumnFactory return db.runQuery(sql, args: args, factory: factory) } let factory = SQLiteHistory.basicHistoryColumnFactory return db.runQuery(historySQL, args: args, factory: factory) } private func getFilteredSitesByFrecencyWithHistoryLimit(limit: Int, bookmarksLimit: Int, whereURLContains filter: String? = nil, groupClause: String = "GROUP BY historyID ", whereData: String? = nil, includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> { let factory: (SDRow) -> Site if includeIcon { factory = SQLiteHistory.iconHistoryColumnFactory } else { factory = SQLiteHistory.basicHistoryColumnFactory } let (query, args) = filteredSitesByFrecencyQueryWithHistoryLimit( limit, bookmarksLimit: bookmarksLimit, whereURLContains: filter, groupClause: groupClause, whereData: whereData, includeIcon: includeIcon ) return db.runQuery(query, args: args, factory: factory) } private func filteredSitesByFrecencyQueryWithHistoryLimit(historyLimit: Int, bookmarksLimit: Int, whereURLContains filter: String? = nil, groupClause: String = "GROUP BY historyID ", whereData: String? = nil, includeIcon: Bool = true) -> (String, Args?) { let includeBookmarks = bookmarksLimit > 0 let localFrecencySQL = getLocalFrecencySQL() let remoteFrecencySQL = getRemoteFrecencySQL() let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24 let sixMonthsAgo = NSDate.nowMicroseconds() - sixMonthsInMicroseconds let args: Args let whereClause: String let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))" if let filter = filter?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) where !filter.isEmpty { let perWordFragment = "((url LIKE ?) OR (title LIKE ?))" let perWordArgs: String -> Args = { ["%\($0)%", "%\($0)%"] } let (filterFragment, filterArgs) = computeWhereFragmentWithFilter(filter, perWordFragment: perWordFragment, perWordArgs: perWordArgs) // No deleted item has a URL, so there is no need to explicitly add that here. whereClause = "WHERE (\(filterFragment))\(whereFragment)" if includeBookmarks { // We'll need them twice: once to filter history, and once to filter bookmarks. args = filterArgs + filterArgs } else { args = filterArgs } } else { whereClause = " WHERE (\(TableHistory).is_deleted = 0)\(whereFragment)" args = [] } // Innermost: grab history items and basic visit/domain metadata. var ungroupedSQL = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, \(TableHistory).title AS title, \(TableHistory).guid AS guid, domain_id, domain" + ", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" + ", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" + ", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" + ", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" + " FROM \(TableHistory) " + "INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " + "INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " if includeBookmarks && AppConstants.MOZ_AWESOMEBAR_DUPES { ungroupedSQL.appendContentsOf("LEFT JOIN \(ViewAllBookmarks) on \(ViewAllBookmarks).url = \(TableHistory).url ") } ungroupedSQL.appendContentsOf(whereClause.stringByReplacingOccurrencesOfString("url", withString: "\(TableHistory).url").stringByReplacingOccurrencesOfString("title", withString: "\(TableHistory).title")) if includeBookmarks && AppConstants.MOZ_AWESOMEBAR_DUPES { ungroupedSQL.appendContentsOf(" AND \(ViewAllBookmarks).url IS NULL") } ungroupedSQL.appendContentsOf(" GROUP BY historyID") // Next: limit to only those that have been visited at all within the last six months. // (Don't do that in the innermost: we want to get the full count, even if some visits are older.) // Discard all but the 1000 most frecent. // Compute and return the frecency for all 1000 URLs. let frecenciedSQL = "SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" + " FROM (" + ungroupedSQL + ")" + " WHERE (" + "((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing. "((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items. ") ORDER BY frecency DESC" + " LIMIT 1000" // Don't even look at a huge set. This avoids work. // Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit. // TODO: make is_bookmarked here accurate by joining against ViewAllBookmarks. // TODO: ensure that the same URL doesn't appear twice in the list, either from duplicate // bookmarks or from being in both bookmarks and history. let historySQL = [ "SELECT historyID, url, title, guid, domain_id, domain,", "max(localVisitDate) AS localVisitDate,", "max(remoteVisitDate) AS remoteVisitDate,", "sum(localVisitCount) AS localVisitCount,", "sum(remoteVisitCount) AS remoteVisitCount,", "sum(frecency) AS frecencies,", "0 AS is_bookmarked", "FROM (", frecenciedSQL, ") ", groupClause, "ORDER BY frecencies DESC", "LIMIT \(historyLimit)", ].joinWithSeparator(" ") if includeIcon { // We select the history items then immediately join to get the largest icon. // We do this so that we limit and filter *before* joining against icons. let historyWithIconsSQL = [ "SELECT historyID, url, title, guid, domain_id, domain,", "localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount,", "iconID, iconURL, iconDate, iconType, iconWidth, frecencies, is_bookmarked", "FROM (", historySQL, ") LEFT OUTER JOIN", "view_history_id_favicon ON historyID = view_history_id_favicon.id", "ORDER BY frecencies DESC", ].joinWithSeparator(" ") if !includeBookmarks { return (historyWithIconsSQL, args) } // Find bookmarks, too. // This isn't required by the protocol we're implementing, but we're able to do // it because we share storage with bookmarks. // Note that this is part-duplicated below. let bookmarksWithIconsSQL = [ "SELECT NULL AS historyID, url, title, guid, NULL AS domain_id, NULL AS domain,", "visitDate AS localVisitDate, 0 AS remoteVisitDate, 0 AS localVisitCount,", "0 AS remoteVisitCount,", "iconID, iconURL, iconDate, iconType, iconWidth,", "visitDate AS frecencies,", // Fake this for ordering purposes. "1 AS is_bookmarked", "FROM", ViewAwesomebarBookmarksWithIcons, whereClause, // The columns match, so we can reuse this. AppConstants.MOZ_AWESOMEBAR_DUPES ? "GROUP BY url" : "", "ORDER BY visitDate DESC LIMIT \(bookmarksLimit)", ].joinWithSeparator(" ") let sql = "SELECT * FROM (SELECT * FROM (\(historyWithIconsSQL)) UNION SELECT * FROM (\(bookmarksWithIconsSQL))) ORDER BY is_bookmarked DESC, frecencies DESC" return (sql, args) } if !includeBookmarks { return (historySQL, args) } // Note that this is part-duplicated above. let bookmarksSQL = [ "SELECT NULL AS historyID, url, title, guid, NULL AS domain_id, NULL AS domain,", "visitDate AS localVisitDate, 0 AS remoteVisitDate, 0 AS localVisitCount,", "0 AS remoteVisitCount,", "visitDate AS frecencies,", // Fake this for ordering purposes. "1 AS is_bookmarked", "FROM", ViewAwesomebarBookmarks, whereClause, // The columns match, so we can reuse this. "GROUP BY url", "ORDER BY visitDate DESC LIMIT \(bookmarksLimit)", ].joinWithSeparator(" ") let allSQL = "SELECT * FROM (SELECT * FROM (\(historySQL)) UNION SELECT * FROM (\(bookmarksSQL))) ORDER BY is_bookmarked DESC, frecencies DESC" return (allSQL, args) } } extension SQLiteHistory: Favicons { // These two getter functions are only exposed for testing purposes (and aren't part of the public interface). func getFaviconsForURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> { let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " + "\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " + "\(TableHistory).id = siteID AND \(TableHistory).url = ?" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory) } func getFaviconsForBookmarkedURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> { let sql = "SELECT " + " \(TableFavicons).id AS id" + ", \(TableFavicons).url AS url" + ", \(TableFavicons).date AS date" + ", \(TableFavicons).type AS type" + ", \(TableFavicons).width AS width" + " FROM \(TableFavicons), \(ViewBookmarksLocalOnMirror) AS bm" + " WHERE bm.faviconID = \(TableFavicons).id AND bm.bmkUri IS ?" let args: Args = [url] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory) } public func getSitesForURLs(urls: [String]) -> Deferred<Maybe<Cursor<Site?>>> { let inExpression = urls.joinWithSeparator("\",\"") let sql = "SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, iconID, iconURL, iconDate, iconType, iconWidth FROM " + "\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " + "\(TableHistory).id = siteID AND \(TableHistory).url IN (\"\(inExpression)\")" let args: Args = [] return db.runQuery(sql, args: args, factory: SQLiteHistory.iconHistoryColumnFactory) } public func clearAllFavicons() -> Success { var err: NSError? = nil db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil) if err == nil { err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil) } return 1 } return failOrSucceed(err, op: "Clear favicons") } public func addFavicon(icon: Favicon) -> Deferred<Maybe<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) return id ?? 0 } if err == nil { return deferMaybe(res) } return deferMaybe(DatabaseError(err: err)) } /** * This method assumes that the site has already been recorded * in the history table. */ public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Maybe<Int>> { if Logger.logPII { log.verbose("Adding favicon \(icon.url) for site \(site.url).") } func doChange(query: String, args: Args?) -> Deferred<Maybe<Int>> { var err: NSError? let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in // Blind! We don't see failure here. let id = self.favicons.insertOrUpdate(conn, obj: icon) // Now set up the mapping. err = conn.executeChange(query, withArgs: args) if let err = err { log.error("Got error adding icon: \(err).") return 0 } // Try to update the favicon ID column in each bookmarks table. There can be // multiple bookmarks with a particular URI, and a mirror bookmark can be // locally changed, so either or both of these statements can update multiple rows. if let id = id { conn.executeChange("UPDATE \(TableBookmarksLocal) SET faviconID = ? WHERE bmkUri = ?", withArgs: [id, site.url]) conn.executeChange("UPDATE \(TableBookmarksMirror) SET faviconID = ? WHERE bmkUri = ?", withArgs: [id, site.url]) } return id ?? 0 } if res == 0 { return deferMaybe(DatabaseError(err: err)) } return deferMaybe(icon.id!) } let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)" let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)" let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES " if let iconID = icon.id { // Easy! if let siteID = site.id { // So easy! let args: Args? = [siteID, iconID] return doChange("\(insertOrIgnore) (?, ?)", args: args) } // Nearly easy. let args: Args? = [site.url, iconID] return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args: args) } // Sigh. if let siteID = site.id { let args: Args? = [siteID, icon.url] return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args: args) } // The worst. let args: Args? = [site.url, icon.url] return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args: args) } } extension SQLiteHistory: SyncableHistory { /** * TODO: * When we replace an existing row, we want to create a deleted row with the old * GUID and switch the new one in -- if the old record has escaped to a Sync server, * we want to delete it so that we don't have two records with the same URL on the server. * We will know if it's been uploaded because it'll have a server_modified time. */ public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success { let args: Args = [guid, url, guid] // The additional IS NOT is to ensure that we don't do a write for no reason. return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args) } public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success { let args: Args = [guid] // This relies on ON DELETE CASCADE to remove visits. return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args) } // Fails on non-existence. private func getSiteIDForGUID(guid: GUID) -> Deferred<Maybe<Int>> { let args: Args = [guid] let query = "SELECT id FROM history WHERE guid = ?" let factory: SDRow -> Int = { return $0["id"] as! Int } return db.runQuery(query, args: args, factory: factory) >>== { cursor in if cursor.count == 0 { return deferMaybe(NoSuchRecordError(guid: guid)) } return deferMaybe(cursor[0]!) } } public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success { return self.getSiteIDForGUID(guid) >>== { (siteID: Int) -> Success in let visitArgs = visits.map { (visit: Visit) -> Args in let realDate = NSNumber(unsignedLongLong: visit.date) let isLocal = 0 let args: Args = [siteID, realDate, visit.type.rawValue, isLocal] return args } // Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness // constraint on `visits`: we allow only one row for (siteID, date, type), so if a // local visit already exists, this silently keeps it. End result? Any new remote // visits are added with only one query, keeping any existing rows. return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs) } } private struct HistoryMetadata { let id: Int let serverModified: Timestamp? let localModified: Timestamp? let isDeleted: Bool let shouldUpload: Bool let title: String } private func metadataForGUID(guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> { let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?" let args: Args = [guid] let factory = { (row: SDRow) -> HistoryMetadata in return HistoryMetadata( id: row["id"] as! Int, serverModified: row.getTimestamp("server_modified"), localModified: row.getTimestamp("local_modified"), isDeleted: row.getBoolean("is_deleted"), shouldUpload: row.getBoolean("should_upload"), title: row["title"] as! String ) } return db.runQuery(select, args: args, factory: factory) >>== { cursor in return deferMaybe(cursor[0]) } } public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> { // One of these things will be true here. // 0. The item is new. // (a) We have a local place with the same URL but a different GUID. // (b) We have never visited this place locally. // In either case, reconcile and proceed. // 1. The remote place is not modified when compared to our mirror of it. This // can occur when we redownload after a partial failure. // (a) And it's not modified locally, either. Nothing to do. Ideally we // will short-circuit so we don't need to update visits. (TODO) // (b) It's modified locally. Don't overwrite anything; let the upload happen. // 2. The remote place is modified (either title or visits). // (a) And it's not locally modified. Update the local entry. // (b) And it's locally modified. Preserve the title of whichever was modified last. // N.B., this is the only instance where we compare two timestamps to see // which one wins. // We use this throughout. let serverModified = NSNumber(unsignedLongLong: modified) // Check to see if our modified time is unchanged, if the record exists locally, etc. let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in if let metadata = metadata { // The item exists locally (perhaps originally with a different GUID). if metadata.serverModified == modified { log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.") return deferMaybe(place.guid) } // Otherwise, the server record must have changed since we last saw it. if metadata.shouldUpload { // Uh oh, it changed locally. // This might well just be a visit change, but we can't tell. Usually this conflict is harmless. log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!") if metadata.localModified > modified { log.debug("Local changes overriding remote.") // Update server modified time only. (Though it'll be overwritten again after a successful upload.) let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?" let args: Args = [serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } log.verbose("Remote changes overriding local.") // Fall through. } // The record didn't change locally. Update it. log.verbose("Updating local history item for guid \(place.guid).") let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?" let args: Args = [place.title, serverModified, metadata.id] return self.db.run(update, withArgs: args) >>> always(place.guid) } // The record doesn't exist locally. Insert it. log.verbose("Inserting remote history item for guid \(place.guid).") if let host = place.url.asURL?.normalizedHost() { if Logger.logPII { log.debug("Inserting: \(place.url).") } let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)" let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " + "SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?" return self.db.run([ (insertDomain, [host]), (insertHistory, [place.guid, place.url, place.title, serverModified, host]) ]) >>> always(place.guid) } else { // This is a URL with no domain. Insert it directly. if Logger.logPII { log.debug("Inserting: \(place.url) with no domain.") } let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " + "VALUES (?, ?, ?, ?, 0, 0, NULL)" return self.db.run([ (insertHistory, [place.guid, place.url, place.title, serverModified]) ]) >>> always(place.guid) } } // Make sure that we only need to compare GUIDs by pre-merging on URL. return self.ensurePlaceWithURL(place.url, hasGUID: place.guid) >>> { self.metadataForGUID(place.guid) >>== insertWithMetadata } } public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> { // Use the partial index on should_upload to make this nice and quick. let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1" let f: SDRow -> String = { $0["guid"] as! String } return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) } } public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> { // What we want to do: find all items flagged for update, selecting some number of their // visits alongside. // // A difficulty here: we don't want to fetch *all* visits, only some number of the most recent. // (It's not enough to only get new ones, because the server record should contain more.) // // That's the greatest-N-per-group problem in SQL. Please read and understand the solution // to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query! // // We can do this in a single query, rather than the N+1 that desktop takes. // We then need to flatten the cursor. We do that by collecting // places as a side-effect of the factory, producing visits as a result, and merging in memory. let args: Args = [ 20, // Maximum number of visits to retrieve. ] // Exclude 'unknown' visits, because they're not syncable. let filter = "history.should_upload = 1 AND v1.type IS NOT 0" let sql = "SELECT " + "history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " + "v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " + "FROM " + "visits AS v1 " + "JOIN history ON history.id = v1.siteID AND \(filter) " + "LEFT OUTER JOIN " + "visits AS v2 " + "ON v1.siteID = v2.siteID AND v1.date < v2.date " + "GROUP BY v1.date " + "HAVING COUNT(*) < ? " + "ORDER BY v1.siteID, v1.date DESC" var places = [Int: Place]() var visits = [Int: [Visit]]() // Add a place to the accumulator, prepare to accumulate visits, return the ID. let ensurePlace: SDRow -> Int = { row in let id = row["siteID"] as! Int if places[id] == nil { let guid = row["guid"] as! String let url = row["url"] as! String let title = row["title"] as! String places[id] = Place(guid: guid, url: url, title: title) visits[id] = Array() } return id } // Store the place and the visit. let factory: SDRow -> Int = { row in let date = row.getTimestamp("visitDate")! let type = VisitType(rawValue: row["visitType"] as! Int)! let visit = Visit(date: date, type: type) let id = ensurePlace(row) visits[id]?.append(visit) return id } return db.runQuery(sql, args: args, factory: factory) >>== { c in // Consume every row, with the side effect of populating the places // and visit accumulators. var ids = Set<Int>() for row in c { // Collect every ID first, so that we're guaranteed to have // fully populated the visit lists, and we don't have to // worry about only collecting each place once. ids.insert(row!) } // Now we're done with the cursor. Close it. c.close() // Now collect the return value. return deferMaybe(ids.map { return (places[$0]!, visits[$0]!) }) } } public func markAsDeleted(guids: [GUID]) -> Success { // TODO: support longer GUID lists. assert(guids.count < BrowserDB.MaxVariableNumber) if guids.isEmpty { return succeed() } log.debug("Wiping \(guids.count) deleted GUIDs.") // We deliberately don't limit this to records marked as should_upload, just // in case a coding error leaves records with is_deleted=1 but not flagged for // upload -- this will catch those and throw them away. let inClause = BrowserDB.varlist(guids.count) let sql = "DELETE FROM \(TableHistory) WHERE " + "is_deleted = 1 AND guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) } public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> { // TODO: support longer GUID lists. assert(guids.count < 99) if guids.isEmpty { return deferMaybe(modified) } log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).") let inClause = BrowserDB.varlist(guids.count) let sql = "UPDATE \(TableHistory) SET " + "should_upload = 0, server_modified = \(modified) " + "WHERE guid IN \(inClause)" let args: Args = guids.map { $0 as AnyObject } return self.db.run(sql, withArgs: args) >>> always(modified) } public func doneApplyingRecordsAfterDownload() -> Success { self.db.checkpoint() return succeed() } public func doneUpdatingMetadataAfterUpload() -> Success { self.db.checkpoint() return succeed() } } extension SQLiteHistory { // Returns a deferred `true` if there are rows in the DB that have a server_modified time. // Because we clear this when we reset or remove the account, and never set server_modified // without syncing, the presence of matching rows directly indicates that a deletion // would be synced to the server. public func hasSyncedHistory() -> Deferred<Maybe<Bool>> { return self.db.queryReturnsResults("SELECT 1 FROM \(TableHistory) WHERE server_modified IS NOT NULL LIMIT 1") } } extension SQLiteHistory: ResettableSyncStorage { // We don't drop deletions when we reset -- we might need to upload a deleted item // that never made it to the server. public func resetClient() -> Success { let flag = "UPDATE \(TableHistory) SET should_upload = 1, server_modified = NULL" return self.db.run(flag) } } extension SQLiteHistory: AccountRemovalDelegate { public func onRemovedAccount() -> Success { log.info("Clearing history metadata and deleted items after account removal.") let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1" return self.db.run(discard) >>> self.resetClient } }
mpl-2.0
c620c1de084e3ac01bc744d7a5f92206
43.972532
212
0.593362
4.806697
false
false
false
false
Raizlabs/RIGImageGallery
RIGImageGallery/RIGImageGalleryViewController.swift
1
12772
// // RIGImageGalleryViewController.swift // RIGPhotoViewer // // Created by Michael Skiba on 2/8/16. // Copyright © 2016 Raizlabs. All rights reserved. // import UIKit open class RIGImageGalleryViewController: UIPageViewController { public typealias GalleryPositionUpdateHandler = (_ gallery: RIGImageGalleryViewController, _ position: Int, _ total: Int) -> Void public typealias ActionButtonPressedHandler = (_ gallery: RIGImageGalleryViewController, _ item: RIGImageGalleryItem) -> Void public typealias GalleryEventHandler = (RIGImageGalleryViewController) -> Void public typealias IndexUpdateHandler = (Int) -> Void /// An optional closure to execute if the action button is tapped open var actionButtonHandler: ActionButtonPressedHandler? /// An optional closure to allow cutom trait collection change handling open var traitCollectionChangeHandler: GalleryEventHandler? { didSet { traitCollectionChangeHandler?(self) } } /// An optional closure to execute when the active index is updated open var indexUpdateHandler: IndexUpdateHandler? /// An optional closure to handle dismissing the gallery, if this is nil the view will call `dismissViewControllerAnimated(true, completion: nil)`, if this is non-nil, the view controller will not dismiss itself open var dismissHandler: GalleryEventHandler? /// An optional closure to handle updating the count text open var countUpdateHandler: GalleryPositionUpdateHandler? { didSet { updateCountText() } } /// The array of images to display. The view controller will automatically handle updates open var images: [RIGImageGalleryItem] = [] { didSet { handleImagesUpdate(oldValue: oldValue) } } /// The bar button item to use for the left side of the screen, `didSet` adds the correct target and action to ensure that `dismissHandler` is called when the button is pressed open var doneButton: UIBarButtonItem? = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) { didSet { configureDoneButton() } } /// The bar button item to use for the right side of the screen, `didSet` adds the correct target and action to ensure that `actionButtonHandler` is called open var actionButton: UIBarButtonItem? { didSet { configureActionButton() } } /// The index of the image currently bieng displayed open var currentImage: Int = 0 { didSet { indexUpdateHandler?(currentImage) updateCountText() } } fileprivate var navigationBarsHidden = false fileprivate var zoomRecognizer = UITapGestureRecognizer() fileprivate var toggleBarRecognizer = UITapGestureRecognizer() fileprivate var currentImageViewController: RIGSingleImageViewController? { return viewControllers?.first as? RIGSingleImageViewController } fileprivate var showDoneButton = true /** Changes the current image bieng displayed - parameter currentImage: The index of the image in `images` to display - parameter animated: A flag that determines if this should be an animated or non-animated transition */ open func setCurrentImage(_ currentImage: Int, animated: Bool) { guard currentImage >= 0 && currentImage < images.count else { self.currentImage = 0 setViewControllers([UIViewController()], direction: .forward, animated: animated, completion: nil) return } let newView = createNewPage(for: images[currentImage]) let direction: UIPageViewControllerNavigationDirection if self.currentImage < currentImage { direction = .forward } else { direction = .reverse } self.currentImage = currentImage setViewControllers([newView], direction: direction, animated: animated, completion: nil) } /// The label used to display the current position in the array open let countLabel: UILabel = { let counter = UILabel() counter.textColor = .white counter.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline) return counter }() /** A convenience initializer to return a configured empty RIGImageGalleryViewController */ public convenience init() { self.init(images: []) } /** A convenience initializer to return a configured RIGImageGalleryViewController with an array of images - parameter images: The images to use in the gallery */ public convenience init(images: [RIGImageGalleryItem]) { self.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: [UIPageViewControllerOptionInterPageSpacingKey: 20]) self.images = images } public override init(transitionStyle style: UIPageViewControllerTransitionStyle, navigationOrientation: UIPageViewControllerNavigationOrientation, options: [String : Any]?) { super.init(transitionStyle: style, navigationOrientation: navigationOrientation, options: options) dataSource = self delegate = self automaticallyAdjustsScrollViewInsets = false handleImagesUpdate(oldValue: []) configureDoneButton() configureActionButton() } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() configureDoneButton() zoomRecognizer.addTarget(self, action: #selector(toggleZoom(_:))) zoomRecognizer.numberOfTapsRequired = 2 zoomRecognizer.delegate = self toggleBarRecognizer.addTarget(self, action: #selector(toggleBarVisiblity(_:))) toggleBarRecognizer.delegate = self view.addGestureRecognizer(zoomRecognizer) view.addGestureRecognizer(toggleBarRecognizer) view.backgroundColor = UIColor.black countLabel.sizeToFit() toolbarItems = [ UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(customView: countLabel), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), ] } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateBarStatus(animated: false) if currentImage < images.count { let photoPage = createNewPage(for: images[currentImage]) setViewControllers([photoPage], direction: .forward, animated: false, completion: nil) } } open override var prefersStatusBarHidden: Bool { return navigationBarsHidden } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() currentImageViewController?.scrollView.baseInsets = scrollViewInset } open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) traitCollectionChangeHandler?(self) } /// Allows subclasses of RIGImageGallery to customize the gallery page /// /// - Parameter viewerItem: The item to be displayed /// - Returns: The view controller that will display the item open func createNewPage(for viewerItem: RIGImageGalleryItem) -> UIViewController { return RIGSingleImageViewController(viewerItem: viewerItem) } } extension RIGImageGalleryViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == zoomRecognizer { return otherGestureRecognizer == toggleBarRecognizer } return false } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == toggleBarRecognizer { return otherGestureRecognizer == zoomRecognizer } return false } } // MARK: - Actions extension RIGImageGalleryViewController { func toggleBarVisiblity(_ recognizer: UITapGestureRecognizer) { navigationBarsHidden = !navigationBarsHidden updateBarStatus(animated: true) } func toggleZoom(_ recognizer: UITapGestureRecognizer) { currentImageViewController?.scrollView.toggleZoom() } func dismissPhotoView(_ sender: UIBarButtonItem) { if dismissHandler != nil { dismissHandler?(self) } else { dismiss(animated: true, completion: nil) } } func performAction(_ sender: UIBarButtonItem) { if let item = currentImageViewController?.viewerItem { actionButtonHandler?(self, item) } } } extension RIGImageGalleryViewController: UIPageViewControllerDataSource { public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let index = indexOf(viewController: viewController), index < images.count - 1 else { return nil } return createNewPage(for: images[index + 1]) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = indexOf(viewController: viewController), index > 0 else { return nil } return createNewPage(for: images[index + -1]) } } extension RIGImageGalleryViewController: UIPageViewControllerDelegate { public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { for viewControl in pendingViewControllers { if let imageControl = viewControl as? RIGSingleImageViewController { imageControl.scrollView.baseInsets = scrollViewInset } } } public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if let index = viewControllers?.first.flatMap({ indexOf(viewController: $0) }) { currentImage = index } } } // MARK: - Private private extension RIGImageGalleryViewController { func indexOf(viewController: UIViewController, imagesArray: [RIGImageGalleryItem]? = nil) -> Int? { guard let item = (viewController as? RIGSingleImageViewController)?.viewerItem else { return nil } return (imagesArray ?? images).index(of: item) } func configureDoneButton() { doneButton?.target = self doneButton?.action = #selector(dismissPhotoView(_:)) navigationItem.leftBarButtonItem = doneButton } func configureActionButton() { actionButton?.target = self actionButton?.action = #selector(performAction(_:)) navigationItem.rightBarButtonItem = actionButton } func updateBarStatus(animated: Bool) { navigationController?.setToolbarHidden(navigationBarsHidden, animated: animated) navigationController?.setNavigationBarHidden(navigationBarsHidden, animated: animated) setNeedsStatusBarAppearanceUpdate() UIView.animate(withDuration: 0.2, animations: { self.currentImageViewController?.scrollView.baseInsets = self.scrollViewInset }) } func handleImagesUpdate(oldValue: [RIGImageGalleryItem]) { for viewController in childViewControllers { if let index = indexOf(viewController: viewController, imagesArray: oldValue), let childView = viewController as? RIGSingleImageViewController, index < images.count { DispatchQueue.main.async { [unowned self] in childView.viewerItem = self.images[index] childView.scrollView.baseInsets = self.scrollViewInset } } } updateCountText() } var scrollViewInset: UIEdgeInsets { loadViewIfNeeded() return UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: bottomLayoutGuide.length, right: 0) } func updateCountText() { if countUpdateHandler != nil { countUpdateHandler?(self, currentImage, images.count) } else { countLabel.text = nil } countLabel.sizeToFit() } }
mit
edde92c3b91644ff4acbc8e482441f89
36.896142
215
0.690784
5.794465
false
false
false
false
ckrey/mqttswift
Sources/MqttSharedSubscriptions.swift
1
2069
// // MqttSharedSubscriptions.swift // mqttswift // // Created by Christoph Krey on 08.10.17. // import Foundation class MqttSharedSubscriptions { private static var theInstance: MqttSharedSubscriptions? var shares: [String: [String]] public class func sharedInstance() -> MqttSharedSubscriptions { if theInstance == nil { theInstance = MqttSharedSubscriptions() } return theInstance! } private init() { self.shares = [String: [String]]() } func remove(subscription: MqttSubscription) { let shareName = subscription.shareName() if shareName != nil { var share = self.shares[shareName!] if share != nil { for (index, topicFilter) in share!.enumerated() { if topicFilter == subscription.topicFilter { share!.remove(at:index) self.shares[shareName!] = share return } } } } } func store(subscription: MqttSubscription) { let shareName = subscription.shareName() if shareName != nil { var share = self.shares[shareName!] if share == nil { share = [String]() } for topicFilter in share! { if topicFilter == subscription.topicFilter { return } } share!.append(subscription.topicFilter) self.shares[shareName!] = share } } func position(subscription: MqttSubscription) -> Int { let shareName = subscription.shareName() if shareName != nil { let share = self.shares[shareName!] if share != nil { for (index, topicFilter) in share!.enumerated() { if topicFilter == subscription.topicFilter { return index + 1 } } } } return 1 } }
gpl-3.0
18c60be8f0b06508c698c381b02496c1
26.586667
67
0.506042
5.133995
false
false
false
false
naokits/my-programming-marathon
RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxDataSourceStarterKit/DataSources/RxCollectionViewSectionedDataSource.swift
6
5285
// // RxCollectionViewSectionedDataSource.swift // RxExample // // Created by Krunoslav Zaher on 7/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit #if !RX_NO_MODULE import RxSwift import RxCocoa #endif public class _RxCollectionViewSectionedDataSource : NSObject , UICollectionViewDataSource { func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 0 } public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return _numberOfSectionsInCollectionView(collectionView) } func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _collectionView(collectionView, numberOfItemsInSection: section) } func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return (nil as UICollectionViewCell?)! } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return _collectionView(collectionView, cellForItemAtIndexPath: indexPath) } func _collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return (nil as UICollectionReusableView?)! } public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return _collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath) } } public class RxCollectionViewSectionedDataSource<S: SectionModelType> : _RxCollectionViewSectionedDataSource { public typealias I = S.Item public typealias Section = S public typealias CellFactory = (UICollectionView, NSIndexPath, I) -> UICollectionViewCell public typealias SupplementaryViewFactory = (UICollectionView, String, NSIndexPath) -> UICollectionReusableView public typealias IncrementalUpdateObserver = AnyObserver<Changeset<S>> public typealias IncrementalUpdateDisposeKey = Bag<IncrementalUpdateObserver>.KeyType // This structure exists because model can be mutable // In that case current state value should be preserved. // The state that needs to be preserved is ordering of items in section // and their relationship with section. // If particular item is mutable, that is irrelevant for this logic to function // properly. public typealias SectionModelSnapshot = SectionModel<S, I> private var _sectionModels: [SectionModelSnapshot] = [] public func sectionAtIndex(section: Int) -> S { return self._sectionModels[section].model } public func itemAtIndexPath(indexPath: NSIndexPath) -> I { return self._sectionModels[indexPath.section].items[indexPath.item] } public func setSections(sections: [S]) { self._sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) } } public var cellFactory: CellFactory! = nil public var supplementaryViewFactory: SupplementaryViewFactory public override init() { self.cellFactory = { _, _, _ in return (nil as UICollectionViewCell?)! } self.supplementaryViewFactory = { _, _, _ in (nil as UICollectionReusableView?)! } super.init() self.cellFactory = { [weak self] _ in precondition(false, "There is a minor problem. `cellFactory` property on \(self!) was not set. Please set it manually, or use one of the `rx_bindTo` methods.") return (nil as UICollectionViewCell!)! } self.supplementaryViewFactory = { [weak self] _, _, _ in precondition(false, "There is a minor problem. `supplementaryViewFactory` property on \(self!) was not set.") return (nil as UICollectionReusableView?)! } } // UITableViewDataSource override func _numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return _sectionModels.count } override func _collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _sectionModels[section].items.count } override func _collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { precondition(indexPath.item < _sectionModels[indexPath.section].items.count) return cellFactory(collectionView, indexPath, itemAtIndexPath(indexPath)) } override func _collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return supplementaryViewFactory(collectionView, kind, indexPath) } }
mit
f11814f79cc394c3d3130b1a70688c65
41.620968
181
0.715367
5.984145
false
false
false
false
taoalpha/XMate
appcode/X-Mates/SearchViewController.swift
1
8567
// // SearchViewController.swift // X-Mates // // Created by Jiangyu Mao on 3/6/16. // Copyright © 2016 CloudGroup. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var exerciseInfoTable: UITableView! @IBOutlet weak var searchResultTable: UITableView! @IBOutlet weak var activityLabel: UILabel! private let fields = ["Date", "Start Time", "End Time", "Categories"] private let catagoryList = ["Basketball", "Football", "Gym", "Swimming", "Running", "Vollyball"] private let scheduleURL = "http://192.168.99.100:4000/schedule/" private let messageURL = "http://192.168.99.100:4000/message/" private var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate private var catagory = "" private var startTime : NSTimeInterval = 0.0 private var endTime : NSTimeInterval = 0.0 private var date = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.appDelegate.xmate.matches.removeAll() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { if tableView == self.searchResultTable { if self.appDelegate.xmate.matches.count == 0 { let defaultMsg = UILabel() defaultMsg.textAlignment = NSTextAlignment.Center defaultMsg.textColor = UIColor.lightGrayColor() defaultMsg.text = "No Match" tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.backgroundView = defaultMsg return 0 } else{ tableView.backgroundView = nil return 1 } } else { return 1 } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.exerciseInfoTable { return self.fields.count } else { return self.appDelegate.xmate.matches.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView == self.exerciseInfoTable { let cell = tableView.dequeueReusableCellWithIdentifier("searchCell", forIndexPath: indexPath) cell.textLabel?.text = fields[indexPath.row] return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("resultCell", forIndexPath: indexPath) as! SearchTableViewCell let formatter = NSDateFormatter() formatter.dateFormat = "MMM-dd-YYYY hh:mm a" cell.userLabel.text = self.appDelegate.xmate.matches[indexPath.row]["username"] as? String if self.appDelegate.xmate.matches[indexPath.row]["start_time"] != nil { cell.userLabel.text = self.appDelegate.xmate.matches[indexPath.row]["creator"] as? String let st = self.appDelegate.xmate.matches[indexPath.row]["start_time"] as! NSTimeInterval let nsdate = NSDate(timeIntervalSince1970: st) cell.startLabel.text = formatter.stringFromDate(nsdate) } cell.joinButton.tag = indexPath.row cell.joinButton.addTarget(self, action: #selector(SearchViewController.joinUser(_:)), forControlEvents: .TouchUpInside) return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView == self.exerciseInfoTable { let index = indexPath.row let cell = tableView.cellForRowAtIndexPath(indexPath)! switch index { case 0: datePicker(cell, mode: "Date") break case 1: datePicker(cell, mode: "Start Time") break case 2: datePicker(cell, mode: "End Time") break case 3: catagoryPicker(cell) break default: break } } else { } } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.catagoryList.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return self.catagoryList[row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print("Your favorite console is \(self.catagoryList[row])") self.catagory = self.catagoryList[row] } func datePicker(cell: UITableViewCell, mode: String) { let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let datePicker = UIDatePicker(frame: CGRectMake(25, 0, 305, 200)) let formatter = NSDateFormatter() datePicker.date = NSDate() if mode == "Date" { datePicker.datePickerMode = UIDatePickerMode.Date formatter.dateStyle = .MediumStyle } else if mode == "Start Time" || mode == "End Time" { datePicker.datePickerMode = UIDatePickerMode.Time formatter.dateFormat = "hh:mm a" } let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in cell.detailTextLabel?.text = formatter.stringFromDate(datePicker.date) if mode == "Start Time" { self.startTime = datePicker.date.timeIntervalSince1970 } else if mode == "End Time" { self.endTime = datePicker.date.timeIntervalSince1970 } else if mode == "Date" { self.date = formatter.stringFromDate(datePicker.date) } }) alertController.addAction(done) alertController.view.addSubview(datePicker) self.presentViewController(alertController, animated: true, completion: nil) } func catagoryPicker(cell: UITableViewCell) { let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let catagoryPicker = UIPickerView(frame: CGRectMake(25, 0, 305, 200)) catagoryPicker.dataSource = self catagoryPicker.delegate = self let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in cell.detailTextLabel?.text = self.catagory }) alertController.addAction(done) alertController.view.addSubview(catagoryPicker) self.presentViewController(alertController, animated: true, completion: nil) } @IBAction func cancelSearch(sender: UIBarButtonItem) { self.performSegueWithIdentifier("cancelSearch", sender: self) } @IBAction func searchExercise(sender: UIBarButtonItem) { if self.endTime < self.startTime { let alertController = UIAlertController(title: "Invalid Search", message: "End Time must later than Start Time", preferredStyle: UIAlertControllerStyle.Alert) let done = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(done) self.presentViewController(alertController, animated: true, completion: nil) } else { // find all matches for the search var data = NSMutableDictionary(dictionary: ["action":"search"]) if self.startTime != 0.0 { data["start_time"] = self.startTime } if self.endTime != 0.0 { data["end_time"] = self.endTime } if self.catagory != "" { data["type"] = self.catagory } print(data) let res = self.appDelegate.xmate.search(self.scheduleURL, data: NSDictionary(dictionary: data) as! [String : AnyObject]) if res == "Server Error" { let alertController = UIAlertController(title: "ERROR", message: "Connection Error\nPlease Try Later", preferredStyle: UIAlertControllerStyle.Alert) let ok = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(ok) self.presentViewController(alertController, animated: true, completion: nil) } self.searchResultTable.reloadData() self.searchResultTable.hidden = false } } @IBAction func joinUser(sender: UIButton) { let alertController = UIAlertController(title: "Confirm Join", message: "", preferredStyle: UIAlertControllerStyle.Alert) let join = UIAlertAction(title: "Join", style: UIAlertActionStyle.Default, handler: {(action) -> Void in let row = sender.tag let pid = self.appDelegate.xmate.matches[row]["_id"] as! String let rid = self.appDelegate.xmate.matches[row]["owner"] as! String self.appDelegate.xmate.post(self.messageURL, mode: "join", pid: pid, rid: rid) }) let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: nil) alertController.addAction(cancel) alertController.addAction(join) self.presentViewController(alertController, animated: true, completion: nil) } }
mit
7f1ff3ad9b6e7603bc22eda08ae17923
30.492647
161
0.721574
3.898953
false
false
false
false
kevinmlong/realm-cocoa
RealmSwift/Tests/ObjectCreationTests.swift
11
21263
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import XCTest import RealmSwift import Foundation class ObjectCreationTests: TestCase { // MARK: Init tests func testInitWithDefaults() { // test all properties are defaults let object = SwiftObject() XCTAssertNil(object.realm) // test defaults values verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false, boolObjectListValues: []) // test realm properties are nil for standalone XCTAssertNil(object.realm) XCTAssertNil(object.objectCol.realm) XCTAssertNil(object.arrayCol.realm) } func testInitWithDictionary() { // dictionary with all values specified let baselineValues = ["boolCol": true as NSNumber, "intCol": 1 as NSNumber, "floatCol": 1.1 as NSNumber, "doubleCol": 11.1 as NSNumber, "stringCol": "b" as NSString, "binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, "dateCol": NSDate(timeIntervalSince1970: 2) as NSDate, "objectCol": SwiftBoolObject(value: [true]) as AnyObject, "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject ] // test with valid dictionary literals let props = Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[props[propNum].name] = validValue let object = SwiftObject(value: values) verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid dictionary literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[props[propNum].name] = invalidValue assertThrows(SwiftObject(value: values), "Invalid property value") } } } func testInitWithDefaultsAndDictionary() { // test with dictionary with mix of default and one specified value let object = SwiftObject(value: ["intCol": 200]) let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) verifySwiftObjectWithDictionaryLiteral(object, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) } func testInitWithArray() { // array with all values specified let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject] // test with valid dictionary literals let props = Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[propNum] = validValue let object = SwiftObject(value: values) verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid dictionary literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[propNum] = invalidValue assertThrows(SwiftObject(value: values), "Invalid property value") } } } func testInitWithKVCObject() { // test with kvc object let objectWithInt = SwiftObject(value: ["intCol": 200]) let objectWithKVCObject = SwiftObject(value: objectWithInt) let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) } func testGenericInit() { func createObject<T: Object>() -> T { return T() } let obj1: SwiftBoolObject = createObject() let obj2 = SwiftBoolObject() XCTAssertEqual(obj1.boolCol, obj2.boolCol, "object created via generic initializer should equal object created by calling initializer directly") } // MARK: Creation tests func testCreateWithDefaults() { let realm = Realm() assertThrows(realm.create(SwiftObject), "Must be in write transaction") var object: SwiftObject! let objects = realm.objects(SwiftObject) XCTAssertEqual(0, objects.count) realm.write { // test create with all defaults object = realm.create(SwiftObject) return } verifySwiftObjectWithDictionaryLiteral(object, dictionary: SwiftObject.defaultValues(), boolObjectValue: false, boolObjectListValues: []) // test realm properties are populated correctly XCTAssertEqual(object.realm!, realm) XCTAssertEqual(object.objectCol.realm!, realm) XCTAssertEqual(object.arrayCol.realm!, realm) } func testCreateWithDictionary() { // dictionary with all values specified let baselineValues = ["boolCol": true as NSNumber, "intCol": 1 as NSNumber, "floatCol": 1.1 as NSNumber, "doubleCol": 11.1 as NSNumber, "stringCol": "b" as NSString, "binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, "dateCol": NSDate(timeIntervalSince1970: 2) as NSDate, "objectCol": SwiftBoolObject(value: [true]) as AnyObject, "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject ] // test with valid dictionary literals let props = Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[props[propNum].name] = validValue Realm().beginWrite() let object = Realm().create(SwiftObject.self, value: values) verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) Realm().commitWrite() verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid dictionary literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[props[propNum].name] = invalidValue Realm().beginWrite() assertThrows(Realm().create(SwiftObject.self, value: values), "Invalid property value") Realm().cancelWrite() } } } func testCreateWithDefaultsAndDictionary() { // test with dictionary with mix of default and one specified value let realm = Realm() realm.beginWrite() let objectWithInt = realm.create(SwiftObject.self, value: ["intCol": 200]) realm.commitWrite() let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) verifySwiftObjectWithDictionaryLiteral(objectWithInt, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) } func testCreateWithArray() { // array with all values specified let baselineValues = [true, 1, 1.1, 11.1, "b", "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, NSDate(timeIntervalSince1970: 2) as NSDate, ["boolCol": true], [[true], [false]]] as [AnyObject] // test with valid dictionary literals let props = Realm().schema["SwiftObject"]!.properties for propNum in 0..<props.count { for validValue in validValuesForSwiftObjectType(props[propNum].type) { // update dict with valid value and init var values = baselineValues values[propNum] = validValue Realm().beginWrite() let object = Realm().create(SwiftObject.self, value: values) verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false]) Realm().commitWrite() verifySwiftObjectWithArrayLiteral(object, array: values, boolObjectValue: true, boolObjectListValues: [true, false]) } } // test with invalid array literals for propNum in 0..<props.count { for invalidValue in invalidValuesForSwiftObjectType(props[propNum].type) { // update dict with invalid value and init var values = baselineValues values[propNum] = invalidValue Realm().beginWrite() assertThrows(Realm().create(SwiftObject.self, value: values), "Invalid property value '\(invalidValue)' for property number \(propNum)") Realm().cancelWrite() } } } func testCreateWithKVCObject() { // test with kvc object Realm().beginWrite() let objectWithInt = Realm().create(SwiftObject.self, value: ["intCol": 200]) let objectWithKVCObject = Realm().create(SwiftObject.self, value: objectWithInt) let valueDict = defaultSwiftObjectValuesWithReplacements(["intCol": 200]) Realm().commitWrite() verifySwiftObjectWithDictionaryLiteral(objectWithKVCObject, dictionary: valueDict, boolObjectValue: false, boolObjectListValues: []) XCTAssertEqual(Realm().objects(SwiftObject).count, 2, "Object should have been copied") } func testCreateWithNestedObjects() { let standalone = SwiftPrimaryStringObject(value: ["p0", 11]) Realm().beginWrite() let objectWithNestedObjects = Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p1", ["p1", 11], [standalone]]) Realm().commitWrite() let stringObjects = Realm().objects(SwiftPrimaryStringObject) XCTAssertEqual(stringObjects.count, 2) let persistedObject = stringObjects.first! XCTAssertNotEqual(standalone, persistedObject) // standalone object should be copied into the realm, not added directly XCTAssertEqual(objectWithNestedObjects.object!, persistedObject) XCTAssertEqual(objectWithNestedObjects.objects.first!, stringObjects.last!) let standalone1 = SwiftPrimaryStringObject(value: ["p3", 11]) Realm().beginWrite() assertThrows(Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["p3", ["p3", 11], [standalone1]]), "Should throw with duplicate primary key") Realm().commitWrite() } func testUpdateWithNestedObjects() { let standalone = SwiftPrimaryStringObject(value: ["primary", 11]) Realm().beginWrite() let object = Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["otherPrimary", ["primary", 12], [["primary", 12]]], update: true) Realm().commitWrite() let stringObjects = Realm().objects(SwiftPrimaryStringObject) XCTAssertEqual(stringObjects.count, 1) let persistedObject = object.object! XCTAssertEqual(persistedObject.intCol, 12) XCTAssertNil(standalone.realm) // the standalone object should be copied, rather than added, to the realm XCTAssertEqual(object.object!, persistedObject) XCTAssertEqual(object.objects.first!, persistedObject) } func testCreateWithObjectsFromAnotherRealm() { let values = [ "boolCol": true as NSNumber, "intCol": 1 as NSNumber, "floatCol": 1.1 as NSNumber, "doubleCol": 11.1 as NSNumber, "stringCol": "b" as NSString, "binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, "dateCol": NSDate(timeIntervalSince1970: 2) as NSDate, "objectCol": SwiftBoolObject(value: [true]) as AnyObject, "arrayCol": [SwiftBoolObject(value: [true]), SwiftBoolObject()] as AnyObject, ] realmWithTestPath().beginWrite() let otherRealmObject = realmWithTestPath().create(SwiftObject.self, value: values) realmWithTestPath().commitWrite() Realm().beginWrite() let object = Realm().create(SwiftObject.self, value: otherRealmObject) Realm().commitWrite() XCTAssertNotEqual(otherRealmObject, object) verifySwiftObjectWithDictionaryLiteral(object, dictionary: values, boolObjectValue: true, boolObjectListValues: [true, false]) } func testUpdateWithObjectsFromAnotherRealm() { realmWithTestPath().beginWrite() let otherRealmObject = realmWithTestPath().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", NSNull(), [["2", 2], ["4", 4]]]) realmWithTestPath().commitWrite() Realm().beginWrite() Realm().create(SwiftLinkToPrimaryStringObject.self, value: ["primary", ["10", 10], [["11", 11]]]) let object = Realm().create(SwiftLinkToPrimaryStringObject.self, value: otherRealmObject, update: true) Realm().commitWrite() XCTAssertNotEqual(otherRealmObject, object) // the object from the other realm should be copied into this realm XCTAssertEqual(Realm().objects(SwiftLinkToPrimaryStringObject).count, 1) XCTAssertEqual(Realm().objects(SwiftPrimaryStringObject).count, 4) } func testCreateWithNSNullLinks() { let values = [ "boolCol": true as NSNumber, "intCol": 1 as NSNumber, "floatCol": 1.1 as NSNumber, "doubleCol": 11.1 as NSNumber, "stringCol": "b" as NSString, "binaryCol": "b".dataUsingEncoding(NSUTF8StringEncoding)! as NSData, "dateCol": NSDate(timeIntervalSince1970: 2) as NSDate, "objectCol": NSNull(), "arrayCol": NSNull(), ] realmWithTestPath().beginWrite() let object = realmWithTestPath().create(SwiftObject.self, value: values) realmWithTestPath().commitWrite() XCTAssertNil(object.objectCol) XCTAssertEqual(object.arrayCol.count, 0) } // test null object // test null list // MARK: Add tests func testAddWithExisingNestedObjects() { Realm().beginWrite() let existingObject = Realm().create(SwiftBoolObject) Realm().commitWrite() Realm().beginWrite() let object = SwiftObject(value: ["objectCol" : existingObject]) Realm().add(object) Realm().commitWrite() XCTAssertNotNil(object.realm) XCTAssertEqual(object.objectCol, existingObject) } func testAddAndUpdateWithExisingNestedObjects() { Realm().beginWrite() let existingObject = Realm().create(SwiftPrimaryStringObject.self, value: ["primary", 1]) Realm().commitWrite() Realm().beginWrite() let object = SwiftLinkToPrimaryStringObject(value: ["primary", ["primary", 2], []]) Realm().add(object, update: true) Realm().commitWrite() XCTAssertNotNil(object.realm) XCTAssertEqual(object.object!, existingObject) // the existing object should be updated XCTAssertEqual(existingObject.intCol, 2) } // MARK: Private utilities private func verifySwiftObjectWithArrayLiteral(object: SwiftObject, array: [AnyObject], boolObjectValue: Bool, boolObjectListValues: [Bool]) { XCTAssertEqual(object.boolCol, array[0] as! Bool) XCTAssertEqual(object.intCol, array[1] as! Int) XCTAssertEqual(object.floatCol, array[2] as! Float) XCTAssertEqual(object.doubleCol, array[3] as! Double) XCTAssertEqual(object.stringCol, array[4] as! String) XCTAssertEqual(object.binaryCol, array[5] as! NSData) XCTAssertEqual(object.dateCol, array[6] as! NSDate) XCTAssertEqual(object.objectCol.boolCol, boolObjectValue) XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count) for i in 0..<boolObjectListValues.count { XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i]) } } private func verifySwiftObjectWithDictionaryLiteral(object: SwiftObject, dictionary: [String:AnyObject], boolObjectValue: Bool, boolObjectListValues: [Bool]) { XCTAssertEqual(object.boolCol, dictionary["boolCol"] as! Bool) XCTAssertEqual(object.intCol, dictionary["intCol"] as! Int) XCTAssertEqual(object.floatCol, dictionary["floatCol"] as! Float) XCTAssertEqual(object.doubleCol, dictionary["doubleCol"] as! Double) XCTAssertEqual(object.stringCol, dictionary["stringCol"] as! String) XCTAssertEqual(object.binaryCol, dictionary["binaryCol"] as! NSData) XCTAssertEqual(object.dateCol, dictionary["dateCol"] as! NSDate) XCTAssertEqual(object.objectCol.boolCol, boolObjectValue) XCTAssertEqual(object.arrayCol.count, boolObjectListValues.count) for i in 0..<boolObjectListValues.count { XCTAssertEqual(object.arrayCol[i].boolCol, boolObjectListValues[i]) } } private func defaultSwiftObjectValuesWithReplacements(replace: [String: AnyObject]) -> [String: AnyObject] { var valueDict = SwiftObject.defaultValues() for (key, value) in replace { valueDict[key] = value } return valueDict } // return an array of valid values that can be used to initialize each type private func validValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] { Realm().beginWrite() let persistedObject = Realm().create(SwiftBoolObject.self, value: [true]) Realm().commitWrite() switch type { case .Bool: return [true, 0 as Int, 1 as Int] case .Int: return [1 as Int] case .Float: return [1 as Int, 1.1 as Float, 11.1 as Double] case .Double: return [1 as Int, 1.1 as Float, 11.1 as Double] case .String: return ["b"] case .Data: return ["b".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! as NSData] case .Date: return [NSDate(timeIntervalSince1970: 2) as AnyObject] case .Object: return [[true], ["boolCol": true], SwiftBoolObject(value: [true]), persistedObject] case .Array: return [[[true], [false]], [["boolCol": true], ["boolCol": false]], [SwiftBoolObject(value: [true]), SwiftBoolObject(value: [false])], [persistedObject, [false]]] case .Any: XCTFail("not supported") } return [] } private func invalidValuesForSwiftObjectType(type: PropertyType) -> [AnyObject] { Realm().beginWrite() let persistedObject = Realm().create(SwiftIntObject) Realm().commitWrite() switch type { case .Bool: return ["invalid", 2 as Int, 1.1 as Float, 11.1 as Double] case .Int: return ["invalid", 1.1 as Float, 11.1 as Double] case .Float: return ["invalid", true, false] case .Double: return ["invalid", true, false] case .String: return [0x197A71D, true, false] case .Data: return ["invalid"] case .Date: return ["invalid"] case .Object: return ["invalid", ["a"], ["boolCol": "a"], SwiftIntObject()] case .Array: return ["invalid", [["a"]], [["boolCol" : "a"]], [[SwiftIntObject()]], [[persistedObject]]] case .Any: XCTFail("not supported") } return [] } }
apache-2.0
679889223e8ec869b9896ba82ef848e0
45.425764
207
0.637728
5.442283
false
true
false
false
jpush/aurora-imui
iOS/sample/sample/IMUICommon/Extension/UIColorExtension.swift
1
703
// // UIColorExtension.swift // IMUIChat // // Created by oshumini on 2017/3/3. // Copyright © 2017年 HXHG. All rights reserved. // import Foundation import UIKit public extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex: Int) { self.init(red: (netHex >> 16) & 0xff, green: (netHex >> 8) & 0xff, blue: netHex & 0xff) } }
mit
7a947fbd7099eeaa8ad01a14151fbd5f
27
112
0.624286
3.225806
false
false
false
false
glessard/async-deferred
Source/deferred/deferred-timeout.swift
3
6774
// // deferred-timeout.swift // deferred // // Created by Guillaume Lessard // Copyright © 2017-2020 Guillaume Lessard. All rights reserved. // import Dispatch /* Definitions that rely on or extend Deferred, but do not need the fundamental, private stuff. */ // MARK: maximum time until a `Deferred` becomes resolved extension Deferred { /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter seconds: a number of seconds as a `Double` or `NSTimeInterval` /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self public func timeout(seconds: Double, reason: String = "") -> Deferred<Success, Error> { return self.timeout(after: .now() + seconds, reason: reason) } /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter timeout: a time interval /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self public func timeout(_ timeout: DispatchTimeInterval, reason: String = "") -> Deferred<Success, Error> { return self.timeout(after: .now() + timeout, reason: reason) } /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter deadline: a timestamp used as a deadline /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self public func timeout(after deadline: DispatchTime, reason: String = "") -> Deferred<Success, Error> { if self.isResolved { return self.withAnyError } let broadened: Deferred<Success, Error> if let t = self as? Deferred<Success, Error> { broadened = t } else { broadened = self.withAnyError } let timedOut = Cancellation.timedOut(reason) if let timedOut = convertCancellation(timedOut) { if deadline < .now() { self.cancel(timedOut) } else if deadline != .distantFuture { let queue = DispatchQueue.global(qos: qos.qosClass) queue.asyncAfter(deadline: deadline) { [weak self] in self?.cancel(timedOut) } } return broadened } if deadline < .now() { broadened.cancel(timedOut) } else if deadline != .distantFuture { let queue = DispatchQueue.global(qos: qos.qosClass) queue.asyncAfter(deadline: deadline) { [weak broadened] in broadened?.cancel(timedOut) } } return broadened } } extension Deferred where Failure == Cancellation { /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter seconds: a number of seconds as a `Double` or `NSTimeInterval` /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self @discardableResult public func timeout(seconds: Double, reason: String = "") -> Deferred<Success, Cancellation> { return self.timeout(after: .now() + seconds, reason: reason) } /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter timeout: a time interval /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self @discardableResult public func timeout(_ timeout: DispatchTimeInterval, reason: String = "") -> Deferred<Success, Cancellation> { return self.timeout(after: .now() + timeout, reason: reason) } /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter deadline: a timestamp used as a deadline /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self @discardableResult public func timeout(after deadline: DispatchTime, reason: String = "") -> Deferred<Success, Cancellation> { if self.isResolved { return self } let timedOut = Cancellation.timedOut(reason) if deadline < .now() { cancel(timedOut) } else if deadline != .distantFuture { let queue = DispatchQueue.global(qos: qos.qosClass) queue.asyncAfter(deadline: deadline) { [weak self] in self?.cancel(timedOut) } } return self } } extension Deferred where Failure == Never { /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter seconds: a number of seconds as a `Double` or `NSTimeInterval` /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self public func timeout(seconds: Double, reason: String = "") -> Deferred<Success, Cancellation> { return self.timeout(after: .now() + seconds, reason: reason) } /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter timeout: a time interval /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self public func timeout(_ timeout: DispatchTimeInterval, reason: String = "") -> Deferred<Success, Cancellation> { return self.timeout(after: .now() + timeout, reason: reason) } /// Ensure this `Deferred` will be resolved by the given deadline. /// /// If `self` has not become resolved before the timeout expires, `self` will be canceled. /// /// - parameter deadline: a timestamp used as a deadline /// - parameter reason: the reason for the cancellation if the operation times out. Defaults to "Deferred operation timed out". /// - returns: self public func timeout(after deadline: DispatchTime, reason: String = "") -> Deferred<Success, Cancellation> { return self.setFailureType(to: Cancellation.self).timeout(after: deadline, reason: reason) } }
mit
7591c29bc5c76b5c7d19814f20ef72f3
35.026596
129
0.683301
4.355627
false
false
false
false
YoungGary/30daysSwiftDemo
day16/day16/day16/PushTableViewController.swift
1
1827
// // PushTableViewController.swift // day16 // // Created by YOUNG on 2016/10/10. // Copyright © 2016年 Young. All rights reserved. // import UIKit protocol sendTitleDelegate{ func sendTitle(title:String) } class PushTableViewController: UITableViewController { var menuItems = ["Everyday Moments", "Popular", "Editors", "Upcoming", "Fresh", "Stock-photos", "Trending"] var currentTitle : String = "" var delegate : sendTitleDelegate? override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.blackColor() tableView.separatorStyle = .None tableView.tableFooterView = UIView() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellcell", forIndexPath: indexPath) cell.textLabel?.text = menuItems[indexPath.row] cell.textLabel?.textColor = (menuItems[indexPath.row] == currentTitle) ? UIColor.whiteColor() : UIColor.grayColor() cell.backgroundColor = UIColor.blackColor() cell.selectionStyle = .None return cell } //点击cell反传值 override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { delegate?.sendTitle(menuItems[indexPath.row]) dismissViewControllerAnimated(true, completion: nil) } }
mit
48d278d876ad52b81193590a479066fa
25.289855
123
0.658214
5.212644
false
false
false
false
mountainKaku/Basic-Algorithms
BucketSort.playground/Contents.swift
1
1095
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" print(str) //BucketSort: 桶排序法 enum SortType { case ascending //升序 case descending //降序 } func bucketSortOf(_ arr: [Int], type:SortType = .ascending) -> [Int] { guard arr.count > 1 else { return arr } let maxNum = arr.max() //桶的数目 var bucket:[Int] = Array.init(repeatElement(0, count: maxNum! + 1)) var newNum:[Int] = Array.init() //给桶加标记 for index in arr { let numId = index bucket[numId] += 1 } for index in bucket.indices { _ = (type == .ascending) ? index : bucket.count - index while bucket[index] > 0 { newNum.append(index) bucket[index] -= 1 } } return newNum } var numbersArray = [10,3,17,8,5,2,1,9,5,4] print("桶排序方案: \(bucketSortOf(numbersArray))") print("桶排序方案: \(bucketSortOf(numbersArray,type: .ascending))") print("桶排序方案: \(bucketSortOf(numbersArray,type: .descending))")
mit
df978bc46cb062ae76f94adf9cb39042
21.911111
71
0.590689
3.252366
false
false
false
false
narner/AudioKit
Examples/iOS/SongProcessor/SongProcessor/View Controllers/LoopsViewController.swift
1
1875
// // LoopsViewController.swift // SongProcessor // // Created by Aurelius Prochazka on 6/22/16. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit import UIKit class LoopsViewController: UIViewController { let songProcessor = SongProcessor.sharedInstance override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(share(barButton:))) } fileprivate func playNew(loop: String) { if loop == "mix" { songProcessor.playersDo { $0.volume = 1 } } else { guard let player = songProcessor.players[loop] else { return } songProcessor.playersDo { $0.volume = $0 == player ? 1 : 0 } } if !songProcessor.loopsPlaying { songProcessor.rewindLoops() } songProcessor.loopsPlaying = true } @IBAction func playMix(_ sender: UIButton) { playNew(loop: "mix") } @IBAction func playDrums(_ sender: UIButton) { playNew(loop: "drum") } @IBAction func playBass(_ sender: UIButton) { playNew(loop: "bass") } @IBAction func playGuitar(_ sender: UIButton) { playNew(loop: "guitar") } @IBAction func playLead(_ sender: UIButton) { playNew(loop: "lead") } @IBAction func stop(_ sender: UIButton) { songProcessor.iTunesFilePlayer?.stop() songProcessor.loopsPlaying = false } @objc func share(barButton: UIBarButtonItem) { renderAndShare { docController in guard let canOpen = docController?.presentOpenInMenu(from: barButton, animated: true) else { return } if !canOpen { self.present(self.alertForShareFail(), animated: true, completion: nil) } } } }
mit
1fbfea336d03e293880f178989db5ff7
26.970149
142
0.615795
4.368298
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Renderers/ChartXAxisRendererRadarChart.swift
3
1989
// // ChartXAxisRendererRadarChart.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 CoreGraphics.CGBase import UIKit.UIFont public class ChartXAxisRendererRadarChart: ChartXAxisRenderer { private weak var _chart: RadarChartView!; public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil); _chart = chart; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled) { return; } var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; var sliceangle = _chart.sliceAngle; // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor; var center = _chart.centerOffsets; for (var i = 0, count = _xAxis.values.count; i < count; i++) { var text = _xAxis.values[i]; var angle = (sliceangle * CGFloat(i) + _chart.rotationAngle) % 360.0; var p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor + _xAxis.labelWidth / 2.0, angle: angle); ChartUtils.drawText(context: context, text: text, point: CGPoint(x: p.x, y: p.y - _xAxis.labelHeight / 2.0), align: .Center, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } public override func renderLimitLines(#context: CGContext) { /// XAxis LimitLines on RadarChart not yet supported. } }
gpl-2.0
5fc54855ca60906ca5e07a019121b03d
31.096774
231
0.628457
4.691038
false
false
false
false
syoung-smallwisdom/BrickBot
BrickBot/BrickBot/RobotSettingsViewController.swift
1
6387
// // RobotSettingsViewController.swift // BrickBot // // Created by Shannon Young on 9/28/15. // Copyright © 2015 Smallwisdom. All rights reserved. // import UIKit class RobotSettingsViewController: UIViewController, UITextFieldDelegate, UIGestureRecognizerDelegate { var robotManager:BBRobotManager! var robot:BBRobot? { return robotManager.connectedRobot } var selectedIndex = 1 // Forward var motorCalibration = BBMotorCalibration() var motorCalibrationChanged = false @IBOutlet weak var robotNameTextField: UITextField! @IBOutlet var arrowButtons: [SWArrowButton]! @IBOutlet var arrowDirectionLabels: [UILabel]! @IBOutlet weak var calibrationDial: CalibrationDial! @IBOutlet weak var motorSwitch: UISwitch! @IBOutlet weak var viewHitGestureRecognizer: UITapGestureRecognizer! @IBOutlet weak var loadingView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // setup initial values robotNameTextField.text = robot?.name ?? generateRandomName() robotManager.readMotorCalibration { [weak self](calibration:BBMotorCalibration?) -> () in guard let calibration = calibration, let strongSelf = self else { return } strongSelf.motorCalibration = calibration strongSelf.calibrationDial.dialPosition = calibration.calibrationStates[strongSelf.selectedIndex] strongSelf.loadingView.hidden = true } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // turn off the motors when exiting the view robotManager.sendBallPosition(CGPointZero, remoteOn: false) } @IBAction func cancelTapped(sender: AnyObject) { if motorCalibrationChanged { robotManager.sendResetCalibration() } self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func saveTapped(sender: AnyObject) { if let robotName = robotNameTextField.text where robotName != robot?.name { robotManager.sendRobotName(robotName) } if motorCalibrationChanged { robotManager.sendSaveCalibration() } self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } @IBAction func arrowTapped(sender: AnyObject) { // Check that not tracking guard !calibrationDial.tracking else { return } // And that this is toggling ON a different button from the currently selected guard let arrowButton = sender as? SWArrowButton, let idx = arrowButtons.indexOf(arrowButton) where idx != selectedIndex else { toggleMotorState() return } // turn motor off turnOffMotors(); // Update arrow button states arrowButtons[selectedIndex].selected = false arrowDirectionLabels[selectedIndex].hidden = true arrowButtons[idx].selected = true arrowDirectionLabels[idx].hidden = false selectedIndex = idx // Update the calibration dial calibrationDial.dialPosition = motorCalibration.calibrationStates[selectedIndex] } func toggleMotorState() { motorSwitch.on = !motorSwitch.on motorSwitchChanged(motorSwitch) } func turnOffMotors() { // Turn off the motor switch motorSwitch.on = false motorSwitchChanged(motorSwitch) } @IBAction func motorSwitchChanged(sender: AnyObject) { if (motorSwitch.on) { robotManager.sendBallPosition(CGPointMake(CGFloat(selectedIndex - 1), 1), remoteOn: true) } else { robotManager.sendBallPosition(CGPointZero, remoteOn: false) } } @IBAction func calibrationDialTouchedDown(sender: AnyObject) { turnOffMotors() } @IBAction func calibrationDialPositionChanged(sender: AnyObject) { motorCalibrationChanged = true motorCalibration.setCalibration(selectedIndex, value:calibrationDial.dialPosition) robotManager.sendMotorCalibration(motorCalibration) } @IBAction func viewTapped(gesture: UIGestureRecognizer) { let location = gesture.locationOfTouch(0, inView: view) if (view.hitTest(location, withEvent: nil) != robotNameTextField) { robotNameTextField.resignFirstResponder() } } // MARK: - UITextFieldDelegate func textFieldDidBeginEditing(textField: UITextField) { // Add listener to dismiss the keyboard viewHitGestureRecognizer.enabled = true } func textFieldDidEndEditing(textField: UITextField) { viewHitGestureRecognizer.enabled = false } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // there is no longer a check for string length for a Swift string so bridge to obj-c let currentLength = textField.text?.lengthOfBytesUsingEncoding(BBNameStringEncoding) ?? 0 let addLength = string.lengthOfBytesUsingEncoding(BBNameStringEncoding) return currentLength - range.length + addLength <= (robot?.maxRobotNameLength ?? 20) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return false } // MARK: - UIGestureRecognizerDelegate func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } // MARK: - Random Name generator let randomNames = ["BeeBoo", "Rev", "Brinkle", "Tribecca", "Susan", "Lotta", "Grumbly"] func generateRandomName() -> String { let idx = Int(arc4random_uniform(UInt32(randomNames.count - 1))) return randomNames[idx] } }
mit
8349ddea254b0d99e5c14fc5df3c49e6
34.477778
172
0.672565
5.290804
false
false
false
false
pinterest/plank
Sources/Core/ObjCModelRenderer.swift
1
15510
// // ObjCModelRenderer.swift // Plank // // Created by Rahul Malik on 7/29/15. // Copyright © 2015 Rahul Malik. All rights reserved. // import Foundation let rootNSObject = SchemaObjectRoot(name: "NSObject", properties: [:], extends: nil, algebraicTypeIdentifier: nil) public struct ObjCModelRenderer: ObjCFileRenderer { let rootSchema: SchemaObjectRoot let params: GenerationParameters init(rootSchema: SchemaObjectRoot, params: GenerationParameters) { self.rootSchema = rootSchema self.params = params } var dirtyPropertyOptionName: String { return "\(className)DirtyProperties" } var booleanPropertiesStructName: String { return "\(className)BooleanProperties" } var dirtyPropertiesIVarName: String { return "\(Languages.objectiveC.snakeCaseToPropertyName(rootSchema.name))DirtyProperties" } var booleanPropertiesIVarName: String { return "\(Languages.objectiveC.snakeCaseToPropertyName(rootSchema.name))BooleanProperties" } // MARK: Model methods func renderClassName() -> ObjCIR.Method { return ObjCIR.method("+ (NSString *)className") { ["return \(self.className.objcLiteral());"] } } func renderPolymorphicTypeIdentifier() -> ObjCIR.Method { return ObjCIR.method("+ (NSString *)polymorphicTypeIdentifier") { ["return \(self.rootSchema.typeIdentifier.objcLiteral());"] } } func renderCopyWithBlock() -> ObjCIR.Method { return ObjCIR.method("- (instancetype)copyWithBlock:(PLANK_NOESCAPE void (^)(\(builderClassName) *builder))block") { [ "NSParameterAssert(block);", "\(self.builderClassName) *builder = [[\(self.builderClassName) alloc] initWithModel:self];", "block(builder);", "return [builder build];", ] } } func renderMergeWithModel() -> ObjCIR.Method { return ObjCIR.method("- (instancetype)mergeWithModel:(\(className) *)modelObject") { ["return [self mergeWithModel:modelObject initType:PlankModelInitTypeFromMerge];"] } } func renderMergeWithModelWithInitType() -> ObjCIR.Method { return ObjCIR.method("- (instancetype)mergeWithModel:(\(className) *)modelObject initType:(PlankModelInitType)initType") { [ "NSParameterAssert(modelObject);", "\(self.builderClassName) *builder = [[\(self.builderClassName) alloc] initWithModel:self];", "[builder mergeWithModel:modelObject];", "return [[\(self.className) alloc] initWithBuilder:builder initType:initType];", ] } } func renderStringEnumerationMethods() -> [ObjCIR.Method] { func renderToStringMethod(param: String, enumValues: [EnumValue<String>]) -> ObjCIR.Method { let enumTypeString = enumTypeName(propertyName: param, className: className) return ObjCIR.method("extern NSString * _Nonnull \(enumTypeString)ToString(\(enumTypeString) enumType)") { [ ObjCIR.switchStmt("enumType") { enumValues.map { (val) -> ObjCIR.SwitchCase in ObjCIR.caseStmt(val.objcOptionName(param: param, className: self.className)) { ["return \(val.defaultValue.objcLiteral());"] } } }, ] } } func renderFromStringMethod(param: String, enumValues: [EnumValue<String>], defaultValue: EnumValue<String>) -> ObjCIR.Method { let enumTypeString = enumTypeName(propertyName: param, className: className) return ObjCIR.method("extern \(enumTypeString) \(enumTypeString)FromString(NSString * _Nonnull str)") { enumValues.map { (val) -> String in ObjCIR.ifStmt("[str isEqualToString:\(val.defaultValue.objcLiteral())]") { [ "return \(val.objcOptionName(param: param, className: self.className));", ] } } + ["return \(defaultValue.objcOptionName(param: param, className: self.className));"] } } return properties.flatMap { (param, prop) -> [ObjCIR.Method] in switch prop.schema { case let .enumT(.string(enumValues, defaultValue)): return [ renderToStringMethod(param: param, enumValues: enumValues), renderFromStringMethod(param: param, enumValues: enumValues, defaultValue: defaultValue), ] default: return [] } } } func renderIsSetMethods() -> [ObjCIR.Method] { return properties.map { param, _ in ObjCIR.method("- (BOOL)is\(Languages.objectiveC.snakeCaseToCamelCase(param))Set") { [ "return _\(self.dirtyPropertiesIVarName).\(dirtyPropertyOption(propertyName: param, className: self.className)) == 1;", ] } } } func renderBooleanPropertyAccessorMethods() -> [ObjCIR.Method] { return properties.flatMap { (param, prop) -> [ObjCIR.Method] in switch prop.schema { case .boolean: return [ObjCIR.method("- (BOOL)\(Languages.objectiveC.snakeCaseToPropertyName(param))") { ["return _\(self.booleanPropertiesIVarName).\(booleanPropertyOption(propertyName: param, className: self.className));"] }] default: return [] } } } func renderRoots() -> [ObjCIR.Root] { let booleanProperties = rootSchema.properties.filter { (arg) -> Bool in let (_, schema) = arg return schema.schema.isBoolean() } let booleanStructDeclaration = !booleanProperties.isEmpty ? [ObjCIR.Root.structDecl(name: self.booleanPropertiesStructName, fields: booleanProperties.keys.map { "unsigned int \(booleanPropertyOption(propertyName: $0, className: self.className)):1;" })] : [] let booleanIvarDeclaration: [SimpleProperty] = !booleanProperties.isEmpty ? [(self.booleanPropertiesIVarName, "struct \(self.booleanPropertiesStructName)", SchemaObjectProperty(schema: .integer, nullability: nil), .readwrite)] : [] let enumProperties = properties.filter { (arg) -> Bool in let (_, schema) = arg switch schema.schema { case .enumT: return true default: return false } } let enumIVarDeclarations: [(Parameter, TypeName)] = enumProperties.compactMap { (arg) -> (Parameter, TypeName) in let (param, _) = arg return (param, enumTypeName(propertyName: param, className: self.className)) } let protocols: [String: [ObjCIR.Method]] = [ "NSSecureCoding": [self.renderSupportsSecureCoding(), self.renderInitWithCoder(), self.renderEncodeWithCoder()], "NSCopying": [ObjCIR.method("- (id)copyWithZone:(NSZone *)zone") { ["return self;"] }], ] let parentName = resolveClassName(parentDescriptor) func enumRoot(from prop: Schema, param: String) -> [ObjCIR.Root] { switch prop { case let .enumT(enumValues): return [ObjCIR.Root.enumDecl(name: enumTypeName(propertyName: param, className: self.className), values: enumValues)] case let .oneOf(types: possibleTypes): return possibleTypes.flatMap { enumRoot(from: $0, param: param) } case let .array(itemType: .some(itemType)): return enumRoot(from: itemType, param: param) case let .map(valueType: .some(additionalProperties)): return enumRoot(from: additionalProperties, param: param) default: return [] } } let enumRoots = properties.flatMap { (param, prop) -> [ObjCIR.Root] in enumRoot(from: prop.schema, param: param) } // TODO: Synthesize oneOf ADT Classes and Class Extension // TODO: (rmalik): Clean this up, too much copy / paste here to support oneOf cases let adtRoots = properties.flatMap { (param, prop) -> [ObjCIR.Root] in switch prop.schema { case let .oneOf(types: possibleTypes): let objProps = possibleTypes.map { SchemaObjectProperty(schema: $0, nullability: $0.isPrimitiveType ? nil : .nullable) } return adtRootsForSchema(property: param, schemas: objProps) case let .array(itemType: .some(itemType)): switch itemType { case let .oneOf(types: possibleTypes): let objProps = possibleTypes.map { SchemaObjectProperty(schema: $0, nullability: $0.isPrimitiveType ? nil : .nullable) } return adtRootsForSchema(property: param, schemas: objProps) default: return [] } case let .map(valueType: .some(additionalProperties)): switch additionalProperties { case let .oneOf(types: possibleTypes): let objProps = possibleTypes.map { SchemaObjectProperty(schema: $0, nullability: $0.isPrimitiveType ? nil : .nullable) } return adtRootsForSchema(property: param, schemas: objProps) default: return [] } default: return [] } } return [ ObjCIR.Root.imports( classNames: Set(self.renderReferencedClasses().map { // Objective-C types contain "*" if they are a pointer type // This information is excessive for import statements so // we're removing it here. $0.replacingOccurrences(of: "*", with: "") }), myName: self.className, parentName: parentName ), ] + adtRoots + enumRoots + [ ObjCIR.Root.structDecl(name: self.dirtyPropertyOptionName, fields: rootSchema.properties.keys .map { "unsigned int \(dirtyPropertyOption(propertyName: $0, className: self.className)):1;" }), ] + booleanStructDeclaration + [ObjCIR.Root.category(className: self.className, categoryName: nil, methods: [], properties: [(self.dirtyPropertiesIVarName, "struct \(self.dirtyPropertyOptionName)", SchemaObjectProperty(schema: .integer, nullability: nil), .readwrite)] + booleanIvarDeclaration, variables: enumIVarDeclarations), ObjCIR.Root.category(className: self.builderClassName, categoryName: nil, methods: [], properties: [(self.dirtyPropertiesIVarName, "struct \(self.dirtyPropertyOptionName)", SchemaObjectProperty(schema: .integer, nullability: nil), .readwrite)], variables: [])] + renderStringEnumerationMethods().map { ObjCIR.Root.function($0) } + [ ObjCIR.Root.macro("NS_ASSUME_NONNULL_BEGIN"), ObjCIR.Root.classDecl( name: self.className, extends: parentName, methods: [ (self.isBaseClass ? .publicM : .privateM, self.renderClassName()), (self.isBaseClass ? .publicM : .privateM, self.renderPolymorphicTypeIdentifier()), (self.isBaseClass ? .publicM : .privateM, self.renderModelObjectWithDictionary()), (self.isBaseClass ? .publicM : .privateM, self.renderModelObjectWithDictionaryError()), (.privateM, self.renderDesignatedInit()), (self.isBaseClass ? .publicM : .privateM, self.renderInitWithModelDictionary()), (self.isBaseClass ? .publicM : .privateM, self.renderInitWithModelDictionaryError()), (.publicM, self.renderInitWithBuilder()), (self.isBaseClass ? .publicM : .privateM, self.renderInitWithBuilderWithInitType()), (.privateM, self.renderDebugDescription()), (.publicM, self.renderCopyWithBlock()), (.privateM, self.renderIsEqual()), (.publicM, self.renderIsEqualToClass(self.booleanPropertiesIVarName)), (.privateM, self.renderHash(self.booleanPropertiesIVarName)), (.publicM, self.renderMergeWithModel()), (.publicM, self.renderMergeWithModelWithInitType()), (self.isBaseClass ? .publicM : .privateM, self.renderGenerateDictionary()), ] + self.renderIsSetMethods().map { (.publicM, $0) } + self.renderBooleanPropertyAccessorMethods().map { (.publicM, $0) }, properties: properties.map { param, prop in (param, typeFromSchema(param, prop), prop, .readonly) }.sorted { $0.0 < $1.0 }, protocols: protocols ), ObjCIR.Root.classDecl( name: self.builderClassName, extends: resolveClassName(self.parentDescriptor).map { "\($0)Builder" }, methods: [ (.publicM, self.renderBuilderInitWithModel()), (.publicM, ObjCIR.method("- (\(self.className) *)build") { ["return [[\(self.className) alloc] initWithBuilder:self];"] }), (.publicM, self.renderBuilderMergeWithModel()), ] + self.renderBuilderPropertySetters().map { (.privateM, $0) }, properties: properties.map { param, prop in (param, typeFromSchema(param, prop), prop, .readwrite) }, protocols: [:] ), ObjCIR.Root.macro("NS_ASSUME_NONNULL_END"), ] } }
apache-2.0
c5f75a0bf7eadd3712a7a830dae0240e
52.113014
228
0.528854
5.181757
false
false
false
false
Contron/Dove
Dove/Dove.swift
1
527
// // Dove.swift // Dove // // Created by Connor Haigh on 03/06/2016. // Copyright © 2016 Connor Haigh. All rights reserved. // import Foundation public typealias ActionBlock = () -> () public typealias ResultBlock = (Bool) -> () public typealias ProgressBlock = () -> Double public let animationConstant = 0.3 public let shorterAnimationConstant = animationConstant / 2 public let longerAnimationConstant = animationConstant * 2 public let springDamping = CGFloat(0.5) public let springInitialVelocity = CGFloat(0.1)
mit
d1b4d97fb8a512395c047b935c8b100e
25.3
59
0.739544
3.811594
false
false
false
false
likumb/SimpleMemo
SimpleMemo/Controller/MemoViewController.swift
2
4461
// // MemoViewController.swift // EverMemo // // Created by  李俊 on 15/8/5. // Copyright (c) 2015年  李俊. All rights reserved. // import UIKit import CoreData import EvernoteSDK import SnapKit import SMKit class MemoViewController: UIViewController { var memo: Memo? fileprivate let textView = UITextView() fileprivate var sharedItem: UIBarButtonItem! convenience init(text: String? = nil) { self.init(nibName: nil, bundle: nil) textView.text = text ?? "" saveCurrentText() } override func viewDidLoad() { super.viewDidLoad() setUI() NotificationCenter.default.addObserver(self, selector: #selector(changeLayOut(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) view.endEditing(true) if let memo = memo, textView.text.isEmpty { ENSession.shared.deleteFromEvernote(with: memo) CoreDataStack.default.managedContext.delete(memo) } CoreDataStack.default.saveContext() } // 3D Touch previewActionItems override var previewActionItems: [UIPreviewActionItem] { let deleteAction = UIPreviewAction(title: "删除", style: .destructive) { (action, controller) in guard let memoController: MemoViewController = controller as? MemoViewController, let memo = memoController.memo else { return } CoreDataStack.default.managedContext.delete(memo) ENSession.shared.deleteFromEvernote(with: memo) } return [deleteAction] } } // MARK: - Private extension private extension MemoViewController { func setUI() { view.backgroundColor = UIColor.white setTextView() sharedItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: self, action: #selector(MemoViewController.perpormShare(_:))) navigationItem.rightBarButtonItem = sharedItem if memo == nil { title = "新便签" textView.becomeFirstResponder() } else { title = memo!.text?.fetchTitle() textView.text = memo!.text } sharedItem.isEnabled = !textView.text.isEmpty } func setTextView() { textView.delegate = self textView.layoutManager.allowsNonContiguousLayout = false textView.keyboardDismissMode = .onDrag textView.translatesAutoresizingMaskIntoConstraints = false setTextViewAttrubt() view.addSubview(textView) setTextViewConstraints(withBottomOffset: -5) } func setTextViewConstraints(withBottomOffset offset: CGFloat) { textView.snp.remakeConstraints { (maker) in maker.top.equalToSuperview() maker.left.equalTo(view).offset(5) maker.right.equalTo(view).offset(-5) maker.bottom.equalTo(view).offset(offset) } } func setTextViewAttrubt() { let paregraphStyle = NSMutableParagraphStyle() paregraphStyle.lineSpacing = 5 let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSParagraphStyleAttributeName: paregraphStyle] textView.typingAttributes = attributes textView.font = UIFont.systemFont(ofSize: 16) textView.textColor = SMColor.content } @objc func perpormShare(_ barButton: UIBarButtonItem) { let activityController = UIActivityViewController(activityItems: [textView.text], applicationActivities: nil) let drivce = UIDevice.current let model = drivce.model if model == "iPhone Simulator" || model == "iPhone" || model == "iPod touch"{ present(activityController, animated: true, completion: nil) } else { let popoverView = UIPopoverController(contentViewController: activityController) popoverView.present(from: barButton, permittedArrowDirections: UIPopoverArrowDirection.any, animated: true) } } @objc func changeLayOut(_ notification: Notification) { let keyboarFrame: CGRect? = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect let keyboardY = keyboarFrame?.origin.y ?? 0 setTextViewConstraints(withBottomOffset: -(view.bounds.size.height - keyboardY + 5)) } func saveCurrentText() { memo = memo ?? Memo.newMemo() memo!.text = textView.text memo!.updateDate = Date() CoreDataStack.default.saveContext() } } // MARK: - UITextViewDelegate extension MemoViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { memo?.isUpload = false sharedItem.isEnabled = !textView.text.isEmpty saveCurrentText() } }
mit
9d5958fdfc16a85a438e1bc076aed605
30.041958
153
0.722911
4.511179
false
false
false
false
RevenueCat/purchases-ios
Sources/SubscriberAttributes/SubscriberAttribute.swift
1
2744
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // SubscriberAttribute.swift // // Created by Joshua Liebowitz on 7/1/21. // import Foundation struct SubscriberAttribute { let setTime: Date let key: String let value: String var isSynced: Bool init(withKey key: String, value: String?, isSynced: Bool, setTime: Date) { self.key = key self.value = value ?? "" self.isSynced = isSynced self.setTime = setTime } init(withKey key: String, value: String?, dateProvider: DateProvider = DateProvider()) { self.init(withKey: key, value: value, isSynced: false, setTime: dateProvider.now()) } } extension SubscriberAttribute { init?(dictionary: [String: Any]) { guard let key = dictionary[Key.key.rawValue] as? String, let isSynced = (dictionary[Key.isSynced.rawValue] as? NSNumber)?.boolValue, let setTime = dictionary[Key.setTime.rawValue] as? Date else { return nil } let value = dictionary[Key.value.rawValue] as? String self.init(withKey: key, value: value, isSynced: isSynced, setTime: setTime) } func asDictionary() -> [String: NSObject] { return [Key.key.rawValue: self.key as NSString, Key.value.rawValue: self.value as NSString, Key.isSynced.rawValue: NSNumber(value: self.isSynced), Key.setTime.rawValue: self.setTime as NSDate] } func asBackendDictionary() -> [String: Any] { return [BackendKey.value.rawValue: self.value, BackendKey.timestamp.rawValue: self.setTime.millisecondsSince1970AsUInt64()] } } extension SubscriberAttribute: Equatable {} extension SubscriberAttribute: CustomStringConvertible { var description: String { return "[SubscriberAttribute] key: \(self.key) value: \(self.value) setTime: \(self.setTime)" } } extension SubscriberAttribute { typealias Dictionary = [String: SubscriberAttribute] } extension SubscriberAttribute { static func map(subscriberAttributes: SubscriberAttribute.Dictionary) -> [String: [String: Any]] { return subscriberAttributes.mapValues { $0.asBackendDictionary() } } } // MARK: - Private extension SubscriberAttribute { private enum Key: String { case key case value case isSynced case setTime } private enum BackendKey: String { case value = "value" case timestamp = "updated_at_ms" } }
mit
96fcefee987fdcdd61fc7bbcf32a5644
24.407407
102
0.649781
4.13253
false
false
false
false
quadro5/swift3_L
Demo/Net2/ShotsTool.swift
1
2662
// // ShotsTool.swift // DemoDriAPI // // Created by PSL on 5/19/17. // Copyright © 2017 PSL. All rights reserved. // import Foundation fileprivate let accessToken = "37ddfc23b82ae5cfc673bc92770caf17272407d0d07bce3c1840fc993a509667" fileprivate let accessParameter = "?access_token=" fileprivate let base = "https://api.dribbble.com/v1/" fileprivate let authUrl = "https://dribbble.com/oauth/authorize" fileprivate let tokenUrl = "https://dribbble.com/oauth/token" fileprivate let redirectUrl = "http://www.google.com/" fileprivate let shotsEndPoint = "https://api.dribbble.com/v1/shots" fileprivate let userEndPoint = "https://api.dribbble.com/v1/user" fileprivate let usersEndPoint = "https://api.dribbble.com/v1/users" fileprivate let followShotEndPoint = "https://api.dribbble.com/v1/user/following/shots" class ShotsTool { static func fetchUser( success: @escaping (User?) -> (), failure: @escaping (Error?) -> ()) { let urlStr = userEndPoint.appending(accessParameter + accessToken) HTTPTools.get(urlStr: urlStr, success: { (data) in let user = User(data: data) success(user) }) { (error) in failure(error) } } static func fetchUser(with id: Int, success: @escaping (User?) -> (), failure: @escaping (Error?) -> ()) { var urlStr = userEndPoint.appending("/\(id)") urlStr.append(accessParameter + accessToken) HTTPTools.get(urlStr: urlStr, success: { (data) in let user = User(data: data) success(user) }) { (error) in failure(error) } } static func fetchShots( success: @escaping ([Shot]?) -> (), failure: @escaping (Error?) -> ()) { let urlStr = shotsEndPoint.appending(accessParameter + accessToken) print("url: \(urlStr) \n\n") HTTPTools.get(urlStr: urlStr, success: { (data) in guard let data = data else { assertionFailure("Error: fail to get valid data") return } guard let obj = try? JSONSerialization.jsonObject(with: data, options: []) as? [Any] else { assertionFailure("Error: fail to serialize") return } if let obj = obj { print(obj) print("size of obj: \(obj.count)") } else { print("Error: fail to get valid obj") } success(nil) }) { (error) in failure(error) } } }
unlicense
12ca459296c692589c4396fb2fd61b25
31.45122
103
0.566328
4.112828
false
false
false
false
rusty1s/RSContactGrid
Example/Example/GridElementNode.swift
1
919
// // GridElementNode.swift // Example // // Created by Matthias Fey on 15.07.15. // Copyright © 2015 Matthias Fey. All rights reserved. // import SpriteKit class GridElementNode : SKShapeNode { init(element: GameScene.TileType) { let path = CGPathCreateMutable() for (index, vertex) in element.vertices.enumerate() { if index == 0 { CGPathMoveToPoint(path, nil, vertex.x, vertex.y) } else { CGPathAddLineToPoint(path, nil, vertex.x, vertex.y) } } CGPathCloseSubpath(path) super.init() self.path = path lineWidth = 1 strokeColor = SKColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1) if element.data.contact != nil { fillColor = SKColor.redColor() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7220c14e824dda182b2773f685153bb2
26
78
0.589325
4.044053
false
false
false
false
salutis/View-PauseTime
View+PauseTime.swift
1
1721
// The MIT License (MIT) // // Copyright (c) 2015 Rudolf Adamkovič // // 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 extension UIView { func pauseTime() { let pausedTime = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) layer.speed = 0 layer.timeOffset = pausedTime } func resumeTime() { let pausedTime = layer.timeOffset layer.speed = 1 layer.timeOffset = 0 layer.beginTime = 0 let timeSincePause = layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pausedTime layer.beginTime = timeSincePause } }
mit
ea23b77d18328a3a849e60621a5eb4a3
34.102041
97
0.69186
4.886364
false
false
false
false
jopamer/swift
test/stdlib/Reflection_objc.swift
1
8325
// RUN: %empty-directory(%t) // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/a.out // RUN: %S/timeout.sh 360 %target-run %t/a.out %S/Inputs/shuffle.jpg | %FileCheck %s // REQUIRES: executable_test // FIXME: timeout wrapper is necessary because the ASan test runs for hours // // DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift. // // XFAIL: linux import Swift import Foundation import simd #if os(macOS) import AppKit typealias OSImage = NSImage typealias OSColor = NSColor typealias OSBezierPath = NSBezierPath #endif #if os(iOS) || os(tvOS) || os(watchOS) import UIKit typealias OSImage = UIImage typealias OSColor = UIColor typealias OSBezierPath = UIBezierPath #endif // Check ObjC mirror implementation. // CHECK-LABEL: ObjC: print("ObjC:") // CHECK-NEXT: <NSObject: {{0x[0-9a-f]+}}> dump(NSObject()) // CHECK-LABEL: ObjC subclass: print("ObjC subclass:") // CHECK-NEXT: woozle wuzzle dump("woozle wuzzle" as NSString) // Test a mixed Swift-ObjC hierarchy. class NSGood : NSObject { let x: Int = 22 } class NSBetter : NSGood { let y: String = "333" } // CHECK-LABEL: Swift ObjC subclass: // CHECK-NEXT: <Reflection.NSBetter: {{0x[0-9a-f]+}}> #0 // CHECK-NEXT: super: Reflection.NSGood // CHECK-NEXT: super: NSObject print("Swift ObjC subclass:") dump(NSBetter()) // CHECK-LABEL: ObjC quick look objects: print("ObjC quick look objects:") // CHECK-LABEL: ObjC enums: print("ObjC enums:") // CHECK-NEXT: We cannot reflect NSComparisonResult yet print("We cannot reflect \(ComparisonResult.orderedAscending) yet") // Don't crash when introspecting framework types such as NSURL. // <rdar://problem/16592777> // CHECK-LABEL: NSURL: // CHECK-NEXT: file:///Volumes/ // CHECK-NEXT: - super: NSObject print("NSURL:") dump(NSURL(fileURLWithPath: "/Volumes", isDirectory: true)) // -- Check that quick look Cocoa objects get binned correctly to their // associated enum tag. // CHECK-NEXT: got the expected quick look text switch PlaygroundQuickLook(reflecting: "woozle wuzzle" as NSString) { case .text("woozle wuzzle"): print("got the expected quick look text") case let x: print("NSString: got something else: \(x)") } // CHECK-NEXT: foobar let somesubclassofnsstring = ("foo" + "bar") as NSString switch PlaygroundQuickLook(reflecting: somesubclassofnsstring) { case .text(let text): print(text) case let x: print("not the expected quicklook: \(x)") } // CHECK-NEXT: got the expected quick look attributed string let astr = NSAttributedString(string: "yizzle pizzle") switch PlaygroundQuickLook(reflecting: astr) { case .attributedString(let astr2 as NSAttributedString) where astr == astr2: print("got the expected quick look attributed string") case let x: print("NSAttributedString: got something else: \(x)") } // CHECK-NEXT: got the expected quick look int switch PlaygroundQuickLook(reflecting: Int.max as NSNumber) { case .int(+Int64(Int.max)): print("got the expected quick look int") case let x: print("NSNumber(Int.max): got something else: \(x)") } // CHECK-NEXT: got the expected quick look uint switch PlaygroundQuickLook(reflecting: NSNumber(value: UInt64.max)) { case .uInt(UInt64.max): print("got the expected quick look uint") case let x: print("NSNumber(Int64.max): got something else: \(x)") } // CHECK-NEXT: got the expected quick look double switch PlaygroundQuickLook(reflecting: 22.5 as NSNumber) { case .double(22.5): print("got the expected quick look double") case let x: print("NSNumber(22.5): got something else: \(x)") } // CHECK-NEXT: got the expected quick look float switch PlaygroundQuickLook(reflecting: Float32(1.25)) { case .float(1.25): print("got the expected quick look float") case let x: print("NSNumber(Float32(1.25)): got something else: \(x)") } // CHECK-NEXT: got the expected quick look image // CHECK-NEXT: got the expected quick look color // CHECK-NEXT: got the expected quick look bezier path let image = OSImage(contentsOfFile:CommandLine.arguments[1])! switch PlaygroundQuickLook(reflecting: image) { case .image(let image2 as OSImage) where image === image2: print("got the expected quick look image") case let x: print("OSImage: got something else: \(x)") } let color = OSColor.black switch PlaygroundQuickLook(reflecting: color) { case .color(let color2 as OSColor) where color === color2: print("got the expected quick look color") case let x: print("OSColor: got something else: \(x)") } let path = OSBezierPath() switch PlaygroundQuickLook(reflecting: path) { case .bezierPath(let path2 as OSBezierPath) where path === path2: print("got the expected quick look bezier path") case let x: print("OSBezierPath: got something else: \(x)") } // CHECK-LABEL: Reflecting NSArray: // CHECK-NEXT: [ 1 2 3 4 5 ] print("Reflecting NSArray:") let intNSArray : NSArray = [1 as NSNumber,2 as NSNumber,3 as NSNumber,4 as NSNumber,5 as NSNumber] let arrayMirror = Mirror(reflecting: intNSArray) var buffer = "[ " for i in arrayMirror.children { buffer += "\(i.1) " } buffer += "]" print(buffer) // CHECK-LABEL: Reflecting NSSet: // CHECK-NEXT: NSSet reflection working fine print("Reflecting NSSet:") let numset = NSSet(objects: 1,2,3,4) let numsetMirror = Mirror(reflecting: numset) var numsetNumbers = Set<Int>() for i in numsetMirror.children { if let number = i.1 as? Int { numsetNumbers.insert(number) } } if numsetNumbers == Set([1, 2, 3, 4]) { print("NSSet reflection working fine") } else { print("NSSet reflection broken: here are the numbers we got: \(numsetNumbers)") } // CHECK-NEXT: (3.0, 6.0) // CHECK-NEXT: x: 3.0 // CHECK-NEXT: y: 6.0 dump(CGPoint(x: 3,y: 6)) // CHECK-NEXT: (30.0, 60.0) // CHECK-NEXT: width: 30.0 // CHECK-NEXT: height: 60.0 dump(CGSize(width: 30, height: 60)) // CHECK-NEXT: (50.0, 60.0, 100.0, 150.0) // CHECK-NEXT: origin: (50.0, 60.0) // CHECK-NEXT: x: 50.0 // CHECK-NEXT: y: 60.0 // CHECK-NEXT: size: (100.0, 150.0) // CHECK-NEXT: width: 100.0 // CHECK-NEXT: height: 150.0 dump(CGRect(x: 50, y: 60, width: 100, height: 150)) // rdar://problem/18513769 -- Make sure that QuickLookObject lookup correctly // manages memory. @objc class CanaryBase { deinit { print("\(type(of: self)) overboard") } required init() { } } var CanaryHandle = false class IsDebugQLO : CanaryBase, CustomStringConvertible { @objc var description: String { return "I'm a QLO" } } class HasDebugQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { return IsDebugQLO() } } class HasNumberQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let number = NSNumber(value: 97210) return number } } class HasAttributedQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSAttributedString(string: "attributed string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } class HasStringQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSString(string: "plain string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } func testQLO<T : CanaryBase>(_ type: T.Type) { autoreleasepool { _ = PlaygroundQuickLook(reflecting: type.init()) } } testQLO(IsDebugQLO.self) // CHECK-NEXT: IsDebugQLO overboard testQLO(HasDebugQLO.self) // CHECK-NEXT: HasDebugQLO overboard // CHECK-NEXT: IsDebugQLO overboard testQLO(HasNumberQLO.self) // CHECK-NEXT: HasNumberQLO overboard // TODO: tagged numbers are immortal, so we can't reliably check for // cleanup here testQLO(HasAttributedQLO.self) // CHECK-NEXT: HasAttributedQLO overboard // CHECK-NEXT: CanaryBase overboard testQLO(HasStringQLO.self) // CHECK-NEXT: HasStringQLO overboard // CHECK-NEXT: CanaryBase overboard // simd types get no reflection info, so should have no mirror children let x = float4(0) print("float4 has \(Mirror(reflecting: x).children.count) children") // CHECK-NEXT: float4 has 0 children // CHECK-LABEL: and now our song is done print("and now our song is done")
apache-2.0
7d8fc11e1c91cd58e506a013daaac23b
27.220339
125
0.706426
3.487641
false
false
false
false
yanif/circator
MetabolicCompass/View Controller/QueryViewController.swift
1
5657
// // QueryViewController.swift // MetabolicCompass // // Created by Yanif Ahmad on 12/19/15. // Copyright © 2015 Yanif Ahmad, Tom Woolf. All rights reserved. // import MetabolicCompassKit import UIKit import MGSwipeTableCell import Crashlytics import SwiftDate /** This class, along with the Builder and the Writer all together, support queries for filtering displayed metrics on 1st and 2nd dashboard screens. By the use of these queries we enable users to view their comparisons with individuals sharing similar weights or the same genders. - note: used in IntroViewController */ class QueryViewController: UITableViewController { override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: false) navigationItem.title = "Queries" tableView.reloadData() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) Answers.logContentViewWithName("Query", contentType: "", contentId: NSDate().toString(DateFormat.Custom("YYYY-MM-dd:HH:mm:ss")), customAttributes: nil) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Theme.universityDarkTheme.backgroundColor tableView.registerClass(MGSwipeTableCell.self, forCellReuseIdentifier: "queryCell") let addQueryButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addQuery") navigationItem.rightBarButtonItem = addQueryButton } func addQuery() { let builder = QueryBuilderViewController() builder.buildMode = BuilderMode.Creating navigationController?.pushViewController(builder, animated: true) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return QueryManager.sharedManager.getQueries().count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("queryCell", forIndexPath: indexPath) as! MGSwipeTableCell let deleteButton = MGSwipeButton(title: "Delete", backgroundColor: .ht_pomegranateColor(), callback: { (sender: MGSwipeTableCell!) -> Bool in if let idx = tableView.indexPathForCell(sender) { QueryManager.sharedManager.removeQuery(idx.row) tableView.deleteRowsAtIndexPaths([idx], withRowAnimation: UITableViewRowAnimation.Right) return false } return true }) deleteButton.titleLabel?.font = .boldSystemFontOfSize(14) let editButton = MGSwipeButton(title: "Edit", backgroundColor: .ht_carrotColor(), callback: { (sender: MGSwipeTableCell!) -> Bool in if let idx = tableView.indexPathForCell(sender) { switch QueryManager.sharedManager.getQueries()[idx.row].1 { case Query.ConjunctiveQuery(_, _, _, _): let builder = QueryBuilderViewController() builder.buildMode = BuilderMode.Editing(idx.row) self.navigationController?.pushViewController(builder, animated: true) } return false } return true }) editButton.titleLabel?.font = .boldSystemFontOfSize(14) cell.rightButtons = [deleteButton, editButton] cell.leftSwipeSettings.transition = MGSwipeTransition.Static if QueryManager.sharedManager.getSelectedQuery() == indexPath.row { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } cell.backgroundColor = Theme.universityDarkTheme.backgroundColor cell.tintColor = cell.selected ? UIColor.ht_belizeHoleColor() : UIColor.ht_sunflowerColor() cell.textLabel?.font = .boldSystemFontOfSize(14) cell.textLabel?.text = QueryManager.sharedManager.getQueries()[indexPath.row].0 cell.textLabel?.textColor = .whiteColor() return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if QueryManager.sharedManager.getSelectedQuery() == indexPath.row { // Deselect query if let cell = tableView.cellForRowAtIndexPath(indexPath) { QueryManager.sharedManager.deselectQuery() cell.accessoryType = .None cell.tintColor = UIColor.ht_sunflowerColor() } } else { if let oldcell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: QueryManager.sharedManager.getSelectedQuery(), inSection: 0)) { oldcell.accessoryType = .None oldcell.tintColor = UIColor.ht_sunflowerColor() } if let cell = tableView.cellForRowAtIndexPath(indexPath) { QueryManager.sharedManager.selectQuery(indexPath.row) cell.accessoryType = .Checkmark cell.tintColor = UIColor.ht_belizeHoleColor() } } } override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.contentView.backgroundColor = Theme.universityDarkTheme.backgroundColor header.textLabel?.textColor = UIColor.whiteColor() } }
apache-2.0
cc107f953f66939eb29046257c108633
40.896296
279
0.672737
5.443696
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Home/Bangumi/ViewModel/YSBangumiViewModel.swift
1
10732
// // YSBangumiViewModel.swift // // Created by zhn on 16/11/30. // Copyright © 2016年 zhn. All rights reserved. // import UIKit import SwiftyJSON import HandyJSON class YSBangumiViewModel { // MARK: - 私有属性 // 新番 fileprivate var previousModelArray = [YSHomeBangumiDetailModel]() // 连载 fileprivate var serializingModelArray = [YSHomeBangumiDetailModel]() // 推荐连载 fileprivate var bangumiRecommendArray = [YSHomeBangumiRecommendModel]() // MARK: - 外部属性 // banner的数组array var headBannerModelArray = [YSHomeBangumiADdetailModel]() // 第一个section底部的banner数组 var bodyBannerModelArray = [YSHomeBangumiADdetailModel]() // 图片string的数组 var headImageStringArray = [String]() var bodyImageStringArray = [String]() // 数据的数组 var statusArray = [Any]() // 判断新番的月份 var season: Int = 0 } //====================================================================== // MARK:- 请求数据 //====================================================================== extension YSBangumiViewModel { func requestDatas(finishCallBack:@escaping ()->(),failueCallBack:@escaping ()->()) { let netGroup = DispatchGroup() // 2. 获取新番和连载番剧的数据 netGroup.enter() YSNetworkTool.shared.requestData(.get, URLString: "http://bangumi.bilibili.com/api/app_index_page_v4?build=3970&device=phone&mobi_app=iphone&platform=ios", finished: { (result) in // 1. 转成json let resultJson = JSON(result) // 2. 转成模型 // <1. 头部的banner let headArrayString = YSJsonHelper.getjsonArrayString(key: "head", json: resultJson["result"]["ad"].dictionaryObject ?? "") if let bannerHeadArray = JSONDeserializer<YSHomeBangumiADdetailModel>.deserializeModelArrayFrom(json: headArrayString){ guard let bannerHeadArray = bannerHeadArray as? [YSHomeBangumiADdetailModel] else {return} self.headBannerModelArray = bannerHeadArray } // 2. top model array -> string array self.headImageStringArray.removeAll() for head in self.headBannerModelArray { guard let img = head.img else {return} self.headImageStringArray.append(img) } // <3. 第一组的底部的banner let bodyArrayString = YSJsonHelper.getjsonArrayString(key: "body", json: resultJson["result"]["ad"].dictionaryObject ?? "") if let bodyBannerArray = JSONDeserializer<YSHomeBangumiADdetailModel>.deserializeModelArrayFrom(json: bodyArrayString){ guard let bodyBannerArray = bodyBannerArray as? [YSHomeBangumiADdetailModel] else {return} self.bodyBannerModelArray = bodyBannerArray } // <4. bottom model array -> string array self.bodyImageStringArray.removeAll() for body in self.bodyBannerModelArray { guard let img = body.img else {return} self.bodyImageStringArray.append(img) } // <3. 新番 let previousArrayString = YSJsonHelper.getjsonArrayString(key: "list", json: resultJson["result"]["previous"].dictionaryObject ?? "") if let previousModelArray = JSONDeserializer<YSHomeBangumiDetailModel>.deserializeModelArrayFrom(json: previousArrayString ){ guard let previousModelArray = previousModelArray as? [YSHomeBangumiDetailModel] else {return} self.previousModelArray = previousModelArray } // <4. 连载番剧 let serializingArrayString = YSJsonHelper.getjsonArrayString(key: "serializing", json: resultJson["result"].dictionaryObject ?? "") if let serializingModelArray = JSONDeserializer<YSHomeBangumiDetailModel>.deserializeModelArrayFrom(json: serializingArrayString){ guard let serializingModelArray = serializingModelArray as? [YSHomeBangumiDetailModel] else {return} self.serializingModelArray = serializingModelArray } // <5. 拿到连载的新番的月份 self.season = resultJson["result"]["previous"]["season"].int! netGroup.leave() }) { (error) in // 错误的处理 netGroup.leave() } // 3. 获取番剧推荐的数据 netGroup.enter() YSNetworkTool.shared.requestData(.get, URLString: "http://bangumi.bilibili.com/api/bangumi_recommend?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3970&cursor=0&device=phone&mobi_app=iphone&pagesize=10&platform=ios&sign=a47247d303f51e1328a43c2d49c69051&ts=1479350934", finished: { (result) in // <1. 转成json let resultJson = JSON(result) // <2. 转modelarray let recommendArrayString = YSJsonHelper.getjsonArrayString(key: "result", json: resultJson.dictionaryObject ?? "") if let recommendArray = JSONDeserializer<YSHomeBangumiRecommendModel>.deserializeModelArrayFrom(json: recommendArrayString) { // <<1. 赋值 guard let recommendArray = recommendArray as? [YSHomeBangumiRecommendModel] else {return} self.bangumiRecommendArray = recommendArray // <<2. 计算行高 for model in recommendArray { model.caluateRowHeight() } } netGroup.leave() }) { (error) in failueCallBack() // 错误的处理 netGroup.leave() } // 3. 合并数据 netGroup.notify(queue: DispatchQueue.main) { // <1. 清空数据 if self.serializingModelArray.count > 0 && self.previousModelArray.count > 0 && self.bangumiRecommendArray.count > 0 { self.statusArray.removeAll() } // <2. 添加数据 self.statusArray.append(self.serializingModelArray) self.statusArray.append(self.previousModelArray) self.statusArray.append(self.bangumiRecommendArray) finishCallBack() } } } //====================================================================== // MARK:- datesource 方法 //====================================================================== extension YSBangumiViewModel { // 组 func sectionCount() -> Int { return statusArray.count } // 行 func rowCount(section: Int) -> Int { guard let array:[Any] = statusArray[section] as? Array else {return 0} return array.count } // cell func createCell(collectionView: UICollectionView , indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 0 || indexPath.section == 1 { // 1. 拿到cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kBangumiALLCellReuseKey, for: indexPath) as! YSBangumiNormalCell // 2. 赋值数据 if let sectionModelArray = statusArray[indexPath.section] as? [YSHomeBangumiDetailModel] { let rowModel = sectionModelArray[indexPath.row] cell.bangumiDetailModel = rowModel } return cell }else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kBangumiRecommendReusekey, for: indexPath) as! YSBangumiRecommendCell cell.recommendModel = bangumiRecommendArray[indexPath.row] return cell } } // head foot func createFootHeadView(kind:String,collectionView:UICollectionView,indexPath:IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { // head if indexPath.section == 0 { let head = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kBangumiBannerMenuReuseKey, for: indexPath) as! YSBangumiTopView // banner的数据可能不存在 if headImageStringArray.count > 0 { head.isNoBanner = false head.imgStringArray = headImageStringArray head.bannerModelArray = headBannerModelArray }else{ head.isNoBanner = true } return head }else { let head = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kBangumiNormalHeadReuseKey, for: indexPath) as! YSBangumiNormalHeaderView head.section = indexPath.section if indexPath.section == 1 { head.season = season } return head } }else{ // foot let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kBangumiBannerFootReuseKey, for: indexPath) as! YSBangumiTopFooterView footer.carouselView.intnetImageArray = bodyImageStringArray footer.modelArray = bodyBannerModelArray return footer } } } //====================================================================== // MARK:- layout delegate 方法 //====================================================================== extension YSBangumiViewModel { func caluateItemSize(indexPath:IndexPath) -> CGSize { if indexPath.section == 2 {// 1. 推荐番剧 let model = bangumiRecommendArray[indexPath.row] return CGSize(width: kScreenWidth - 2 * kPadding, height: CGFloat(model.rowHight)) }else {// 2. 普通 return CGSize(width: (kScreenWidth - 4 * kPadding)/3, height: 200) } } func caluateHeadSize(section:Int) -> CGSize { if section == 0 { if headImageStringArray.count > 0 { return CGSize(width: kScreenWidth, height: 275) }else { return CGSize(width: kScreenWidth, height: 275 - kCarouseHeight) } }else { return CGSize(width: kScreenWidth, height: 40) } } func caluateFootSize(section:Int) -> CGSize { if section == 0 { if bodyImageStringArray.count > 0 { return CGSize(width: kScreenWidth, height: 90) } return CGSize(width: 0, height: 0) }else { return CGSize(width: 0, height: 0) } } }
mit
fe1e0a9cc9b14b065b86b9b4c4d2e623
40.652
301
0.584078
4.891029
false
false
false
false
olkakusiak/SearchInGitHub
SearchInGitHub/RepoDetailsViewController.swift
1
2845
// // RepoDetailsViewController.swift // SearchInGitHub // // Created by Aleksandra Kusiak on 27.11.2016. // Copyright © 2016 ola. All rights reserved. // import UIKit class RepoDetailsViewController: UIViewController { @IBOutlet weak var userAvatar: UIImageView! @IBOutlet weak var userDetailsContainer: UIView! @IBOutlet weak var fullNameLabel: UILabel! @IBOutlet weak var languageLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var numberOfStarsLabel: UILabel! @IBOutlet weak var numberOfForksLabel: UILabel! @IBOutlet weak var numberOfIssuesLabel: UILabel! @IBOutlet weak var numberOfWatchersLabel: UILabel! @IBOutlet weak var starsLabel: UILabel! @IBOutlet weak var forksLabel: UILabel! @IBOutlet weak var issuesLabel: UILabel! @IBOutlet weak var watchersLabel: UILabel! var singleRepo: SingleRepoData? var userLogin: String? var repoName: String? override func viewDidLoad() { super.viewDidLoad() setupView() DataManager.instance.getSingleRepo(userLogin: userLogin!, repoName: repoName!, repoDownloaded: {repo in self.singleRepo = repo self.reloadLabels() }, error: {error in print("error with getting single repo") }) } func setupView(){ userDetailsContainer.backgroundColor = UIColor.forkMidnightBlue userAvatar.layer.cornerRadius = 10.0 userAvatar.clipsToBounds = true userAvatar.layer.borderWidth = 1 userAvatar.layer.borderColor = UIColor.cloudsGrey.cgColor fullNameLabel.textColor = UIColor.cloudsGrey languageLabel.textColor = UIColor.cloudsGrey descriptionLabel.textColor = UIColor.cloudsGrey starsLabel.textColor = UIColor.forkMidnightBlue numberOfStarsLabel.textColor = UIColor.forkMidnightBlue forksLabel.textColor = UIColor.forkMidnightBlue numberOfForksLabel.textColor = UIColor.forkMidnightBlue issuesLabel.textColor = UIColor.forkMidnightBlue numberOfIssuesLabel.textColor = UIColor.forkMidnightBlue watchersLabel.textColor = UIColor.forkMidnightBlue numberOfWatchersLabel.textColor = UIColor.forkMidnightBlue userAvatar.image = #imageLiteral(resourceName: "placeholder") fullNameLabel.text = "" languageLabel.text = "" descriptionLabel.text = "" numberOfStarsLabel.text = "" numberOfForksLabel.text = "" numberOfIssuesLabel.text = "" numberOfWatchersLabel.text = "" } func reloadLabels(){ if let repo = singleRepo{ userAvatar.sd_setImage(with: URL(string: repo.avatarURL), placeholderImage: #imageLiteral(resourceName: "placeholder")) fullNameLabel.text = repo.fullName languageLabel.text = "language: \(repo.language)" descriptionLabel.text = repo.description numberOfStarsLabel.text = "\(repo.stars)" numberOfForksLabel.text = "\(repo.forks)" numberOfIssuesLabel.text = "\(repo.issues)" numberOfWatchersLabel.text = "\(repo.watchers)" } } }
mit
efba17af85b47613feae443048d07ceb
31.689655
122
0.768284
3.944521
false
false
false
false
xiaominfc/iosLayoutXML
TestXMLView/widget.swift
1
14010
// // widget.swift // TestXMLView // // Created by xiaominfc on 12/9/15. // Copyright © 2015 fc. All rights reserved. // import UIKit import libxml2 protocol ViewLayoutAttriModeDelegate { func buildViewLayoutAttriMode(xmlNode:XMLNode)->ViewLayoutAttriMode func setUpViewLayoutAttriMode(mode:ViewLayoutAttriMode) func layoutSelf() } class ViewLayoutAttriMode { //layout size @nonobjc static let widthKey = "width" @nonobjc static let heightKey = "height" //layout by position @nonobjc static let xKey = "x" @nonobjc static let yKey = "y" //layout by superview @nonobjc static let relativeKey = "relative" @nonobjc static let marginTopKey = "marginTop" @nonobjc static let marginLeftKey = "marginLeft" @nonobjc static let marginRightKey = "marginRight" @nonobjc static let marginBottomKey = "marginBottom" //layout by other view @nonobjc static let toLeftOfKey = "toLeftOf" @nonobjc static let toRightOfKey = "toRightOf" @nonobjc static let belowKey = "below" @nonobjc static let aboveKey = "above" var attriDic:NSMutableDictionary? convenience init(xmlNode:XMLNode) { self.init() attriDic = NSMutableDictionary() self.initLayoutAttri(xmlNode) } func initLayoutAttri(xmlNode:XMLNode) { setAttriForKey(ViewLayoutAttriMode.xKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.yKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.widthKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.heightKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.relativeKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.marginRightKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.marginLeftKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.marginTopKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.marginBottomKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.toLeftOfKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.toRightOfKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.belowKey, xmlNode: xmlNode) setAttriForKey(ViewLayoutAttriMode.aboveKey, xmlNode: xmlNode) } func setAttriForKey(key:String,xmlNode:XMLNode) { if let value = xmlNode.getStringAttriValue(key) { attriDic?.setObject(value, forKey: key) } } func layoutView(view:UIView,point_x:CGFloat,point_y:CGFloat,width:CGFloat,height:CGFloat) { view.sizeToFit() var frame:CGRect = view.frame var w:CGFloat = ResourceUtil.convertToFloatValue((attriDic?.objectForKey(ViewLayoutAttriMode.widthKey) as! String), maxValue: width) if w < 0 { w = frame.size.width } var h:CGFloat = ResourceUtil.convertToFloatValue((attriDic?.objectForKey(ViewLayoutAttriMode.heightKey) as! String), maxValue: height) if h < 0 { h = frame.size.height } var x:CGFloat = 0 var y:CGFloat = 0 if let xValue = attriDic?.objectForKey(ViewLayoutAttriMode.xKey) { x = ResourceUtil.convertToFloatValue((xValue as! String), maxValue: width) } if let yValue = attriDic?.objectForKey(ViewLayoutAttriMode.yKey) { y = ResourceUtil.convertToFloatValue((yValue as! String), maxValue: height) } // frame.size = CGSizeMake(w, h) var needX:Bool = true var needY:Bool = true if let _ = attriDic?.objectForKey(ViewLayoutAttriMode.toLeftOfKey) { x = (width - w) - configureMargin(ViewLayoutAttriMode.marginRightKey) needX = false } if let _ = attriDic?.objectForKey(ViewLayoutAttriMode.toRightOfKey) { x = configureMargin(ViewLayoutAttriMode.marginLeftKey) } if let _ = attriDic?.objectForKey(ViewLayoutAttriMode.aboveKey) { y = (height - h) - configureMargin(ViewLayoutAttriMode.marginBottomKey) needY = false } if let _ = attriDic?.objectForKey(ViewLayoutAttriMode.belowKey) { y = configureMargin(ViewLayoutAttriMode.marginTopKey) } if let value = attriDic?.objectForKey(ViewLayoutAttriMode.relativeKey) { switch (value as! String) { case "centerX": x = (width - w) / 2 break case "topcenterX": x = (width - w) / 2 if y == 0 { y = configureMargin(ViewLayoutAttriMode.marginTopKey) } break case "bottomcenterX": x = (width - w) / 2 y = (height - h) - configureMargin(ViewLayoutAttriMode.marginBottomKey) break case "leftcenterY": x = configureMargin(ViewLayoutAttriMode.marginLeftKey) y = (height - h) / 2 break case "rightcenterY": x = (width - w) - configureMargin(ViewLayoutAttriMode.marginRightKey) y = (height - h) / 2 break case "centerY": y = (height - h) / 2 if x == 0 { x = configureMargin(ViewLayoutAttriMode.marginLeftKey) } break case "center": y = (height - h) / 2 x = (width - w) / 2 break case "bottomleft": y = (height - h) - configureMargin(ViewLayoutAttriMode.marginBottomKey) x = configureMargin(ViewLayoutAttriMode.marginLeftKey) break case "bottomright": y = (height - h) - configureMargin(ViewLayoutAttriMode.marginBottomKey) x = (width - w) - configureMargin(ViewLayoutAttriMode.marginRightKey) break case "topright": y = (height - h) + configureMargin(ViewLayoutAttriMode.marginTopKey) x = (height - w) - configureMargin(ViewLayoutAttriMode.marginRightKey) break default: x = 0 + configureMargin(ViewLayoutAttriMode.marginLeftKey) y = 0 + configureMargin(ViewLayoutAttriMode.marginTopKey) break } }else { //if x == 0 { if needX && x==0{ x = configureMargin(ViewLayoutAttriMode.marginLeftKey) } //} if needY && y==0{ y = configureMargin(ViewLayoutAttriMode.marginTopKey) } } frame.origin.x = x + point_x frame.origin.y = y + point_y if (frame.origin.x + w) > (point_x + width) { w = (point_x + width) - frame.origin.x } if (frame.origin.y + h) > (point_y + height) { h = (point_y + height) - frame.origin.y } if (frame.origin.x < 0) { w = w + frame.origin.x frame.origin.x = 0 } if (frame.origin.y < 0) { h = h + frame.origin.y frame.origin.y = 0 } // frame.size = CGSizeMake(w, h) view.frame = frame } func bindAttriForView(view:UIView) { var point_x:CGFloat = 0 var point_y:CGFloat = 0 var width:CGFloat = view.getParentWidth() var height:CGFloat = view.getParentHeight() if let value = attriDic?.objectForKey(ViewLayoutAttriMode.toLeftOfKey) { let tag = ResourceUtil.convertToIntValue((value as! String)) if let otherView = view.superview?.viewWithTag(tag) { // if let viewLayoutAttriModeDelegate = (subView as? ViewLayoutAttriModeDelegate) { // viewLayoutAttriModeDelegate.layoutSelf() // } width = otherView.frame.origin.x } } if let value = attriDic?.objectForKey(ViewLayoutAttriMode.toRightOfKey) { let tag = ResourceUtil.convertToIntValue((value as! String)) if let otherView = view.superview?.viewWithTag(tag) { // if let viewLayoutAttriModeDelegate = (subView as? ViewLayoutAttriModeDelegate) { // viewLayoutAttriModeDelegate.layoutSelf() // } point_x = otherView.frame.origin.x + otherView.frame.size.width width = width - point_x } } if let value = attriDic?.objectForKey(ViewLayoutAttriMode.aboveKey) { let tag = ResourceUtil.convertToIntValue((value as! String)) if let otherView = view.superview?.viewWithTag(tag) { // if let viewLayoutAttriModeDelegate = (subView as? ViewLayoutAttriModeDelegate) { // viewLayoutAttriModeDelegate.layoutSelf() // } height = otherView.frame.origin.y } } if let value = attriDic?.objectForKey(ViewLayoutAttriMode.belowKey) { let tag = ResourceUtil.convertToIntValue((value as! String)) if let otherView = view.superview?.viewWithTag(tag) { // if let viewLayoutAttriModeDelegate = (subView as? ViewLayoutAttriModeDelegate) { // viewLayoutAttriModeDelegate.layoutSelf() // } point_y = otherView.frame.origin.y + otherView.frame.size.height height = height - point_y } } self.layoutView(view, point_x: point_x, point_y: point_y, width: width, height: height) } func configureMargin(marginKey:String) -> CGFloat{ var result:CGFloat = 0; if let value = attriDic?.objectForKey(marginKey) { result = ResourceUtil.convertToFloatValue((value as! String), maxValue: 0) } return result } } class FCView: UIView,ViewLayoutAttriModeDelegate{ var viewLayoutAttriMode:ViewLayoutAttriMode? func buildViewLayoutAttriMode(xmlNode: XMLNode) -> ViewLayoutAttriMode { //bind other attri return ViewLayoutAttriMode(xmlNode: xmlNode) } func setUpViewLayoutAttriMode(mode: ViewLayoutAttriMode) { self.viewLayoutAttriMode = mode } override func layoutSubviews() { super.layoutSubviews() layoutSelf() } func layoutSelf() { self.viewLayoutAttriMode?.bindAttriForView(self) self.subviews.forEach { subview in if let viewLayoutAttriModeDelegate = (subview as? ViewLayoutAttriModeDelegate) { viewLayoutAttriModeDelegate.layoutSelf() } } } } class FCImageView: UIImageView,ViewLayoutAttriModeDelegate{ var viewLayoutAttriMode:ViewLayoutAttriMode? func buildViewLayoutAttriMode(xmlNode: XMLNode) -> ViewLayoutAttriMode { return ViewLayoutAttriMode(xmlNode: xmlNode) } func setUpViewLayoutAttriMode(mode: ViewLayoutAttriMode) { self.viewLayoutAttriMode = mode } func layoutSelf() { self.viewLayoutAttriMode?.bindAttriForView(self) } } class FCButton: UIButton,ViewLayoutAttriModeDelegate{ var viewLayoutAttriMode:ViewLayoutAttriMode? func buildViewLayoutAttriMode(xmlNode: XMLNode) -> ViewLayoutAttriMode { return ViewLayoutAttriMode(xmlNode: xmlNode) } func setUpViewLayoutAttriMode(mode: ViewLayoutAttriMode) { self.viewLayoutAttriMode = mode } func layoutSelf() { self.viewLayoutAttriMode?.bindAttriForView(self) } } class FCLabel: UILabel,ViewLayoutAttriModeDelegate{ var viewLayoutAttriMode:ViewLayoutAttriMode? func buildViewLayoutAttriMode(xmlNode: XMLNode) -> ViewLayoutAttriMode { return ViewLayoutAttriMode(xmlNode: xmlNode) } func setUpViewLayoutAttriMode(mode: ViewLayoutAttriMode) { self.viewLayoutAttriMode = mode } func layoutSelf() { self.viewLayoutAttriMode?.bindAttriForView(self) } } class FCTableViewCell:UITableViewCell ,ViewLayoutAttriModeDelegate{ var viewLayoutAttriMode:ViewLayoutAttriMode? convenience init(style: UITableViewCellStyle, reuseIdentifier: String?,xmlName:String?) { self.init(style: style, reuseIdentifier: reuseIdentifier) if let path = NSBundle.mainBundle().pathForResource(xmlName,ofType:"xml") { xmlKeepBlanksDefault(0); let doc = xmlReadFile(path, "UTF-8", Int32(XML_PARSE_RECOVER.rawValue)) let root = xmlDocGetRootElement(doc) let viewName = String.fromCString(UnsafeMutablePointer(root.memory.name)) if "FCTableViewCell" == viewName { self.initContentBy(XMLNode(nodePtr:root)) }else { xmlFreeDoc(doc); self.addSubview(LayoutInflater.inflater(xmlName)!) return } xmlFreeDoc(doc); } } func buildViewLayoutAttriMode(xmlNode: XMLNode) -> ViewLayoutAttriMode { return ViewLayoutAttriMode(xmlNode: xmlNode) } func setUpViewLayoutAttriMode(mode: ViewLayoutAttriMode) { self.viewLayoutAttriMode = mode } override func layoutSubviews() { super.layoutSubviews() layoutSelf() } func layoutSelf() { self.subviews.forEach { subview in if let viewLayoutAttriModeDelegate = (subview as? ViewLayoutAttriModeDelegate) { viewLayoutAttriModeDelegate.layoutSelf() } } } }
apache-2.0
f478ef64153d5deb8e5c92a3169043ec
32.594724
142
0.595117
4.470006
false
false
false
false
yusuga/RemoteNotificationHandling
Example/RemoteNotificationHandling/RemoteNotificationManager.swift
1
1493
// // RemoteNotificationManager.swift // RemoteNotificationHandling // // Created by Yu Sugawara on 7/18/17. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation import RemoteNotificationHandling import UserNotifications struct RemoteNotificationManager { static let shared = RemoteNotificationManager() private init() { if #available(iOS 10.0, *) { let handler = iOS10RemoteNotificationHandler() // Use the delegate object to respond to selected actions or to hide notifications while your app is in the foreground. To guarantee that your app is able to respond to actionable notifications, you must set the value of this property before your app finishes launching. For example, this means assigning a delegate object to this property in an iOS app’s application(_:willFinishLaunchingWithOptions:) or application(_:didFinishLaunchingWithOptions:) method. // https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649522-delegate UNUserNotificationCenter.current().delegate = handler iOS10Handler = handler } else { iOS9AndBelowHandler = iOS9AndBelowRemoteNotificationHandler() } } let deviceTokenHandler = DeviceTokenHandler() private(set) var iOS10Handler: iOS10RemoteNotificationHandler? private(set) var iOS9AndBelowHandler: iOS9AndBelowRemoteNotificationHandler? }
mit
551b110e2a613844c737807405c33a83
45.5625
482
0.72953
5.265018
false
false
false
false
Caiflower/SwiftWeiBo
花菜微博/花菜微博/Classes/View(视图和控制器)/Main/NewFeature(新特性)/CFWelcomeView.swift
1
2943
// // CFWelcomeView.swift // 花菜微博 // // Created by 花菜ChrisCai on 2016/12/19. // Copyright © 2016年 花菜ChrisCai. All rights reserved. // import UIKit import SnapKit import SDWebImage class CFWelcomeView: UIView { fileprivate lazy var iconView = UIImageView(image: UIImage(named: "avatar_default_big")) fileprivate lazy var label: UILabel = UILabel(text: "欢迎回来", fontSize: 16) override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.red setupOwerViews() setupLayoutConstraint() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI界面相关 extension CFWelcomeView { /// 添加子控件 fileprivate func setupOwerViews() { // 背景图片 let backImageView = UIImageView(image: UIImage(named: "ad_background")) backImageView.frame = UIScreen.main.bounds addSubview(backImageView) // 头像 addSubview(iconView) // 文字 addSubview(label) label.alpha = 0 // 设置图片 guard let urlString = CFNetworker.shared.userAccount.avatar_large, let url = URL(string: urlString) else { return } iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big")) // 设置圆角半径 iconView.cornerRadius = 85 * 0.5 } } /// 添加约束 extension CFWelcomeView { fileprivate func setupLayoutConstraint() { iconView.snp.makeConstraints { (make) in make.bottom.equalToSuperview().offset(-200) make.centerX.equalToSuperview() make.width.height.equalTo(85) } label.snp.makeConstraints { (make) in make.top.equalTo(iconView.snp.bottom).offset(10) make.centerX.equalToSuperview() } } } // MARK: - 动画相关 extension CFWelcomeView { // 视图添加到window上,标识视图已经显示 override func didMoveToWindow() { super.didMoveToWindow() // 强制更新约束 self.layoutIfNeeded() // 更新头像的底部约束 iconView.snp.updateConstraints { (make) in make.bottom.equalToSuperview().offset(-(UIScreen.main.bounds.height - 200)) } // 执行动画 UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .curveEaseIn, animations: { // 更新约束 self.layoutIfNeeded() }) { (_) in // 透明度动画 UIView.animate(withDuration: 1, animations: { self.label.alpha = 1 }, completion: { (_) in // 动画完成后移除欢迎页 self.removeFromSuperview() }) } } }
apache-2.0
d56339ff5a10743d431e2d2beef0175c
26.69697
141
0.588621
4.3872
false
false
false
false
nodekit-io/nodekit-darwin
test/NKT_TestRunner.swift
1
1947
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation @testable import NodeKit class NKT_TestRunner: NSObject, NKScriptExport { static var current: NKT_TestRunner = NKT_TestRunner() class func attachTo(context: NKScriptContext) { context.loadPlugin(NKT_TestRunner.current, namespace: "io.nodekit.test.runner", options: [String:AnyObject]()) } func rewriteGeneratedStub(stub: String, forKey: String) -> String { switch (forKey) { case ".global": let url = NSBundle(forClass: NKT_TestRunner.self).pathForResource("testrunner", ofType: "js", inDirectory: "lib-test") let appjs = try? NSString(contentsOfFile: url!, encoding: NSUTF8StringEncoding) as String return "function loadplugin(){\n" + appjs! + "\n}\n" + stub + "\n" + "loadplugin();" + "\n" default: return stub } } override init() { done = nil; } private var done: ((Bool) -> Void)? func ready() -> Void { NKEventEmitter.global.emit("nkt.Ready", 0); } func _start(callback: (Bool) -> Void) -> Void { self.done = callback self.NKscriptObject!.invokeMethod("emit", withArguments: ["nk.TestStart", 0], completionHandler: nil) } func complete(passed: Bool) { done?(passed) } }
apache-2.0
c09e59e41d47f53df51080313f474fb6
31.466667
130
0.647149
4.031056
false
true
false
false
matthewpalmer/Locksmith
Examples/Locksmith iOS Example/Locksmith Extension/InterfaceController.swift
1
1860
// // InterfaceController.swift // LocksmithExample WatchKit Extension // // Created by Tai Heng on 05/09/2015. // Copyright © 2015 matthewpalmer. All rights reserved. // import WatchKit import Foundation import Locksmith import WatchConnectivity class InterfaceController: WKInterfaceController, WCSessionDelegate { override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() if (WCSession.isSupported()) { let session = WCSession.default() session.delegate = self session.activate() } struct TwitterAccount: ReadableSecureStorable, CreateableSecureStorable, DeleteableSecureStorable, GenericPasswordSecureStorable { let username: String let password: String let service = "Twitter" var account: String { return username } var data: [String: Any] { return ["password": password] } } let account = TwitterAccount(username: "_matthewpalmer", password: "my_password") // CreateableSecureStorable lets us create the account in the keychain try! account.createInSecureStore() // ReadableSecureStorable lets us read the account from the keychain let result = account.readFromSecureStore() print("Watch app: \(result), \(result?.data)") // DeleteableSecureStorable lets us delete the account from the keychain try! account.deleteFromSecureStore() } @available(watchOSApplicationExtension 2.2, *) func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } }
mit
31c2b538924a78efb46bf619749dd963
32.8
138
0.637439
5.388406
false
false
false
false
ppraveentr/MobileCore
Sources/CoreComponents/Contollers/UIViewController+Extension.swift
1
4649
// // UIViewController+Extension.swift // MobileCore-CoreComponents // // Created by Praveen Prabhakar on 21/10/18. // Copyright © 2018 Praveen Prabhakar. All rights reserved. // import Foundation import UIKit // MARK: Protocol implementation extension UIViewController { var isBaseViewAdded: Bool { // If baseView is not added, then retun false return (self.baseView?.superview != self.view && self.view != self.baseView) } // MARK: Utility public var mainView: UIView? { // If baseView is not added, then retun nil if isBaseViewAdded { return nil } return self.baseView?.mainPinnedView } // MARK: Navigation Bar // default - left Button Actopm public var kleftButtonAction: Selector { #selector(UIViewController.leftButtonAction) } public var kRightButtonAction: Selector { #selector(UIViewController.rightButtonAction) } func configureBarButton(button: UIBarButtonItem?, defaultAction action: Selector) { guard let button = button else { return } if button.action == nil { button.action = action } if button.target == nil { button.target = self } } // MARK: Dissmiss Self model func self_dismissSelf(_ animated: Bool = true) { if navigationController != nil, navigationController?.viewControllers.first != self { navigationController?.popViewController(animated: animated) } else if let presentedViewController = self.presentedViewController { presentedViewController.dismiss(animated: animated, completion: nil) } else { self.dismiss(animated: animated, completion: nil) } } } extension UIViewController { // MARK: Keyboard func setupKeyboardTapRecognizer() { // To Dismiss keyboard if shouldDissmissKeyboardOnTap() { let touchAction = UITapGestureRecognizer(target: self, action: #selector(UIViewController.endEditing)) touchAction.cancelsTouchesInView = false self.view.addGestureRecognizer(touchAction) } } @objc public func endEditing() { self.view.endEditing(true) } // MARK: Keyboard Notifications // Registering for keyboard notification. public func registerKeyboardNotifications() { // Registering for keyboard notification. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: self) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide(_:)), name: UIResponder.keyboardDidHideNotification, object: self) } public func unregisterKeyboardNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardDidHideNotification, object: nil) } /* UIKeyboardWillShow. */ @objc func keyboardWillShow(_ notification: Notification?) { // Optional Protocol implementation: intentionally empty } /* UIKeyboardDidHide. */ @objc func keyboardDidHide(_ notification: Notification?) { // Optional Protocol implementation: intentionally empty } } extension UIViewController { // MARK: AlertViewController public var defaultAlertAction: UIAlertAction { UIAlertAction(title: "Ok", style: .default, handler: nil) } public func showAlert( title: String? = nil, message: String? = nil, action: UIAlertAction? = nil, actions: [UIAlertAction]? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) // Add actions to alertView if let action = action { alert.addAction(action) } actions?.forEach { action in alert.addAction(action) } // if no actions avaialble, show default Action. if alert.actions.isEmpty { alert.addAction(defaultAlertAction) } // present alertView present(alert, animated: true, completion: nil) } // MARK: Activity indicator public func showActivityIndicator() { LoadingIndicator.show() } public func hideActivityIndicator(_ completionBlock: LoadingIndicator.CompletionBlock? = nil) { DispatchQueue.main.async { LoadingIndicator.hide(completionBlock) } } }
mit
c8c134245100dfcc5c1120c11dd8464f
32.2
157
0.654905
5.281818
false
false
false
false
not4mj/think
Think Golf/Libs/3rd Party/UPCarouselFlowLayout/UPCarouselFlowLayout.swift
2
6259
// // UPCarouselFlowLayout.swift // UPCarouselFlowLayoutDemo // // Created by Paul Ulric on 23/06/2016. // Copyright © 2016 Paul Ulric. All rights reserved. // import UIKit public enum UPCarouselFlowLayoutSpacingMode { case fixed(spacing: CGFloat) case overlap(visibleOffset: CGFloat) } open class UPCarouselFlowLayout: UICollectionViewFlowLayout { fileprivate struct LayoutState { var size: CGSize var direction: UICollectionViewScrollDirection func isEqual(_ otherState: LayoutState) -> Bool { return self.size.equalTo(otherState.size) && self.direction == otherState.direction } } @IBInspectable open var sideItemScale: CGFloat = 0.6 @IBInspectable open var sideItemAlpha: CGFloat = 0.6 @IBInspectable open var sideItemShift: CGFloat = 0.0 open var spacingMode = UPCarouselFlowLayoutSpacingMode.fixed(spacing: 40) fileprivate var state = LayoutState(size: CGSize.zero, direction: .horizontal) override open func prepare() { super.prepare() let currentState = LayoutState(size: self.collectionView!.bounds.size, direction: self.scrollDirection) if !self.state.isEqual(currentState) { self.setupCollectionView() self.updateLayout() self.state = currentState } } fileprivate func setupCollectionView() { guard let collectionView = self.collectionView else { return } if collectionView.decelerationRate != UIScrollViewDecelerationRateFast { collectionView.decelerationRate = UIScrollViewDecelerationRateFast } } fileprivate func updateLayout() { guard let collectionView = self.collectionView else { return } let collectionSize = collectionView.bounds.size let isHorizontal = (self.scrollDirection == .horizontal) let yInset = (collectionSize.height - self.itemSize.height) / 2 let xInset = (collectionSize.width - self.itemSize.width) / 2 self.sectionInset = UIEdgeInsetsMake(yInset, xInset, yInset, xInset) let side = isHorizontal ? self.itemSize.width : self.itemSize.height let scaledItemOffset = (side - side*self.sideItemScale) / 2 switch self.spacingMode { case .fixed(let spacing): self.minimumLineSpacing = spacing - scaledItemOffset case .overlap(let visibleOffset): let fullSizeSideItemOverlap = visibleOffset + scaledItemOffset let inset = isHorizontal ? xInset : yInset self.minimumLineSpacing = inset - fullSizeSideItemOverlap } } override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let superAttributes = super.layoutAttributesForElements(in: rect), let attributes = NSArray(array: superAttributes, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil } return attributes.map({ self.transformLayoutAttributes($0) }) } fileprivate func transformLayoutAttributes(_ attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { guard let collectionView = self.collectionView else { return attributes } let isHorizontal = (self.scrollDirection == .horizontal) let collectionCenter = isHorizontal ? collectionView.frame.size.width/2 : collectionView.frame.size.height/2 let offset = isHorizontal ? collectionView.contentOffset.x : collectionView.contentOffset.y let normalizedCenter = (isHorizontal ? attributes.center.x : attributes.center.y) - offset let maxDistance = (isHorizontal ? self.itemSize.width : self.itemSize.height) + self.minimumLineSpacing let distance = min(abs(collectionCenter - normalizedCenter), maxDistance) let ratio = (maxDistance - distance)/maxDistance let alpha = ratio * (1 - self.sideItemAlpha) + self.sideItemAlpha let scale = ratio * (1 - self.sideItemScale) + self.sideItemScale let shift = (1 - ratio) * self.sideItemShift attributes.alpha = alpha attributes.transform3D = CATransform3DScale(CATransform3DIdentity, scale, scale, 1) attributes.zIndex = Int(alpha * 10) if isHorizontal { attributes.center.y = attributes.center.y + shift } else { attributes.center.x = attributes.center.x + shift } return attributes } override open func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = collectionView , !collectionView.isPagingEnabled, let layoutAttributes = self.layoutAttributesForElements(in: collectionView.bounds) else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset) } let isHorizontal = (self.scrollDirection == .horizontal) let midSide = (isHorizontal ? collectionView.bounds.size.width : collectionView.bounds.size.height) / 2 let proposedContentOffsetCenterOrigin = (isHorizontal ? proposedContentOffset.x : proposedContentOffset.y) + midSide var targetContentOffset: CGPoint if isHorizontal { let closest = layoutAttributes.sorted { abs($0.center.x - proposedContentOffsetCenterOrigin) < abs($1.center.x - proposedContentOffsetCenterOrigin) }.first ?? UICollectionViewLayoutAttributes() targetContentOffset = CGPoint(x: floor(closest.center.x - midSide), y: proposedContentOffset.y) } else { let closest = layoutAttributes.sorted { abs($0.center.y - proposedContentOffsetCenterOrigin) < abs($1.center.y - proposedContentOffsetCenterOrigin) }.first ?? UICollectionViewLayoutAttributes() targetContentOffset = CGPoint(x: proposedContentOffset.x, y: floor(closest.center.y - midSide)) } return targetContentOffset } }
apache-2.0
4257a9df06ebc1c150d42f8c9a434dcd
44.021583
205
0.683605
5.298899
false
false
false
false
safx/iOS9-InterApp-DnD-Demo
SampleX/ViewController.swift
1
6505
// // ViewController.swift // SampleX // // Created by Safx Developer on 2015/09/27. // // import UIKit class ViewController: UIViewController { @IBOutlet weak var bundleLabel: UILabel! { didSet { bundleLabel.text = myID.componentsSeparatedByString(".").last } } @IBOutlet weak var otherLabel: UILabel! private var previousData: String = "" private var queue: dispatch_queue_t! private var timer: dispatch_source_t! private var model: [Shape] = [] private var draggingModelIndex: Int = -1 private var dragOffset: CGPoint! = CGPointZero private var modelOfOtherProcess: Shape? private lazy var myPasteboard: UIPasteboard = { return UIPasteboard(name: self.myID, create: true)! }() private var myID: String = NSBundle.mainBundle().bundleIdentifier! private lazy var otherID: String = { return self.myID == "com.blogspot.safx-dev.SampleX" ? "com.blogspot.safx-dev.SampleY" : "com.blogspot.safx-dev.SampleX" }() deinit { UIPasteboard.removePasteboardWithName(myID) } override func viewDidLoad() { super.viewDidLoad() (view as! ShapeView).delegate = self if myID == "com.blogspot.safx-dev.SampleX" { model.append(.Rectangle(pos: CGPointMake(80, 280), size: CGSizeMake(80, 80), color: UIColor.blueColor())) model.append(.Ellipse(pos: CGPointMake(20, 220), size: CGSizeMake(50, 50), color: UIColor.redColor())) } else { model.append(.Rectangle(pos: CGPointMake(80, 320), size: CGSizeMake(50, 50), color: UIColor.greenColor())) model.append(.Ellipse(pos: CGPointMake(20, 220), size: CGSizeMake(80, 80), color: UIColor.cyanColor())) } queue = myID.withCString { dispatch_queue_create($0, nil) } timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue) dispatch_source_set_timer(timer, dispatch_time_t(DISPATCH_TIME_NOW), USEC_PER_SEC * 50, 0) dispatch_source_set_event_handler(timer) { () -> Void in self.updateModelOfOtherProcess() } dispatch_resume(timer) } private func updateModelOfOtherProcess() { assert(NSThread.mainThread() != NSThread.currentThread()) if let otherpb = UIPasteboard(name: otherID, create: false), s = otherpb.string where s != previousData { previousData = s let ss = s.componentsSeparatedByString(",") switch (ss[0], ss.count) { case ("B", 7): // touchBegan let size = ss[2...3].flatMap{Int($0)}.flatMap{CGFloat($0)} let offset = ss[5...6].flatMap{Int($0)}.flatMap{CGFloat($0)} if let shape = Shape.createShape(ss[1], size: CGSizeMake(size[0], size[1]), color: ss[4]) { modelOfOtherProcess = shape dragOffset = CGPointMake(offset[0], offset[1]) } case ("M", 3): // touchMoved if modelOfOtherProcess == nil { return } let ns = ss[1...2].flatMap{Int($0)}.flatMap{CGFloat($0)} let x = ns[0] let p = CGPointMake(x >= 0 ? x : view.frame.size.width + x, ns[1]) modelOfOtherProcess!.changePosition(CGPointMake(dragOffset.x + p.x, dragOffset.y + p.y)) case ("O", 1): // touchMoved but model is still contained in other view if modelOfOtherProcess == nil { return } let p = CGPointMake(-10000, -10000) // FIXME modelOfOtherProcess!.changePosition(p) case ("E", 1): // touchEnded if modelOfOtherProcess == nil { return } model.append(modelOfOtherProcess!) modelOfOtherProcess = nil case ("C", 1): fallthrough // touchCancelled default: modelOfOtherProcess = nil } dispatch_async(dispatch_get_main_queue()) { () -> Void in self.otherLabel.text = s self.view.setNeedsDisplay() } } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) let p = touches.first!.locationInView(view) for (idx, e) in model.enumerate() { if e.isClicked(p) { draggingModelIndex = idx let m = model[draggingModelIndex] dragOffset = CGPointMake(m.position.x - p.x, m.position.y - p.y) myPasteboard.string = "B,\(m.string),\(Int(dragOffset.x)),\(Int(dragOffset.y))" return } } draggingModelIndex = -1 } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) if 0 > draggingModelIndex || draggingModelIndex >= model.count { return } let p = touches.first!.locationInView(view) model[draggingModelIndex].changePosition(CGPointMake(dragOffset.x + p.x, dragOffset.y + p.y)) let f = view.frame if p.x < f.minX { myPasteboard.string = "M,\(Int(p.x-0.5)),\(Int(p.y))" } else if f.maxX <= p.x { myPasteboard.string = "M,\(Int(p.x-f.maxX)),\(Int(p.y))" } else { myPasteboard.string = "O" } view.setNeedsDisplay() } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) myPasteboard.string = "C" draggingModelIndex = -1 } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) if 0 > draggingModelIndex || draggingModelIndex >= model.count { return } let p = touches.first!.locationInView(view) model[draggingModelIndex].changePosition(CGPointMake(dragOffset.x + p.x, dragOffset.y + p.y)) if view.frame.contains(p) { myPasteboard.string = "C" } else { myPasteboard.string = "E" model.removeAtIndex(draggingModelIndex) } view.setNeedsDisplay() draggingModelIndex = -1 } override func viewDidLayoutSubviews() { view.setNeedsDisplay() } } extension ViewController: ShapeViewDelegate { func draw(rect: CGRect) { model.forEach { $0.draw() } modelOfOtherProcess?.draw() } }
mit
7cf5ac8d9a71adb22d8f8d1abbd67314
35.751412
127
0.591852
4.177906
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Content Router/Routes/Settings/SettingsRoute.swift
1
1029
import ComponentBase import RouterCore import UIKit public struct SettingsRoute { private let modalWireframe: any ModalWireframe private let settingsComponentFactory: any SettingsComponentFactory public init(modalWireframe: any ModalWireframe, settingsComponentFactory: any SettingsComponentFactory) { self.modalWireframe = modalWireframe self.settingsComponentFactory = settingsComponentFactory } } // MARK: - SettingsRoute + Route extension SettingsRoute: Route { public typealias Parameter = SettingsRouteable public func route(_ parameter: Parameter) { let viewController = settingsComponentFactory.makeSettingsModule() if let barButtonItem = parameter.sender as? UIBarButtonItem { viewController.modalPresentationStyle = .popover viewController.popoverPresentationController?.barButtonItem = barButtonItem } modalWireframe.presentModalContentController(viewController) } }
mit
c6d8f4afb9c07d8bac7f6fadcb83d384
29.264706
109
0.728863
6.391304
false
false
false
false
imex94/KCLTech-iOS-2015
Hackalendar/Hackalendar/Hackalendar/HCCalendarUtility.swift
1
1502
// // HTLCalendatUtility.swift // Hackalendar // // Created by Alex Telek on 24/11/2015. // Copyright © 2015 Alex Telek. All rights reserved. // import UIKit /** HTLCalendarUtility, helper methods to get current year, month and month names. All the calendar related methods we were using across the project */ class HCCalendarUtility: NSObject { /** Get current year. */ class func getCurrentYear() -> Int { let dateComponents = NSCalendar.currentCalendar().components(.Year, fromDate: NSDate()) return dateComponents.year } /** Get current month */ class func getCurrentMonth() -> Int { let dateComponents = NSCalendar.currentCalendar().components(.Month, fromDate: NSDate()) return dateComponents.month } /** Get month names in an array */ class func getMonths() -> [String] { return NSDateFormatter().monthSymbols } class func getETADays(dateString: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMMM dd" let date = dateFormatter.dateFromString(dateString) let components = NSCalendar.currentCalendar().components(.Day, fromDate: NSDate(), toDate: date!, options: .MatchStrictly) let days = components.day if days < 0 { return "Finished" } else { return "\(days) days" } } }
mit
e1b898a1bda46aa160be2af318c67faf
25.333333
130
0.607595
4.873377
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/KnowledgeDetailComponent/View/UIKit/KnowledgeDetailViewController.swift
1
3697
import ComponentBase import UIKit class KnowledgeDetailViewController: UIViewController, KnowledgeDetailScene { // MARK: IBOutlets @IBOutlet private weak var tableView: UITableView! private lazy var tableController = TableController(tableView: self.tableView) // MARK: IBActions @IBAction private func shareEntry(_ sender: UIBarButtonItem) { delegate?.knowledgeDetailSceneShareButtonTapped(sender) } // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() Theme.global.apply(to: tableView) tableView.dataSource = tableController tableView.delegate = tableController delegate?.knowledgeDetailSceneDidLoad() } // MARK: KnowledgeDetailScene private var delegate: KnowledgeDetailSceneDelegate? func setKnowledgeDetailSceneDelegate(_ delegate: KnowledgeDetailSceneDelegate) { self.delegate = delegate } func setKnowledgeDetailTitle(_ title: String) { super.title = title } func setAttributedKnowledgeEntryContents(_ contents: NSAttributedString) { let contentsItem = ContentsItem(contents: contents) tableController.add(contentsItem) } func presentLinks(count: Int, using binder: LinksBinder) { let linkItems = (0..<count).map({ LinkItem(binder: binder, index: $0, delegate: delegate) }) linkItems.forEach(tableController.add) } func bindImages(count: Int, using binder: KnowledgEntryImagesBinder) { (0..<count).map({ ImageItem(binder: binder, index: $0) }).forEach(tableController.add) } // MARK: Private private struct ContentsItem: TableViewDataItem { var contents: NSAttributedString func makeCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(KnowledgeDetailContentsTableViewCell.self) cell.configure(contents) return cell } } private struct ImageItem: TableViewDataItem { var binder: KnowledgEntryImagesBinder var index: Int func makeCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(KnowledgeDetailImageTableViewCell.self) binder.bind(cell, at: index) cell.hideSeperator() return cell } } private struct LinkItem: TableViewDataItem { var binder: LinksBinder var index: Int var delegate: KnowledgeDetailSceneDelegate? func makeCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(LinkTableViewCell.self) binder.bind(cell, at: index) return cell } } private class TableController: NSObject, UITableViewDataSource, UITableViewDelegate { private let tableView: UITableView private(set) var items = [TableViewDataItem]() init(tableView: UITableView) { self.tableView = tableView } func add(_ item: TableViewDataItem) { items.append(item) tableView.reloadData() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return items[indexPath.row].makeCell(for: tableView, at: indexPath) } } } private protocol TableViewDataItem { func makeCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell }
mit
1a91f90e8edb9ccc6d196fcb4b497310
28.34127
104
0.664052
5.243972
false
false
false
false
HackSheffieldTeamImperial/Blockspot
Geotify/Geotify/AddGeotificationViewController.swift
1
2858
/** * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import MapKit protocol AddGeotificationsViewControllerDelegate { func addGeotificationViewController(controller: AddGeotificationViewController, didAddCoordinate coordinate: CLLocationCoordinate2D, radius: Double, identifier: String, note: String, eventType: EventType) } class AddGeotificationViewController: UITableViewController { @IBOutlet var addButton: UIBarButtonItem! @IBOutlet var zoomButton: UIBarButtonItem! @IBOutlet weak var eventTypeSegmentedControl: UISegmentedControl! @IBOutlet weak var radiusTextField: UITextField! @IBOutlet weak var noteTextField: UITextField! @IBOutlet weak var mapView: MKMapView! var delegate: AddGeotificationsViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItems = [addButton, zoomButton] addButton.isEnabled = false } @IBAction func textFieldEditingChanged(sender: UITextField) { addButton.isEnabled = !radiusTextField.text!.isEmpty && !noteTextField.text!.isEmpty } @IBAction func onCancel(sender: AnyObject) { dismiss(animated: true, completion: nil) } @IBAction private func onAdd(sender: AnyObject) { let coordinate = mapView.centerCoordinate let radius = Double(radiusTextField.text!) ?? 0 let identifier = NSUUID().uuidString let note = noteTextField.text let eventType: EventType = (eventTypeSegmentedControl.selectedSegmentIndex == 0) ? .onEntry : .onExit delegate?.addGeotificationViewController(controller: self, didAddCoordinate: coordinate, radius: radius, identifier: identifier, note: note!, eventType: eventType) } @IBAction private func onZoomToCurrentLocation(sender: AnyObject) { mapView.zoomToUserLocation() } }
gpl-3.0
6e40a088527f2977b9f8bdea1ce2955c
41.029412
167
0.772218
4.819562
false
false
false
false
danielmartin/swift
stdlib/public/core/Stride.swift
5
21061
//===--- Stride.swift - Components for stride(...) iteration --------------===// // // 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 // //===----------------------------------------------------------------------===// /// A type representing continuous, one-dimensional values that can be offset /// and measured. /// /// You can use a type that conforms to the `Strideable` protocol with the /// `stride(from:to:by:)` and `stride(from:through:by:)` functions. For /// example, you can use `stride(from:to:by:)` to iterate over an /// interval of floating-point values: /// /// for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) { /// let degrees = Int(radians * 180 / .pi) /// print("Degrees: \(degrees), radians: \(radians)") /// } /// // Degrees: 0, radians: 0.0 /// // Degrees: 90, radians: 1.5707963267949 /// // Degrees: 180, radians: 3.14159265358979 /// // Degrees: 270, radians: 4.71238898038469 /// /// The last parameter of these functions is of the associated `Stride` /// type---the type that represents the distance between any two instances of /// the `Strideable` type. /// /// Types that have an integer `Stride` can be used as the boundaries of a /// countable range or as the lower bound of an iterable one-sided range. For /// example, you can iterate over a range of `Int` and use sequence and /// collection methods. /// /// var sum = 0 /// for x in 1...100 { /// sum += x /// } /// // sum == 5050 /// /// let digits = (0..<10).map(String.init) /// // ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] /// /// Conforming to the Strideable Protocol /// ===================================== /// /// To add `Strideable` conformance to a custom type, choose a `Stride` type /// that can represent the distance between two instances and implement the /// `advanced(by:)` and `distance(to:)` methods. For example, this /// hypothetical `Date` type stores its value as the number of days before or /// after January 1, 2000: /// /// struct Date: Equatable, CustomStringConvertible { /// var daysAfterY2K: Int /// /// var description: String { /// // ... /// } /// } /// /// The `Stride` type for `Date` is `Int`, inferred from the parameter and /// return types of `advanced(by:)` and `distance(to:)`: /// /// extension Date: Strideable { /// func advanced(by n: Int) -> Date { /// var result = self /// result.daysAfterY2K += n /// return result /// } /// /// func distance(to other: Date) -> Int { /// return other.daysAfterY2K - self.daysAfterY2K /// } /// } /// /// The `Date` type can now be used with the `stride(from:to:by:)` and /// `stride(from:through:by:)` functions and as the bounds of an iterable /// range. /// /// let startDate = Date(daysAfterY2K: 0) // January 1, 2000 /// let endDate = Date(daysAfterY2K: 15) // January 16, 2000 /// /// for date in stride(from: startDate, to: endDate, by: 7) { /// print(date) /// } /// // January 1, 2000 /// // January 8, 2000 /// // January 15, 2000 /// /// - Important: The `Strideable` protocol provides default implementations for /// the equal-to (`==`) and less-than (`<`) operators that depend on the /// `Stride` type's implementations. If a type conforming to `Strideable` is /// its own `Stride` type, it must provide concrete implementations of the /// two operators to avoid infinite recursion. public protocol Strideable : Comparable { /// A type that represents the distance between two values. associatedtype Stride : SignedNumeric, Comparable /// Returns the distance from this value to the given value, expressed as a /// stride. /// /// If this type's `Stride` type conforms to `BinaryInteger`, then for two /// values `x` and `y`, and a distance `n = x.distance(to: y)`, /// `x.advanced(by: n) == y`. Using this method with types that have a /// noninteger `Stride` may result in an approximation. /// /// - Parameter other: The value to calculate the distance to. /// - Returns: The distance from this value to `other`. /// /// - Complexity: O(1) func distance(to other: Self) -> Stride /// Returns a value that is offset the specified distance from this value. /// /// Use the `advanced(by:)` method in generic code to offset a value by a /// specified distance. If you're working directly with numeric values, use /// the addition operator (`+`) instead of this method. /// /// func addOne<T: Strideable>(to x: T) -> T /// where T.Stride : ExpressibleByIntegerLiteral /// { /// return x.advanced(by: 1) /// } /// /// let x = addOne(to: 5) /// // x == 6 /// let y = addOne(to: 3.5) /// // y = 4.5 /// /// If this type's `Stride` type conforms to `BinaryInteger`, then for a /// value `x`, a distance `n`, and a value `y = x.advanced(by: n)`, /// `x.distance(to: y) == n`. Using this method with types that have a /// noninteger `Stride` may result in an approximation. /// /// - Parameter n: The distance to advance this value. /// - Returns: A value that is offset from this value by `n`. /// /// - Complexity: O(1) func advanced(by n: Stride) -> Self /// `_step` is an implementation detail of Strideable; do not use it directly. static func _step( after current: (index: Int?, value: Self), from start: Self, by distance: Self.Stride ) -> (index: Int?, value: Self) } extension Strideable { @inlinable public static func < (x: Self, y: Self) -> Bool { return x.distance(to: y) > 0 } @inlinable public static func == (x: Self, y: Self) -> Bool { return x.distance(to: y) == 0 } } extension Strideable { @inlinable // protocol-only public static func _step( after current: (index: Int?, value: Self), from start: Self, by distance: Self.Stride ) -> (index: Int?, value: Self) { return (nil, current.value.advanced(by: distance)) } } extension Strideable where Stride : FloatingPoint { @inlinable // protocol-only public static func _step( after current: (index: Int?, value: Self), from start: Self, by distance: Self.Stride ) -> (index: Int?, value: Self) { if let i = current.index { // When Stride is a floating-point type, we should avoid accumulating // rounding error from repeated addition. return (i + 1, start.advanced(by: Stride(i + 1) * distance)) } return (nil, current.value.advanced(by: distance)) } } extension Strideable where Self : FloatingPoint, Self == Stride { @inlinable // protocol-only public static func _step( after current: (index: Int?, value: Self), from start: Self, by distance: Self.Stride ) -> (index: Int?, value: Self) { if let i = current.index { // When both Self and Stride are the same floating-point type, we should // take advantage of fused multiply-add (where supported) to eliminate // intermediate rounding error. return (i + 1, start.addingProduct(Stride(i + 1), distance)) } return (nil, current.value.advanced(by: distance)) } } /// An iterator for a `StrideTo` instance. @_fixed_layout public struct StrideToIterator<Element : Strideable> { @usableFromInline internal let _start: Element @usableFromInline internal let _end: Element @usableFromInline internal let _stride: Element.Stride @usableFromInline internal var _current: (index: Int?, value: Element) @inlinable internal init(_start: Element, end: Element, stride: Element.Stride) { self._start = _start _end = end _stride = stride _current = (0, _start) } } extension StrideToIterator: IteratorProtocol { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable public mutating func next() -> Element? { let result = _current.value if _stride > 0 ? result >= _end : result <= _end { return nil } _current = Element._step(after: _current, from: _start, by: _stride) return result } } // FIXME: should really be a Collection, as it is multipass /// A sequence of values formed by striding over a half-open interval. /// /// Use the `stride(from:to:by:)` function to create `StrideTo` instances. @_fixed_layout public struct StrideTo<Element : Strideable> { @usableFromInline internal let _start: Element @usableFromInline internal let _end: Element @usableFromInline internal let _stride: Element.Stride @inlinable internal init(_start: Element, end: Element, stride: Element.Stride) { _precondition(stride != 0, "Stride size must not be zero") // At start, striding away from end is allowed; it just makes for an // already-empty Sequence. self._start = _start self._end = end self._stride = stride } } extension StrideTo: Sequence { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public __consuming func makeIterator() -> StrideToIterator<Element> { return StrideToIterator(_start: _start, end: _end, stride: _stride) } // FIXME(conditional-conformances): this is O(N) instead of O(1), leaving it // here until a proper Collection conformance is possible @inlinable public var underestimatedCount: Int { var it = self.makeIterator() var count = 0 while it.next() != nil { count += 1 } return count } @inlinable public func _customContainsEquatableElement( _ element: Element ) -> Bool? { if element < _start || _end <= element { return false } return nil } } extension StrideTo: CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["from": _start, "to": _end, "by": _stride]) } } // FIXME(conditional-conformances): This does not yet compile (SR-6474). #if false extension StrideTo : RandomAccessCollection where Element.Stride : BinaryInteger { public typealias Index = Int public typealias SubSequence = Slice<StrideTo<Element>> public typealias Indices = Range<Int> @inlinable public var startIndex: Index { return 0 } @inlinable public var endIndex: Index { return count } @inlinable public var count: Int { let distance = _start.distance(to: _end) guard distance != 0 && (distance < 0) == (_stride < 0) else { return 0 } return Int((distance - 1) / _stride) + 1 } public subscript(position: Index) -> Element { _failEarlyRangeCheck(position, bounds: startIndex..<endIndex) return _start.advanced(by: Element.Stride(position) * _stride) } public subscript(bounds: Range<Index>) -> Slice<StrideTo<Element>> { _failEarlyRangeCheck(bounds, bounds: startIndex ..< endIndex) return Slice(base: self, bounds: bounds) } @inlinable public func index(before i: Index) -> Index { _failEarlyRangeCheck(i, bounds: startIndex + 1...endIndex) return i - 1 } @inlinable public func index(after i: Index) -> Index { _failEarlyRangeCheck(i, bounds: startIndex - 1..<endIndex) return i + 1 } } #endif /// Returns a sequence from a starting value to, but not including, an end /// value, stepping by the specified amount. /// /// You can use this function to stride over values of any type that conforms /// to the `Strideable` protocol, such as integers or floating-point types. /// Starting with `start`, each successive value of the sequence adds `stride` /// until the next value would be equal to or beyond `end`. /// /// for radians in stride(from: 0.0, to: .pi * 2, by: .pi / 2) { /// let degrees = Int(radians * 180 / .pi) /// print("Degrees: \(degrees), radians: \(radians)") /// } /// // Degrees: 0, radians: 0.0 /// // Degrees: 90, radians: 1.5707963267949 /// // Degrees: 180, radians: 3.14159265358979 /// // Degrees: 270, radians: 4.71238898038469 /// /// You can use `stride(from:to:by:)` to create a sequence that strides upward /// or downward. Pass a negative value as `stride` to create a sequence from a /// higher start to a lower end: /// /// for countdown in stride(from: 3, to: 0, by: -1) { /// print("\(countdown)...") /// } /// // 3... /// // 2... /// // 1... /// /// If you pass a value as `stride` that moves away from `end`, the sequence /// contains no values. /// /// for x in stride(from: 0, to: 10, by: -1) { /// print(x) /// } /// // Nothing is printed. /// /// - Parameters: /// - start: The starting value to use for the sequence. If the sequence /// contains any values, the first one is `start`. /// - end: An end value to limit the sequence. `end` is never an element of /// the resulting sequence. /// - stride: The amount to step by with each iteration. A positive `stride` /// iterates upward; a negative `stride` iterates downward. /// - Returns: A sequence from `start` toward, but not including, `end`. Each /// value in the sequence steps by `stride`. @inlinable public func stride<T>( from start: T, to end: T, by stride: T.Stride ) -> StrideTo<T> { return StrideTo(_start: start, end: end, stride: stride) } /// An iterator for a `StrideThrough` instance. @_fixed_layout public struct StrideThroughIterator<Element : Strideable> { @usableFromInline internal let _start: Element @usableFromInline internal let _end: Element @usableFromInline internal let _stride: Element.Stride @usableFromInline internal var _current: (index: Int?, value: Element) @usableFromInline internal var _didReturnEnd: Bool = false @inlinable internal init(_start: Element, end: Element, stride: Element.Stride) { self._start = _start _end = end _stride = stride _current = (0, _start) } } extension StrideThroughIterator: IteratorProtocol { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable public mutating func next() -> Element? { let result = _current.value if _stride > 0 ? result >= _end : result <= _end { // This check is needed because if we just changed the above operators // to > and <, respectively, we might advance current past the end // and throw it out of bounds (e.g. above Int.max) unnecessarily. if result == _end && !_didReturnEnd { _didReturnEnd = true return result } return nil } _current = Element._step(after: _current, from: _start, by: _stride) return result } } // FIXME: should really be a Collection, as it is multipass /// A sequence of values formed by striding over a closed interval. /// /// Use the `stride(from:through:by:)` function to create `StrideThrough` /// instances. @_fixed_layout public struct StrideThrough<Element: Strideable> { @usableFromInline internal let _start: Element @usableFromInline internal let _end: Element @usableFromInline internal let _stride: Element.Stride @inlinable internal init(_start: Element, end: Element, stride: Element.Stride) { _precondition(stride != 0, "Stride size must not be zero") self._start = _start self._end = end self._stride = stride } } extension StrideThrough: Sequence { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public __consuming func makeIterator() -> StrideThroughIterator<Element> { return StrideThroughIterator(_start: _start, end: _end, stride: _stride) } // FIXME(conditional-conformances): this is O(N) instead of O(1), leaving it // here until a proper Collection conformance is possible @inlinable public var underestimatedCount: Int { var it = self.makeIterator() var count = 0 while it.next() != nil { count += 1 } return count } @inlinable public func _customContainsEquatableElement( _ element: Element ) -> Bool? { if element < _start || _end < element { return false } return nil } } extension StrideThrough: CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: ["from": _start, "through": _end, "by": _stride]) } } // FIXME(conditional-conformances): This does not yet compile (SR-6474). #if false extension StrideThrough : RandomAccessCollection where Element.Stride : BinaryInteger { public typealias Index = ClosedRangeIndex<Int> public typealias SubSequence = Slice<StrideThrough<Element>> @inlinable public var startIndex: Index { let distance = _start.distance(to: _end) return distance == 0 || (distance < 0) == (_stride < 0) ? ClosedRangeIndex(0) : ClosedRangeIndex() } @inlinable public var endIndex: Index { return ClosedRangeIndex() } @inlinable public var count: Int { let distance = _start.distance(to: _end) guard distance != 0 else { return 1 } guard (distance < 0) == (_stride < 0) else { return 0 } return Int(distance / _stride) + 1 } public subscript(position: Index) -> Element { let offset = Element.Stride(position._dereferenced) * _stride return _start.advanced(by: offset) } public subscript(bounds: Range<Index>) -> Slice<StrideThrough<Element>> { return Slice(base: self, bounds: bounds) } @inlinable public func index(before i: Index) -> Index { switch i._value { case .inRange(let n): _precondition(n > 0, "Incrementing past start index") return ClosedRangeIndex(n - 1) case .pastEnd: _precondition(_end >= _start, "Incrementing past start index") return ClosedRangeIndex(count - 1) } } @inlinable public func index(after i: Index) -> Index { switch i._value { case .inRange(let n): return n == (count - 1) ? ClosedRangeIndex() : ClosedRangeIndex(n + 1) case .pastEnd: _preconditionFailure("Incrementing past end index") } } } #endif /// Returns a sequence from a starting value toward, and possibly including, an end /// value, stepping by the specified amount. /// /// You can use this function to stride over values of any type that conforms /// to the `Strideable` protocol, such as integers or floating-point types. /// Starting with `start`, each successive value of the sequence adds `stride` /// until the next value would be beyond `end`. /// /// for radians in stride(from: 0.0, through: .pi * 2, by: .pi / 2) { /// let degrees = Int(radians * 180 / .pi) /// print("Degrees: \(degrees), radians: \(radians)") /// } /// // Degrees: 0, radians: 0.0 /// // Degrees: 90, radians: 1.5707963267949 /// // Degrees: 180, radians: 3.14159265358979 /// // Degrees: 270, radians: 4.71238898038469 /// // Degrees: 360, radians: 6.28318530717959 /// /// You can use `stride(from:through:by:)` to create a sequence that strides /// upward or downward. Pass a negative value as `stride` to create a sequence /// from a higher start to a lower end: /// /// for countdown in stride(from: 3, through: 1, by: -1) { /// print("\(countdown)...") /// } /// // 3... /// // 2... /// // 1... /// /// The value you pass as `end` is not guaranteed to be included in the /// sequence. If stepping from `start` by `stride` does not produce `end`, /// the last value in the sequence will be one step before going beyond `end`. /// /// for multipleOfThree in stride(from: 3, through: 10, by: 3) { /// print(multipleOfThree) /// } /// // 3 /// // 6 /// // 9 /// /// If you pass a value as `stride` that moves away from `end`, the sequence /// contains no values. /// /// for x in stride(from: 0, through: 10, by: -1) { /// print(x) /// } /// // Nothing is printed. /// /// - Parameters: /// - start: The starting value to use for the sequence. If the sequence /// contains any values, the first one is `start`. /// - end: An end value to limit the sequence. `end` is an element of /// the resulting sequence if and only if it can be produced from `start` /// using steps of `stride`. /// - stride: The amount to step by with each iteration. A positive `stride` /// iterates upward; a negative `stride` iterates downward. /// - Returns: A sequence from `start` toward, and possibly including, `end`. /// Each value in the sequence is separated by `stride`. @inlinable public func stride<T>( from start: T, through end: T, by stride: T.Stride ) -> StrideThrough<T> { return StrideThrough(_start: start, end: end, stride: stride) }
apache-2.0
72a48250bb17843fceffeab1f929c980
31.805296
83
0.636152
3.824405
false
false
false
false
mmoaay/MBMotion
MBMotion/Classes/HamburgButton/MBMotionHamburgButton.swift
1
5810
// // MBMotionHamburgButton.swift // MBMotion // // Created by Perry on 15/12/3. // Copyright © 2015年 MmoaaY. All rights reserved. // import UIKit public protocol MBMotionHamburgButtonDelegate { func buttonPressed(_ status:MBMotionHamburgButtonStatus) } public enum MBMotionHamburgButtonStatus:Int{ case open case close } public class MBMotionHamburgButton: UIView { @IBOutlet var button: UIButton! @IBOutlet var view: UIView! public var delegate: MBMotionHamburgButtonDelegate? fileprivate var status = MBMotionHamburgButtonStatus.open /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ @IBOutlet var lineView: UIView! @IBOutlet fileprivate var topLine: UIView! @IBOutlet fileprivate var bottomLine: UIView! @IBAction func buttonPressed(_ sender: AnyObject) { self.delegate?.buttonPressed(self.status) self.animatedWithButton() } fileprivate func animatedWithButton() { if self.status == MBMotionHamburgButtonStatus.open { self.closeSwitchButton() } else { self.openSwithButton() } } fileprivate func animtedWithLineColor(_ line:UIView!, color:UIColor, duration:TimeInterval) { UIView.animate(withDuration: duration, animations: { () -> Void in line.layer.backgroundColor = color.cgColor }) } fileprivate func animtedWithLineShape(_ line:UIView!, angle:CGFloat, tx:CGFloat,ty:CGFloat, duration:TimeInterval) { var transform = CATransform3DIdentity transform = CATransform3DTranslate(transform, tx, ty, 0) transform = CATransform3DRotate(transform, angle, 0, 0, 1) let animation = CABasicAnimation(keyPath: "transform") animation.fromValue = NSValue(caTransform3D: line.layer.transform) animation.toValue = NSValue(caTransform3D: transform) animation.duration = duration line.layer.add(animation, forKey: "lineshape") line.layer.transform = transform } fileprivate func closeSwitchButton() { self.button.isEnabled = false self.animtedWithLineShape(self.topLine, angle: 0.0, tx: 0, ty: 3, duration: 0.2) self.animtedWithLineShape(self.bottomLine, angle: 0.0, tx: 0, ty: -3, duration: 0.2) self.animtedWithLineColor(self.topLine, color: UIColor(red: 173/255, green: 181/255, blue: 184/255, alpha: 1), duration: 0.8) self.animtedWithLineColor(self.bottomLine, color: UIColor(red: 173/255, green: 181/255, blue: 184/255, alpha: 1), duration: 0.8) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.2) { self.animtedWithLineShape(self.topLine, angle: 0.0, tx: 0, ty: 4.5, duration: 0.2) self.animtedWithLineShape(self.bottomLine, angle: 0.0, tx: 0, ty: -4.5, duration: 0.2) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) { self.animtedWithLineShape(self.topLine, angle: CGFloat(M_PI_4+M_PI_4/5), tx: 0, ty: 4.5, duration: 0.3) self.animtedWithLineShape(self.bottomLine, angle: CGFloat(M_PI_4*3+M_PI_4/5), tx: 0, ty: -4.5, duration: 0.3) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.7) { self.animtedWithLineShape(self.topLine, angle: CGFloat(M_PI_4), tx: 0, ty: 4.5, duration: 0.1) self.animtedWithLineShape(self.bottomLine, angle: CGFloat(M_PI_4*3), tx: 0, ty: -4.5, duration: 0.1) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.8) { self.status = MBMotionHamburgButtonStatus.close self.button.isEnabled = true } } fileprivate func openSwithButton() { self.button.isEnabled = false self.animtedWithLineShape(self.topLine, angle: CGFloat(M_PI_4+M_PI_4/5), tx: 0, ty: 4.5, duration: 0.1) self.animtedWithLineShape(self.bottomLine, angle: CGFloat(M_PI_4*3+M_PI_4/5), tx: 0, ty: -4.5, duration: 0.1) self.animtedWithLineColor(self.topLine, color: UIColor.white, duration: 0.8) self.animtedWithLineColor(self.bottomLine, color: UIColor.white, duration: 0.8) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.1) { self.animtedWithLineShape(self.topLine, angle: 0.0, tx: 0, ty: 4.5, duration: 0.3) self.animtedWithLineShape(self.bottomLine, angle: 0.0, tx: 0, ty: -4.5, duration: 0.3) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) { self.animtedWithLineShape(self.topLine, angle: 0.0, tx: 0, ty: 3, duration: 0.2) self.animtedWithLineShape(self.bottomLine, angle: 0.0, tx: 0, ty: -3, duration: 0.2) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.6) { self.animtedWithLineShape(self.topLine, angle: 0.0, tx: 0, ty: 0, duration: 0.2) self.animtedWithLineShape(self.bottomLine, angle: 0.0, tx: 0, ty: 0, duration: 0.2) } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.8) { self.status = MBMotionHamburgButtonStatus.open self.button.isEnabled = true } } override public func awakeFromNib() { super.awakeFromNib() Bundle(for: self.classForCoder).loadNibNamed("MBMotionHamburgButton", owner: self, options: nil) self.addSubview(self.view) self.view.snp.makeConstraints { (make) -> Void in make.leading.top.bottom.trailing.equalTo(self) } } }
mit
1e69de8631bb305aadd1c579244e4d4f
40.184397
136
0.644567
3.710543
false
false
false
false
drunknbass/Emby.ApiClient.Swift
Emby.ApiClient/model/dto/BaseItemDto.swift
1
9715
// // BaseItemDto.swift // Emby.ApiClient // import Foundation public class BaseItemDto { var name: String? var serverId: String? var id: String? var etag: String? var playlistItemid: String? var dateCreated: NSDate? var dateLastMediaAdded: NSDate? var extraType: ExtraType? var airsBeforeSeasonNumber: Int? var airsAfterSeasonNumber: Int? var airsBeforeEpisodeNumber: Int? var absoluteEpisodeNumber: Int? var displaySpecialWithSeasons: Bool? var canDelete: Bool? var canDownload: Bool? var hasSubtitles: Bool? var preferredMetadataLanguage: String? var preferredMetadataCountryCode: String? var awardSummary: String? var shareUrl: String? var metascore: Float? var hasDynamicCategories: Bool? var animeSeriesIndex: Int? var supportsSync: Bool? var hasSyncJob: Bool? var isSynced: Bool? var syncStatus: SyncJobStatus? var syncPercent: Double? var dvdSeasonNumber: Int? var dvdEpisodeNumber: Int? var sortName: String? var forcedSortName: String? var video3dFormat: Video3DFormat? var premierDate: NSDate? var externalUrls: [ExternalUrl]? var mediaSources: [MediaSourceInfo]? var criticRating: Float? var gameSystem: String? var criticRatingSummary: String? var multiPartGameFiles: [String]? var path: String? var officialRating: String? var customRating: String? var channelId: String? var channelName: String? var overview: String? var shortOverview: String? var tmdbCollectionName: String? var tagLines: [String]? var genres: [String]? var seriesGenres: [String]? var communityRating: Float? var voteCount: Int? var cumulativeRunTimeTicks: Int? var originalRunTimeTicks: Int? var runTimeTicks: Int? var playAccess: PlayAccess? var aspectRation: String? var productionYear: Int? var players: Int? var isPlaceHolder: Bool? var indexNumber: Int? var indexNumberEnd: Int? var parentIndexNumber: Int? var remoteTrailers: [MediaUrl]? var soundtrackIds: [String]? var providerIds: [String:String]? var isHd: Bool? var isFolder: Bool? var parentId: String? var type: String? var people: [BaseItemPerson]? var studios: [StudioDto]? var parentLogoItemId: String? var parentBackdropItemId: String? var parentBackdropImageTags: [String]? var localTrailerCount: Int? var userData: UserItemDataDto? var seasonUserData: UserItemDataDto? var recursiveItemCount: Int? var childCount: Int? var seriesName: String? var seriesId: String? var seasonId: String? var specialFeatureCount: Int? var displayPreferencesId: String? var status: String? var seriesStatus: SeriesStatus? { get { if let status = self.status { return SeriesStatus(rawValue: status) } else { return nil } } set { status = newValue!.rawValue } } var recordingStatus: RecordingStatus? { get { if let status = self.status { return RecordingStatus(rawValue: status) } else { return nil } } set { status = newValue!.rawValue } } var airTime: String? var airDays: [String]? var indexOptions: [String]? var tags: [String]? var keywords: [String]? var primaryImageAspectRatio: Double? var originalPrimaryImageAspectRatio: Double? var artists: [String]? var artistItems: [NameIdPair]? var album: String? var collectionType: String? var displayOrder: String? var albumId: String? var albumPrimaryImageTag: String? var seriesPrimaryImageTag: String? var albumArtist: String? var albumArtists: [NameIdPair]? var seasonName: String? var mediaStreams: [MediaStream]? var videoType: VideoType? var displayMediaType: String? var partCount: Int? var mediaSourceCount: Int? var supportsPlayLists: Bool { get { return (runTimeTicks != nil) || ((isFolder != nil) && isFolder!) || isGenre || isMusicGenre || isArtist } } public func isType(type: String) -> Bool { return self.type == type } var imageTags: [ImageType: String]? var backdropImageTags: [String]? var screenshotImageTags: [String]? var parentLogoImageTag: String? var parentArtItemId: String? var parentArtImageTag: String? var seriesThumbImageTag: String? var seriesStudio: String? var parentThumbItemId: String? var parentThumbImageTag: String? var parentPrimaryImageItemId: String? var parentPrimaryImageTag: String? var chapters: [ChapterInfoDto]? var locationType: LocationType? var isoType: IsoType? var mediaType: String? var endDate: NSDate? var homePageUrl: String? var productionLocations: [String]? var budget: Double? var revenue: Double? var lockedFields: [MetadataFields]? var movieCount: Int? var seriesCount: Int? var episodeCount: Int? var gameCount: Int? var songCount: Int? var albumCount: Int? var musicVideoCount: Int? var lockData: Bool? var width: Int? var height: Int? var cameraMake: String? var cameraModel: String? var software: String? var exposureTime: Double? var focalLength: Double? var imageOrientation: ImageOrientation? var aperture: Double? var shutterSpeed: Double? var latitude: Double? var longitude: Double? var altitude: Double? var isoSpeedRating: Int? var recordingCount: Int? var seriesTimerId: String? var canResume: Bool { get { if let playbackPositionTicks = userData?.playbackPositionTicks { return playbackPositionTicks > 0 } else { return false } } } var resumePositionTicks: Int { get { if let playbackPositionTicks = userData?.playbackPositionTicks { return playbackPositionTicks } else { return 0 } } } var backdropCount: Int { get { return (backdropImageTags != nil) ? backdropImageTags!.count : 0 } } var screenshotCount: Int { get { return (screenshotImageTags != nil) ? screenshotImageTags!.count : 0 } } var hasBanner: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Banner] != nil : false } } var hasArtImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Art] != nil : false } } var hasLogo: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Logo] != nil : false } } var hasThumb: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Thumb] != nil : false } } var hasPrimaryImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Primary] != nil : false } } var hasDiscImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Disc] != nil : false } } var hasBoxImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Box] != nil : false } } var hasBoxRearImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.BoxRear] != nil : false } } var hasMenuImage: Bool { get { return (imageTags != nil) ? imageTags![ImageType.Menu] != nil : false } } var isVideo: Bool { get { return mediaType == MediaType.Video.rawValue } } var isGame: Bool { get { return mediaType == MediaType.Game.rawValue } } var isPerson: Bool { get { return mediaType == "Person" } } var isRoot: Bool { get { return mediaType == "AggregateFolder" } } var isMusicGenre: Bool { get { return mediaType == "MusicGenre" } } var isGameGenre: Bool { get { return mediaType == "GameGenre" } } var isGenre: Bool { get { return mediaType == "Genre" } } var isArtist: Bool { get { return mediaType == "MusicArtist" } } var isAlbum: Bool { get { return mediaType == "MusicAlbum" } } var IsStudio: Bool { get { return mediaType == "Studio" } } var supportsSimilarItems: Bool { get { return isType("Movie") || isType("Series") || isType("MusicAlbum") || isType("MusicArtist") || isType("Program") || isType("Recording") || isType("ChannelVideoItem") || isType("Game") } } var programId: String? var channelPrimaryImageTag: String? var startDate: NSDate? var completionPercentage: Double? var isRepeat: Bool? var episodeTitle: String? var channelType: ChannelType? var audio: ProgramAudio? var isMovie: Bool? var isSports: Bool? var isSeries: Bool? var isLive: Bool? var isNews: Bool? var isKids: Bool? var isPremiere: Bool? var timerId: String? var currentProgram: BaseItemDto? }
mit
35344edf5fb431bc507cbfd6b95295f9
25.048257
195
0.591354
4.333185
false
false
false
false
triestpa/GetHome-iOS
GetHome/LocationHelper.swift
1
1834
// // LocationHelper.swift // GetHome // // Created by Patrick on 12/2/14. // Copyright (c) 2014 Patrick Triest. All rights reserved. // import UIKit import CoreLocation class LocationHelper: NSObject, CLLocationManagerDelegate { private let locationManager = CLLocationManager() var lastLocation: CLLocation? override init() { super.init() if CLLocationManager.authorizationStatus() == .NotDetermined { locationManager.requestWhenInUseAuthorization() } locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters //kCLLocationAccuracyThreeKilometers//kCLLocationAccuracyHundredMeters //kCLLocationAccuracyNearestTenMeters } func startLocationUpdate() { locationManager.startUpdatingLocation() } func stopLocationUpdate() { locationManager.stopUpdatingLocation() } // MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { let newLocation = locations.last! as CLLocation if newLocation.horizontalAccuracy >= 0 && newLocation.horizontalAccuracy >= locationManager.desiredAccuracy { lastLocation = newLocation println("latitude: \(newLocation.coordinate.latitude) longitude: \(newLocation.coordinate.longitude)") stopLocationUpdate() } else { println("Location Accuracy Not Valid: " + "\(newLocation.horizontalAccuracy)") } } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println("Failed to get location: " + error.localizedDescription) stopLocationUpdate() } }
gpl-2.0
2604edce3a6362e45bd8eb0a3777fc12
31.192982
186
0.671756
6.195946
false
false
false
false
einsteinx2/iSub
Carthage/Checkouts/Nuke/Tests/RateLimiterTests.swift
1
2551
// The MIT License (MIT) // // Copyright (c) 2016 Alexander Grebenyuk (github.com/kean). import XCTest import Nuke class RateLimiterTests: XCTestCase { // MARK: Thread Safety func testThreadSafety() { let scheduler = MockScheduler() let limiter = RateLimiter(scheduler: scheduler, rate: 10000, burst: 1000) // can't figure out how to put closures that accept // escaping closures as parameters directly in the array struct Op { let closure: (@escaping (Void) -> Void) -> Void } var ops = [Op]() ops.append(Op() { fulfill in limiter.execute(token: nil) { finish in sleep(UInt32(Double(rnd(10)) / 100.0)) finish() fulfill() } }) ops.append(Op() { fulfill in // cancel after executing let cts = CancellationTokenSource() limiter.execute(token: cts.token) { finish in sleep(UInt32(Double(rnd(10)) / 100.0)) finish() } cts.cancel() fulfill() // we don't except fulfil }) ops.append(Op() { fulfill in // cancel immediately let cts = CancellationTokenSource() cts.cancel() limiter.execute(token: cts.token) { finish in sleep(UInt32(Double(rnd(10)) / 100.0)) finish() XCTFail() // must not be executed } fulfill() }) for _ in 0..<5000 { expect { fulfill in let queue = OperationQueue() // RateLimiter is not designed (unlike user-facing classes) to // handle unlimited pressure from the outside, thus we limit // the number of concurrent ops queue.maxConcurrentOperationCount = 50 queue.addOperation { ops.randomItem().closure(fulfill) } } } wait() } } private class MockScheduler: Nuke.AsyncScheduler { private let queue: OperationQueue = { let queue = OperationQueue() queue.maxConcurrentOperationCount = 50 return queue }() fileprivate func execute(token: CancellationToken?, closure: @escaping (@escaping (Void) -> Void) -> Void) { queue.addOperation { closure { return } } } }
gpl-3.0
6507b4992e2b3c19c6c8dc760309f001
28.662791
112
0.50686
5.206122
false
false
false
false
Hydropal/Hydropal-iOS
HydroPal/HydroPal/BluetoothSerial.swift
1
11769
// // BluetoothSerial.swift (originally DZBluetoothSerialHandler.swift) // HM10 Serial // // Created by Alex on 09-08-15. // Copyright (c) 2015 Balancing Rock. All rights reserved. // // IMPORTANT: Don't forget to set the variable 'writeType' or else the whole thing might not work. // // The MIT License (MIT) // // Copyright (c) 2015 hoiberg // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CoreBluetooth /// Global serial handler, don't forget to initialize it with init(delgate:) var serial: BluetoothSerial! // Delegate functions protocol BluetoothSerialDelegate { // ** Required ** /// Called when de state of the CBCentralManager changes (e.g. when bluetooth is turned on/off) func serialDidChangeState() /// Called when a peripheral disconnected func serialDidDisconnect(_ peripheral: CBPeripheral, error: NSError?) // ** Optionals ** /// Called when a message is received func serialDidReceiveString(_ message: String) /// Called when a message is received func serialDidReceiveBytes(_ bytes: [UInt8]) /// Called when a message is received func serialDidReceiveData(_ data: Data) /// Called when the RSSI of the connected peripheral is read func serialDidReadRSSI(_ rssi: NSNumber) /// Called when a new peripheral is discovered while scanning. Also gives the RSSI (signal strength) func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?) /// Called when a peripheral is connected (but not yet ready for cummunication) func serialDidConnect(_ peripheral: CBPeripheral) /// Called when a pending connection failed func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?) /// Called when a peripheral is ready for communication func serialIsReady(_ peripheral: CBPeripheral) } // Make some of the delegate functions optional extension BluetoothSerialDelegate { func serialDidReceiveString(_ message: String) {} func serialDidReceiveBytes(_ bytes: [UInt8]) {} func serialDidReceiveData(_ data: Data) {} func serialDidReadRSSI(_ rssi: NSNumber) {} func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?) {} func serialDidConnect(_ peripheral: CBPeripheral) {} func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?) {} func serialIsReady(_ peripheral: CBPeripheral) {} } final class BluetoothSerial: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate { //MARK: Variables /// The delegate object the BluetoothDelegate methods will be called upon var delegate: BluetoothSerialDelegate! /// The CBCentralManager this bluetooth serial handler uses for... well, everything really var centralManager: CBCentralManager! /// The peripheral we're trying to connect to (nil if none) var pendingPeripheral: CBPeripheral? /// The connected peripheral (nil if none is connected) var connectedPeripheral: CBPeripheral? /// The characteristic 0xFFE1 we need to write to, of the connectedPeripheral weak var writeCharacteristic: CBCharacteristic? /// Whether this serial is ready to send and receive data var isReady: Bool { get { return centralManager.state == .poweredOn && connectedPeripheral != nil && writeCharacteristic != nil } } /// Whether to write to the HM10 with or without response. /// Legit HM10 modules (from JNHuaMao) require 'Write without Response', /// while fake modules (e.g. from Bolutek) require 'Write with Response'. var writeType: CBCharacteristicWriteType = .withoutResponse //MARK: functions /// Always use this to initialize an instance init(delegate: BluetoothSerialDelegate) { super.init() self.delegate = delegate centralManager = CBCentralManager(delegate: self, queue: nil) } /// Start scanning for peripherals func startScan() { guard centralManager.state == .poweredOn else { return } // start scanning for peripherals with correct service UUID let uuid = CBUUID(string: "FFE0") centralManager.scanForPeripherals(withServices: [uuid], options: nil) // retrieve peripherals that are already connected // see this stackoverflow question http://stackoverflow.com/questions/13286487 let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [uuid]) for peripheral in peripherals { delegate.serialDidDiscoverPeripheral(peripheral, RSSI: nil) } } /// Stop scanning for peripherals func stopScan() { centralManager.stopScan() } /// Try to connect to the given peripheral func connectToPeripheral(_ peripheral: CBPeripheral) { pendingPeripheral = peripheral centralManager.connect(peripheral, options: nil) } /// Disconnect from the connected peripheral or stop connecting to it func disconnect() { if let p = connectedPeripheral { centralManager.cancelPeripheralConnection(p) } else if let p = pendingPeripheral { centralManager.cancelPeripheralConnection(p) //TODO: Test whether its neccesary to set p to nil } } /// The didReadRSSI delegate function will be called after calling this function func readRSSI() { guard isReady else { return } connectedPeripheral!.readRSSI() } /// Send a string to the device func sendMessageToDevice(_ message: String) { guard isReady else { return } if let data = message.data(using: String.Encoding.utf8) { connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType) } } /// Send an array of bytes to the device func sendBytesToDevice(_ bytes: [UInt8]) { guard isReady else { return } let data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count) connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType) } /// Send data to the device func sendDataToDevice(_ data: Data) { guard isReady else { return } connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType) } //MARK: CBCentralManagerDelegate functions func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { // just send it to the delegate delegate.serialDidDiscoverPeripheral(peripheral, RSSI: RSSI) } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { // set some stuff right peripheral.delegate = self pendingPeripheral = nil connectedPeripheral = peripheral // send it to the delegate delegate.serialDidConnect(peripheral) // Okay, the peripheral is connected but we're not ready yet! // First get the 0xFFE0 service // Then get the 0xFFE1 characteristic of this service // Subscribe to it & create a weak reference to it (for writing later on), // and then we're ready for communication peripheral.discoverServices([CBUUID(string: "FFE0")]) } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { connectedPeripheral = nil pendingPeripheral = nil // send it to the delegate delegate.serialDidDisconnect(peripheral, error: error as NSError?) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { pendingPeripheral = nil // just send it to the delegate delegate.serialDidFailToConnect(peripheral, error: error as NSError?) } func centralManagerDidUpdateState(_ central: CBCentralManager) { // note that "didDisconnectPeripheral" won't be called if BLE is turned off while connected connectedPeripheral = nil pendingPeripheral = nil // send it to the delegate delegate.serialDidChangeState() } //MARK: CBPeripheralDelegate functions func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { // discover the 0xFFE1 characteristic for all services (though there should only be one) for service in peripheral.services! { peripheral.discoverCharacteristics([CBUUID(string: "FFE1")], for: service) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { // check whether the characteristic we're looking for (0xFFE1) is present - just to be sure for characteristic in service.characteristics! { if characteristic.uuid == CBUUID(string: "FFE1") { // subscribe to this value (so we'll get notified when there is serial data for us..) peripheral.setNotifyValue(true, for: characteristic) // keep a reference to this characteristic so we can write to it writeCharacteristic = characteristic // notify the delegate we're ready for communication delegate.serialIsReady(peripheral) } } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { // notify the delegate in different ways // if you don't use one of these, just comment it (for optimum efficiency :]) let data = characteristic.value guard data != nil else { return } // first the data delegate.serialDidReceiveData(data!) // then the string if let str = String(data: data!, encoding: String.Encoding.utf8) { delegate.serialDidReceiveString(str) } else { //print("Received an invalid string!") uncomment for debugging } // now the bytes array var bytes = [UInt8](repeating: 0, count: data!.count / MemoryLayout<UInt8>.size) (data! as NSData).getBytes(&bytes, length: data!.count) delegate.serialDidReceiveBytes(bytes) } func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { delegate.serialDidReadRSSI(RSSI) } }
mit
a55a6e8282b5ebb32546e280aceed306
38.361204
148
0.67134
5.261064
false
false
false
false
hollanderbart/NPOStream
NPOStream/NPOStream.swift
1
3176
// // NPOStream.swift // NPOStreamFramework // // Created by Bart den Hollander on 28-01-16. // Copyright © 2016 Bart den Hollander. All rights reserved. // import Foundation import UIKit public class NPOStream { public static func getStreamURL(for channelTitle: ChannelStreamTitle, _ onCompletion: @escaping (Result<URL>) -> Void) { let API_URL = "http://ida.omroep.nl/app.php/" let TOKEN_URL = URL(string: "http://ida.omroep.nl/app.php/auth")! DispatchQueue.global(qos: .userInteractive).async { let authenticateURLSession = URLSession.shared.dataTask(with: TOKEN_URL) { (data, response, error) in guard let data = data, let auth = try? data.decoded() as Auth else { DispatchQueue.main.async { onCompletion(.error(NPOStreamError.parsingAuthenticateURLFailed)) } return } guard var channelURLComponents = URLComponents(string: API_URL + channelTitle.rawValue) else { return } let channelURLQueryItems = [URLQueryItem(name: "adaptive", value: "yes"), URLQueryItem(name: "token", value: auth.token)] channelURLComponents.queryItems = channelURLQueryItems guard let channelURL = channelURLComponents.url else { return } let channelURLSession = URLSession.shared.dataTask(with: channelURL) { (data, response, error) in guard let data = data, let channelRequest = try? data.decoded() as ChannelRequest, let channelRequestURL = channelRequest.items.first?.first?.url else { DispatchQueue.main.async { onCompletion(.error(NPOStreamError.parsingChannelURLFailed)) } return } let channelSourceURLSession = URLSession.shared.dataTask(with: channelRequestURL) { (data, response, error) in guard let data = data, let response = String(data: data, encoding: .utf8), let urlString = response.sliceFrom("setSource(\"", to: "\"")?.replacingOccurrences(of: "\\/", with: "/"), let resultURL = URL(string: urlString) else { DispatchQueue.main.async { onCompletion(.error(NPOStreamError.channelSourceURLFailed)) } return } DispatchQueue.main.async { onCompletion(.success(resultURL)) } } channelSourceURLSession.resume() } channelURLSession.resume() } authenticateURLSession.resume() } } }
mit
748a1ea4c96ba51dddfe20404267822f
45.014493
134
0.500472
5.679785
false
false
false
false
masters3d/xswift
exercises/grains/Sources/GrainsExample.swift
3
905
import Foundation struct Grains { enum GrainsError: Error { case inputTooLow(String) case inputTooHigh(String) } static func square(_ num: Int) throws -> UInt64 { guard num >= 1 else { let message = "Input[\(num)] invalid. Input should be between 1 and 64 (inclusive)" throw GrainsError.inputTooLow(message) } guard num <= 64 else { let message = "Input[\(num)] invalid. Input should be between 1 and 64 (inclusive)" throw GrainsError.inputTooHigh(message) } let one: UInt64 = 1 let shift = UInt64(num - 1) return one << shift } static var total: UInt64 { let numbers = (1...64).map { $0 } return numbers.reduce(UInt64(0)) { guard let squared = try? square($1) else { return $0 } return $0 + squared } } }
mit
8bc648cafc785f0ea32213b009e8b357
25.617647
95
0.551381
4.076577
false
false
false
false
xu6148152/binea_project_for_ios
RangeSlider/RangeSlider/RangeSliderThumbLayer.swift
1
1586
// // RangeSliderThumbLayer.swift // RangeSlider // // Created by Binea Xu on 7/5/15. // Copyright (c) 2015 Binea Xu. All rights reserved. // import UIKit import QuartzCore class RangeSliderThumbLayer: CALayer { var highlighted: Bool = false { didSet { setNeedsDisplay() } } weak var rangeSlider: RangeSlider? override func drawInContext(ctx: CGContext!) { if let slider = rangeSlider { let thumbFrame = bounds.rectByInsetting(dx: 2.0, dy: 2.0) let cornerRadius = thumbFrame.height * slider.curvaceousness / 2.0 let thumbPath = UIBezierPath(roundedRect: thumbFrame, cornerRadius: cornerRadius) // Fill - with a subtle shadow let shadowColor = UIColor.grayColor() CGContextSetShadowWithColor(ctx, CGSize(width: 0.0, height: 1.0), 1.0, shadowColor.CGColor) CGContextSetFillColorWithColor(ctx, slider.thumbTintColor.CGColor) CGContextAddPath(ctx, thumbPath.CGPath) CGContextFillPath(ctx) // Outline CGContextSetStrokeColorWithColor(ctx, shadowColor.CGColor) CGContextSetLineWidth(ctx, 0.5) CGContextAddPath(ctx, thumbPath.CGPath) CGContextStrokePath(ctx) if highlighted { CGContextSetFillColorWithColor(ctx, UIColor(white: 0.0, alpha: 0.1).CGColor) CGContextAddPath(ctx, thumbPath.CGPath) CGContextFillPath(ctx) } } } }
mit
0c7ed5d74f7c9cda02977b7640be58df
31.367347
103
0.604666
5.034921
false
false
false
false
sstanic/Shopfred
Shopfred/Pods/Groot/Groot/Groot.swift
2
6568
// Groot.swift // // Copyright (c) 2014-2016 Guillermo Gonzalez // // 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 CoreData extension NSManagedObjectContext { internal var managedObjectModel: NSManagedObjectModel? { if let persistentStoreCoordinator = persistentStoreCoordinator { return persistentStoreCoordinator.managedObjectModel } if let parent = parent { return parent.managedObjectModel } return nil } } extension NSManagedObject { internal static func entity(inManagedObjectContext context: NSManagedObjectContext) -> NSEntityDescription { guard let model = context.managedObjectModel else { fatalError("Could not find managed object model for the provided context.") } let className = String(reflecting: self) for entity in model.entities { if entity.managedObjectClassName == className { return entity } } fatalError("Could not locate the entity for \(className).") } } /// Creates or updates a set of managed objects from JSON data. /// /// - parameter name: The name of an entity. /// - parameter data: A data object containing JSON data. /// - parameter context: The context into which to fetch or insert the managed objects. /// /// - returns: An array of managed objects public func objects(withEntityName name: String, fromJSONData data: Data, inContext context: NSManagedObjectContext) throws -> [NSManagedObject] { return try GRTJSONSerialization.objects(withEntityName: name, fromJSONData: data, in: context) } /// Creates or updates a set of managed objects from JSON data. /// /// - parameter data: A data object containing JSON data. /// - parameter context: The context into which to fetch or insert the managed objects. /// /// - returns: An array of managed objects. public func objects<T: NSManagedObject>(fromJSONData data: Data, inContext context: NSManagedObjectContext) throws -> [T] { let entity = T.entity(inManagedObjectContext: context) let managedObjects = try objects(withEntityName: entity.name!, fromJSONData: data, inContext: context) return managedObjects as! [T] } public typealias JSONDictionary = [String: Any] /// Creates or updates a managed object from a JSON dictionary. /// /// This method converts the specified JSON dictionary into a managed object of a given entity. /// /// - parameter name: The name of an entity. /// - parameter dictionary: A dictionary representing JSON data. /// - parameter context: The context into which to fetch or insert the managed objects. /// /// - returns: A managed object. public func object(withEntityName name: String, fromJSONDictionary dictionary: JSONDictionary, inContext context: NSManagedObjectContext) throws -> NSManagedObject { return try GRTJSONSerialization.object(withEntityName: name, fromJSONDictionary: dictionary, in: context) } /// Creates or updates a managed object from a JSON dictionary. /// /// This method converts the specified JSON dictionary into a managed object. /// /// - parameter dictionary: A dictionary representing JSON data. /// - parameter context: The context into which to fetch or insert the managed objects. /// /// - returns: A managed object. public func object<T: NSManagedObject>(fromJSONDictionary dictionary: JSONDictionary, inContext context: NSManagedObjectContext) throws -> T { let entity = T.entity(inManagedObjectContext: context) let managedObject = try object(withEntityName: entity.name!, fromJSONDictionary: dictionary, inContext: context) return managedObject as! T } public typealias JSONArray = [Any] /// Creates or updates a set of managed objects from a JSON array. /// /// - parameter name: The name of an entity. /// - parameter array: An array representing JSON data. /// - parameter context: The context into which to fetch or insert the managed objects. /// /// - returns: An array of managed objects. public func objects(withEntityName name: String, fromJSONArray array: JSONArray, inContext context: NSManagedObjectContext) throws -> [NSManagedObject] { return try GRTJSONSerialization.objects(withEntityName: name, fromJSONArray: array, in: context) } /// Creates or updates a set of managed objects from a JSON array. /// /// - parameter array: An array representing JSON data. /// - parameter context: The context into which to fetch or insert the managed objects. /// /// - returns: An array of managed objects. public func objects<T: NSManagedObject>(fromJSONArray array: JSONArray, inContext context: NSManagedObjectContext) throws -> [T] { let entity = T.entity(inManagedObjectContext: context) let managedObjects = try objects(withEntityName: entity.name!, fromJSONArray: array, inContext: context) return managedObjects as! [T] } /// Converts a managed object into a JSON representation. /// /// - parameter object: The managed object to use for JSON serialization. /// /// - returns: A JSON dictionary. public func json(fromObject object: NSManagedObject) -> JSONDictionary { return GRTJSONSerialization.jsonDictionary(from: object) as! JSONDictionary; } /// Converts an array of managed objects into a JSON representation. /// /// - parameter objects: The array of managed objects to use for JSON serialization. /// /// - returns: A JSON array. public func json(fromObjects objects: [NSManagedObject]) -> JSONArray { return GRTJSONSerialization.jsonArray(from: objects) }
mit
86ec53a4e9dd751e4991771c82d33d4d
41.102564
165
0.735079
4.811722
false
false
false
false
Pretz/SwiftGraphics
SwiftGraphics/Geometry/Triangle.swift
2
5843
// // Geometry+Triangle.swift // SwiftGraphics // // Created by Jonathan Wight on 1/16/15. // Copyright (c) 2015 schwa.io. All rights reserved. // import CoreGraphics import SwiftUtilities public struct Triangle { public let vertex: (CGPoint, CGPoint, CGPoint) public init(_ p0: CGPoint, _ p1: CGPoint, _ p2: CGPoint) { self.vertex = (p0, p1, p2) } } public extension Triangle { /** Convenience initializer creating trangle from points in a rect. p0 is top middle, p1 and p2 are bottom left and bottom right */ init(rect: CGRect, rotation: CGFloat = 0.0) { var p0 = rect.midXMinY var p1 = rect.minXMaxY var p2 = rect.maxXMaxY if rotation != 0.0 { let mid = rect.mid let transform = CGAffineTransform(rotation: rotation, origin: mid) p0 *= transform p1 *= transform p2 *= transform } self.vertex = (p0, p1, p2) } } public extension Triangle { init(points: [CGPoint]) { assert(points.count == 3) self.vertex = (points[0], points[1], points[2]) } public var pointsArray: [CGPoint] { return [vertex.0, vertex.1, vertex.2] } } public extension Triangle { public var lengths: (CGFloat, CGFloat, CGFloat) { return ( (vertex.0 - vertex.1).magnitude, (vertex.1 - vertex.2).magnitude, (vertex.2 - vertex.0).magnitude ) } public var angles: (CGFloat, CGFloat, CGFloat) { let a1 = angle(vertex.0, vertex.1, vertex.2) let a2 = angle(vertex.1, vertex.2, vertex.0) let a3 = DegreesToRadians(180) - a1 - a2 return (a1,a2,a3) } public var isEquilateral: Bool { return equalities(self.lengths, test: { $0 ==% $1 }) == 3 } public var isIsosceles: Bool { return equalities(self.lengths, test: { $0 ==% $1 }) == 2 } public var isScalene: Bool { return equalities(self.lengths, test: { $0 ==% $1 }) == 1 } public var isRightAngled: Bool { let a = self.angles let rightAngle = CGFloat(0.5 * M_PI) return a.0 ==% rightAngle || a.1 ==% rightAngle || a.2 ==% rightAngle } public var isOblique: Bool { return isRightAngled == false } public var isAcute: Bool { let a = self.angles let rightAngle = CGFloat(0.5 * M_PI) return a.0 < rightAngle && a.1 < rightAngle && a.2 < rightAngle } public var isObtuse: Bool { let a = self.angles let rightAngle = CGFloat(0.5 * M_PI) return a.0 > rightAngle || a.1 > rightAngle || a.2 > rightAngle } public var isDegenerate: Bool { let a = self.angles let r180 = CGFloat(M_PI) return a.0 ==% r180 || a.1 ==% r180 || a.2 ==% r180 } public var signedArea: CGFloat { let (a, b, c) = vertex let signedArea = 0.5 * ( a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y) ) return signedArea } public var area: CGFloat { return abs(signedArea) } // https: //en.wikipedia.org/wiki/Circumscribed_circle public var circumcenter : CGPoint { let (a, b, c) = vertex let D = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y)) let a2 = a.x ** 2 + a.y ** 2 let b2 = b.x ** 2 + b.y ** 2 let c2 = c.x ** 2 + c.y ** 2 let X = (a2 * (b.y - c.y) + b2 * (c.y - a.y) + c2 * (a.y - b.y)) / D let Y = (a2 * (c.x - b.x) + b2 * (a.x - c.x) + c2 * (b.x - a.x)) / D return CGPoint(x: X, y: Y) } public var circumcircle : Circle { let (a,b,c) = lengths let diameter = (a * b * c) / (2 * area) return Circle(center: circumcenter, diameter: diameter) } public var inradius : CGFloat { let (a, b, c) = lengths return 2 * area / (a + b + c) } } // Cartesian coordinates public extension Triangle { public var incenter : CGPoint { let (oppositeC, oppositeA, oppositeB) = lengths let (a, b, c) = vertex let x = (oppositeA * a.x + oppositeB * b.x + oppositeC * c.x) / (oppositeC + oppositeB + oppositeA) let y = (oppositeA * a.y + oppositeB * b.y + oppositeC * c.y) / (oppositeC + oppositeB + oppositeA) return CGPointMake(x, y) } // converts trilinear coordinates to Cartesian coordinates relative // to the incenter; thus, the incenter has coordinates (0.0, 0.0) public func toLocalCartesian(alpha alpha: CGFloat, beta: CGFloat, gamma: CGFloat) -> CGPoint { let area = self.area let (a,b,c) = lengths let r = 2 * area / (a + b + c) let k = 2 * area / (a * alpha + b * beta + c * gamma) let C = angles.2 let x = (k * beta - r + (k * alpha - r) * cos(C)) / sin(C) let y = k * alpha - r return CGPoint(x: x, y: y) } // TODO: This seems broken! --- validate that this is still needed.. public func toCartesian(alpha alpha: CGFloat, beta: CGFloat, gamma: CGFloat) -> CGPoint { let a = toLocalCartesian(alpha: alpha, beta: beta, gamma: gamma) let delta = toLocalCartesian(alpha: 0,beta: 0, gamma: 1) return vertex.0 + a - delta } } // MARK: Utilities func equalities <T> (e: (T, T, T), test: ((T, T) -> Bool)) -> Int { var c = 1 if test(e.0, e.1) { c++ } if test(e.1, e.2) { c++ } if test(e.2, e.0) { c++ } return min(c, 3) } extension Triangle: Geometry { public var frame: CGRect { // TODO faster to just do min/maxes return CGRect.unionOfPoints([vertex.0, vertex.1, vertex.2]) } }
bsd-2-clause
cb3f031967ae4836da8f7cf001f22157
26.561321
107
0.529865
3.302996
false
false
false
false
bengottlieb/ios
FiveCalls/FiveCalls/BlueButton.swift
1
1889
// // BlueButton.swift // FiveCalls // // Created by Patrick McCarron on 2/4/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit @IBDesignable class BlueButton: UIButton { @IBInspectable var customFontSize: CGFloat = 20 { didSet { _commonInit() } } var normalBackgroundColor: UIColor = .fvc_lightBlueBackground var highlightBackgroundColor: UIColor = .fvc_darkBlue var selectedBackgroundColor: UIColor = .fvc_darkBlue var defaultTextColor: UIColor = .white override init(frame: CGRect) { super.init(frame: frame) _commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _commonInit() } override func prepareForInterfaceBuilder() { _commonInit() } private func _commonInit() { updateColors() setTitle(titleLabel?.text?.capitalized, for: .normal) titleLabel?.font = R.font.robotoCondensedBold(size: customFontSize) layer.cornerRadius = 5 clipsToBounds = true } override var isHighlighted: Bool { didSet { updateColors() } } override var isSelected: Bool { didSet { updateColors() } } override var isEnabled: Bool { didSet { updateColors() } } func updateColors() { if isHighlighted { backgroundColor = highlightBackgroundColor } else if isSelected { backgroundColor = selectedBackgroundColor } else { backgroundColor = normalBackgroundColor } setTitleColor(.white, for: .selected) setTitleColor(.white, for: .highlighted) setTitleColor(defaultTextColor, for: .normal) titleLabel?.alpha = 1.0 alpha = isEnabled ? 1.0 : 0.5 } }
mit
9261879a0282c6b1f45a342028ea78d0
23.205128
75
0.594809
5.034667
false
false
false
false
brandhill/WeatherMap
WeatherAroundUs/WeatherAroundUs/BasicWeatherView.swift
3
8814
// // BasicWeatherView.swift // WeatherAroundUs // // Created by Wang Yu on 4/24/15. // Copyright (c) 2015 Kedan Li. All rights reserved. // import UIKit import Spring class BasicWeatherView: DesignableView, InternetConnectionDelegate { //@IBOutlet var hourForcastScrollView: UIScrollView! @IBOutlet weak var upperLine: UIImageView! @IBOutlet weak var lowerLine: UIImageView! @IBOutlet weak var scrollViewPosition: UIScrollView! var hourForcastScrollView: UIScrollView! let displayedDays: Int = 9 var parentController: CityDetailViewController! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func timeConvert(var curTime: Int) -> String { if (curTime < 12) { if curTime == 0 { curTime = 12 } return "\(curTime)AM" } else { curTime %= 12 if curTime == 0 { curTime = 12 } return "\(curTime)PM" } } var hourForcastTemperatureLabelArr = [SpringLabel]() var hourForcastTemperatureIntArr = [Int]() var dayForcastMinTemperatureLabelArr = [UILabel]() var dayForcastMinTemperatureIntArr = [Int]() var dayForcastMaxTemperatureLabelArr = [UILabel]() var dayForcastMaxTemperatureIntArr = [Int]() func setup(forecastInfos: [[String: AnyObject]]) { hourForcastScrollView = UIScrollView(frame: scrollViewPosition.frame) self.addSubview(hourForcastScrollView) // each daily display block height let blockHeight: CGFloat = 30 let labelFont = UIFont(name: "AvenirNext-Regular", size: 16) parentController.basicForecastViewHeight.constant = hourForcastScrollView.frame.height + CGFloat(displayedDays) * blockHeight + 50 /// set up week weather forcast let date = NSDate() let calendar = NSCalendar.currentCalendar() let component = calendar.component(NSCalendarUnit.CalendarUnitWeekday, fromDate: date) let week = [0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday"] var weekDate = [Int: String]() for var index = 0; index < displayedDays; index++ { weekDate[index] = week[(index + component - 1) % 7] } weekDate[0] = "Today" weekDate[1] = "Tomorrow" let beginY = hourForcastScrollView.frame.origin.y + hourForcastScrollView.frame.height + 8 let beginX = hourForcastScrollView.frame.origin.x for var index = 0; index < displayedDays; index++ { var backView = SpringView(frame: CGRectMake(beginX, beginY + CGFloat(index) * blockHeight, hourForcastScrollView.frame.width, blockHeight)) self.addSubview(backView) var dateLabel = UILabel(frame: CGRectMake(0, 0, 100, blockHeight)) dateLabel.text = weekDate[index] dateLabel.textColor = UIColor.whiteColor() dateLabel.textAlignment = .Left dateLabel.font = labelFont backView.addSubview(dateLabel) var maxTempLabel = UILabel(frame: CGRectMake(backView.frame.width - 90, 0, 50, blockHeight)) maxTempLabel.textColor = UIColor.whiteColor() maxTempLabel.textAlignment = .Right maxTempLabel.font = labelFont let maxTemp = (forecastInfos[index]["temp"] as! [String: AnyObject])["max"]!.doubleValue maxTempLabel.text = "\(WeatherMapCalculations.kelvinConvert(maxTemp, unit: parentController.unit))°" backView.addSubview(maxTempLabel) dayForcastMaxTemperatureIntArr.append(Int(round(maxTemp))) dayForcastMaxTemperatureLabelArr.append(maxTempLabel) var minTempLabel = UILabel(frame: CGRectMake(backView.frame.width - 50, 0, 50, blockHeight)) minTempLabel.textColor = UIColor(hex: "#ADD8E6") minTempLabel.textAlignment = .Right minTempLabel.font = labelFont let minTemp = (forecastInfos[index]["temp"] as! [String: AnyObject])["min"]!.doubleValue minTempLabel.text = "\(WeatherMapCalculations.kelvinConvert(minTemp, unit: parentController.unit))°" backView.addSubview(minTempLabel) dayForcastMinTemperatureIntArr.append(Int(round(minTemp))) dayForcastMinTemperatureLabelArr.append(minTempLabel) var weatherIcon = UIImageView(frame: CGRect(x: backView.frame.width/2 - 10, y: 4, width: blockHeight - 8, height: blockHeight - 8)) let iconString = ((forecastInfos[index]["weather"] as! [AnyObject])[0] as! [String: AnyObject])["icon"] as! String weatherIcon.image = UIImage(named: iconString) backView.addSubview(weatherIcon) backView.animation = "fadeIn" backView.delay = 0.1 * CGFloat(index) backView.animate() } // get three hour forcast data var connection = InternetConnection() connection.delegate = self connection.getThreeHourForcast(parentController.cityID) } func gotThreeHourForcastData(cityID: String, forcast: [AnyObject]) { parentController.loadingIndicator.stopAnimating() /// set up scroll view daily forcast let hourItemViewWidth: CGFloat = 40 let numOfDailyWeatherForcast = forcast.count hourForcastScrollView.contentSize = CGSize(width: hourItemViewWidth * CGFloat(numOfDailyWeatherForcast), height: hourForcastScrollView.frame.height) for var index = 0; index < numOfDailyWeatherForcast; index++ { let hourItemView = SpringView(frame: CGRectMake(hourItemViewWidth * CGFloat(index), 0, hourItemViewWidth, hourForcastScrollView.frame.height)) hourForcastScrollView.addSubview(hourItemView) var timeData = (forcast[index]["dt_txt"]) as! String timeData = timeData.substringWithRange(Range<String.Index>(start: advance(timeData.startIndex, 11), end: advance(timeData.endIndex, -6))) let curTime = timeData.toInt() let hourTimeLabel = SpringLabel(frame: CGRectMake(0, 5, hourItemViewWidth, 20)) hourTimeLabel.font = UIFont(name: "AvenirNext-Regular", size: 12) hourTimeLabel.text = "\(timeConvert(curTime!))" hourTimeLabel.textColor = UIColor.whiteColor() hourTimeLabel.textAlignment = .Center hourItemView.addSubview(hourTimeLabel) let iconString = ((forcast[index]["weather"] as! [AnyObject])[0] as! [String: AnyObject])["icon"] as! String let hourImageIcon = SpringImageView(frame: CGRectMake(0, hourTimeLabel.frame.origin.y + hourTimeLabel.frame.height, hourItemViewWidth, 20)) hourImageIcon.image = UIImage(named: iconString) hourImageIcon.contentMode = UIViewContentMode.ScaleAspectFit hourItemView.addSubview(hourImageIcon) let temp = (forcast[index]["main"] as! [String: AnyObject])["temp"]!.doubleValue let hourTemperatureLabel = SpringLabel(frame: CGRectMake(0, hourImageIcon.frame.origin.y + hourImageIcon.frame.height, hourItemViewWidth, 20)) hourTemperatureLabel.font = UIFont(name: "AvenirNext-Regular", size: 12) hourTemperatureLabel.textColor = UIColor.whiteColor() hourTemperatureLabel.textAlignment = .Center hourTemperatureLabel.text = "\(WeatherMapCalculations.kelvinConvert(temp, unit: parentController.unit))°" hourItemView.addSubview(hourTemperatureLabel) //hourItemView.animation = "fadeIn" //hourItemView.delay = 0.1 * CGFloat(index) //hourItemView.animate() hourForcastTemperatureLabelArr.append(hourTemperatureLabel) hourForcastTemperatureIntArr.append(Int(round(temp))) } } func reloadTempatureContent() { for var index = 0; index < hourForcastTemperatureLabelArr.count; index++ { hourForcastTemperatureLabelArr[index].text = "\(WeatherMapCalculations.kelvinConvert(hourForcastTemperatureIntArr[index], unit: parentController.unit))°" } for var index = 0; index < dayForcastMaxTemperatureLabelArr.count; index++ { dayForcastMaxTemperatureLabelArr[index].text = "\(WeatherMapCalculations.kelvinConvert(dayForcastMaxTemperatureIntArr[index], unit: parentController.unit))°" dayForcastMinTemperatureLabelArr[index].text = "\(WeatherMapCalculations.kelvinConvert(dayForcastMinTemperatureIntArr[index], unit: parentController.unit))°" } } }
apache-2.0
3017e71f73fa2822a99041afdc828cc8
47.662983
169
0.652134
4.643121
false
false
false
false
amnuaym/TiAppBuilder
Day8/MyCloudNoteApp/MyCloudNoteApp/CloudNoteListViewController.swift
1
5590
// // CloudNoteListViewController.swift // MyCloudNoteApp // // Created by DrKeng on 9/30/2560 BE. // Copyright © 2560 ANT. All rights reserved. // import UIKit import CloudKit class CloudNoteListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ //AM: Array to collect data loaded from Cloud var notesList : [CKRecord]? = [] @IBOutlet weak var myTableView: UITableView! func fetchNotesListFromiCloud(){ //AM: Create Variable named Container and specify Database let container = CKContainer.default() let privateDatabase = container.privateCloudDatabase // let publicDatabase = container.publicCloudDatabase // let sharedDatabase = container.sharedCloudDatabase let myPredicate = NSPredicate(value: true) //AM: Create Query variable let myQuery = CKQuery(recordType: "MyNotes", predicate: myPredicate) privateDatabase.perform(myQuery, inZoneWith: nil) { (results, error) in if error != nil{ print(error!) }else{ print(results!) OperationQueue.main.addOperation { self.notesList!.removeAll() for result in results!{ self.notesList?.append(result) } self.myTableView.reloadData() } } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "My iCloud Note" myTableView.dataSource = self myTableView.delegate = self } override func viewWillAppear(_ animated: Bool) { self.fetchNotesListFromiCloud() } // MARK: - Table view data source func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return notesList!.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let noteRecord : CKRecord = notesList![indexPath.row] // Configure the cell... //Date and time for note last save let dateFormatter : DateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM-dd-yyyy HH:mm:ss" let postedDate = dateFormatter.string(from: (noteRecord.value(forKey: "noteEditedDate") as! Date)) cell.textLabel?.text = noteRecord.value(forKey: "noteTitle") as? String cell.detailTextLabel?.text = "Posted at \(postedDate)" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 65.0 } // Override to support conditional editing of the table view. func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { //AM: create variable to point to RecordID we want to delete let deleteRecordID = notesList![indexPath.row].recordID //AM: Create variable to specify Container and Database we want to delete let container = CKContainer.default() let privateDatabase = container.privateCloudDatabase privateDatabase.delete(withRecordID: deleteRecordID, completionHandler: { (recordID, error) in if error != nil{ print(error!) }else{ OperationQueue.main.addOperation { self.notesList!.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .right) } } }) } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ //MARK: Prepare for Segue //In a storyboard based application, you will often need to do a little preparation before navigation // override func prepareForInterfaceBuilder() { // <#code#> // } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "editNoteSqgue"{ let indexPath = myTableView.indexPathForSelectedRow! let myVC = segue.destination as! AddNewNoteViewController myVC.editedNoteRecord = notesList![indexPath.row] } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
5d556dc59ed3ce8e8ccee9ff159e363c
34.150943
127
0.62462
5.327931
false
false
false
false
SnapKit/SnapKit
Sources/ConstraintAttributes.swift
3
8609
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // 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. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif internal struct ConstraintAttributes : OptionSet, ExpressibleByIntegerLiteral { typealias IntegerLiteralType = UInt internal init(rawValue: UInt) { self.rawValue = rawValue } internal init(_ rawValue: UInt) { self.init(rawValue: rawValue) } internal init(nilLiteral: ()) { self.rawValue = 0 } internal init(integerLiteral rawValue: IntegerLiteralType) { self.init(rawValue: rawValue) } internal private(set) var rawValue: UInt internal static var allZeros: ConstraintAttributes { return 0 } internal static func convertFromNilLiteral() -> ConstraintAttributes { return 0 } internal var boolValue: Bool { return self.rawValue != 0 } internal func toRaw() -> UInt { return self.rawValue } internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) } internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) } // normal internal static let none: ConstraintAttributes = 0 internal static let left: ConstraintAttributes = ConstraintAttributes(UInt(1) << 0) internal static let top: ConstraintAttributes = ConstraintAttributes(UInt(1) << 1) internal static let right: ConstraintAttributes = ConstraintAttributes(UInt(1) << 2) internal static let bottom: ConstraintAttributes = ConstraintAttributes(UInt(1) << 3) internal static let leading: ConstraintAttributes = ConstraintAttributes(UInt(1) << 4) internal static let trailing: ConstraintAttributes = ConstraintAttributes(UInt(1) << 5) internal static let width: ConstraintAttributes = ConstraintAttributes(UInt(1) << 6) internal static let height: ConstraintAttributes = ConstraintAttributes(UInt(1) << 7) internal static let centerX: ConstraintAttributes = ConstraintAttributes(UInt(1) << 8) internal static let centerY: ConstraintAttributes = ConstraintAttributes(UInt(1) << 9) internal static let lastBaseline: ConstraintAttributes = ConstraintAttributes(UInt(1) << 10) @available(iOS 8.0, OSX 10.11, *) internal static let firstBaseline: ConstraintAttributes = ConstraintAttributes(UInt(1) << 11) @available(iOS 8.0, *) internal static let leftMargin: ConstraintAttributes = ConstraintAttributes(UInt(1) << 12) @available(iOS 8.0, *) internal static let rightMargin: ConstraintAttributes = ConstraintAttributes(UInt(1) << 13) @available(iOS 8.0, *) internal static let topMargin: ConstraintAttributes = ConstraintAttributes(UInt(1) << 14) @available(iOS 8.0, *) internal static let bottomMargin: ConstraintAttributes = ConstraintAttributes(UInt(1) << 15) @available(iOS 8.0, *) internal static let leadingMargin: ConstraintAttributes = ConstraintAttributes(UInt(1) << 16) @available(iOS 8.0, *) internal static let trailingMargin: ConstraintAttributes = ConstraintAttributes(UInt(1) << 17) @available(iOS 8.0, *) internal static let centerXWithinMargins: ConstraintAttributes = ConstraintAttributes(UInt(1) << 18) @available(iOS 8.0, *) internal static let centerYWithinMargins: ConstraintAttributes = ConstraintAttributes(UInt(1) << 19) // aggregates internal static let edges: ConstraintAttributes = [.horizontalEdges, .verticalEdges] internal static let horizontalEdges: ConstraintAttributes = [.left, .right] internal static let verticalEdges: ConstraintAttributes = [.top, .bottom] internal static let directionalEdges: ConstraintAttributes = [.directionalHorizontalEdges, .directionalVerticalEdges] internal static let directionalHorizontalEdges: ConstraintAttributes = [.leading, .trailing] internal static let directionalVerticalEdges: ConstraintAttributes = [.top, .bottom] internal static let size: ConstraintAttributes = [.width, .height] internal static let center: ConstraintAttributes = [.centerX, .centerY] @available(iOS 8.0, *) internal static let margins: ConstraintAttributes = [.leftMargin, .topMargin, .rightMargin, .bottomMargin] @available(iOS 8.0, *) internal static let directionalMargins: ConstraintAttributes = [.leadingMargin, .topMargin, .trailingMargin, .bottomMargin] @available(iOS 8.0, *) internal static let centerWithinMargins: ConstraintAttributes = [.centerXWithinMargins, .centerYWithinMargins] internal var layoutAttributes:[LayoutAttribute] { var attrs = [LayoutAttribute]() if (self.contains(ConstraintAttributes.left)) { attrs.append(.left) } if (self.contains(ConstraintAttributes.top)) { attrs.append(.top) } if (self.contains(ConstraintAttributes.right)) { attrs.append(.right) } if (self.contains(ConstraintAttributes.bottom)) { attrs.append(.bottom) } if (self.contains(ConstraintAttributes.leading)) { attrs.append(.leading) } if (self.contains(ConstraintAttributes.trailing)) { attrs.append(.trailing) } if (self.contains(ConstraintAttributes.width)) { attrs.append(.width) } if (self.contains(ConstraintAttributes.height)) { attrs.append(.height) } if (self.contains(ConstraintAttributes.centerX)) { attrs.append(.centerX) } if (self.contains(ConstraintAttributes.centerY)) { attrs.append(.centerY) } if (self.contains(ConstraintAttributes.lastBaseline)) { attrs.append(.lastBaseline) } #if os(iOS) || os(tvOS) if (self.contains(ConstraintAttributes.firstBaseline)) { attrs.append(.firstBaseline) } if (self.contains(ConstraintAttributes.leftMargin)) { attrs.append(.leftMargin) } if (self.contains(ConstraintAttributes.rightMargin)) { attrs.append(.rightMargin) } if (self.contains(ConstraintAttributes.topMargin)) { attrs.append(.topMargin) } if (self.contains(ConstraintAttributes.bottomMargin)) { attrs.append(.bottomMargin) } if (self.contains(ConstraintAttributes.leadingMargin)) { attrs.append(.leadingMargin) } if (self.contains(ConstraintAttributes.trailingMargin)) { attrs.append(.trailingMargin) } if (self.contains(ConstraintAttributes.centerXWithinMargins)) { attrs.append(.centerXWithinMargins) } if (self.contains(ConstraintAttributes.centerYWithinMargins)) { attrs.append(.centerYWithinMargins) } #endif return attrs } } internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes { return left.union(right) } internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.formUnion(right) } internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) { left.subtract(right) } internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool { return left.rawValue == right.rawValue }
mit
10de65684aae2f04a2409c95abbbf9a9
41.408867
127
0.68289
5.03156
false
false
false
false
ianyh/Highball
Highball/Modules/Posts/PostsViewController.swift
1
10796
// // PostsViewController.swift // Highball // // Created by Ian Ynda-Hummel on 10/26/14. // Copyright (c) 2014 ianynda. All rights reserved. // import Cartography import FontAwesomeKit import SafariServices import UIKit import XExtensionItem public protocol PostsView: class { var tableView: UITableView! { get } var refreshControl: UIRefreshControl? { get } var tableViewAdapter: PostsTableViewAdapter? { get } func presentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) } public extension PostsView { public func currentWidth() -> CGFloat { return tableView.frame.width } public func finishRefreshing() { refreshControl?.endRefreshing() } public func reloadWithNewIndices(indexSet: NSIndexSet?) { guard let indexSet = indexSet else { tableView.reloadData() return } tableViewAdapter?.resetCache() // Gross UIView.setAnimationsEnabled(false) tableView.insertSections(indexSet, withRowAnimation: UITableViewRowAnimation.None) UIView.setAnimationsEnabled(true) guard indexSet.firstIndex == 0 else { return } guard let originalCellIndexPath = tableView.indexPathsForVisibleRows?.first else { return } let originalRow = originalCellIndexPath.row let newSection = originalCellIndexPath.section + indexSet.count let newIndexPath = NSIndexPath(forRow: originalRow, inSection: newSection) tableView.scrollToRowAtIndexPath(newIndexPath, atScrollPosition: .Top, animated: false) let newOffset = tableView.contentOffset.y - (refreshControl?.frame.height ?? 0) tableView.contentOffset = CGPoint(x: 0, y: newOffset) } public func presentMessage(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(action) presentViewController(alertController, animated: true, completion: nil) } } extension PostsViewController: PostsView {} public class PostsViewController: UITableViewController { public weak var presenter: PostsPresenter? private let requiredRefreshDistance: CGFloat = 60 private var longPressGestureRecognizer: UILongPressGestureRecognizer! private var panGestureRecognizer: UIPanGestureRecognizer! private var reblogViewController: QuickReblogViewController? public let postHeightCache: PostHeightCache public private(set) var tableViewAdapter: PostsTableViewAdapter? public init(postHeightCache: PostHeightCache) { self.postHeightCache = postHeightCache super.init(style: .Plain) } public required init?(coder aDecoder: NSCoder) { fatalError() } public override func viewDidLoad() { super.viewDidLoad() tableViewAdapter = PostsTableViewAdapter( tableView: tableView, postHeightCache: postHeightCache, delegate: self ) longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(didLongPress(_:))) longPressGestureRecognizer.delegate = self longPressGestureRecognizer.minimumPressDuration = 0.3 if let gestureRecognizers = view.gestureRecognizers { for gestureRecognizer in gestureRecognizers { guard let gestureRecognizer = gestureRecognizer as? UILongPressGestureRecognizer else { continue } gestureRecognizer.requireGestureRecognizerToFail(longPressGestureRecognizer) } } view.addGestureRecognizer(longPressGestureRecognizer) panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(didPan(_:))) panGestureRecognizer.delegate = self view.addGestureRecognizer(panGestureRecognizer) refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(refresh(_:)), forControlEvents: .ValueChanged) } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) presenter?.viewDidAppear() } public func refresh(sender: UIRefreshControl) { presenter?.viewDidRefresh() } } // MARK: Quick Reblog public extension PostsViewController { public func didLongPress(sender: UILongPressGestureRecognizer) { if sender.state == UIGestureRecognizerState.Began { longPressDidBegin(sender) } else if sender.state == UIGestureRecognizerState.Ended { longPressDidEnd(sender) } } public func longPressDidBegin(gestureRecognizer: UILongPressGestureRecognizer) { tableView.scrollEnabled = false let point = gestureRecognizer.locationInView(navigationController!.tabBarController!.view) let collectionViewPoint = gestureRecognizer.locationInView(tableView) guard let indexPath = tableView.indexPathForRowAtPoint(collectionViewPoint) where tableView.cellForRowAtIndexPath(indexPath) != nil else { return } guard let post = presenter?.postAtIndex(indexPath.section) else { return } let viewController = QuickReblogViewController() viewController.startingPoint = point viewController.post = post viewController.transitioningDelegate = self viewController.modalPresentationStyle = UIModalPresentationStyle.Custom viewController.view.bounds = navigationController!.tabBarController!.view.bounds navigationController!.tabBarController!.view.addSubview(viewController.view) viewController.view.layoutIfNeeded() viewController.viewDidAppear(false) reblogViewController = viewController } public func longPressDidEnd(gestureRecognizer: UILongPressGestureRecognizer) { tableView.scrollEnabled = true defer { reblogViewController = nil } guard let viewController = reblogViewController else { return } let point = viewController.startingPoint let collectionViewPoint = tableView.convertPoint(point, fromView: navigationController!.tabBarController!.view) defer { viewController.view.removeFromSuperview() } guard let indexPath = tableView.indexPathForRowAtPoint(collectionViewPoint), cell = tableView.cellForRowAtIndexPath(indexPath) else { return } guard let post = presenter?.postAtIndex(indexPath.section), quickReblogAction = viewController.reblogAction() else { return } switch quickReblogAction { case .Reblog(let reblogType): let reblogViewController = TextReblogViewController( post: post, reblogType: reblogType, blogName: AccountsService.account.primaryBlog.name, postHeightCache: postHeightCache ) let sourceRect = view.convertRect(cell.bounds, fromView: cell) let presentationViewController = reblogViewController.controllerToPresent(fromView: view, rect: sourceRect) presentViewController(presentationViewController, animated: true, completion: nil) case .Share: let extensionItemSource = XExtensionItemSource(URL: post.url) var additionalAttachments: [AnyObject] = post.photos.map { $0.urlWithWidth(CGFloat.max) } if let photosetCell = cell as? PhotosetRowTableViewCell, image = photosetCell.imageAtPoint(view.convertPoint(point, toView: cell)) { additionalAttachments.append(image) } extensionItemSource.additionalAttachments = additionalAttachments let activityViewController = UIActivityViewController(activityItems: [extensionItemSource], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = cell activityViewController.popoverPresentationController?.sourceRect = CGRect(origin: cell.center, size: CGSize(width: 1, height: 1)) presentViewController(activityViewController, animated: true, completion: nil) case .Like: presenter?.toggleLikeForPostAtIndex(indexPath.section) } } func didPan(sender: UIPanGestureRecognizer) { guard let viewController = reblogViewController else { return } viewController.updateWithPoint(sender.locationInView(viewController.view)) } } // MARK: UIGestureRecognizerDelegate extension PostsViewController: UIGestureRecognizerDelegate { public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } // MARK: UIViewControllerTransitioningDelegate extension PostsViewController: UIViewControllerTransitioningDelegate { public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return ReblogTransitionAnimator() } public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { let animator = ReblogTransitionAnimator() animator.presenting = false return animator } } // MARK: TagsTableViewCellDelegate extension PostsViewController: TagsTableViewCellDelegate { public func tagsTableViewCell(cell: TagsTableViewCell, didSelectTag tag: String) { let tagModule = TagModule(tag: tag, postHeightCache: postHeightCache) tagModule.installInNavigationController(navigationController!) } } extension PostsViewController: PostsTableViewAdapterDelegate { public func numberOfPostsForAdapter(adapter: PostsTableViewAdapter) -> Int { return presenter?.numberOfPosts() ?? 0 } public func postAdapter(adapter: PostsTableViewAdapter, sectionAdapterAtIndex index: Int) -> PostSectionAdapter { let post = presenter!.postAtIndex(index) return PostSectionAdapter(post: post) } public func adapter(adapter: PostsTableViewAdapter, didSelectImageForPostAtIndex index: Int) { let viewController = ImagesViewController() let post = presenter!.postAtIndex(index) viewController.post = post presentViewController(viewController, animated: true, completion: nil) } public func adapter(adapter: PostsTableViewAdapter, didSelectURLForPostAtIndex index: Int) { let post = presenter!.postAtIndex(index) navigationController?.pushViewController(SFSafariViewController(URL: post.url), animated: true) } public func adapter(adapter: PostsTableViewAdapter, didSelectBlogName blogName: String) { let blogModule = BlogModule(blogName: blogName, postHeightCache: postHeightCache) blogModule.installInNavigationController(navigationController!) } public func adapter(adapter: PostsTableViewAdapter, didSelectTag tag: String) { let tagModule = TagModule(tag: tag, postHeightCache: postHeightCache) tagModule.installInNavigationController(navigationController!) } public func adapter(adapter: PostsTableViewAdapter, didEmitViewController viewController: UIViewController, forPresentation presented: Bool) { if presented { presentViewController(viewController, animated: true, completion: nil) } else { navigationController?.pushViewController(viewController, animated: true) } } public func adapterDidEncounterLoadMoreBoundary(adapter: PostsTableViewAdapter) { presenter?.didEncounterLoadMoreBoundary() } }
mit
2eb0c053ae4b5e5c2e1a7c788b3f35b1
32.320988
221
0.797518
4.826106
false
false
false
false
amcnary/cs147_instagator
instagator-prototype/instagator-prototype/PollVoteViewController.swift
1
4238
// // PollVoteViewController.swift // instagator-prototype // // Created by Amanda McNary on 11/29/15. // Copyright © 2015 ThePenguins. All rights reserved. // // TODO: make cells reorderable import Foundation import UIKit protocol PollVoteViewControllerDelegate { func pollVoteViewControllerSubmitPressed(pollVoteViewController: PollVoteViewController) } class PollVoteViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: Interface Outlets @IBOutlet weak var pollVoteTitleLabel: UILabel! @IBOutlet weak var pollOptionsTableView: UITableView! // MARK: other variables var poll: Poll? var delegate: PollVoteViewControllerDelegate? // MARK: lifecycle override func viewDidLoad() { let pollActivityOptionNib = UINib(nibName: PollOptionTableViewCell.reuseIdentifier, bundle: nil) self.pollOptionsTableView.registerNib(pollActivityOptionNib, forCellReuseIdentifier: PollOptionTableViewCell.reuseIdentifier) if let unwrappedPoll = poll { self.pollVoteTitleLabel.text = "Vote on \(unwrappedPoll.Name)" } self.pollOptionsTableView.tableFooterView = UIView(frame: CGRectZero) self.pollOptionsTableView.editing = true super.viewDidLoad() } // MARK: UITableViewDataSource protocol func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let unwrappedPoll = self.poll, cell = tableView.dequeueReusableCellWithIdentifier( PollOptionTableViewCell.reuseIdentifier, forIndexPath: indexPath) as? PollOptionTableViewCell { let currentOption = unwrappedPoll.Options[indexPath.row] cell.activityNameLabel.text = "\(indexPath.row + 1). \(currentOption.Name)" let startTime = dateTimeFormatter.stringFromDate(currentOption.StartDate) let endTime = dateTimeFormatter.stringFromDate(currentOption.EndDate) cell.activityDatesLabel.text = "\(startTime) to \(endTime)" cell.activityDescriptionLabel.text = currentOption.Description if let projectedCost = currentOption.Cost { cell.activityProjectedCostLabel.text = "$\(projectedCost)0" } return cell } return UITableViewCell() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return poll?.Options.count ?? 0 } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .None } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if let unwrappedPoll = self.poll { let eventToMove = unwrappedPoll.Options[sourceIndexPath.row] unwrappedPoll.Options.removeAtIndex(sourceIndexPath.row) unwrappedPoll.Options.insert(eventToMove, atIndex: destinationIndexPath.row) tableView.reloadData() } } // MARK: interface actions @IBAction func submitButtonTapped(sender: AnyObject) { let pollChangeAlertController = UIAlertController(title: "Warning", message: "You can only submit one poll response. Continue?", preferredStyle: .Alert) let continueAction = UIAlertAction(title: "Continue", style: .Default, handler: { _ in self.delegate?.pollVoteViewControllerSubmitPressed(self) }) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) pollChangeAlertController.addAction(cancelAction) pollChangeAlertController.addAction(continueAction) self.presentViewController(pollChangeAlertController, animated: true, completion: nil) } }
apache-2.0
1f165632d459bfb8c7fab8ab60bb08d6
39.361905
140
0.692707
5.502597
false
false
false
false
jankase/JKJSON
JKJSONTests/JSONDateTest.swift
1
3108
// // Created by Jan Kase on 31/12/15. // Copyright (c) 2015 Jan Kase. All rights reserved. // import Foundation import XCTest @testable import JKJSON class JSONDateTest: XCTestCase { typealias T = JSONDate var jsonDateString = JSONDateTest.__jsonDateString var jsonDate: NSDate = JSONDateTest.__jsonDate var newJsonDateString = JSONDateTest.__jsonNewDateSting override func setUp() { super.setUp() jsonDateString = JSONDateTest.__jsonDateString jsonDate = JSONDateTest.__jsonDate newJsonDateString = JSONDateTest.__jsonNewDateSting } func testCreation() { JSONCreateableTests<T>.testCreationFromJSONRepresentation(jsonDateString) } func testStringCreation() { JSONCreateableTests<T>.testCreationFromString(jsonDateString) } func testBadCreation() { let aMappedObject = JSONDate.instanceFromJSON("XX") XCTAssertNil(aMappedObject, "Date created even from bad input") } func testMultipleCreation() { JSONCreateableTests<T>.testCreationFromMultipleJSONRepresentation([jsonDateString, newJsonDateString]) } func testBadMultipleCreation() { let aMappedObjects = JSONDate.instancesFromJSON(["XX"]) XCTAssertNil(aMappedObjects, "Date created even from bad input") } func testEquality() { let aMappedObject = T.instanceFromJSON(JSONDateTest.__jsonDateString) XCTAssertNotNil(aMappedObject, "Mapped object not created") NSLog("Reference value : \(JSONDateTest.__jsonDate), mapped value: \(aMappedObject)") XCTAssertEqual(aMappedObject, JSONDateTest.__jsonDate, "A mapped object not equal to source") } func testEncodingDecoding() { let aData = NSMutableData() let anArchiver = NSKeyedArchiver(forWritingWithMutableData: aData) anArchiver.encodeObject(JSONDateTest.__jsonDate, forKey: "date") anArchiver.finishEncoding() let aDataForReading = aData.copy() as! NSData let anUnarchiver = NSKeyedUnarchiver(forReadingWithData: aDataForReading) let aObject = anUnarchiver.decodeObjectForKey("date") if let aJsonDate = aObject as? JSONDate { XCTAssertEqual(aJsonDate, JSONDateTest.__jsonDate, "Unarchived object does not match source object") } else { XCTFail("Failed unarchiveing object from strore") } } func testNSDateToJSON() { let aJsonDateString = JSONDateTest.__date.json XCTAssertEqual(aJsonDateString, JSONDateTest.__jsonDate.json, "JSON representation for plain NSDate is bad") } private static let __jsonDate: JSONDate = { return JSONDate(date: __date) }() private static let __date: NSDate = { let dc = NSDateComponents() dc.month = 12 dc.year = 2015 dc.day = 31 dc.hour = 12 dc.minute = 0 dc.second = 0 dc.timeZone = NSTimeZone(forSecondsFromGMT: 0) let c = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! return c.dateFromComponents(dc)! }() private static let __jsonDateString = "2015-12-31T12:00:00+00:00" as T.JSONRepresentationType private static let __jsonNewDateSting = "2016-01-01T12:00:00+00:00" as T.JSONRepresentationType }
mit
5d3eae36440475a0e478c27c530148df
31.715789
112
0.727799
4.160643
false
true
false
false
envoyproxy/envoy-mobile
test/swift/integration/CancelStreamTest.swift
2
3882
import Envoy import EnvoyEngine import Foundation import XCTest final class CancelStreamTests: XCTestCase { func testCancelStream() { let remotePort = Int.random(in: 10001...11000) // swiftlint:disable:next line_length let emhcmType = "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.EnvoyMobileHttpConnectionManager" let lefType = "type.googleapis.com/envoymobile.extensions.filters.http.local_error.LocalError" // swiftlint:disable:next line_length let pbfType = "type.googleapis.com/envoymobile.extensions.filters.http.platform_bridge.PlatformBridge" let filterName = "cancel_validation_filter" let config = """ static_resources: listeners: - name: base_api_listener address: socket_address: { protocol: TCP, address: 0.0.0.0, port_value: 10000 } api_listener: api_listener: "@type": \(emhcmType) config: stat_prefix: api_hcm route_config: name: api_router virtual_hosts: - name: api domains: ["*"] routes: - match: { prefix: "/" } route: { cluster: fake_remote } http_filters: - name: envoy.filters.http.local_error typed_config: "@type": \(lefType) - name: envoy.filters.http.platform_bridge typed_config: "@type": \(pbfType) platform_filter_name: \(filterName) - name: envoy.router typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router clusters: - name: fake_remote connect_timeout: 0.25s type: STATIC lb_policy: ROUND_ROBIN load_assignment: cluster_name: fake_remote endpoints: - lb_endpoints: - endpoint: address: socket_address: { address: 127.0.0.1, port_value: \(remotePort) } """ struct CancelValidationFilter: ResponseFilter { let expectation: XCTestExpectation func onResponseHeaders(_ headers: ResponseHeaders, endStream: Bool, streamIntel: StreamIntel) -> FilterHeadersStatus<ResponseHeaders> { return .continue(headers: headers) } func onResponseData(_ body: Data, endStream: Bool, streamIntel: StreamIntel) -> FilterDataStatus<ResponseHeaders> { return .continue(data: body) } func onResponseTrailers(_ trailers: ResponseTrailers, streamIntel: StreamIntel) -> FilterTrailersStatus<ResponseHeaders, ResponseTrailers> { return .continue(trailers: trailers) } func onError(_ error: EnvoyError, streamIntel: FinalStreamIntel) {} func onCancel(streamIntel: FinalStreamIntel) { self.expectation.fulfill() } func onComplete(streamIntel: FinalStreamIntel) {} } let runExpectation = self.expectation(description: "Run called with expected cancellation") let filterExpectation = self.expectation(description: "Filter called with cancellation") let engine = EngineBuilder(yaml: config) .addLogLevel(.trace) .addPlatformFilter( name: filterName, factory: { CancelValidationFilter(expectation: filterExpectation) } ) .build() let client = engine.streamClient() let requestHeaders = RequestHeadersBuilder(method: .get, scheme: "https", authority: "example.com", path: "/test") .addUpstreamHttpProtocol(.http2) .build() client .newStreamPrototype() .setOnCancel { _ in runExpectation.fulfill() } .start() .sendHeaders(requestHeaders, endStream: false) .cancel() XCTAssertEqual(XCTWaiter.wait(for: [filterExpectation, runExpectation], timeout: 3), .completed) engine.terminate() } }
apache-2.0
1e1ad21a55bb2c9d445c28ca46e4d373
31.35
134
0.633694
4.327759
false
true
false
false
mshhmzh/firefox-ios
Client/Application/AppDelegate.swift
2
27535
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Storage import AVFoundation import XCGLogger import MessageUI import WebImage import SwiftKeychainWrapper import LocalAuthentication private let log = Logger.browserLogger let LatestAppVersionProfileKey = "latestAppVersion" let AllowThirdPartyKeyboardsKey = "settings.allowThirdPartyKeyboards" private let InitialPingSentKey = "initialPingSent" class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var browserViewController: BrowserViewController! var rootViewController: UIViewController! weak var profile: Profile? var tabManager: TabManager! var adjustIntegration: AdjustIntegration? var foregroundStartTime = 0 weak var application: UIApplication? var launchOptions: [NSObject: AnyObject]? let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String var openInFirefoxParams: LaunchParams? = nil var appStateStore: AppStateStore! var systemBrightness: CGFloat = UIScreen.mainScreen().brightness func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Hold references to willFinishLaunching parameters for delayed app launch self.application = application self.launchOptions = launchOptions log.debug("Configuring window…") self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIConstants.AppBackgroundColor // Short circuit the app if we want to email logs from the debug menu if DebugSettingsBundleOptions.launchIntoEmailComposer { self.window?.rootViewController = UIViewController() presentEmailComposerWithLogs() return true } else { return startApplication(application, withLaunchOptions: launchOptions) } } private func startApplication(application: UIApplication, withLaunchOptions launchOptions: [NSObject: AnyObject]?) -> Bool { log.debug("Setting UA…") // Set the Firefox UA for browsing. setUserAgent() log.debug("Starting keyboard helper…") // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() log.debug("Starting dynamic font helper…") DynamicFontHelper.defaultHelper.startObserving() log.debug("Setting custom menu items…") MenuHelper.defaultHelper.setItems() log.debug("Creating Sync log file…") let logDate = NSDate() // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(logDate) log.debug("Creating Browser log file…") Logger.browserLogger.newLogWithDate(logDate) log.debug("Getting profile…") let profile = getProfile(application) appStateStore = AppStateStore(prefs: profile.prefs) log.debug("Initializing telemetry…") Telemetry.initWithPrefs(profile.prefs) if !DebugSettingsBundleOptions.disableLocalWebServer { log.debug("Starting web server…") // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) } log.debug("Setting AVAudioSession category…") do { // for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) } catch _ { log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar") } let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality) log.debug("Configuring tabManager…") self.tabManager = TabManager(prefs: profile.prefs, imageStore: imageStore) self.tabManager.stateDelegate = self // Add restoration class, the factory that will return the ViewController we // will restore with. log.debug("Initing BVC…") browserViewController = BrowserViewController(profile: self.profile!, tabManager: self.tabManager) browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self let navigationController = UINavigationController(rootViewController: browserViewController) navigationController.delegate = self navigationController.navigationBarHidden = true if AppConstants.MOZ_STATUS_BAR_NOTIFICATION { rootViewController = NotificationRootViewController(rootViewController: navigationController) } else { rootViewController = navigationController } self.window!.rootViewController = rootViewController do { log.debug("Configuring Crash Reporting...") try PLCrashReporter.sharedReporter().enableCrashReporterAndReturnError() } catch let error as NSError { log.error("Failed to enable PLCrashReporter - \(error.description)") } log.debug("Adding observers…") NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL { let title = (userInfo["Title"] as? String) ?? "" profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.currentDevice().name) } } // check to see if we started 'cos someone tapped on a notification. if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification { viewURLInNewTab(localNotification) } adjustIntegration = AdjustIntegration(profile: profile) // We need to check if the app is a clean install to use for // preventing the What's New URL from appearing. if getProfile(application).prefs.intForKey(IntroViewControllerSeenProfileKey) == nil { getProfile(application).prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } log.debug("Updating authentication keychain state to reflect system state") self.updateAuthenticationInfo() SystemUtils.onFirstRun() resetForegroundStartTime() if !(profile.prefs.boolForKey(InitialPingSentKey) ?? false) { // Try to send an initial core ping when the user first opens the app so that they're // "on the map". This lets us know they exist if they try the app once, crash, then uninstall. // sendCorePing() only sends the ping if the user is offline, so if the first ping doesn't // go through *and* the user crashes then uninstalls on the first run, then we're outta luck. profile.prefs.setBool(true, forKey: InitialPingSentKey) sendCorePing() } log.debug("Done with setting up the application.") return true } func applicationWillTerminate(application: UIApplication) { log.debug("Application will terminate.") // We have only five seconds here, so let's hope this doesn't take too long. self.profile?.shutdown() // Allow deinitializers to close our database connections. self.profile = nil self.tabManager = nil self.browserViewController = nil self.rootViewController = nil } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", app: application) self.profile = p return p } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Override point for customization after application launch. var shouldPerformAdditionalDelegateHandling = true log.debug("Did finish launching.") log.debug("Setting up Adjust") self.adjustIntegration?.triggerApplicationDidFinishLaunchingWithOptions(launchOptions) log.debug("Making window key and visible…") self.window!.makeKeyAndVisible() // Now roll logs. log.debug("Triggering log roll.") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { Logger.syncLogger.deleteOldLogsDownToSizeLimit() Logger.browserLogger.deleteOldLogsDownToSizeLimit() } if #available(iOS 9, *) { // If a shortcut was launched, display its information and take the appropriate action if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem { QuickActions.sharedInstance.launchedShortcutItem = shortcutItem // This will block "performActionForShortcutItem:completionHandler" from being called. shouldPerformAdditionalDelegateHandling = false } } log.debug("Done with applicationDidFinishLaunching.") return shouldPerformAdditionalDelegateHandling } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { guard let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) else { return false } guard let urlTypes = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleURLTypes") as? [AnyObject], urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else { // Something very strange has happened; org.mozilla.Client should be the zeroeth URL type. log.error("Custom URL schemes not available for validating") return false } guard let scheme = components.scheme where urlSchemes.contains(scheme) else { log.warning("Cannot handle \(components.scheme) URL scheme") return false } var url: String? var isPrivate: Bool = false for item in (components.queryItems ?? []) as [NSURLQueryItem] { switch item.name { case "url": url = item.value case "private": isPrivate = NSString(string: item.value ?? "false").boolValue default: () } } let params: LaunchParams if let url = url, newURL = NSURL(string: url) { params = LaunchParams(url: newURL, isPrivate: isPrivate) } else { params = LaunchParams(url: nil, isPrivate: isPrivate) } if application.applicationState == .Active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. launchFromURL(params) } else { openInFirefoxParams = params } return true } func launchFromURL(params: LaunchParams) { let isPrivate = params.isPrivate ?? false if let newURL = params.url { self.browserViewController.switchToTabForURLOrOpen(newURL, isPrivate: isPrivate) } else { self.browserViewController.openBlankNewTabAndFocus(isPrivate: isPrivate) } } func application(application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: String) -> Bool { if let thirdPartyKeyboardSettingBool = getProfile(application).prefs.boolForKey(AllowThirdPartyKeyboardsKey) where extensionPointIdentifier == UIApplicationKeyboardExtensionPointIdentifier { return thirdPartyKeyboardSettingBool } return false } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(application: UIApplication) { guard !DebugSettingsBundleOptions.launchIntoEmailComposer else { return } NightModeHelper.restoreNightModeBrightness((self.profile?.prefs)!, toForeground: true) self.profile?.syncManager.applicationDidBecomeActive() // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. self.browserViewController.loadQueuedTabs() // handle quick actions is available if #available(iOS 9, *) { let quickActions = QuickActions.sharedInstance if let shortcut = quickActions.launchedShortcutItem { // dispatch asynchronously so that BVC is all set up for handling new tabs // when we try and open them quickActions.handleShortCutItem(shortcut, withBrowserViewController: browserViewController) quickActions.launchedShortcutItem = nil } // we've removed the Last Tab option, so we should remove any quick actions that we already have that are last tabs // we do this after we've handled any quick actions that have been used to open the app so that we don't b0rk if // the user has opened the app for the first time after upgrade with a Last Tab quick action QuickActions.sharedInstance.removeDynamicApplicationShortcutItemOfType(ShortcutType.OpenLastTab, fromApplication: application) } // Check if we have a URL from an external app or extension waiting to launch, // then launch it on the main thread. if let params = openInFirefoxParams { openInFirefoxParams = nil dispatch_async(dispatch_get_main_queue()) { self.launchFromURL(params) } } } func applicationDidEnterBackground(application: UIApplication) { // Workaround for crashing in the background when <select> popovers are visible (rdar://24571325). let jsBlurSelect = "if (document.activeElement && document.activeElement.tagName === 'SELECT') { document.activeElement.blur(); }" tabManager.selectedTab?.webView?.evaluateJavaScript(jsBlurSelect, completionHandler: nil) syncOnDidEnterBackground(application: application) let elapsed = Int(NSDate().timeIntervalSince1970) - foregroundStartTime Telemetry.recordEvent(UsageTelemetry.makeEvent(elapsed)) sendCorePing() } private func syncOnDidEnterBackground(application application: UIApplication) { // Short circuit and don't sync if we don't have a syncable account. guard self.profile?.hasSyncableAccount() ?? false else { return } self.profile?.syncManager.applicationDidEnterBackground() var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTaskWithExpirationHandler { _ in log.warning("Running out of background time, but we have a profile shutdown pending.") self.profile?.shutdown() application.endBackgroundTask(taskId) } let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) self.profile?.syncManager.syncEverything().uponQueue(backgroundQueue) { _ in self.profile?.shutdown() application.endBackgroundTask(taskId) } } func applicationWillResignActive(application: UIApplication) { NightModeHelper.restoreNightModeBrightness((self.profile?.prefs)!, toForeground: false) } func applicationWillEnterForeground(application: UIApplication) { // The reason we need to call this method here instead of `applicationDidBecomeActive` // is that this method is only invoked whenever the application is entering the foreground where as // `applicationDidBecomeActive` will get called whenever the Touch ID authentication overlay disappears. self.updateAuthenticationInfo() resetForegroundStartTime() } private func resetForegroundStartTime() { foregroundStartTime = Int(NSDate().timeIntervalSince1970) } /// Send a telemetry ping if the user hasn't disabled reporting. /// We still create and log the ping for non-release channels, but we don't submit it. private func sendCorePing() { guard let profile = profile where (profile.prefs.boolForKey("settings.sendUsageData") ?? true) else { log.debug("Usage sending is disabled. Not creating core telemetry ping.") return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { // The core ping resets data counts when the ping is built, meaning we'll lose // the data if the ping doesn't go through. To minimize loss, we only send the // core ping if we have an active connection. Until we implement a fault-handling // telemetry layer that can resend pings, this is the best we can do. guard DeviceInfo.hasConnectivity() else { log.debug("No connectivity. Not creating core telemetry ping.") return } let ping = CorePing(profile: profile) Telemetry.sendPing(ping) } } private func updateAuthenticationInfo() { if let authInfo = KeychainWrapper.authenticationInfo() { if !LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) { authInfo.useTouchID = false KeychainWrapper.setAuthenticationInfo(authInfo) } } } private func setUpWebServer(profile: Profile) { let server = WebServer.sharedInstance ReaderModeHandlers.register(server, profile: profile) ErrorPageHelper.register(server, certStore: profile.certStore) AboutHomeHandler.register(server) AboutLicenseHandler.register(server) // Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task // catching and handling the error seemed to fix things, but we're not sure why. // Either way, not implicitly unwrapping a try is not a great way of doing things // so this is better anyway. do { try server.start() } catch let err as NSError { log.error("Unable to start WebServer \(err)") } } private func setUserAgent() { let firefoxUA = UserAgent.defaultUserAgent() // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. Note that we use defaults here that are // readable from extensions, so they can just use the cached identifier. let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())! defaults.registerDefaults(["UserAgent": firefoxUA]) SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent") // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA // Some sites will only serve HTML that points to .ico files. // The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent. FaviconFetcher.userAgent = UserAgent.desktopUserAgent() } func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) { if let actionId = identifier { if let action = SentTabAction(rawValue: actionId) { viewURLInNewTab(notification) switch(action) { case .Bookmark: addBookmark(notification) break case .ReadingList: addToReadingList(notification) break default: break } } else { print("ERROR: Unknown notification action received") } } else { print("ERROR: Unknown notification received") } } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { viewURLInNewTab(notification) } private func presentEmailComposerWithLogs() { if let buildNumber = NSBundle.mainBundle().objectForInfoDictionaryKey(String(kCFBundleVersionKey)) as? NSString { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setSubject("Debug Info for iOS client version v\(appVersion) (\(buildNumber))") if DebugSettingsBundleOptions.attachLogsToDebugEmail { do { let logNamesAndData = try Logger.diskLogFilenamesAndData() logNamesAndData.forEach { nameAndData in if let data = nameAndData.1 { mailComposeViewController.addAttachmentData(data, mimeType: "text/plain", fileName: nameAndData.0) } } } catch _ { print("Failed to retrieve logs from device") } } if DebugSettingsBundleOptions.attachTabStateToDebugEmail { if let tabStateDebugData = TabManager.tabRestorationDebugInfo().dataUsingEncoding(NSUTF8StringEncoding) { mailComposeViewController.addAttachmentData(tabStateDebugData, mimeType: "text/plain", fileName: "tabState.txt") } if let tabStateData = TabManager.tabArchiveData() { mailComposeViewController.addAttachmentData(tabStateData, mimeType: "application/octet-stream", fileName: "tabsState.archive") } } self.window?.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil) } } func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool { if let url = userActivity.webpageURL { browserViewController.switchToTabForURLOrOpen(url) return true } return false } private func viewURLInNewTab(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String { if let urlToOpen = NSURL(string: alertURL) { browserViewController.openURLInNewTab(urlToOpen) } } } private func addBookmark(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { let tabState = TabState(isPrivate: false, desktopSite: false, isBookmarked: false, url: NSURL(string: alertURL), title: title, favicon: nil) browserViewController.addBookmark(tabState) if #available(iOS 9, *) { let userData = [QuickActions.TabURLKey: alertURL, QuickActions.TabTitleKey: title] QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.OpenLastBookmark, withUserData: userData, toApplication: UIApplication.sharedApplication()) } } } private func addToReadingList(notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { if let urlToOpen = NSURL(string: alertURL) { NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title]) } } } @available(iOS 9.0, *) func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) { let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: browserViewController) completionHandler(handledShortCutItem) } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.Push { return BrowserToTrayAnimator() } else if operation == UINavigationControllerOperation.Pop { return TrayToBrowserAnimator() } else { return nil } } } extension AppDelegate: TabManagerStateDelegate { func tabManagerWillStoreTabs(tabs: [Tab]) { // It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL. let storedTabs: [RemoteTab] = tabs.flatMap( Tab.toTab ) // Don't insert into the DB immediately. We tend to contend with more important // work like querying for top sites. let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(ProfileRemoteTabsSyncDelay * Double(NSEC_PER_MSEC))), queue) { self.profile?.storeTabs(storedTabs) } } } extension AppDelegate: MFMailComposeViewControllerDelegate { func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { // Dismiss the view controller and start the app up controller.dismissViewControllerAnimated(true, completion: nil) startApplication(application!, withLaunchOptions: self.launchOptions) } } struct LaunchParams { let url: NSURL? let isPrivate: Bool? }
mpl-2.0
ae23f05a58eb77277790d768fac96791
43.796417
198
0.673841
5.643209
false
false
false
false
remobjects/Marzipan
CodeGen4/CGCodeGenerator.swift
1
60912
public __abstract class CGCodeGenerator { internal var currentUnit: CGCodeUnit! internal var tabSize = 2 internal var useTabs = false internal var definitionOnly = false internal var keywords: List<String>? internal var keywordsAreCaseSensitive = true // keywords List must be lowercase when this is set to false internal var codeCompletionMode = false override public init() { } // // Public APIS // public __abstract var defaultFileExtension: String { get } public var omitNamespacePrefixes: Boolean = false public var splitLinesLongerThan: Integer = 2048 public final func GenerateUnit(_ unit: CGCodeUnit) -> String { // overload for VC# compastibility return GenerateUnit(unit, definitionOnly: false) } public final func GenerateUnit(_ unit: CGCodeUnit, definitionOnly: Boolean /*= false*/) -> String { currentUnit = unit currentCode = StringBuilder() self.definitionOnly = definitionOnly generateAll() return currentCode.ToString() } // // Additional public APIs used by IDE Smarts & Co // public final func GenerateUnitForSingleType(_ type: CGTypeDefinition, unit: CGCodeUnit? = nil) -> String { currentUnit = unit currentCode = StringBuilder() definitionOnly = false generateHeader() generateDirectives() generateImports() if type is CGGlobalTypeDefinition { generateGlobals() } else { generateTypeDefinition(type) } generateFooter() return currentCode.ToString() } public final func GenerateType(_ type: CGTypeDefinition, unit: CGCodeUnit? = nil) -> String { currentUnit = unit currentCode = StringBuilder() definitionOnly = false if type is CGGlobalTypeDefinition { generateGlobals() } else { generateTypeDefinition(type) } return currentCode.ToString() } public final func GenerateTypeDefinitionOnly(_ type: CGTypeDefinition, unit: CGCodeUnit? = nil) -> String { currentUnit = unit currentCode = StringBuilder() definitionOnly = true if type is CGGlobalTypeDefinition { generateGlobals() } else { generateTypeDefinition(type) } return currentCode.ToString() } public final func GenerateMember(_ member: CGMemberDefinition, type: CGTypeDefinition?, unit: CGCodeUnit? = nil) -> String { return doGenerateMember(member, type: type, unit: unit, definitionOnly: false) } public final func GenerateMemberDefinition(_ member: CGMemberDefinition, type: CGTypeDefinition?, unit: CGCodeUnit? = nil) -> String { return doGenerateMember(member, type: type, unit: unit, definitionOnly: true) } internal final func doGenerateMember(_ member: CGMemberDefinition, type: CGTypeDefinition?, unit: CGCodeUnit? = nil, definitionOnly: Boolean) -> String { currentUnit = unit currentCode = StringBuilder() self.definitionOnly = definitionOnly if let type = type { generateTypeMember(member, type: type) } else { generateTypeMember(member, type: CGGlobalTypeDefinition.GlobalType) } return currentCode.ToString() } public final func GenerateMemberImplementation(_ member: CGMemberDefinition, type: CGTypeDefinition?, unit: CGCodeUnit? = nil) -> String? { currentUnit = unit currentCode = StringBuilder() self.definitionOnly = definitionOnly if let type = type { doGenerateMemberImplementation(member, type: type) } else { doGenerateMemberImplementation(member, type: CGGlobalTypeDefinition.GlobalType) } return currentCode.ToString() } public final func GenerateParameterDefinition(_ parameter: CGParameterDefinition, unit: CGCodeUnit? = nil) -> String { currentUnit = unit currentCode = StringBuilder() self.definitionOnly = definitionOnly generateParameterDefinition(parameter) return currentCode.ToString() } public final func GenerateStatement(_ statement: CGStatement, unit: CGCodeUnit? = nil) -> String? { currentUnit = unit currentCode = StringBuilder() definitionOnly = false generateStatement(statement) return currentCode.ToString() } public func doGenerateMemberImplementation(_ member: CGMemberDefinition, type: CGTypeDefinition) { // no-op for most languages, except Pascal } // // Private // internal func generateAll() { generateHeader() generateDirectives() generateImports() generateForwards() generateGlobals() generateTypeDefinitions() generateFooter() } internal final func incIndent(step: Int32 = 1) { indent += step } internal final func decIndent(step: Int32 = 1) { indent -= step if indent < 0 { indent = 0 } } /* */ public var failOnAsserts: Boolean = false @inline(__always) internal func assert(_ ok: Boolean, _ message: String) { if !ok { assert(message) } } internal func assert(_ message: String) { if failOnAsserts { throw Exception(message) } else { generateInlineComment(message) } } /* These following functions *can* be overriden by descendants, if needed */ internal func generateHeader() { // descendant can override, if needed if let comment = currentUnit.HeaderComment, comment.Lines.Count > 0 { generateStatement(comment) AppendLine() } } internal func generateFooter() { // descendant can override, if needed } internal func generateForwards() { // descendant can override, if needed } internal func generateDirectives() { if currentUnit.Directives.Count > 0 { for d in currentUnit.Directives { generateDirective(d) } AppendLine() } } internal func generateImports() { if currentUnit.Imports.Count > 0 { for i in currentUnit.Imports { if let condition = i.Condition { generateConditionStart(condition) } generateImport(i) if let condition = i.Condition { generateConditionEnd(condition) } } AppendLine() } if currentUnit.FileImports.Count > 0 { for i in currentUnit.FileImports { if let condition = i.Condition { generateConditionStart(condition) } generateFileImport(i) if let condition = i.Condition { generateConditionEnd(condition) } } AppendLine() } } internal func generateTypeDefinitions() { // descendant should not usually override generateTypeDefinitions(currentUnit.Types) } internal func generateTypeDefinitions(_ Types : List<CGTypeDefinition>) { // descendant should not usually override for t in Types { generateTypeDefinition(t) AppendLine() } } internal func generateGlobals() { var lastGlobal: CGGlobalDefinition? = nil for g in currentUnit.Globals { if let lastGlobal = lastGlobal, globalNeedsSpace(g, afterGlobal: lastGlobal) { AppendLine() } generateGlobal(g) lastGlobal = g; } if lastGlobal != nil { AppendLine() } } internal final func generateDirective(_ directive: CGCompilerDirective) { if let condition = directive.Condition { generateConditionStart(condition) incIndent() } AppendLine(directive.Directive) if let condition = directive.Condition { decIndent() generateConditionEnd(condition) } } internal func generateSingleLineCommentPrefix() { // descendant may override, but this will work for all current languages we support. Append("// ") } internal func generateImport(_ `import`: CGImport) { // descendant must override this or generateImports() assert(false, "generateImport not implemented") } internal func generateFileImport(_ `import`: CGImport) { // descendant should override if it supports file imports } // // Helpers // internal func memberNeedsSpace(_ member: CGMemberDefinition, afterMember lastMember: CGMemberDefinition) -> Boolean { if memberIsSingleLine(member) && memberIsSingleLine(lastMember) { return false; } return true } internal func globalNeedsSpace(_ global: CGGlobalDefinition, afterGlobal lastGlobal: CGGlobalDefinition) -> Boolean { if globalIsSingleLine(global) && globalIsSingleLine(lastGlobal) { return false; } return true } internal func memberIsSingleLine(_ member: CGMemberDefinition) -> Boolean { // reasoablew default, works for al current languages if member is CGFieldDefinition { return true } if let property = member as? CGPropertyDefinition { return property.GetStatements == nil && property.SetStatements == nil && property.GetExpression == nil && property.SetExpression == nil } return false } internal func globalIsSingleLine(_ global: CGGlobalDefinition) -> Boolean { if global is CGGlobalVariableDefinition { return true } return false } // // Indentifiers // @inline(__always) internal final func generateIdentifier(_ name: String) { generateIdentifier(name, escaped: true) } @inline(__always) internal final func generateIdentifier(_ name: String, escaped: Boolean) { generateIdentifier(name, escaped: escaped, alwaysEmitNamespace: false) } @inline(__always) internal final func generateIdentifier(_ name: String, keywords: List<String>?) { generateIdentifier(name, keywords: keywords, alwaysEmitNamespace: false) } @inline(__always) internal final func generateIdentifier(_ name: String, alwaysEmitNamespace: Boolean) { generateIdentifier(name, escaped: true, alwaysEmitNamespace: alwaysEmitNamespace) } @inline(__always) internal final func generateIdentifier(_ name: String, escaped: Boolean, alwaysEmitNamespace: Boolean) { generateIdentifier(name, keywords: escaped ? keywords : nil, alwaysEmitNamespace: alwaysEmitNamespace) } internal final func generateIdentifier(_ name: String, keywords: List<String>?, alwaysEmitNamespace: Boolean) { if omitNamespacePrefixes && !alwaysEmitNamespace { if name.Contains(".") { if let parts = name.Split("."), length(parts) > 0 { generateIdentifier(parts[length(parts)-1], keywords: keywords) return } } } if let keywords = keywords { if name.Contains(".") { let parts = name.Split(".") helpGenerateCommaSeparatedList(parts, separator: { self.Append(".") }, wrapWhenItExceedsLineLength: false, callback: { part in self.generateIdentifier(part, escaped: true) }) } else { var checkName = name if !keywordsAreCaseSensitive { checkName = checkName.ToLower() } if keywords?.Contains(checkName) { Append(escapeIdentifier(name)) } else { Append(name) } } } else { Append(name) } } internal func escapeIdentifier(_ name: String) -> String { // descendant must override this assert(false, "escapeIdentifier not implemented") return name } // // Statements // internal final func generateStatements(_ statements: List<CGStatement>) { // descendant should not override for g in statements { generateStatement(g) } } internal final func generateStatements(variables statements: List<CGVariableDeclarationStatement>?) { // descendant should not override if let statements = statements { for g in statements { generateStatement(g) } } } internal final func generateStatementsSkippingOuterBeginEndBlock(_ statements: List<CGStatement>) { //if statements.Count == 1, let block = statements[0] as? CGBeginEndBlockStatement { if statements.Count == 1 && statements[0] is CGBeginEndBlockStatement { //generateStatements(block.Statements) generateStatements((statements[0] as! CGBeginEndBlockStatement).Statements) } else { generateStatements(statements) } } internal final func generateStatementSkippingOuterBeginEndBlock(_ statement: CGStatement) { if let block = statement as? CGBeginEndBlockStatement { generateStatements(block.Statements) } else { generateStatement(statement) } } internal func generateStatementIndentedUnlessItsABeginEndBlock(_ statement: CGStatement) { if let block = statement as? CGBeginEndBlockStatement { generateStatement(block) } else { incIndent() generateStatement(statement) decIndent() } } internal func generateStatementsIndentedUnlessItsASingleBeginEndBlock(_ statements: List<CGStatement>) { if statements.Count == 1 && statements[0] is CGBeginEndBlockStatement { generateStatement(statements[0]) } else { incIndent() generateStatements(statements) decIndent() } } internal func generateStatementIndentedOrTrailingIfItsABeginEndBlock(_ statement: CGStatement) { if let block = statement as? CGBeginEndBlockStatement { Append(" ") generateStatement(block) } else { AppendLine() incIndent() generateStatement(statement) decIndent() } } internal final func generateStatement(_ statement: CGStatement) { statement.startLocation = currentLocation; // descendant should not override if let commentStatement = statement as? CGCommentStatement { generateCommentStatement(commentStatement) } else if let commentStatement = statement as? CGSingleLineCommentStatement { generateSingleLineCommentStatement(commentStatement) } else if let commentStatement = statement as? CGCodeCommentStatement { generateCodeCommentStatement(commentStatement) } else if let rawStatement = statement as? CGRawStatement { for line in rawStatement.Lines { AppendLine(line) } } else if let statement = statement as? CGBeginEndBlockStatement { generateBeginEndStatement(statement) } else if let statement = statement as? CGConditionalBlockStatement { generateConditionalBlockStatement(statement) } else if let statement = statement as? CGIfThenElseStatement { generateIfElseStatement(statement) } else if let statement = statement as? CGForToLoopStatement { generateForToLoopStatement(statement) } else if let statement = statement as? CGForEachLoopStatement { generateForEachLoopStatement(statement) } else if let statement = statement as? CGWhileDoLoopStatement { generateWhileDoLoopStatement(statement) } else if let statement = statement as? CGDoWhileLoopStatement { generateDoWhileLoopStatement(statement) } else if let statement = statement as? CGInfiniteLoopStatement { generateInfiniteLoopStatement(statement) } else if let statement = statement as? CGSwitchStatement { generateSwitchStatement(statement) } else if let statement = statement as? CGLockingStatement { generateLockingStatement(statement) } else if let statement = statement as? CGUsingStatement { generateUsingStatement(statement) } else if let statement = statement as? CGAutoReleasePoolStatement { generateAutoReleasePoolStatement(statement) } else if let statement = statement as? CGTryFinallyCatchStatement { generateTryFinallyCatchStatement(statement) } else if let statement = statement as? CGReturnStatement { generateReturnStatement(statement) } else if let statement = statement as? CGYieldStatement { generateYieldStatement(statement) } else if let statement = statement as? CGThrowStatement { generateThrowStatement(statement) } else if let statement = statement as? CGBreakStatement { generateBreakStatement(statement) } else if let statement = statement as? CGContinueStatement { generateContinueStatement(statement) } else if let statement = statement as? CGVariableDeclarationStatement { generateVariableDeclarationStatement(statement) } else if let statement = statement as? CGAssignmentStatement { generateAssignmentStatement(statement) } else if let statement = statement as? CGConstructorCallStatement { generateConstructorCallStatement(statement) } else if let statement = statement as? CGEmptyStatement { AppendLine() } else if let expression = statement as? CGGotoStatement { generateGotoStatement(expression) } else if let expression = statement as? CGLabelStatement { generateLabelStatement(expression) } else if let expression = statement as? CGExpression { // should be last but one generateExpressionStatement(expression) } else { assert(false, "unsupported statement found: \(typeOf(statement).ToString())") } //if !assigned(statement.endLocation) { statement.endLocation = currentLocation; //} // 72543: Silver: cannot check if nullable struct is assigned } internal func generateCommentStatement(_ commentStatement: CGCommentStatement?) { if let commentStatement = commentStatement { for line in commentStatement.Lines { generateSingleLineCommentPrefix() AppendLine(line) } } } internal func generateSingleLineCommentStatement(_ commentStatement: CGSingleLineCommentStatement?) { if let commentStatement = commentStatement { generateSingleLineCommentPrefix() AppendLine(commentStatement.Comment) } } private var inCodeCommentStatement = false internal func generateCodeCommentStatement(_ commentStatement: CGCodeCommentStatement) { assert(!inCodeCommentStatement, "Cannot nest CGCodeCommentStatements") inCodeCommentStatement = true __try { generateStatement(commentStatement.CommentedOutStatement) } __finally { inCodeCommentStatement = false } } internal func generateConditionalDefine(_ condition: CGConditionalDefine) { inConditionExpression = true defer { inConditionExpression = false } generateExpression(condition.Expression) } internal func generateConditionStart(_ condition: CGConditionalDefine) { // descendant must override this assert(false, "generateConditionStart not implemented") } internal func generateConditionElse() { // descendant must override this assert(false, "generateConditionElse not implemented") } internal func generateConditionEnd(_ condition: CGConditionalDefine) { // descendant must override this assert(false, "generateConditionEnd not implemented") } internal func generateConditionalBlockStatement(_ statement: CGConditionalBlockStatement) { generateConditionStart(statement.Condition) incIndent() generateStatements(statement.Statements) decIndent() if let elseStatements = statement.ElseStatements { generateConditionElse() incIndent() generateStatements(elseStatements) decIndent() } generateConditionEnd(statement.Condition) } internal func generateBeginEndStatement(_ statement: CGBeginEndBlockStatement) { // descendant must override this or generateImports() assert(false, "generateBeginEndStatement not implemented") } internal func generateIfElseStatement(_ statement: CGIfThenElseStatement) { // descendant must override this or generateImports() assert(false, "generateIfElseStatement not implemented") } internal func generateForToLoopStatement(_ statement: CGForToLoopStatement) { // descendant must override this or generateImports() assert(false, "generateForToLoopStatement not implemented") } internal func generateForEachLoopStatement(_ statement: CGForEachLoopStatement) { // descendant must override this or generateImports() assert(false, "generateForEachLoopStatement not implemented") } internal func generateWhileDoLoopStatement(_ statement: CGWhileDoLoopStatement) { // descendant must override this or generateImports() assert(false, "generagenerateWhileDoLoopStatementteImport not implemented") } internal func generateDoWhileLoopStatement(_ statement: CGDoWhileLoopStatement) { // descendant must override this or generateImports() assert(false, "generateDoWhileLoopStatement not implemented") } internal func generateInfiniteLoopStatement(_ statement: CGInfiniteLoopStatement) { // descendant may override, but this will work for all languages. generateWhileDoLoopStatement(CGWhileDoLoopStatement(CGBooleanLiteralExpression(true), statement.NestedStatement)) } internal func generateSwitchStatement(_ statement: CGSwitchStatement) { // descendant must override this or generateImports() assert(false, "generateSwitchStatement not implemented") } internal func generateLockingStatement(_ statement: CGLockingStatement) { // descendant must override this or generateImports() assert(false, "generateLockingStatement not implemented") } internal func generateUsingStatement(_ statement: CGUsingStatement) { // descendant must override this or generateImports() assert(false, "generateUsingStatement not implemented") } internal func generateAutoReleasePoolStatement(_ statement: CGAutoReleasePoolStatement) { // descendant must override this or generateImports() assert(false, "generateAutoReleasePoolStatement not implemented") } internal func generateTryFinallyCatchStatement(_ statement: CGTryFinallyCatchStatement) { // descendant must override this or generateImports() assert(false, "generateTryFinallyCatchStatement not implemented") } internal func generateReturnStatement(_ statement: CGReturnStatement) { // descendant must override this or generateImports() assert(false, "generateReturnStatement not implemented") } internal func generateYieldStatement(_ statement: CGYieldStatement) { // descendant must override this or generateImports() assert(false, "generateYieldStatement not implemented") } internal func generateThrowStatement(_ statement: CGThrowStatement) { // descendant must override this or generateImports() assert(false, "generateThrowStatement not implemented") } internal func generateBreakStatement(_ statement: CGBreakStatement) { // descendant must override this or generateImports() assert(false, "generateBreakStatement not implemented") } internal func generateContinueStatement(_ statement: CGContinueStatement) { // descendant must override this or generateImports() assert(false, "generateContinueStatement not implemented") } internal func generateVariableDeclarationStatement(_ statement: CGVariableDeclarationStatement) { // descendant must override this or generateImports() assert(false, "generateVariableDeclarationStatement not implemented") } internal func generateAssignmentStatement(_ statement: CGAssignmentStatement) { // descendant must override this or generateImports() assert(false, "generateAssignmentStatement not implemented") } internal func generateConstructorCallStatement(_ statement: CGConstructorCallStatement) { // descendant must override this or generateImports() assert(false, "generateConstructorCallStatement not implemented") } internal func generateGotoStatement(_ statement: CGGotoStatement) { // descendant must override this or generateImports() assert(false, "generateGotoStatement not implemented") } internal func generateLabelStatement(_ statement: CGLabelStatement) { // descendant must override this or generateImports() assert(false, "generateLabelStatement not implemented") } internal func generateStatementTerminator() { AppendLine(";") } internal func generateExpressionStatement(_ expression: CGExpression) { generateExpression(expression) generateStatementTerminator() } // // Expressions // internal final func generateExpression(_ expression: CGExpression, ignoreNullability: Boolean) { if let expression = expression as? CGTypeReferenceExpression { generateTypeReferenceExpression(expression, ignoreNullability: ignoreNullability) } else { generateExpression(expression) } } internal final func generateExpression(_ expression: CGExpression) { // descendant should not override expression.startLocation = currentLocation; if let rawExpression = expression as? CGRawExpression { helpGenerateCommaSeparatedList(rawExpression.Lines, separator: { self.AppendLine() }) { line in self.Append(line) } } else if let expression = expression as? CGNamedIdentifierExpression { generateNamedIdentifierExpression(expression) } else if let expression = expression as? CGAssignedExpression { generateAssignedExpression(expression) } else if let expression = expression as? CGSizeOfExpression { generateSizeOfExpression(expression) } else if let expression = expression as? CGTypeOfExpression { generateTypeOfExpression(expression) } else if let expression = expression as? CGDefaultExpression { generateDefaultExpression(expression) } else if let expression = expression as? CGSelectorExpression { generateSelectorExpression(expression) } else if let expression = expression as? CGTypeCastExpression { generateTypeCastExpression(expression) } else if let expression = expression as? CGInheritedExpression { generateInheritedExpression(expression) } else if let expression = expression as? CGSelfExpression { generateSelfExpression(expression) } else if let expression = expression as? CGNilExpression { generateNilExpression(expression) } else if let expression = expression as? CGPropertyValueExpression { generatePropertyValueExpression(expression) } else if let expression = expression as? CGAwaitExpression { generateAwaitExpression(expression) } else if let expression = expression as? CGAnonymousMethodExpression { generateAnonymousMethodExpression(expression) } else if let expression = expression as? CGAnonymousTypeExpression { generateAnonymousTypeExpression(expression) } else if let expression = expression as? CGPointerDereferenceExpression { generatePointerDereferenceExpression(expression) } else if let expression = expression as? CGParenthesesExpression { generateParenthesesExpression(expression) } else if let expression = expression as? CGRangeExpression { generateRangeExpression(expression) } else if let expression = expression as? CGUnaryOperatorExpression { generateUnaryOperatorExpression(expression) } else if let expression = expression as? CGBinaryOperatorExpression { generateBinaryOperatorExpression(expression) } else if let expression = expression as? CGIfThenElseExpression { generateIfThenElseExpression(expression) } else if let expression = expression as? CGLocalVariableAccessExpression { generateLocalVariableAccessExpression(expression) } else if let expression = expression as? CGEventAccessExpression { generateEventAccessExpression(expression) } else if let expression = expression as? CGFieldAccessExpression { generateFieldAccessExpression(expression) } else if let expression = expression as? CGArrayElementAccessExpression { generateArrayElementAccessExpression(expression) } else if let expression = expression as? CGMethodCallExpression { generateMethodCallExpression(expression) } else if let expression = expression as? CGNewInstanceExpression { generateNewInstanceExpression(expression) } else if let expression = expression as? CGDestroyInstanceExpression { generateDestroyInstanceExpression(expression) } else if let expression = expression as? CGPropertyAccessExpression { generatePropertyAccessExpression(expression) } else if let expression = expression as? CGEnumValueAccessExpression { generateEnumValueAccessExpression(expression) } else if let expression = expression as? CGStringLiteralExpression { generateStringLiteralExpression(expression) } else if let expression = expression as? CGCharacterLiteralExpression { generateCharacterLiteralExpression(expression) } else if let expression = expression as? CGIntegerLiteralExpression { generateIntegerLiteralExpression(expression) } else if let expression = expression as? CGFloatLiteralExpression { generateFloatLiteralExpression(expression) } else if let expression = expression as? CGImaginaryLiteralExpression { generateImaginaryLiteralExpression(expression) } else if let literalExpression = expression as? CGLanguageAgnosticLiteralExpression { Append(valueForLanguageAgnosticLiteralExpression(literalExpression)) } else if let expression = expression as? CGArrayLiteralExpression { generateArrayLiteralExpression(expression) } else if let expression = expression as? CGSetLiteralExpression { generateSetLiteralExpression(expression) } else if let expression = expression as? CGDictionaryLiteralExpression { generateDictionaryExpression(expression) } else if let expression = expression as? CGTupleLiteralExpression { generateTupleExpression(expression) } else if let expression = expression as? CGTypeReferenceExpression { generateTypeReferenceExpression(expression) } else { Append("[UNSUPPORTED: "+expression.ToString()+"]") assert(false, "unsupported expression found: \(typeOf(expression).ToString())") } //if !assigned(expression.endLocation) { expression.endLocation = currentLocation; //} // 72543: Silver: cannot check if nullable struct is assigned } internal func generateNamedIdentifierExpression(_ expression: CGNamedIdentifierExpression) { // descendant may override, but this will work for all languages. generateIdentifier(expression.Name) } internal func generateAssignedExpression(_ expression: CGAssignedExpression) { // descendant may override, but this will work for all languages. generateExpression(CGBinaryOperatorExpression(expression.Value, CGNilExpression.Nil, expression.Inverted ? CGBinaryOperatorKind.Equals : CGBinaryOperatorKind.NotEquals)) } internal func generateSizeOfExpression(_ expression: CGSizeOfExpression) { // descendant must override assert(false, "generateSizeOfExpression not implemented") } internal func generateTypeOfExpression(_ expression: CGTypeOfExpression) { // descendant must override assert(false, "generateTypeOfExpression not implemented") } internal func generateDefaultExpression(_ expression: CGDefaultExpression) { // descendant must override assert(false, "generateDefaultExpression not implemented") } internal func generateSelectorExpression(_ expression: CGSelectorExpression) { // descendant must override assert(false, "generateSelectorExpression not implemented") } internal func generateTypeCastExpression(_ expression: CGTypeCastExpression) { // descendant must override assert(false, "generateTypeCastExpression not implemented") } internal func generateInheritedExpression(_ expression: CGInheritedExpression) { // descendant must override assert(false, "generateInheritedExpression not implemented") } internal func generateSelfExpression(_ expression: CGSelfExpression) { // descendant must override assert(false, "generateSelfExpression not implemented") } internal func generateNilExpression(_ expression: CGNilExpression) { // descendant must override assert(false, "generateNilExpression not implemented") } internal func generatePropertyValueExpression(_ expression: CGPropertyValueExpression) { // descendant must override assert(false, "generatePropertyValueExpression not implemented") } internal func generateAwaitExpression(_ expression: CGAwaitExpression) { // descendant must override assert(false, "generateAwaitExpression not implemented") } internal func generateAnonymousMethodExpression(_ expression: CGAnonymousMethodExpression) { // descendant must override assert(false, "generateAnonymousMethodExpression not implemented") } internal func generateAnonymousTypeExpression(_ expression: CGAnonymousTypeExpression) { // descendant must override assert(false, "generateAnonymousTypeExpression not implemented") } internal func generatePointerDereferenceExpression(_ expression: CGPointerDereferenceExpression) { // descendant must override assert(false, "generatePointerDereferenceExpression not implemented") } internal func generateParenthesesExpression(_ expression: CGParenthesesExpression) { Append("(") generateExpression(expression.Value) Append(")") } internal func generateRangeExpression(_ expression: CGRangeExpression) { // descendant must override assert(false, "generateRangeExpression not implemented") } internal func generateUnaryOperatorExpression(_ expression: CGUnaryOperatorExpression) { // descendant may override, but this will work for most languages. if let operatorString = expression.OperatorString { Append(operatorString) } else if let `operator` = expression.Operator { generateUnaryOperator(`operator`) } generateExpression(expression.Value) } internal func generateBinaryOperatorExpression(_ expression: CGBinaryOperatorExpression) { // descendant may override, but this will work for most languages. generateExpression(expression.LefthandValue) Append(" ") if let operatorString = expression.OperatorString { Append(operatorString) } else if let `operator` = expression.Operator { generateBinaryOperator(`operator`) } Append(" ") generateExpression(expression.RighthandValue) } internal func generateUnaryOperator(_ `operator`: CGUnaryOperatorKind) { // descendant must override assert(false, "generateUnaryOperator not implemented") } internal func generateBinaryOperator(_ `operator`: CGBinaryOperatorKind) { // descendant must override assert(false, "generateBinaryOperator not implemented") } internal func generateIfThenElseExpression(_ expression: CGIfThenElseExpression) { // descendant must override assert(false, "generateIfThenElseExpression not implemented") } internal func generateLocalVariableAccessExpression(_ expression: CGLocalVariableAccessExpression) { // descendant may override, but this will work for all languages. generateIdentifier(expression.Name) } internal func generateFieldAccessExpression(_ expression: CGFieldAccessExpression) { // descendant must override assert(false, "generateFieldAccessExpression not implemented") } internal func generateEventAccessExpression(_ expression: CGEventAccessExpression) { generateFieldAccessExpression(expression) } internal func generateArrayElementAccessExpression(_ expression: CGArrayElementAccessExpression) { // descendant may override, but this will work for most languages. generateExpression(expression.Array) Append("[") for p in 0 ..< expression.Parameters.Count { let param = expression.Parameters[p] if p > 0 { Append(", ") } generateExpression(param) } Append("]") } internal func generateMethodCallExpression(_ expression: CGMethodCallExpression) { // descendant must override assert(false, "generateMethodCallExpression not implemented") } internal func generateNewInstanceExpression(_ expression: CGNewInstanceExpression) { // descendant must override assert(false, "generateNewInstanceExpression not implemented") } internal func generateDestroyInstanceExpression(_ expression: CGDestroyInstanceExpression) { // descendant must override, if they support this assert(false, "generateDestroyInstanceExpression not implemented") } internal func generatePropertyAccessExpression(_ expression: CGPropertyAccessExpression) { // descendant must override assert(false, "generatePropertyAccessExpression not implemented") } internal func generateEnumValueAccessExpression(_ expression: CGEnumValueAccessExpression) { // descendant may override, but this will work for most languages. generateTypeReference(expression.`Type`, ignoreNullability: true) Append(".") generateIdentifier(expression.ValueName) } internal func generateStringLiteralExpression(_ expression: CGStringLiteralExpression) { // descendant must override assert(false, "generateStringLiteralExpression not implemented") } internal func generateCharacterLiteralExpression(_ expression: CGCharacterLiteralExpression) { // descendant must override assert(false, "generateCharacterLiteralExpression not implemented") } internal func generateIntegerLiteralExpression(_ literalExpression: CGIntegerLiteralExpression) { // descendant should override switch literalExpression.Base { case 10: Append(valueForLanguageAgnosticLiteralExpression(literalExpression)) default: throw Exception("Base \(literalExpression.Base) integer literals are not currently supported for this languages.") } } internal func generateFloatLiteralExpression(_ literalExpression: CGFloatLiteralExpression) { // descendant should override switch literalExpression.Base { case 10: Append(valueForLanguageAgnosticLiteralExpression(literalExpression)) default: throw Exception("Base \(literalExpression.Base) integer literals are not currently supported for this languages.") } } internal func generateImaginaryLiteralExpression(_ literalExpression: CGImaginaryLiteralExpression) { // descendant should override assert(false, "generateImaginaryLiteralExpression not implemented") } internal func generateArrayLiteralExpression(_ expression: CGArrayLiteralExpression) { // descendant must override assert(false, "generateArrayLiteralExpression not implemented") } internal func generateSetLiteralExpression(_ expression: CGSetLiteralExpression) { // descendant must override assert(false, "generateSetLiteralExpression not implemented") } internal func generateDictionaryExpression(_ expression: CGDictionaryLiteralExpression) { // descendant must override assert(false, "generateDictionaryExpression not implemented") } internal func generateTupleExpression(_ expression: CGTupleLiteralExpression) { // descendant may override, but this will work for most languages. Append("(") for m in 0 ..< expression.Members.Count { if m > 0 { Append(", ") } generateExpression(expression.Members[m]) } Append(")") } internal func generateTypeReferenceExpression(_ expression: CGTypeReferenceExpression, ignoreNullability: Boolean) { // descendant may override, but this will work for most languages. generateTypeReference(expression.`Type`, ignoreNullability: ignoreNullability) } internal func generateTypeReferenceExpression(_ expression: CGTypeReferenceExpression) { // descendant may override, but this will work for most languages. generateTypeReference(expression.`Type`) } internal func valueForLanguageAgnosticLiteralExpression(_ expression: CGLanguageAgnosticLiteralExpression) -> String { // descendant may override if they aren't happy with the default return expression.StringRepresentation() } // // Globals // internal func generateGlobal(_ global: CGGlobalDefinition) { if let global = global as? CGGlobalFunctionDefinition { generateTypeMember(global.Function, type: CGGlobalTypeDefinition.GlobalType) } else if let global = global as? CGGlobalVariableDefinition { generateTypeMember(global.Variable, type: CGGlobalTypeDefinition.GlobalType) } else if let global = global as? CGGlobalPropertyDefinition { generateTypeMember(global.Property, type: CGGlobalTypeDefinition.GlobalType) } else { assert(false, "unsupported global found: \(typeOf(global).ToString())") } } // // Type Definitions // func generateAttributes(_ attributes: List<CGAttribute>?) { generateAttributes(attributes, inline: false) } func generateAttributes(_ attributes: List<CGAttribute>?, inline: Boolean) { if let attributes = attributes, attributes.Count > 0 { for a in attributes { if let condition = a.Condition { generateConditionStart(condition) generateAttribute(a, inline: false) generateConditionEnd(condition) } else { generateAttribute(a, inline: inline) } } } } final func generateAttribute(_ attribute: CGAttribute) { // descendant must override generateAttribute(attribute, inline: false); } internal func generateAttribute(_ attribute: CGAttribute, inline: Boolean) { // descendant must override assert(false, "generateAttribute not implemented") } internal final func generateTypeDefinition(_ type: CGTypeDefinition) { if let condition = type.Condition { generateConditionStart(condition) } type.startLocation = currentLocation; generateCommentStatement(type.Comment) generateAttributes(type.Attributes) if let type = type as? CGTypeAliasDefinition { generateAliasType(type) } else if let type = type as? CGBlockTypeDefinition { generateBlockType(type) } else if let type = type as? CGEnumTypeDefinition { generateEnumType(type) } else if let type = type as? CGClassTypeDefinition { generateClassType(type) } else if let type = type as? CGStructTypeDefinition { generateStructType(type) } else if let type = type as? CGInterfaceTypeDefinition { generateInterfaceType(type) } else if let type = type as? CGExtensionTypeDefinition { generateExtensionType(type) } else { assert(false, "unsupported type found: \(typeOf(type).ToString())") } if !assigned(type.endLocation) { type.endLocation = currentLocation; } // 72543: Silver: cannot check if nullable struct is assigned if let condition = type.Condition { generateConditionEnd(condition) } } internal func generateInlineComment(_ comment: String) { // descendant must override assert(false, "generateInlineComment not implemented") } internal func generateAliasType(_ type: CGTypeAliasDefinition) { // descendant must override assert(false, "generateAliasType not implemented") } internal func generateBlockType(_ type: CGBlockTypeDefinition) { // descendant must override assert(false, "generateBlockType not implemented") } internal func generateEnumType(_ type: CGEnumTypeDefinition) { // descendant must override assert(false, "generateEnumType not implemented") } internal func generateClassType(_ type: CGClassTypeDefinition) { // descendant should not usually override generateClassTypeStart(type) generateTypeMembers(type) generateClassTypeEnd(type) } internal func generateStructType(_ type: CGStructTypeDefinition) { // descendant should not usually override generateStructTypeStart(type) generateTypeMembers(type) generateStructTypeEnd(type) } internal func generateInterfaceType(_ type: CGInterfaceTypeDefinition) { // descendant should not usually override generateInterfaceTypeStart(type) generateTypeMembers(type) generateInterfaceTypeEnd(type) } internal func generateExtensionType(_ type: CGExtensionTypeDefinition) { // descendant should not usually override generateExtensionTypeStart(type) generateTypeMembers(type) generateExtensionTypeEnd(type) } internal func generateTypeMembers(_ type: CGTypeDefinition) { var lastMember: CGMemberDefinition? = nil for m in type.Members { if let lastMember = lastMember, memberNeedsSpace(m, afterMember: lastMember) && !definitionOnly { AppendLine() } generateTypeMember(m, type: type) lastMember = m; } } internal func generateClassTypeStart(_ type: CGClassTypeDefinition) { // descendant must override assert(false, "generateClassTypeStart not implemented") } internal func generateClassTypeEnd(_ type: CGClassTypeDefinition) { // descendant must override assert(false, "generateClassTypeEnd not implemented") } internal func generateStructTypeStart(_ type: CGStructTypeDefinition) { // descendant must override assert(false, "generateStructTypeStart not implemented") } internal func generateStructTypeEnd(_ type: CGStructTypeDefinition) { // descendant must override assert(false, "generateStructTypeEnd not implemented") } internal func generateInterfaceTypeStart(_ type: CGInterfaceTypeDefinition) { // descendant must override assert(false, "generateInterfaceTypeStart not implemented") } internal func generateInterfaceTypeEnd(_ type: CGInterfaceTypeDefinition) { // descendant must override assert(false, "generateInterfaceTypeEnd not implemented") } internal func generateExtensionTypeStart(_ type: CGExtensionTypeDefinition) { // descendant must override assert(false, "generateExtensionTypeStart not implemented") } internal func generateExtensionTypeEnd(_ type: CGExtensionTypeDefinition) { // descendant must override assert(false, "generateExtensionTypeEnd not implemented") } // // Type members // internal final func generateTypeMember(_ member: CGMemberDefinition, type: CGTypeDefinition) { if let condition = type.Condition { generateConditionStart(condition) } if let condition = member.Condition { generateConditionStart(condition) } member.startLocation = currentLocation; generateCommentStatement(member.Comment) generateAttributes(member.Attributes) if let member = member as? CGConstructorDefinition { generateConstructorDefinition(member, type:type) } else if let member = member as? CGDestructorDefinition { generateDestructorDefinition(member, type:type) } else if let member = member as? CGFinalizerDefinition { generateFinalizerDefinition(member, type:type) } else if let member = member as? CGMethodDefinition { generateMethodDefinition(member, type:type) } else if let member = member as? CGFieldDefinition { generateFieldDefinition(member, type:type) } else if let member = member as? CGPropertyDefinition { generatePropertyDefinition(member, type:type) } else if let member = member as? CGEventDefinition { generateEventDefinition(member, type:type) } else if let member = member as? CGCustomOperatorDefinition { generateCustomOperatorDefinition(member, type:type) } else if let member = member as? CGNestedTypeDefinition { generateNestedTypeDefinition(member, type:type) } //... else { assert(false, "unsupported type member found: \(typeOf(type).ToString())") } //72543: Silver: cannot check if nullable struct is assigned /*if member.endLocation != nil { member.endLocation = currentLocation; } if !assigned(member.endLocation) { member.endLocation = currentLocation; }*/ member.endLocation = currentLocation; if let condition = member.Condition { generateConditionEnd(condition) } if let condition = type.Condition { generateConditionEnd(condition) } } internal func generateConstructorDefinition(_ member: CGConstructorDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateConstructorDefinition not implemented") } internal func generateDestructorDefinition(_ member: CGDestructorDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateDestructorDefinition not implemented") } internal func generateFinalizerDefinition(_ member: CGFinalizerDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateFinalizerDefinition not implemented") } internal func generateMethodDefinition(_ member: CGMethodDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateMethodDefinition not implemented") } internal func generateFieldDefinition(_ member: CGFieldDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateFieldDefinition not implemented") } internal func generatePropertyDefinition(_ member: CGPropertyDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generatePropertyDefinition not implemented") } internal func generateEventDefinition(_ member: CGEventDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateEventDefinition not implemented") } internal func generateCustomOperatorDefinition(_ member: CGCustomOperatorDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateCustomOperatorDefinition not implemented") } internal func generateNestedTypeDefinition(_ member: CGNestedTypeDefinition, type: CGTypeDefinition) { // descendant must override assert(false, "generateNestedTypeDefinition not implemented") } internal func generateParameterDefinition(_ parameter: CGParameterDefinition) { // descendant must override omnly if they use this, or to support GenerateParameterDefinition() assert(false, "generateParameterDefinition not implemented") } // // Type References // internal final func generateTypeReference(_ type: CGTypeReference) { generateTypeReference(type, ignoreNullability: false) } internal final func generateTypeReference(_ type: CGTypeReference, ignoreNullability: Boolean) { type.startLocation = currentLocation; //Append("["+type+"|"+Int32(type.ActualNullability).description+"]") // descendant should not override if let type = type as? CGNamedTypeReference { generateNamedTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGPredefinedTypeReference { generatePredefinedTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGIntegerRangeTypeReference { generateIntegerRangeTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGInlineBlockTypeReference { generateInlineBlockTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGPointerTypeReference { generatePointerTypeReference(type) } else if let type = type as? CGConstantTypeReference { generateConstantTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGKindOfTypeReference { generateKindOfTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGTupleTypeReference { generateTupleTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGSetTypeReference { generateSetTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGSequenceTypeReference { generateSequenceTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGArrayTypeReference { generateArrayTypeReference(type, ignoreNullability: ignoreNullability) } else if let type = type as? CGDictionaryTypeReference { generateDictionaryTypeReference(type, ignoreNullability: ignoreNullability) } else { assert(false, "unsupported type reference found: \(typeOf(type).ToString())") } //if !assigned(type.endLocation) { type.endLocation = currentLocation; //} // 72543: Silver: cannot check if nullable struct is assigned } internal func generateNamedTypeReference(_ type: CGNamedTypeReference) { generateNamedTypeReference(type, ignoreNamespace: false, ignoreNullability: false) } internal func generateGenericArguments(_ genericArguments: List<CGTypeReference>?) { if let genericArguments = genericArguments, genericArguments.Count > 0 { // descendant may override, but this will work for most languages. Append("<") for p in 0 ..< genericArguments.Count { let param = genericArguments[p] if p > 0 { Append(",") } generateTypeReference(param, ignoreNullability: false) } Append(">") } } internal func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNullability: Boolean) { generateNamedTypeReference(type, ignoreNamespace: false, ignoreNullability: ignoreNullability) } internal func generateNamedTypeReference(_ type: CGNamedTypeReference, ignoreNamespace: Boolean, ignoreNullability: Boolean) { // descendant may override, but this will work for most languages. if ignoreNamespace { generateIdentifier(type.Name) } else { generateIdentifier(type.FullName) } generateGenericArguments(type.GenericArguments) } internal func generatePredefinedTypeReference(_ type: CGPredefinedTypeReference, ignoreNullability: Boolean = false) { // most languages will want to override this switch (type.Kind) { case .Int: generateIdentifier("Int") case .UInt: generateIdentifier("UInt") case .Int8: generateIdentifier("SByte") case .UInt8: generateIdentifier("Byte") case .Int16: generateIdentifier("Int16") case .UInt16: generateIdentifier("UInt16") case .Int32: generateIdentifier("Int32") case .UInt32: generateIdentifier("UInt32") case .Int64: generateIdentifier("Int64") case .UInt64: generateIdentifier("UInt16") case .IntPtr: generateIdentifier("IntPtr") case .UIntPtr: generateIdentifier("UIntPtr") case .Single: generateIdentifier("Float") case .Double: generateIdentifier("Double") case .Boolean: generateIdentifier("Boolean") case .String: generateIdentifier("String") case .AnsiChar: generateIdentifier("AnsiChar") case .UTF16Char: generateIdentifier("Char") case .UTF32Char: generateIdentifier("UInt32") case .Dynamic: generateIdentifier("dynamic") case .InstanceType: generateIdentifier("instancetype") case .Void: generateIdentifier("Void") case .Object: generateIdentifier("Object") case .Class: generateIdentifier("Class") } } internal func generateIntegerRangeTypeReference(_ type: CGIntegerRangeTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateIntegerRangeTypeReference not implemented") } internal func generateInlineBlockTypeReference(_ type: CGInlineBlockTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateInlineBlockTypeReference not implemented") } internal func generatePointerTypeReference(_ type: CGPointerTypeReference) { assert(false, "generatPointerTypeReference not implemented") } internal func generateConstantTypeReference(_ type: CGConstantTypeReference, ignoreNullability: Boolean = false) { // override if the language supports const types generateTypeReference(type.`Type`) } internal func generateKindOfTypeReference(_ type: CGKindOfTypeReference, ignoreNullability: Boolean = false) { assert(false, "generatKindOfTypeReference not implemented") } internal func generateTupleTypeReference(_ type: CGTupleTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateTupleTypeReference not implemented") } internal func generateSetTypeReference(_ type: CGSetTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSetTypeReference not implemented") } internal func generateSequenceTypeReference(_ type: CGSequenceTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateSequenceTypeReference not implemented") } internal func generateArrayTypeReference(_ type: CGArrayTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateArrayTypeReference not implemented") } internal func generateDictionaryTypeReference(_ type: CGDictionaryTypeReference, ignoreNullability: Boolean = false) { assert(false, "generateDictionaryTypeReference not implemented") } // // Helpers // @inline(__always) func helpGenerateCommaSeparatedList<T>(_ list: ISequence<T>, callback: (T) -> ()) { helpGenerateCommaSeparatedList(list, separator: { self.Append(", ") }, wrapWhenItExceedsLineLength: true, callback: callback) } @inline(__always) func helpGenerateCommaSeparatedList<T>(_ list: ISequence<T>, separator: () -> (), callback: (T) -> ()) { helpGenerateCommaSeparatedList(list, separator: separator, wrapWhenItExceedsLineLength: true, callback: callback) } var lastStartLocation: Integer? func helpGenerateCommaSeparatedList<T>(_ list: ISequence<T>, separator: () -> (), wrapWhenItExceedsLineLength: Boolean, callback: (T) -> ()) { let startLocation = lastStartLocation ?? currentLocation.virtualColumn lastStartLocation = nil var first = true for i in list { if !first { separator() if wrapWhenItExceedsLineLength && currentLocation.virtualColumn > splitLinesLongerThan { AppendLine() AppendIndentToVirtualColumn(startLocation) } } else { first = false } callback(i) } lastStartLocation = startLocation // keep this as possible indent for the next round } public static final func uppercaseFirstLetter(_ name: String) -> String { var name = name if length(name) >= 1 { name = name.Substring(0, 1).ToUpper()+name.Substring(1) } return name } public static final func lowercaseFirstLetter(_ name: String) -> String { var name = name if length(name) >= 1 { if length(name) < 2 || String([name[1]]) != String([name[1]]).ToUpper() { name = name.Substring(0, 1).ToLower()+name.Substring(1) } } return name } // // // StringBuilder Access // // private var currentCode: StringBuilder! private var indent: Int32 = 0 private var atStart = true internal var inConditionExpression = false internal var positionedAfterPeriod: Boolean { let length = currentCode.Length return (length > 0) && (currentCode[length-1] == ".") } internal private(set) var currentLocation = CGLocation() @discardableResult internal final func Append(_ line: String) -> StringBuilder { if length(line) > 0 { if atStart { AppendIndent() atStart = false if inCodeCommentStatement { generateSingleLineCommentPrefix() } } currentCode.Append(line) atStart = false let len = line.Length currentLocation.column += len currentLocation.virtualColumn += len currentLocation.offset += len } return currentCode } @discardableResult internal final func AppendLine(_ line: String? = nil) -> StringBuilder { if let line = line { Append(line) } currentCode.AppendLine() //currentLocation.line++// cannot use binary operator? currentLocation.line += 1 // workaround for currentLocation.line++ // E111 Variable expected currentLocation.column = 0 currentLocation.virtualColumn = 0 currentLocation.offset = currentCode.Length atStart = true return currentCode } @discardableResult private final func AppendIndent() -> StringBuilder { if !codeCompletionMode { if useTabs { currentLocation.column += indent currentLocation.virtualColumn += indent*tabSize currentLocation.offset += indent //74141: Compiler doesn't see .ctor from extension (and badly shows $New in error message) //currentCode.Append(String(count: indent, repeatingValue:"\t")) for i in 0 ..< indent { currentCode.Append("\t") } } else { currentLocation.column += indent*tabSize currentLocation.virtualColumn += indent*tabSize currentLocation.offset += indent*tabSize //74141: Compiler doesn't see .ctor from extension (and badly shows $New in error message) //currentCode.Append(String(count: indent*tabSize, repeatedValue:" ")) for i in 0 ..< indent*tabSize { currentCode.Append(" ") } } } lastStartLocation = nil return currentCode } internal final func AppendIndentToVirtualColumn(_ targetColumn: Integer) { atStart = false if useTabs { currentLocation.column += targetColumn/tabSize+targetColumn%tabSize currentLocation.virtualColumn += targetColumn currentLocation.offset += targetColumn/tabSize+targetColumn%tabSize //74141: Compiler doesn't see .ctor from extension (and badly shows $New in error message) //currentCode.Append(String(count: targetColumn/tabSize, repeatedValue:"\t")) //currentCode.Append(String(count: targetColumn%tabSize, repeatedValue:" ")) for i in 0 ..< targetColumn/tabSize { currentCode.Append("\t") } for i in 0 ..< targetColumn%tabSize { currentCode.Append(" ") } } else { currentLocation.column += targetColumn currentLocation.virtualColumn += targetColumn currentLocation.offset += targetColumn //74141: Compiler doesn't see .ctor from extension (and badly shows $New in error message) //currentCode.Append(String(count: targetColumn, repeatedValue:" ")) for i in 0 ..< targetColumn { currentCode.Append(" ") } } } public final func ExpressionToString(_ expression: CGExpression) -> String { currentCode = StringBuilder() generateExpression(expression); return currentCode.ToString() } public final func StatementToString(_ statement: CGStatement) -> String { currentCode = StringBuilder() generateStatement(statement); return currentCode.ToString() } }
bsd-3-clause
7438f34fe9fe375c701743be262b31ba
33.662763
178
0.745231
4.295184
false
false
false
false
ivanfoong/MDCSwipeToChoose
Examples/SwiftLikedOrNope/SwiftLikedOrNope/AppDelegate.swift
14
6167
// // AppDelegate.swift // SwiftLikedOrNope // // Created by richard burdish on 3/28/15. // Copyright (c) 2015 Richard Burdish. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "MDCSwipeToChoose.SwiftLikedOrNope" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftLikedOrNope", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftLikedOrNope.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
0987f5ed237ff96cd1af113f6b69bec0
54.558559
290
0.717529
5.731413
false
false
false
false
gintsmurans/SwiftCollection
Sources/Controllers/BasicSearchController.swift
1
11296
// // SearchUserController.swift // // Created by Gints Murans on 18.02.16. // Copyright © 2016 Gints Murans. All rights reserved. // #if !os(macOS) import UIKit public enum BasicSearchControllerError : Error { case loadDataNotImplemented case additionalUserInfoDataRequired case generalError(message: String) var description: String { get { switch self { case .loadDataNotImplemented: return "Method loadData is not yet overridden" case .additionalUserInfoDataRequired: return "Some additional data set in userInfo is required" case .generalError(let message): return "Error: \(message)" } } } } public typealias BasicSearchControllerCallback = (_ selectedItem: [String: Any?]?)->() /** BasicSearchController - Interface for basic search UITableView, can be customized when extended. FilterData example for scope: let categoryMatch = (scope.lowercaseString == "all" || (item["group_name"] as! String).lowercaseString == scope.lowercaseString) if (searchText == "") { return categoryMatch } else { return categoryMatch && ( (item["ean_code"] as! String).lowercaseString.containsString(searchText.lowercaseString) || (item["title"] as! String).lowercaseString.containsString(searchText.lowercaseString) ) } */ open class BasicSearchController: UITableViewController, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate { public let searchController = UISearchController(searchResultsController: nil) open var userInfo: NSMutableDictionary = NSMutableDictionary() open var tableReuseIdentificator = "BasicSearchControllerCell" open var data: [[String: Any?]]? { didSet { guard let groupBy = self.dataGroupedByKey else { return } guard let data = self.data else { return } // Categorize and map let categories = data.categorise { (item) -> String in return (item[groupBy] as! String).uppercased() } let mapped = categories.map { (item) -> (name: String, items: [[String: Any?]]) in return (name: item.key, items: item.value) } // Finally sort if groupSortDirection == "ASC" { self.dataGrouped = mapped.sorted { $0.name < $1.name } } else { self.dataGrouped = mapped.sorted { $0.name > $1.name } } } } open var dataGrouped: [(name: String, items:[[String: Any?]])]? open var dataGroupedByKey: String? open var groupSortDirection: String = "ASC" open var filteredData: [[String: Any?]]? open var groups: [String]? = nil { didSet { if (groups != nil) { groups!.insert("ALL", at: 0) searchController.searchBar.scopeButtonTitles = groups searchController.searchBar.sizeToFit() } } } open var selectedItem: [String: Any?]? open var selectItemCallback: BasicSearchControllerCallback? open var readyToLoadData = true open var noRefresh: Bool = false open var noSearchBar: Bool = false open var searchWrapperView: UIView? // MARK: - View Lifecycle override open func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = false self.definesPresentationContext = true // Setup the Search Controller if self.noSearchBar == false { searchController.delegate = self searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = true searchController.searchBar.scopeButtonTitles = groups if let wrapperView = self.searchWrapperView { wrapperView.addSubview(searchController.searchBar) } else { self.tableView.tableHeaderView = searchController.searchBar } searchController.searchBar.sizeToFit() } // Refresh control if noRefresh == false { self.refreshControl = UIRefreshControl() self.refreshControl?.addTarget(self, action: #selector(self.refreshData(_:)), for: UIControl.Event.valueChanged) } // Load data if readyToLoadData { do { try self.loadData() } catch { print(error) } } } deinit { // Fix UISearchController issues if searchController.view.superview != nil { searchController.view.removeFromSuperview() } } // MARK: - Helpers /// Load data open func loadData(_ ignoreCache: Bool = false) throws { throw BasicSearchControllerError.loadDataNotImplemented } /// Load data ignoring cache @IBAction open func refreshData(_ sender: AnyObject?) { if readyToLoadData { do { try self.loadData(true) } catch { print(error) } } } open func beginRefreshing() { guard let refreshControl = self.refreshControl else { return } refreshControl.beginRefreshing() } open func endRefreshing() { guard let refreshControl = self.refreshControl else { return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) { refreshControl.endRefreshing() } } open func displayText(_ item: [String: Any?], cell: UITableViewCell? = nil) -> String? { return item["name"] as? String } open func displayDetailsText(_ item: [String: Any?], cell: UITableViewCell? = nil) -> String? { return item["name"] as? String } open func displayGroupText(_ text: String, items: [[String: Any?]]) -> String? { return text } open func customCell(_ item: [String: Any?], cell: UITableViewCell?) { if let cell = cell { cell.textLabel?.text = self.displayText(item, cell: cell) cell.detailTextLabel?.text = self.displayDetailsText(item, cell: cell) } } open func filterData(_ searchText: String, scope: String?) -> (Dictionary<String, Any>) -> (Bool) { return {(item : Dictionary<String, Any>) -> Bool in return (item["name"] as! String).lowercased().contains(searchText.lowercased()) } } // MARK: - Table View override open func numberOfSections(in tableView: UITableView) -> Int { if searchController.searchBar.text != "" || searchController.searchBar.selectedScopeButtonIndex > 0 || tableView.style == .plain || self.dataGrouped == nil { return 1 } return self.dataGrouped!.count } open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if searchController.searchBar.text != "" || searchController.searchBar.selectedScopeButtonIndex > 0 || tableView.style == .plain || self.dataGrouped == nil { return nil } return self.displayGroupText(self.dataGrouped![section].name, items: self.dataGrouped![section].items) } override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if filteredData != nil && (searchController.searchBar.text != "" || searchController.searchBar.selectedScopeButtonIndex > 0) { return filteredData!.count } if tableView.style == .plain || self.dataGrouped == nil { return data == nil ? 0 : data!.count } return self.dataGrouped![section].items.count } override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: tableReuseIdentificator, for: indexPath) let item: [String: Any?] if filteredData != nil && (searchController.searchBar.text != "" || searchController.searchBar.selectedScopeButtonIndex > 0) { item = filteredData![(indexPath as NSIndexPath).row] } else if tableView.style == .plain || self.dataGrouped == nil { item = data![(indexPath as NSIndexPath).row] } else { item = dataGrouped![indexPath.section].items[indexPath.row] } self.customCell(item, cell: cell) return cell } override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if filteredData != nil && (searchController.searchBar.text != "" || searchController.searchBar.selectedScopeButtonIndex > 0) { selectedItem = filteredData![(indexPath as NSIndexPath).row] } else if tableView.style == .plain || self.dataGrouped == nil { selectedItem = data![(indexPath as NSIndexPath).row] } else { selectedItem = dataGrouped![indexPath.section].items[indexPath.row] } if let callback = self.selectItemCallback { callback(self.selectedItem) } } // MARK: - Filter open func filterContentForSearchText(_ searchText: String, scope: String?) { guard let data = self.data else { return } filteredData = data.filter(self.filterData(searchText, scope: scope)) tableView.reloadData() } // MARK: - UISearchBar Delegate open func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { guard let text = searchBar.text else { return } filterContentForSearchText(text, scope: searchBar.scopeButtonTitles![selectedScope]) } // MARK: - UISearchResultsUpdating Delegate open func updateSearchResults(for searchController: UISearchController) { let searchBar = searchController.searchBar var scope: String? if let scopes = searchBar.scopeButtonTitles { scope = scopes[searchBar.selectedScopeButtonIndex] } guard let text = searchController.searchBar.text else { return } filterContentForSearchText(text, scope: scope) } // MARK: - UISearchController Delegate func resizeTableViewHeaderHeight() { guard let headerView = self.tableView.tableHeaderView else { return } let height = searchController.searchBar.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height if let wrapperView = self.searchWrapperView { wrapperView.frame.size.height = height } else { headerView.frame.size.height = height } } public func didPresentSearchController(_ searchController: UISearchController) { resizeTableViewHeaderHeight() } public func didDismissSearchController(_ searchController: UISearchController) { resizeTableViewHeaderHeight() } } #endif
mit
9ae787071c358558afcbf0b07fd7f14d
32.616071
165
0.620806
5.282975
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 2/4-3 Playgrounds/Closures.playground/Pages/Retain Cycles.xcplaygroundpage/Contents.swift
1
10883
//: [Previous](@previous) import UIKit import XCPlayground //: ![Closures](Banner.jpg) //: ## Retain Cycles and Capture Lists //:[The Swift Programming Language]: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID48 "Open in Browser" //: //:For more information, see the chapter on Automatic Reference Counting in [The Swift Programming Language]. //: So far, we've not discussed memory management. The reason for this is simply that there was little need. //: For value types (the majority), you can think of these like an `int` or `double` in C or C++. There is one copy, and one //: (under the hood) reference to it. Assign a value type to another, and a copy is made. *The lifetime of value types is dictated by scope*. //: //: [Dangling Reference]: https://en.wikipedia.org/wiki/Dangling_pointer "Open in Browser" //: //: Reference types are different and present greater challenges in terms of memory management. //: * You can have multiple references to the same object. //: * Classes, closures and functions are all reference types. //: * If an object is deallocated, but references to that object still exist, these are known as a [Dangling Reference] and if dereferened, can cause a crash. //: //: A system known as *reference counting* is used to decide when to deallocate an object. //: * The **reference count** is simply the number of **strong** references to an object. //: * **weak** or **unowned** references do not contribute to the reference count. //: * when an object is first instantiated, it has a reference count of 1 //: * for each additional strong reference that is made, the reference count is automatically incremented by 1 //: * for every strong reference that is lost, the reference count is decremented by 1 //: * the increment and decrement of reference counts is performed by hidden code that is added to your source by the build tools //: * when a reference count becomes zero, the object is dealloced AND all `weak` references are set to nil //: * **note**: You can only make `weak` references to Optional types (only Optionals can be `nil`) //: * for all others, you use `unowned` //: //: For example, in the figure below *object 2 has a retain count of RC = 2* //: * `object 1` instantiates `object2`, and maintains a strong reference to it //: * `object 3` also stores a strong reference to `object 2` (by assignment) //: * `object 4` also stores a reference to `object 2`, but this is a *weak reference*. This has no impact on the retain count. //: ![References](references.jpg) //: To deallocate `object 2`, all strong references much be lost //: * If `object 3` is deallocated, then then RC will drop to RC = 1 //: * If `object 1` is *then* delallocated two things will happen: //: * `object 2` will be deallocated because RC=0 //: * The reference in `object 4` will become automatically set to `nil` //: We can demonstrate this in code. class Object2 { let _id : String init(id : String) { print("Init \(id)",separator: "", terminator: "") _id = id } deinit { print("deinit \(_id)",separator: "", terminator: "") if _id == "Object 2" { XCPlaygroundPage.currentPage.captureValue(_id, withIdentifier: "Object 2 is deallocated") } } } class Object1or3 : Object2 { let strongReference : Object2 override init(id : String) { strongReference = Object2(id: "Object 2") super.init(id: id) } init(id: String, ref: Object2) { strongReference = ref super.init(id: id) } } class Object4 : Object2 { //Put a property observer on this property weak var weakReference : Object2? init(id: String, ref: Object2) { weakReference = ref super.init(id: id) } } //: Create references for 1,3 and 4 var object1 : Object1or3? var object3 : Object1or3? var object4 : Object4? //: To demonstrate the weak reference behaviour in a Playground, I need to write this in a function func testARC() { //: Instantiate `object1`, which in turn instantiates `object2` object1 = Object1or3(id: "Object 1") //: We can confirm that `object2` also exists object1?.strongReference._id //:Instantiate `object3`, and give a reference to `object2` object3 = Object1or3(id: "Object 3", ref: object1!.strongReference) //:Instantuate `object4`, and give a weak reference to `object2` object4 = Object4(id: "Object 4", ref: object1!.strongReference) //: **EXPERIMENT** //: * Uncomment each of the following lines to dealocate the associated objects in turn. //: * Observe the deinit methods on the above classes //: * or view the timeline and look for the message "Object 2 is deallocated" // object1 = nil // object3 = nil //: Note - the process of deallocation and setting weak pointers to nil may not complete immediately. If it does not, it will occur at the end of the current scope and/or run-loop. For those who were writing Objective C before ARC, this suggests it is *autoreleased*. object4?.weakReference?._id } //: Run the experiment testARC() //: **EXPERIMENT FOLLOW UP** //: Here we see how the weak reference is now automatically set to `nil`. Comment out either of the two lines again and see this change. object4?.weakReference?._id //: Apple use a technology they call Automatic Reference Counting (ARC) to handle reference counting for you. For the most part, you don't have to do anything. However, there is one scenario where you need to intervene, and that is the avoidance *retain cycles*. This is not difficult to do, and is a small price to pay for the convenience ARC brings. Furthermore, ARC removes the need for a garbage collector. //: //: Remember - this discussion only applies to *reference types* (classes, closures and functions) //: #### SCENARIO 1 - strong reverse reference //: All pet owners need this basic skill protocol CanOpenATin : class { func openPetFoodTin() -> Bool } //: Pet class - has a reverse reference back to the owner. This class does not instantiate the owner, so therefore should not noramlly maintain a strong reference to its owner. class Pet { let timeLastFed = NSDate() let name : String var isHungry : Bool { get { let hrsElapsed = NSDate().timeIntervalSinceDate(timeLastFed) / 3600.0 return hrsElapsed > 12 } } //Reverse reference weak var owner : CanOpenATin? //: **EXPERIMENT** //: //: * check the `deinit` function in `Owner` being called (also shown in the timeline) //: * now remove the word `weak` from the above statement and check again //Designated initialiser - must be called (so that all properties are initialised) init(name petName : String) { name = petName } } //: Owner class - instantiates the pet object, so maintans a strong reference to it. //: It also conforms to the protocol `CanOpenATin`, thus guaranteeing it will implement the method `openPetFoodTin() -> Bool` class Owner : CanOpenATin { let onlyPet : Pet //Strong reference func openPetFoodTin() -> Bool { return true } //Designated initialiser - must be called (so that all properties are initialised) init(withPet pet : Pet) { onlyPet = pet pet.owner = self XCPlaygroundPage.currentPage.captureValue(pet.name, withIdentifier: "Pet Name") } //This should be called once there are no more strong references to this instance deinit { print("Deallocating", terminator: "") XCPlaygroundPage.currentPage.captureValue(onlyPet.name, withIdentifier: "Owner for the following pet is being deallocated") } } //: Two strong references to pets - these will survive let cat = Pet(name: "Yoda") let dog = Pet(name: "Chewy") //: First, the owner with a cat var owner = Owner(withPet: cat) //: Double check everything is hooked up if let opened = cat.owner?.openPetFoodTin() where opened == true { print("Purrrrrr",separator: "", terminator: "") } //: Now switch the reference to another instance of Owner. The old should be deallocated as this was the only reference. //: This new owner wants a dog owner = Owner(withPet: dog) //: Perform the above experiement, and you will find that the first owner is never delalocated, yet we no longer have a reference to it! //: This memory leak is caused by the strong reverse reference from the instance of cat back to its owner. I cannot deallocate cat, and I //: don't want to as I might want to realocate to another owner. //: #### SCENARIO 2 - closure properties referencing self //: We have not yet discussed properties, although we've added them in view controllers in previous exercises. Whenever you add an instance variable to a class or strucure, you are in fact adding a property. Many properties are value types - this is simple. Problems with memory management can only occur with reference types. We saw previously how a reference to a class can lead to a retain cycle. Closures are also reference types, and thus need careful handling when set as a class property. //: Let's go back to a simple idea class Person { //Properties private let lastName : String private let title : String? //Although Optional, I can use let because it is guaranteed to be initialised in init // Salutation is a reference type (a closure) lazy var giveTime : () -> String = { //Capture list - written in [ square braces] before the parameters and 'in' //Listing self as unowned prevents a retain cycle //Note that in this context, self cannot be nil, so we saw it is "unowned" as opposed to "weak" //: **EXPERIMENT** Comment out the following line (capture list) - does the de-init still run? (check in the timeline for the words "Instance being deallocated Spock" [unowned self] in //: NOTE how this closure makes reference to self, therefore captures it by default let tmStr = ", it is \(NSDate())" if let t = self.title { return t + " " + self.lastName + tmStr } else { return self.lastName + tmStr } } //Designated initialised - this has to be called so that the properties are initialised init(lastName name : String, title: String?) { self.lastName = name self.title = title } //This should run when deallocated deinit { print("Deallocating person \(lastName)", terminator: "") XCPlaygroundPage.currentPage.captureValue(self.lastName, withIdentifier: "Instance being deallocated") } } var person : Person? = Person(lastName: "Spock", title: "Mr") person?.giveTime() person = nil //: At this point the `deinit` method *should* run as the `Spock` instance has no remaining strong references. //: [Next](@next)
mit
962eb3f7cc91fb30c71239220770ee43
40.538168
495
0.699072
4.099058
false
false
false
false
andreuke/tasty-imitation-keyboard
Keyboard/EditProfiles.swift
2
15336
// // EditProfile.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 11/2/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // import UIKit import SQLite class EditProfiles: ExtraView, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView? @IBOutlet var effectsView: UIVisualEffectView? @IBOutlet weak var addButton: UIBarButtonItem! @IBOutlet weak var keyboardButton: UIBarButtonItem! @IBOutlet var settingsLabel: UILabel? @IBOutlet var pixelLine: UIView? var callBack: (String) -> () var deleteCallback: (String) -> () override var darkMode: Bool { didSet { self.updateAppearance(darkMode) } } let cellBackgroundColorDark = UIColor.white.withAlphaComponent(CGFloat(0.25)) let cellBackgroundColorLight = UIColor.white.withAlphaComponent(CGFloat(1)) let cellLabelColorDark = UIColor.white let cellLabelColorLight = UIColor.black let cellLongLabelColorDark = UIColor.lightGray let cellLongLabelColorLight = UIColor.gray var deleteScreen:DeleteViewController? // TODO: these probably don't belong here, and also need to be localized var profilesList: [(String, [String])]? required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) { self.callBack = tempCallBack self.deleteCallback = tempCallBack super.init(globalColors: globalColors, darkMode: darkMode, solidColorMode: solidColorMode) self.loadNib() let profiles: [String] = Database().getProfiles() self.profilesList = [("Profiles", profiles)] } required init?(coder aDecoder: NSCoder) { fatalError("loading from nib not supported") } required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool, outputFunc: () -> Void) { fatalError("init(globalColors:darkMode:solidColorMode:outputFunc:) has not been implemented") } func loadNib() { let assets = Bundle(for: type(of: self)).loadNibNamed("EditProfile", owner: self, options: nil) if (assets?.count)! > 0 { if let rootView = assets?.first as? UIView { rootView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(rootView) let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0) let right = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.right, multiplier: 1, constant: 0) let top = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0) self.addConstraint(left) self.addConstraint(right) self.addConstraint(top) self.addConstraint(bottom) } } self.tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell") self.tableView?.estimatedRowHeight = 44; self.tableView?.rowHeight = UITableViewAutomaticDimension; let longpress = UILongPressGestureRecognizer(target: self, action: #selector(EditProfiles.longPressGestureRecognized(_:))) self.tableView?.addGestureRecognizer(longpress) let tap = UITapGestureRecognizer(target: self, action: #selector(EditProfiles.clickCallback(_:))) self.tableView?.addGestureRecognizer(tap) // XXX: this is here b/c a totally transparent background does not support scrolling in blank areas self.tableView?.backgroundColor = UIColor.white.withAlphaComponent(0.01) self.updateAppearance(self.darkMode) } ///drag and drop code func longPressGestureRecognized(_ gestureRecognizer: UIGestureRecognizer) { let longPress = gestureRecognizer as! UILongPressGestureRecognizer let state = longPress.state let locationInView = longPress.location(in: tableView) let indexPath = tableView?.indexPathForRow(at: locationInView) struct My { static var cellSnapshot : UIView? = nil static var cellIsAnimating : Bool = false static var cellNeedToShow : Bool = false } struct Path { static var initialIndexPath : IndexPath? = nil } switch state { case UIGestureRecognizerState.began: if indexPath != nil { Path.initialIndexPath = indexPath let cell = tableView?.cellForRow(at: indexPath!) as UITableViewCell! My.cellSnapshot = snapshotOfCell(cell!) var center = cell?.center My.cellSnapshot!.center = center! My.cellSnapshot!.alpha = 0.0 tableView?.addSubview(My.cellSnapshot!) UIView.animate(withDuration: 0.25, animations: { () -> Void in center?.y = locationInView.y My.cellIsAnimating = true My.cellSnapshot!.center = center! My.cellSnapshot!.transform = CGAffineTransform(scaleX: 1.05, y: 1.05) My.cellSnapshot!.alpha = 0.98 cell?.alpha = 0.0 }, completion: { (finished) -> Void in if finished { My.cellIsAnimating = false if My.cellNeedToShow { My.cellNeedToShow = false UIView.animate(withDuration: 0.25, animations: { () -> Void in cell?.alpha = 1 }) } else { cell?.isHidden = true } } }) } case UIGestureRecognizerState.changed: if My.cellSnapshot != nil { var center = My.cellSnapshot!.center center.y = locationInView.y My.cellSnapshot!.center = center if ((indexPath != nil) && (indexPath != Path.initialIndexPath)) { self.profilesList![0].1.insert(self.profilesList![0].1.remove(at: Path.initialIndexPath!.row), at: indexPath!.row) tableView?.moveRow(at: Path.initialIndexPath!, to: indexPath!) Path.initialIndexPath = indexPath } } default: if Path.initialIndexPath != nil { let cell = tableView?.cellForRow(at: Path.initialIndexPath!) as UITableViewCell! if My.cellIsAnimating { My.cellNeedToShow = true } else { cell?.isHidden = false cell?.alpha = 0.0 } UIView.animate(withDuration: 0.25, animations: { () -> Void in My.cellSnapshot!.center = (cell?.center)! My.cellSnapshot!.transform = CGAffineTransform.identity My.cellSnapshot!.alpha = 0.0 cell?.alpha = 1.0 }, completion: { (finished) -> Void in if finished { Path.initialIndexPath = nil My.cellSnapshot!.removeFromSuperview() My.cellSnapshot = nil if indexPath != nil { let profileName = self.profilesList![0].1[indexPath!.row] let newRow = indexPath!.row Database().reorderProfiles(profileName: profileName, newRowNum: newRow) } } }) } } } func snapshotOfCell(_ inputView: UIView) -> UIView { UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0) inputView.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() let cellSnapshot : UIView = UIImageView(image: image) cellSnapshot.layer.masksToBounds = false cellSnapshot.layer.cornerRadius = 0.0 cellSnapshot.layer.shadowOffset = CGSize(width: -5.0, height: 0.0) cellSnapshot.layer.shadowRadius = 5.0 cellSnapshot.layer.shadowOpacity = 0.4 return cellSnapshot } //table functions func numberOfSections(in tableView: UITableView) -> Int { return self.profilesList!.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.profilesList![section].1.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == (self.profilesList?.count)! - 1 { return 50 } else { return 0 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.profilesList?[section].0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") { let key = self.profilesList?[(indexPath as NSIndexPath).section].1[(indexPath as NSIndexPath).row] let title = key! cell.textLabel?.text = title cell.backgroundColor = (self.darkMode ? cellBackgroundColorDark : cellBackgroundColorLight) cell.accessoryType = .disclosureIndicator return cell } else { assert(false, "this is a bad thing that just happened") return UITableViewCell() } } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let profile = (self.profilesList?[(indexPath as NSIndexPath).section].1[(indexPath as NSIndexPath).row])! if profile != "Default" { let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in self.deleteScreen = DeleteViewController(view: self as UIView, type: "profile", name: profile) self.deleteScreen?.cancelButton.addTarget(self, action: #selector(self.removeDeleteScreen), for: .touchUpInside) self.deleteScreen?.deleteButton.tag = (indexPath as NSIndexPath).row self.deleteScreen?.deleteButton.addTarget(self, action: #selector(self.deleteElm(_:)), for: .touchUpInside) } return [delete] } else { let noDelete = UITableViewRowAction(style: .normal, title: "Delete") { (action, indexPath) in self.tableView?.setEditing(false, animated: false) } return [noDelete] } } func updateAppearance(_ dark: Bool) { if dark { self.effectsView?.effect let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.withAlphaComponent(CGFloat(0.5)) self.settingsLabel?.textColor = UIColor.white if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { cell.backgroundColor = cellBackgroundColorDark let label = cell.viewWithTag(2) as? UILabel label?.textColor = cellLabelColorDark let longLabel = cell.viewWithTag(3) as? UITextView longLabel?.textColor = cellLongLabelColorDark } } } else { let blueColor = UIColor(red: 0/CGFloat(255), green: 122/CGFloat(255), blue: 255/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.withAlphaComponent(CGFloat(0.5)) self.settingsLabel?.textColor = UIColor.gray if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { cell.backgroundColor = cellBackgroundColorLight let label = cell.viewWithTag(2) as? UILabel label?.textColor = cellLabelColorLight let longLabel = cell.viewWithTag(3) as? UITextView longLabel?.textColor = cellLongLabelColorLight } } } } func toggleSetting(_ sender: UISwitch) { if let cell = sender.superview as? UITableViewCell { if let indexPath = self.tableView?.indexPath(for: cell) { let key = self.profilesList?[(indexPath as NSIndexPath).section].1[(indexPath as NSIndexPath).row] UserDefaults.standard.set(sender.isOn, forKey: key!) } } } func clickCallback(_ gestureRecognizer: UIGestureRecognizer) { let tap = gestureRecognizer as! UITapGestureRecognizer let locationInView = tap.location(in: tableView) let indexPath = tableView?.indexPathForRow(at: locationInView) if (self.tableView?.isEditing == false) { let text = self.profilesList?[((indexPath)?.section)!].1[(((indexPath))?.row)!] self.callBack(text!) } } func removeDeleteScreen() { if self.deleteScreen != nil { self.deleteScreen?.warningView.removeFromSuperview() } self.tableView?.setEditing(false, animated: false) self.deleteScreen = nil } func deleteElm(_ sender:UIButton) { let profile = (self.profilesList?[0].1[sender.tag])! self.deleteCallback(profile) /*Database().deleteProfile(profile_name: profile) UserDefaults.standard.string(forKey: "profile") UserDefaults.standard.register(defaults: ["profile": "Default"]) self.banner?.profileSelector.setTitle(UserDefaults.standard.string(forKey: "profile")!, for: UIControlState())*/ removeDeleteScreen() self.reloadData() } func reloadData() { let profiles: [String] = Database().getProfiles() self.profilesList = [("Profiles", profiles)] tableView?.reloadData() } } func tempCallBack(tempString:String) { print("Not innitialized") }
bsd-3-clause
f89748d53f37e6aec2b3593218723da5
42.2
214
0.591875
5.351012
false
false
false
false
HarukaMa/iina
iina/PlayerCore.swift
1
25970
// // PlayerCore.swift // iina // // Created by lhc on 8/7/16. // Copyright © 2016年 lhc. All rights reserved. // import Cocoa class PlayerCore: NSObject { static let shared = PlayerCore() unowned let ud: UserDefaults = UserDefaults.standard var mainWindow: MainWindowController? lazy var mpvController: MPVController = MPVController() let supportedSubtitleFormat: [String] = ["utf", "utf8", "utf-8", "idx", "sub", "srt", "smi", "rt", "txt", "ssa", "aqt", "jss", "js", "ass", "mks", "vtt", "sup"] lazy var info: PlaybackInfo = PlaybackInfo() var syncPlayTimeTimer: Timer? var displayOSD: Bool = true var isMpvTerminated: Bool = false // test seeking var triedUsingExactSeekForCurrentFile: Bool = false var useExactSeekForCurrentFile: Bool = true // need enter fullscreen for nect file var needEnterFullScreenForNextMedia: Bool = true static var keyBindings: [String: KeyMapping] = [:] // MARK: - Control commands // Open a file func openFile(_ url: URL?) { guard let path = url?.path else { Utility.log("Error: empty file path or url") return } openMainWindow(path: path, url: url!, isNetwork: false) } func openURL(_ url: URL) { let path = url.absoluteString openMainWindow(path: path, url: url, isNetwork: true) } func openURLString(_ str: String) { guard let str = str.addingPercentEncoding(withAllowedCharacters: .urlAllowed), let url = URL(string: str) else { return } openMainWindow(path: str, url: url, isNetwork: true) } private func openMainWindow(path: String, url: URL, isNetwork: Bool) { if mainWindow == nil || !mainWindow!.isWindowLoaded { mainWindow = nil mainWindow = MainWindowController() } info.currentURL = url info.isNetworkResource = isNetwork mainWindow!.showWindow(nil) mainWindow!.windowDidOpen() // Send load file command info.fileLoading = true info.justOpenedFile = true mpvController.command(.loadfile, args: [path]) } func startMPV() { // set path for youtube-dl let oldPath = String(cString: getenv("PATH")!) var path = Utility.exeDirURL.path + ":" + oldPath if let customYtdlPath = ud.string(forKey: Preference.Key.ytdlSearchPath), !customYtdlPath.isEmpty { path = customYtdlPath + ":" + path } setenv("PATH", path, 1) // load keybindings let userConfigs = UserDefaults.standard.dictionary(forKey: Preference.Key.inputConfigs) var inputConfPath = PrefKeyBindingViewController.defaultConfigs["IINA Default"] if let confFromUd = UserDefaults.standard.string(forKey: Preference.Key.currentInputConfigName) { if let currentConfigFilePath = Utility.getFilePath(Configs: userConfigs, forConfig: confFromUd, showAlert: false) { inputConfPath = currentConfigFilePath } } let mapping = KeyMapping.parseInputConf(at: inputConfPath!)! PlayerCore.keyBindings = [:] mapping.forEach { PlayerCore.keyBindings[$0.key] = $0 } // set http proxy if let proxy = ud.string(forKey: Preference.Key.httpProxy), !proxy.isEmpty { setenv("http_proxy", "http://" + proxy, 1) } mpvController.mpvInit() } func startMPVOpenGLCB(_ videoView: VideoView) { let mpvGLContext = mpvController.mpvInitCB() videoView.mpvGLContext = OpaquePointer(mpvGLContext) } // unload main window video view func unloadMainWindowVideoView() { guard let mw = mainWindow, mw.isWindowLoaded else { return } mw.videoView.uninit() } // Terminate mpv func terminateMPV(sendQuit: Bool = true) { guard !isMpvTerminated else { return } savePlaybackPosition() invalidateTimer() unloadMainWindowVideoView() if sendQuit { mpvController.mpvQuit() } isMpvTerminated = true } // invalidate timer func invalidateTimer() { syncPlayTimeTimer?.invalidate() } // MARK: - MPV commands /** Pause / resume. Reset speed to 0 when pause. */ func togglePause(_ set: Bool?) { if let setPause = set { // if paused by EOF, replay the video. if !setPause { if mpvController.getFlag(MPVProperty.eofReached) { seek(absoluteSecond: 0) } } mpvController.setFlag(MPVOption.PlaybackControl.pause, setPause) } else { if (info.isPaused) { if mpvController.getFlag(MPVProperty.eofReached) { seek(absoluteSecond: 0) } mpvController.setFlag(MPVOption.PlaybackControl.pause, false) } else { mpvController.setFlag(MPVOption.PlaybackControl.pause, true) } } } func stop() { mpvController.command(.stop) invalidateTimer() } func toogleMute(_ set: Bool?) { let newState = set ?? !mpvController.getFlag(MPVOption.Audio.mute) mpvController.setFlag(MPVOption.Audio.mute, newState) } func seek(percent: Double, forceExact: Bool = false) { let useExact = forceExact ? true : ud.bool(forKey: Preference.Key.useExactSeek) let seekMode = useExact ? "absolute-percent+exact" : "absolute-percent" mpvController.command(.seek, args: ["\(percent)", seekMode], checkError: false) } func seek(relativeSecond: Double, option: Preference.SeekOption) { switch option { case .relative: mpvController.command(.seek, args: ["\(relativeSecond)", "relative"], checkError: false) case .extract: mpvController.command(.seek, args: ["\(relativeSecond)", "relative+exact"], checkError: false) case .auto: // for each file , try use exact and record interval first if !triedUsingExactSeekForCurrentFile { mpvController.recordedSeekTimeListener = { [unowned self] interval in // if seek time < 0.05, then can use exact self.useExactSeekForCurrentFile = interval < 0.05 } mpvController.needRecordSeekTime = true triedUsingExactSeekForCurrentFile = true } let seekMode = useExactSeekForCurrentFile ? "relative+exact" : "relative" mpvController.command(.seek, args: ["\(relativeSecond)", seekMode], checkError: false) } } func seek(absoluteSecond: Double) { mpvController.command(.seek, args: ["\(absoluteSecond)", "absolute+exact"]) } func frameStep(backwards: Bool) { if backwards { mpvController.command(.frameBackStep) } else { mpvController.command(.frameStep) } } func screenShot() { let option = ud.bool(forKey: Preference.Key.screenshotIncludeSubtitle) ? "subtitles" : "video" mpvController.command(.screenshot, args: [option]) sendOSD(.screenShot) } func abLoop() { // may subject to change mpvController.command(.abLoop) let a = mpvController.getDouble(MPVOption.PlaybackControl.abLoopA) let b = mpvController.getDouble(MPVOption.PlaybackControl.abLoopB) if a == 0 && b == 0 { info.abLoopStatus = 0 } else if b != 0 { info.abLoopStatus = 2 } else { info.abLoopStatus = 1 } sendOSD(.abLoop(info.abLoopStatus)) } func toggleFileLoop() { let isLoop = mpvController.getFlag(MPVOption.PlaybackControl.loopFile) mpvController.setFlag(MPVOption.PlaybackControl.loopFile, !isLoop) } func togglePlaylistLoop() { let loopStatus = mpvController.getString(MPVOption.PlaybackControl.loop) let isLoop = (loopStatus == "inf" || loopStatus == "force") mpvController.setString(MPVOption.PlaybackControl.loop, isLoop ? "no" : "inf") } func toggleShuffle() { mpvController.command(.playlistShuffle) NotificationCenter.default.post(Notification(name: Constants.Noti.playlistChanged)) } func setVolume(_ volume: Double, constrain: Bool = true) { let constrainedVolume = volume.constrain(min: 0, max: 100) let appliedVolume = constrain ? constrainedVolume : volume info.volume = appliedVolume mpvController.setDouble(MPVOption.Audio.volume, appliedVolume) ud.set(constrainedVolume, forKey: Preference.Key.softVolume) } func setTrack(_ index: Int, forType: MPVTrack.TrackType) { let name: String switch forType { case .audio: name = MPVOption.TrackSelection.aid case .video: name = MPVOption.TrackSelection.vid case .sub: name = MPVOption.TrackSelection.sid case .secondSub: name = MPVOption.Subtitles.secondarySid } mpvController.setInt(name, index) getSelectedTracks() } /** Set speed. */ func setSpeed(_ speed: Double) { mpvController.setDouble(MPVOption.PlaybackControl.speed, speed) info.playSpeed = speed } func setVideoAspect(_ aspect: String) { if Regex.aspect.matches(aspect) { mpvController.setString(MPVProperty.videoAspect, aspect) info.unsureAspect = aspect } else { mpvController.setString(MPVProperty.videoAspect, "-1") // if not a aspect string, set aspect to default, and also the info string. info.unsureAspect = "Default" } } func setVideoRotate(_ degree: Int) { if AppData.rotations.index(of: degree)! >= 0 { mpvController.setInt(MPVOption.Video.videoRotate, degree) info.rotation = degree } } func setFlip(_ enable: Bool) { if enable { if info.flipFilter == nil { let vf = MPVFilter.flip() if addVideoFilter(vf) { info.flipFilter = vf } } } else { if let vf = info.flipFilter { removeVideoFiler(vf) info.flipFilter = nil } } } func setMirror(_ enable: Bool) { if enable { if info.mirrorFilter == nil { let vf = MPVFilter.mirror() if addVideoFilter(vf) { info.mirrorFilter = vf } } } else { if let vf = info.mirrorFilter { removeVideoFiler(vf) info.mirrorFilter = nil } } } func toggleDeinterlace(_ enable: Bool) { mpvController.setFlag(MPVOption.Video.deinterlace, enable) } enum VideoEqualizerType { case brightness, contrast, saturation, gamma, hue } func setVideoEqualizer(forOption option: VideoEqualizerType, value: Int) { let optionName: String switch option { case .brightness: optionName = MPVOption.Equalizer.brightness case .contrast: optionName = MPVOption.Equalizer.contrast case .saturation: optionName = MPVOption.Equalizer.saturation case .gamma: optionName = MPVOption.Equalizer.gamma case .hue: optionName = MPVOption.Equalizer.hue } mpvController.command(.set, args: [optionName, value.toStr()]) } func loadExternalAudioFile(_ url: URL) { mpvController.command(.audioAdd, args: [url.path], checkError: false) { code in if code < 0 { DispatchQueue.main.async { Utility.showAlert("unsupported_audio") } } } } func loadExternalSubFile(_ url: URL) { guard !(info.subTracks.contains { $0.externalFilename == url.path }) else { return } mpvController.command(.subAdd, args: [url.path], checkError: false) { code in if code < 0 { DispatchQueue.main.async { Utility.showAlert("unsupported_sub") } } } } func setAudioDelay(_ delay: Double) { mpvController.setDouble(MPVOption.Audio.audioDelay, delay) } func setSubDelay(_ delay: Double) { mpvController.setDouble(MPVOption.Subtitles.subDelay, delay) } func addToPlaylist(_ path: String) { mpvController.command(.loadfile, args: [path, "append"]) } func playlistMove(_ from: Int, to: Int) { mpvController.command(.playlistMove, args: ["\(from)", "\(to)"]) } func playlistRemove(_ index: Int) { mpvController.command(.playlistRemove, args: [index.toStr()]) } func clearPlaylist() { mpvController.command(.playlistClear) } func removeFromPlaylist(index: Int) { mpvController.command(.playlistRemove, args: ["\(index)"]) } func playFile(_ path: String) { info.justOpenedFile = true mpvController.command(.loadfile, args: [path, "replace"]) getPLaylist() } func playFileInPlaylist(_ pos: Int) { mpvController.setInt(MPVProperty.playlistPos, pos) getPLaylist() } func navigateInPlaylist(nextOrPrev: Bool) { mpvController.command(nextOrPrev ? .playlistNext : .playlistPrev) } func playChapter(_ pos: Int) { let chapter = info.chapters[pos] mpvController.command(.seek, args: ["\(chapter.time.second)", "absolute"]) // need to update time pos syncUITime() } func setCrop(fromString str: String) { let vwidth = info.videoWidth! let vheight = info.videoHeight! if let aspect = Aspect(string: str) { let cropped = NSMakeSize(CGFloat(vwidth), CGFloat(vheight)).crop(withAspect: aspect) let vf = MPVFilter.crop(w: Int(cropped.width), h: Int(cropped.height), x: nil, y: nil) setCrop(fromFilter: vf) // warning! may should not update it here info.unsureCrop = str info.cropFilter = vf } else { if let filter = info.cropFilter { removeVideoFiler(filter) info.unsureCrop = "None" } } } func setCrop(fromFilter filter: MPVFilter) { filter.label = "iina_crop" if addVideoFilter(filter) { info.cropFilter = filter } } func setAudioEq(fromFilter filter: MPVFilter) { filter.label = "iina_aeq" addAudioFilter(filter) info.audioEqFilter = filter } func removeAudioEqFilter() { if let prevFilter = info.audioEqFilter { removeAudioFilter(prevFilter) info.audioEqFilter = nil } } func addVideoFilter(_ filter: MPVFilter) -> Bool { var result = true mpvController.command(.vf, args: ["add", filter.stringFormat], checkError: false) { result = $0 >= 0 } return result } func removeVideoFiler(_ filter: MPVFilter) { mpvController.command(.vf, args: ["del", filter.stringFormat], checkError: false) } func addAudioFilter(_ filter: MPVFilter) { mpvController.command(.af, args: ["add", filter.stringFormat], checkError: false) } func removeAudioFilter(_ filter: MPVFilter) { mpvController.command(.af, args: ["del", filter.stringFormat], checkError: false) } func getAudioDevices() -> [[String: String]] { let raw = mpvController.getNode(MPVProperty.audioDeviceList) if let list = raw as? [[String: String]] { return list } else { return [] } } func setAudioDevice(_ name: String) { mpvController.setString(MPVProperty.audioDevice, name) } /** Scale is a double value in [-100, -1] + [1, 100] */ func setSubScale(_ scale: Double) { if scale > 0 { mpvController.setDouble(MPVOption.Subtitles.subScale, scale) } else { mpvController.setDouble(MPVOption.Subtitles.subScale, -scale) } } func setSubPos(_ pos: Int) { mpvController.setInt(MPVOption.Subtitles.subPos, pos) } func setSubTextColor(_ colorString: String) { mpvController.setString("options/" + MPVOption.Subtitles.subColor, colorString) } func setSubTextSize(_ size: Double) { mpvController.setDouble("options/" + MPVOption.Subtitles.subFontSize, size) } func setSubTextBold(_ bold: Bool) { mpvController.setFlag("options/" + MPVOption.Subtitles.subBold, bold) } func setSubTextBorderColor(_ colorString: String) { mpvController.setString("options/" + MPVOption.Subtitles.subBorderColor, colorString) } func setSubTextBorderSize(_ size: Double) { mpvController.setDouble("options/" + MPVOption.Subtitles.subBorderSize, size) } func setSubTextBgColor(_ colorString: String) { mpvController.setString("options/" + MPVOption.Subtitles.subBackColor, colorString) } func setSubEncoding(_ encoding: String) { mpvController.setString(MPVOption.Subtitles.subCodepage, encoding) info.subEncoding = encoding } func setSubFont(_ font: String) { mpvController.setString(MPVOption.Subtitles.subFont, font) } func execKeyCode(_ code: String) { mpvController.command(.keypress, args: [code], checkError: false) { errCode in if errCode < 0 { Utility.log("Error when executing key code (\(errCode))") } } } func savePlaybackPosition() { mpvController.command(.writeWatchLaterConfig) } struct GeometryDef { var x: String?, y: String?, w: String?, h: String?, xSign: String?, ySign: String? } func getGeometry() -> GeometryDef? { let geometry = mpvController.getString(MPVOption.Window.geometry) ?? "" // guard option value guard !geometry.isEmpty else { return nil } // match the string, replace empty group by nil let captures: [String?] = Regex.geometry.captures(in: geometry).map { $0.isEmpty ? nil : $0 } // guard matches guard captures.count == 10 else { return nil } // return struct return GeometryDef(x: captures[7], y: captures[9], w: captures[2], h: captures[4], xSign: captures[6], ySign: captures[8]) } // MARK: - Other func fileStarted() { info.justStartedFile = true info.disableOSDForFileLoading = true if let path = mpvController.getString(MPVProperty.path) { info.currentURL = URL(fileURLWithPath: path) } } /** This function is called right after file loaded. Should load all meta info here. */ func fileLoaded() { guard let mw = mainWindow else { Utility.fatal("Window is nil at fileLoaded") } guard let vwidth = info.displayWidth, let vheight = info.displayHeight else { Utility.fatal("Cannot get video width and height") } invalidateTimer() triedUsingExactSeekForCurrentFile = false info.fileLoading = false info.haveDownloadedSub = false DispatchQueue.main.sync { self.getTrackInfo() self.getSelectedTracks() self.getPLaylist() self.getChapters() syncPlayTimeTimer = Timer.scheduledTimer(timeInterval: TimeInterval(AppData.getTimeInterval), target: self, selector: #selector(self.syncUITime), userInfo: nil, repeats: true) mw.updateTitle() if #available(OSX 10.12.2, *) { mw.setupTouchBarUI() } mw.adjustFrameByVideoSize(vwidth, vheight) // whether enter full screen if needEnterFullScreenForNextMedia { if ud.bool(forKey: Preference.Key.fullScreenWhenOpen) && !mw.isInFullScreen { mw.toggleWindowFullScreen() } // only enter fullscreen for first file needEnterFullScreenForNextMedia = false } } NotificationCenter.default.post(Notification(name: Constants.Noti.fileLoaded)) } func notifyMainWindowVideoSizeChanged() { guard let mw = mainWindow else { return } guard let dwidth = info.displayWidth, let dheight = info.displayHeight else { Utility.fatal("Cannot get video width and height") } if dwidth != 0 && dheight != 0 { DispatchQueue.main.sync { mw.adjustFrameByVideoSize(dwidth, dheight) } } } func playbackRestarted() { DispatchQueue.main.async { Timer.scheduledTimer(timeInterval: TimeInterval(0.2), target: self, selector: #selector(self.reEnableOSDAfterFileLoading), userInfo: nil, repeats: false) } } @objc private func reEnableOSDAfterFileLoading() { info.disableOSDForFileLoading = false } // MARK: - Sync with UI in MainWindow // difficult to use option set enum SyncUIOption { case time case timeAndCache case playButton case volume case muteButton case chapterList case playlist } func syncUITime() { if info.isNetworkResource { syncUI(.timeAndCache) } else { syncUI(.time) } } func syncUI(_ option: SyncUIOption) { // if window not loaded, ignore guard let mw = mainWindow, mw.isWindowLoaded else { return } switch option { case .time: let time = mpvController.getDouble(MPVProperty.timePos) info.videoPosition = VideoTime(time) DispatchQueue.main.async { mw.updatePlayTime(withDuration: false, andProgressBar: true) } case .timeAndCache: let time = mpvController.getDouble(MPVProperty.timePos) info.videoPosition = VideoTime(time) info.pausedForCache = mpvController.getFlag(MPVProperty.pausedForCache) info.cacheSize = mpvController.getInt(MPVProperty.cacheSize) info.cacheUsed = mpvController.getInt(MPVProperty.cacheUsed) info.cacheSpeed = mpvController.getInt(MPVProperty.cacheSpeed) info.cacheTime = mpvController.getInt(MPVProperty.demuxerCacheTime) info.bufferingState = mpvController.getInt(MPVProperty.cacheBufferingState) DispatchQueue.main.async { mw.updatePlayTime(withDuration: true, andProgressBar: true) mw.updateNetworkState() } case .playButton: let pause = mpvController.getFlag(MPVOption.PlaybackControl.pause) info.isPaused = pause DispatchQueue.main.async { mw.updatePlayButtonState(pause ? NSOffState : NSOnState) } case .volume: DispatchQueue.main.async { mw.updateVolume() } case .muteButton: let mute = mpvController.getFlag(MPVOption.Audio.mute) DispatchQueue.main.async { mw.muteButton.state = mute ? NSOnState : NSOffState } case .chapterList: DispatchQueue.main.async { // this should avoid sending reload when table view is not ready if mw.sideBarStatus == .playlist { mw.playlistView.chapterTableView.reloadData() } } case .playlist: DispatchQueue.main.async { if mw.sideBarStatus == .playlist { mw.playlistView.playlistTableView.reloadData() } } } } func sendOSD(_ osd: OSDMessage) { // querying `mainWindow.isWindowLoaded` will initialize mainWindow unexpectly guard let mw = mainWindow, mw.isWindowLoaded else { return } if info.disableOSDForFileLoading { guard case .fileStart = osd else { return } } DispatchQueue.main.async { mw.displayOSD(osd) } } func errorOpeningFileAndCloseMainWindow() { DispatchQueue.main.async { Utility.showAlert("error_open") self.mainWindow?.close() } } func closeMainWindow() { DispatchQueue.main.async { self.mainWindow?.close() } } // MARK: - Getting info func getTrackInfo() { info.audioTracks.removeAll(keepingCapacity: true) info.videoTracks.removeAll(keepingCapacity: true) info.subTracks.removeAll(keepingCapacity: true) let trackCount = mpvController.getInt(MPVProperty.trackListCount) for index in 0..<trackCount { // get info for each track guard let trackType = mpvController.getString(MPVProperty.trackListNType(index)) else { continue } let track = MPVTrack(id: mpvController.getInt(MPVProperty.trackListNId(index)), type: MPVTrack.TrackType(rawValue: trackType)!, isDefault: mpvController.getFlag(MPVProperty.trackListNDefault(index)), isForced: mpvController.getFlag(MPVProperty.trackListNForced(index)), isSelected: mpvController.getFlag(MPVProperty.trackListNSelected(index)), isExternal: mpvController.getFlag(MPVProperty.trackListNExternal(index))) track.srcId = mpvController.getInt(MPVProperty.trackListNSrcId(index)) track.title = mpvController.getString(MPVProperty.trackListNTitle(index)) track.lang = mpvController.getString(MPVProperty.trackListNLang(index)) track.codec = mpvController.getString(MPVProperty.trackListNCodec(index)) track.externalFilename = mpvController.getString(MPVProperty.trackListNExternalFilename(index)) track.decoderDesc = mpvController.getString(MPVProperty.trackListNDecoderDesc(index)) track.demuxFps = mpvController.getDouble(MPVProperty.trackListNDemuxFps(index)) track.demuxChannels = mpvController.getString(MPVProperty.trackListNDemuxChannels(index)) track.demuxSamplerate = mpvController.getInt(MPVProperty.trackListNDemuxSamplerate(index)) // add to lists switch track.type { case .audio: info.audioTracks.append(track) case .video: info.videoTracks.append(track) case .sub: info.subTracks.append(track) default: break } } } func getSelectedTracks() { info.aid = mpvController.getInt(MPVOption.TrackSelection.aid) info.vid = mpvController.getInt(MPVOption.TrackSelection.vid) info.sid = mpvController.getInt(MPVOption.TrackSelection.sid) info.secondSid = mpvController.getInt(MPVOption.Subtitles.secondarySid) } func getPLaylist() { info.playlist.removeAll() let playlistCount = mpvController.getInt(MPVProperty.playlistCount) for index in 0..<playlistCount { let playlistItem = MPVPlaylistItem(filename: mpvController.getString(MPVProperty.playlistNFilename(index))!, isCurrent: mpvController.getFlag(MPVProperty.playlistNCurrent(index)), isPlaying: mpvController.getFlag(MPVProperty.playlistNPlaying(index)), title: mpvController.getString(MPVProperty.playlistNTitle(index))) info.playlist.append(playlistItem) } } func getChapters() { info.chapters.removeAll() let chapterCount = mpvController.getInt(MPVProperty.chapterListCount) if chapterCount == 0 { return } for index in 0..<chapterCount { let chapter = MPVChapter(title: mpvController.getString(MPVProperty.chapterListNTitle(index)), startTime: mpvController.getDouble(MPVProperty.chapterListNTime(index)), index: index) info.chapters.append(chapter) } } }
gpl-3.0
a94d9cd92c616a000736591e42a1206e
30.323281
159
0.664613
4.08222
false
false
false
false
kstaring/swift
validation-test/stdlib/Algorithm.swift
5
6465
// -*- swift -*- // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest import StdlibCollectionUnittest import SwiftPrivate var Algorithm = TestSuite("Algorithm") // FIXME(prext): remove this conformance. extension String.UnicodeScalarView : Equatable {} // FIXME(prext): remove this function. public func == ( lhs: String.UnicodeScalarView, rhs: String.UnicodeScalarView) -> Bool { return Array(lhs) == Array(rhs) } // FIXME(prext): move this struct to the point of use. Algorithm.test("min,max") { // Identities are unique in this set. let a1 = MinimalComparableValue(0, identity: 1) let a2 = MinimalComparableValue(0, identity: 2) let a3 = MinimalComparableValue(0, identity: 3) let b1 = MinimalComparableValue(1, identity: 4) let b2 = MinimalComparableValue(1, identity: 5) let b3 = MinimalComparableValue(1, identity: 6) let c1 = MinimalComparableValue(2, identity: 7) let c2 = MinimalComparableValue(2, identity: 8) let c3 = MinimalComparableValue(2, identity: 9) // 2-arg min() expectEqual(a1.identity, min(a1, b1).identity) expectEqual(a1.identity, min(b1, a1).identity) expectEqual(a1.identity, min(a1, a2).identity) // 2-arg max() expectEqual(c1.identity, max(c1, b1).identity) expectEqual(c1.identity, max(b1, c1).identity) expectEqual(c1.identity, max(c2, c1).identity) // 3-arg min() expectEqual(a1.identity, min(a1, b1, c1).identity) expectEqual(a1.identity, min(b1, a1, c1).identity) expectEqual(a1.identity, min(c1, b1, a1).identity) expectEqual(a1.identity, min(c1, a1, b1).identity) expectEqual(a1.identity, min(a1, a2, a3).identity) expectEqual(a1.identity, min(a1, a2, b1).identity) expectEqual(a1.identity, min(a1, b1, a2).identity) expectEqual(a1.identity, min(b1, a1, a2).identity) // 3-arg max() expectEqual(c1.identity, max(c1, b1, a1).identity) expectEqual(c1.identity, max(a1, c1, b1).identity) expectEqual(c1.identity, max(b1, a1, c1).identity) expectEqual(c1.identity, max(b1, c1, a1).identity) expectEqual(c1.identity, max(c3, c2, c1).identity) expectEqual(c1.identity, max(c2, c1, b1).identity) expectEqual(c1.identity, max(c2, b1, c1).identity) expectEqual(c1.identity, max(b1, c2, c1).identity) // 4-arg min() expectEqual(a1.identity, min(a1, b1, a2, b2).identity) expectEqual(a1.identity, min(b1, a1, a2, b2).identity) expectEqual(a1.identity, min(c1, b1, b2, a1).identity) expectEqual(a1.identity, min(c1, b1, a1, a2).identity) // 4-arg max() expectEqual(c1.identity, max(c2, b1, c1, b2).identity) expectEqual(c1.identity, max(b1, c2, c1, b2).identity) expectEqual(c1.identity, max(a1, b1, b2, c1).identity) expectEqual(c1.identity, max(a1, b1, c2, c1).identity) } Algorithm.test("sorted/strings") .xfail(.nativeRuntime("String comparison: ICU vs. Foundation " + "https://bugs.swift.org/browse/SR-530")) .code { expectEqual( ["Banana", "apple", "cherry"], ["apple", "Banana", "cherry"].sorted()) let s = ["apple", "Banana", "cherry"].sorted() { $0.characters.count > $1.characters.count } expectEqual(["Banana", "cherry", "apple"], s) } // A wrapper around Array<T> that disables any type-specific algorithm // optimizations and forces bounds checking on. struct A<T> : MutableCollection, RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ a: Array<T>) { impl = a } var startIndex: Int { return 0 } var endIndex: Int { return impl.count } func makeIterator() -> Array<T>.Iterator { return impl.makeIterator() } subscript(i: Int) -> T { get { expectTrue(i >= 0 && i < impl.count) return impl[i] } set (x) { expectTrue(i >= 0 && i < impl.count) impl[i] = x } } subscript(r: Range<Int>) -> Array<T>.SubSequence { get { expectTrue(r.lowerBound >= 0 && r.lowerBound <= impl.count) expectTrue(r.upperBound >= 0 && r.upperBound <= impl.count) return impl[r] } set (x) { expectTrue(r.lowerBound >= 0 && r.lowerBound <= impl.count) expectTrue(r.upperBound >= 0 && r.upperBound <= impl.count) impl[r] = x } } var impl: Array<T> } func randomArray() -> A<Int> { let count = Int(rand32(exclusiveUpperBound: 50)) return A(randArray(count)) } Algorithm.test("invalidOrderings") { withInvalidOrderings { var a = randomArray() _blackHole(a.sorted(by: $0)) } withInvalidOrderings { var a: A<Int> a = randomArray() let lt = $0 let first = a.first _ = a.partition(by: { !lt($0, first!) }) } /* // FIXME: Disabled due to <rdar://problem/17734737> Unimplemented: // abstraction difference in l-value withInvalidOrderings { var a = randomArray() var pred = $0 _insertionSort(&a, a.indices, &pred) } */ } // The routine is based on http://www.cs.dartmouth.edu/~doug/mdmspe.pdf func makeQSortKiller(_ len: Int) -> [Int] { var candidate: Int = 0 var keys = [Int: Int]() func Compare(_ x: Int, y : Int) -> Bool { if keys[x] == nil && keys[y] == nil { if (x == candidate) { keys[x] = keys.count } else { keys[y] = keys.count } } if keys[x] == nil { candidate = x return true } if keys[y] == nil { candidate = y return false } return keys[x]! > keys[y]! } var ary = [Int](repeating: 0, count: len) var ret = [Int](repeating: 0, count: len) for i in 0..<len { ary[i] = i } ary = ary.sorted(by: Compare) for i in 0..<len { ret[ary[i]] = i } return ret } Algorithm.test("sorted/complexity") { var ary: [Int] = [] // Check performance of sorting an array of repeating values. var comparisons_100 = 0 ary = [Int](repeating: 0, count: 100) ary.sort { comparisons_100 += 1; return $0 < $1 } var comparisons_1000 = 0 ary = [Int](repeating: 0, count: 1000) ary.sort { comparisons_1000 += 1; return $0 < $1 } expectTrue(comparisons_1000/comparisons_100 < 20) // Try to construct 'bad' case for quicksort, on which the algorithm // goes quadratic. comparisons_100 = 0 ary = makeQSortKiller(100) ary.sort { comparisons_100 += 1; return $0 < $1 } comparisons_1000 = 0 ary = makeQSortKiller(1000) ary.sort { comparisons_1000 += 1; return $0 < $1 } expectTrue(comparisons_1000/comparisons_100 < 20) } Algorithm.test("sorted/return type") { let x: Array = ([5, 4, 3, 2, 1] as ArraySlice).sorted() } runAllTests()
apache-2.0
207ca00cdc6fa14feb46f32a2d97703a
27.355263
73
0.644857
3.103697
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 08/SportsStore/SportsStore/Product.swift
2
1255
import Foundation class Product : NSObject, NSCopying { private(set) var name:String; private(set) var productDescription:String; private(set) var category:String; private var stockLevelBackingValue:Int = 0; private var priceBackingValue:Double = 0; init(name:String, description:String, category:String, price:Double, stockLevel:Int) { self.name = name; self.productDescription = description; self.category = category; super.init(); self.price = price; self.stockLevel = stockLevel; } var stockLevel:Int { get { return stockLevelBackingValue;} set { stockLevelBackingValue = max(0, newValue);} } private(set) var price:Double { get { return priceBackingValue;} set { priceBackingValue = max(1, newValue);} } var stockValue:Double { get { return price * Double(stockLevel); } } func copyWithZone(zone: NSZone) -> AnyObject { return Product(name: self.name, description: self.description, category: self.category, price: self.price, stockLevel: self.stockLevel); } }
mit
c1b501bd19d04b69aaa64af51aa75072
27.522727
72
0.591235
4.648148
false
false
false
false
oskarpearson/rileylink_ios
MinimedKit/GlucoseEvents/SensorCalGlucoseEvent.swift
1
966
// // SensorCalGlucoseEvent.swift // RileyLink // // Created by Timothy Mecklem on 10/16/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public struct SensorCalGlucoseEvent: RelativeTimestampedGlucoseEvent { public let length: Int public let rawData: Data public let waiting: String public var timestamp: DateComponents public init?(availableData: Data) { length = 2 guard length <= availableData.count else { return nil } func d(_ idx:Int) -> Int { return Int(availableData[idx] as UInt8) } rawData = availableData.subdata(in: 0..<length) waiting = d(1) == 1 ? "waiting" : "meter_bg_now" timestamp = DateComponents() } public var dictionaryRepresentation: [String: Any] { return [ "name": "SensorCal", "waiting": waiting ] } }
mit
559768a6f64ad8018749b9236458b9bc
22.536585
70
0.582383
4.530516
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/EditExperimentPhotoView.swift
1
5116
/* * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import third_party_objective_c_material_components_ios_components_Buttons_Buttons protocol EditExperimentPhotoViewDelegate: class { func choosePhotoButtonPressed() } /// A view allowing a user to choose a photo for an experiment. class EditExperimentPhotoView: UIView { // MARK: - Properties private let buttonStack = UIStackView() private let changeButton = MDCFlatButton() private let chooseButton = MDCFlatButton() weak var delegate: EditExperimentPhotoViewDelegate? private let imageView = UIImageView() private let placeholderImageView = UIImageView(image: UIImage(named: "ic_landscape_large")) private let placeholderStack = UIStackView() var photo: UIImage? { didSet { if photo == nil && photo != oldValue { imageView.image = nil addSubview(placeholderStack) placeholderStack.pinToEdgesOfView(self) buttonStack.removeFromSuperview() return } // Clean up the view. placeholderStack.removeFromSuperview() // Set the image. imageView.image = photo // Add the buttons. addSubview(buttonStack) buttonStack.pinToEdgesOfView(self) } } // MARK: - Public override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureView() } override var intrinsicContentSize: CGSize { return CGSize(width: UIView.noIntrinsicMetric, height: 140.0) } // MARK: - Private private func configureView() { layer.cornerRadius = 6.0 clipsToBounds = true backgroundColor = UIColor(red: 0.808, green: 0.808, blue: 0.808, alpha: 1.0) // The image view, which shows the photo for the experiment if/when it exists. addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.isUserInteractionEnabled = false imageView.isOpaque = false imageView.pinToEdgesOfView(self) if #available(iOS 11.0, *) { imageView.accessibilityIgnoresInvertColors = true } // The placeholder image view which shows an icon. placeholderImageView.contentMode = .center placeholderImageView.tintColor = UIColor(red: 0.420, green: 0.416, blue: 0.424, alpha: 1.0) placeholderImageView.translatesAutoresizingMaskIntoConstraints = false placeholderImageView.setContentHuggingPriority(.defaultLow, for: .vertical) // The choose photo button. chooseButton.setTitleColor(.appBarReviewBackgroundColor, for: .normal) chooseButton.setBackgroundColor(.clear, for: .normal) chooseButton.setTitle(String.choosePhotoButtonText.uppercased(), for: .normal) // Change button. changeButton.setBackgroundColor(.white, for: .normal) changeButton.setTitleColor(.black, for: .normal) changeButton.setTitle(String.editExperimentChangePhoto.uppercased(), for: .normal) [chooseButton, changeButton].forEach { (button) in button.translatesAutoresizingMaskIntoConstraints = false button.setContentHuggingPriority(.defaultHigh, for: .vertical) button.addTarget(self, action: #selector(choosePhotoButtonPressed), for: .touchUpInside) } // The outer stack view. placeholderStack.addArrangedSubview(placeholderImageView) placeholderStack.addArrangedSubview(chooseButton) placeholderStack.axis = .vertical placeholderStack.alignment = .center placeholderStack.translatesAutoresizingMaskIntoConstraints = false placeholderStack.layoutMargins = UIEdgeInsets(top: 30, left: 0, bottom: 20, right: 0) placeholderStack.isLayoutMarginsRelativeArrangement = true addSubview(placeholderStack) placeholderStack.pinToEdgesOfView(self) // Configure the button stack but don't add it to the view yet. let innerButtonStack = UIStackView(arrangedSubviews: [changeButton]) innerButtonStack.axis = .vertical innerButtonStack.alignment = .center innerButtonStack.spacing = 10.0 innerButtonStack.translatesAutoresizingMaskIntoConstraints = false innerButtonStack.setContentHuggingPriority(.defaultHigh, for: .vertical) buttonStack.addArrangedSubview(innerButtonStack) buttonStack.alignment = .center buttonStack.translatesAutoresizingMaskIntoConstraints = false } // MARK: - User actions @objc private func choosePhotoButtonPressed() { delegate?.choosePhotoButtonPressed() } }
apache-2.0
df5af3c69bf42f117aaa0cbefc2b7f27
34.527778
95
0.739054
4.803756
false
false
false
false
ios-archy/Sinaweibo_swift
SinaWeibo_swift/SinaWeibo_swift/Classess/Main/MainViewController.swift
1
7562
// // MainViewController.swift // SinaWeibo_swift // // Created by yuqi on 16/10/17. // Copyright © 2016年 archy. All rights reserved. // import UIKit class MainViewController: UITabBarController { private lazy var composeBtn : UIButton = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button") override func viewDidLoad() { super.viewDidLoad() setUpcenterBtn() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } } //Mark:--设置UI界面 extension MainViewController { /** 设置发布按钮 */ private func setUpcenterBtn() { //1.添加到tabbar中 tabBar.addSubview(composeBtn) //2.设置位置 composeBtn.center = CGPointMake(tabBar.center.x, tabBar.bounds.size.height * 0.5) //3.监听发布按钮的点击 //Selector两种写法:1。Selector()括号里放字符串 :Selector("composeBtnClick") 2.直接传字符串:"composeBtnClick" composeBtn.addTarget(self, action: "composeBtnClick", forControlEvents: .TouchUpInside) } } //MARK:--事件监听 extension MainViewController { //事件监听本质是发送消息,但是发送消息是OC的特性 //将方法包装秤@SEL-->类中查找方法列表-->根据@SEL找到imp指针(函数)->>执行函数 //如果swift中将一个函数申明为private,那么该函数不会被添加到方法列表 //如果在priv 前面加上objc,那么该方法依然会被添加到方法列表中 @objc private func composeBtnClick(){ //1.创建发布控制器 let compseVc = ComposeViewController() //2.包装导航控制器 let composeNav = UINavigationController(rootViewController: compseVc) //3.弹出控制器 presentViewController(composeNav, animated: true, completion: nil) } } //extension MainViewController //{ // // //Mark :懒加载属性 // private lazy var imageNames = ["tabbar_home","tabbar_message_center","","tabbar_discover","tabbar_profile"] // func addTabbarImage() { // //1.遍历所有的Item // for i in 0..<tabBar.items!.count // { // //2.获取item // let item = tabBar.items![i] // //3.如果是下标值为2,则该item不可以和用户交互 // if i == 2 { // item.enabled = false // continue // } // // //4.设置其他item的选中时候的图片 // item.selectedImage = UIImage(named: imageNames[i] + "_highlighted") // } // // // } //} //// MARK: - 一下文件都没啥用了 //extension MainViewController { // // func addchildController (){ // // //1.获取json文件路径 // guard let jsonPath = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) else { // print("没有获取到对应的文件路径") // return // } // // //2.读取json文件的内容 // // guard let jsonData = NSData(contentsOfFile: jsonPath) else // { // print("没有获取到json文件中数据") // return // } // // //3.将data转成数组 // //如果在调用系统某一个方法时,该方法最后有一个throws,说明该方法会抛出异常。如果一个方法会抛出异常,需要对异常进行处理 // //swift中提供三种处理异常的方法 // /* // //方法一:try方式 程序员手动捕捉异常 // // do { // // try NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) // // } // // catch { // // print(error) // // } // // //方式二:try?方式(常用方式)系统帮助我们处理异常,如果该方法出现了异常,则该方法返回nil,如果没有异常,则返回对应的对象 // // guard let anyObject = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) else { // // return // // } // // // //方法三:try!方法(不建议,非常危险)直接告诉系统,该方法没有异常,注意:如果该方法出现了异常,那么程序会报错(崩溃) // // let anyObject = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) // */ // // guard let anyObject = try? NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers) else // { // return // } // // guard let dictArray = anyObject as? [[NSString :AnyObject]] else { // // return // } // // //4.遍历字典获取对应的信息 // for dict in dictArray { // // //4.1获取控制器的对应的字符串 // guard let vcName = dict["vcName"] as? String else // { // continue // } // // guard let title = dict["title"] as? String else { // continue // } // // guard let imageName = dict["imageName"] as? String else { // continue // } // addChildViewController(vcName, title: title, imageName: imageName) // // } // // // } //} // //extension MainViewController { // // func addChildviewControllers() // { // addChildViewController("HomeViewController", title: "首页", imageName: "tabbar_home") // addChildViewController("MessageViewController", title: "消息", imageName: "tabbar_message_center") // addChildViewController("DisCoverViewController", title: "发现", imageName: "tabbar_discover") // addChildViewController("ProfileViewController", title: "我", imageName: "tabbar_profile") // } //} // //extension MainViewController { // // private func addChildViewController(childVCname: String , title :String , imageName : String) { // //0.获取命名空间 // guard let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String // else { // print("没有获取到命名空间") // return // } // // //1.根据字符串获取对应的Class // guard let ChildVcClass = NSClassFromString(nameSpace + "." + childVCname) // else // { // print("没有获取到字符串对应的class") // return // } // // //2.将对应的AnyObject转成控制器的类型 // // guard let childVcType = ChildVcClass as? UIViewController.Type else { // print("没有获取对应控制器类型") // return // } // //3.创建对应控制器对象 // let childVC = childVcType.init() // // //4.设置自控制器的属性 // childVC.title = title; // childVC.tabBarItem.image = UIImage(named: imageName) // childVC.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") // // //2.包装导航控制器 // let childNav = UINavigationController(rootViewController: childVC) // // //3.添加控制器 // addChildViewController(childNav) // } // //}
mit
fb4445cf45784f25f4e752341b68ca6a
27.726457
131
0.550039
3.837627
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/EBS/EBS_Error.swift
1
3431
//===----------------------------------------------------------------------===// // // 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 EBS public struct EBSErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case concurrentLimitExceededException = "ConcurrentLimitExceededException" case conflictException = "ConflictException" case internalServerException = "InternalServerException" case requestThrottledException = "RequestThrottledException" case resourceNotFoundException = "ResourceNotFoundException" case serviceQuotaExceededException = "ServiceQuotaExceededException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize EBS 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 } /// You do not have sufficient access to perform this action. public static var accessDeniedException: Self { .init(.accessDeniedException) } /// You have reached the limit for concurrent API requests. For more information, see Optimizing performance of the EBS direct APIs in the Amazon Elastic Compute Cloud User Guide. public static var concurrentLimitExceededException: Self { .init(.concurrentLimitExceededException) } /// The request uses the same client token as a previous, but non-identical request. public static var conflictException: Self { .init(.conflictException) } /// An internal error has occurred. public static var internalServerException: Self { .init(.internalServerException) } /// The number of API requests has exceed the maximum allowed API request throttling limit. public static var requestThrottledException: Self { .init(.requestThrottledException) } /// The specified resource does not exist. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// Your current service quotas do not allow you to perform this action. public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) } /// The input fails to satisfy the constraints of the EBS direct APIs. public static var validationException: Self { .init(.validationException) } } extension EBSErrorType: Equatable { public static func == (lhs: EBSErrorType, rhs: EBSErrorType) -> Bool { lhs.error == rhs.error } } extension EBSErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
324f1381545423140b0b08aa97a991db
42.987179
183
0.693967
5.159398
false
false
false
false
profburke/AppLister
AppLister/AppInfoDataSource.swift
1
1148
// // AppInfoDataSource.swift // AppLister // // Created by Matthew Burke on 11/13/14. // Copyright (c) 2014-2017 BlueDino Software. Availble under the MIT License. See the file, LICENSE, for details. // import UIKit class AppInfoDataSource: NSObject, UITableViewDataSource { let appProxy: AppInfo let CellIdentifier = "DetailCell" init(appProxy: AppInfo) { self.appProxy = appProxy super.init() } func getBundleID() -> String { return appProxy["bundleIdentifier"] as! String } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appProxy.propertyCount() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier, for: indexPath) let propName = appProxy[(indexPath as NSIndexPath).row] as! String let prop = appProxy[propName] as! String cell.textLabel?.text = prop cell.detailTextLabel?.text = propName return cell } }
mit
3724b7a82c1a0d9889af08f6022a20b9
25.090909
114
0.70122
4.365019
false
false
false
false
Eflet/Charts
Charts/Classes/Data/Implementations/Standard/LineChartDataSet.swift
2
6001
// // LineChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 26/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics public class LineChartDataSet: LineRadarChartDataSet, ILineChartDataSet { @objc(LineChartMode) public enum Mode: Int { case Linear case Stepped case CubicBezier case HorizontalBezier } private func initialize() { // default color circleColors.append(NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)) } public required init() { super.init() initialize() } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// The drawing mode for this line dataset /// /// **default**: Linear public var mode: Mode = Mode.Linear private var _cubicIntensity = CGFloat(0.2) /// Intensity for cubic lines (min = 0.05, max = 1) /// /// **default**: 0.2 public var cubicIntensity: CGFloat { get { return _cubicIntensity } set { _cubicIntensity = newValue if (_cubicIntensity > 1.0) { _cubicIntensity = 1.0 } if (_cubicIntensity < 0.05) { _cubicIntensity = 0.05 } } } @available(*, deprecated=1.0, message="Use `mode` instead.") public var drawCubicEnabled: Bool { get { return mode == .CubicBezier } set { mode = newValue ? LineChartDataSet.Mode.CubicBezier : LineChartDataSet.Mode.Linear } } @available(*, deprecated=1.0, message="Use `mode` instead.") public var isDrawCubicEnabled: Bool { return drawCubicEnabled } @available(*, deprecated=1.0, message="Use `mode` instead.") public var drawSteppedEnabled: Bool { get { return mode == .Stepped } set { mode = newValue ? LineChartDataSet.Mode.Stepped : LineChartDataSet.Mode.Linear } } @available(*, deprecated=1.0, message="Use `mode` instead.") public var isDrawSteppedEnabled: Bool { return drawSteppedEnabled } /// The radius of the drawn circles. public var circleRadius = CGFloat(8.0) public var circleColors = [NSUIColor]() /// - returns: the color at the given index of the DataSet's circle-color array. /// Performs a IndexOutOfBounds check by modulus. public func getCircleColor(index: Int) -> NSUIColor? { let size = circleColors.count let index = index % size if (index >= size) { return nil } return circleColors[index] } /// Sets the one and ONLY color that should be used for this DataSet. /// Internally, this recreates the colors array and adds the specified color. public func setCircleColor(color: NSUIColor) { circleColors.removeAll(keepCapacity: false) circleColors.append(color) } /// Resets the circle-colors array and creates a new one public func resetCircleColors(index: Int) { circleColors.removeAll(keepCapacity: false) } /// If true, drawing circles is enabled public var drawCirclesEnabled = true /// - returns: true if drawing circles for this DataSet is enabled, false if not public var isDrawCirclesEnabled: Bool { return drawCirclesEnabled } /// The color of the inner circle (the circle-hole). public var circleHoleColor = NSUIColor.whiteColor() /// True if drawing circles for this DataSet is enabled, false if not public var drawCircleHoleEnabled = true /// - returns: true if drawing the circle-holes is enabled, false if not. public var isDrawCircleHoleEnabled: Bool { return drawCircleHoleEnabled } /// This is how much (in pixels) into the dash pattern are we starting from. public var lineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] public var lineDashLengths: [CGFloat]? /// Line cap type, default is CGLineCap.Butt public var lineCapType = CGLineCap.Butt /// formatter for customizing the position of the fill-line private var _fillFormatter: ChartFillFormatter = ChartDefaultFillFormatter() /// Sets a custom FillFormatter to the chart that handles the position of the filled-line for each DataSet. Set this to null to use the default logic. public var fillFormatter: ChartFillFormatter? { get { return _fillFormatter } set { if newValue == nil { _fillFormatter = ChartDefaultFillFormatter() } else { _fillFormatter = newValue! } } } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! LineChartDataSet copy.circleColors = circleColors copy.circleRadius = circleRadius copy.cubicIntensity = cubicIntensity copy.lineDashPhase = lineDashPhase copy.lineDashLengths = lineDashLengths copy.lineCapType = lineCapType copy.drawCirclesEnabled = drawCirclesEnabled copy.drawCircleHoleEnabled = drawCircleHoleEnabled copy.mode = mode return copy } }
apache-2.0
e83c3e6f11e244992c2b3d46e341d313
27.57619
154
0.596401
4.939095
false
false
false
false
ReiVerdugo/uikit-fundamentals
ChallengeTextfieldApp/ChallengeTextfieldApp/ViewController.swift
1
896
// // ViewController.swift // ChallengeTextfieldApp // // Created by Reinaldo Verdugo on 9/10/16. // Copyright © 2016 Reinaldo Verdugo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var zipcodeField: UITextField! @IBOutlet weak var cashField: UITextField! @IBOutlet weak var lockableField: UITextField! var zipcodeFieldDelegate = ZipCodeFieldDelegate() var lockableFieldDelegate = LockableFieldDelegate() var cashFieldDelegate = CashFieldDelegate() override func viewDidLoad() { super.viewDidLoad() zipcodeField.delegate = zipcodeFieldDelegate lockableField.delegate = lockableFieldDelegate cashField.delegate = cashFieldDelegate } @IBAction func switched(_ sender: UISwitch) { lockableFieldDelegate.shouldEdit = sender.isOn } }
mit
ca5afdfde50cbd586962ad1c6b305b2e
23.861111
59
0.702793
4.589744
false
false
false
false
jmgc/swift
test/Constraints/fixes.swift
1
17498
// RUN: %target-typecheck-verify-swift func f1() -> Int { } func f2(_: Int = 5) -> Int { } func f3(_: Int...) -> Int { } class A { } class B : A { func iAmAB() {} func createB() -> B { return B() } } func f4() -> B { } func f5(_ a: A) { } func f6(_ a: A, _: Int) { } func createB() -> B { } func createB(_ i: Int) -> B { } func f7(_ a: A, _: @escaping () -> Int) -> B { } func f7(_ a: A, _: Int) -> Int { } // Forgot the '()' to call a function. func forgotCall() { // Simple cases var x: Int x = f1 // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}} x = f2 // expected-error{{cannot assign value of type '(Int) -> Int' to type 'Int'}} x = f3 // expected-error{{cannot assign value of type '(Int...) -> Int' to type 'Int'}} // With a supertype conversion var a = A() a = f4 // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{9-9=()}} // As a call f5(f4) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{8-8=()}} f6(f4, f2) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}}{{8-8=()}} // expected-error@-1 {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{12-12=()}} // With overloading: only one succeeds. a = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} let _: A = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} {{21-21=()}} let _: B = createB // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} {{21-21=()}} // With overloading, pick the fewest number of fixes. var b = f7(f4, f1) // expected-error{{function produces expected type 'B'; did you mean to call it with '()'?}} b.iAmAB() } /// Forgot the '!' to unwrap an optional. func parseInt() -> Int? { } func <(lhs: A, rhs: A) -> A? { return nil } func forgotOptionalBang(_ a: A, obj: AnyObject) { var i: Int = parseInt() // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{26-26= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{26-26=!}} var a = A(), b = B() b = a as? B // expected-error{{value of optional type 'B?' must be unwrapped to a value of type 'B'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{14-14= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{7-7=(}}{{14-14=)!}} a = a < a // expected-error{{value of optional type 'A?' must be unwrapped to a value of type 'A'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{7-7=(}}{{12-12=) ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{7-7=(}}{{12-12=)!}} // rdar://problem/20377684 -- take care that the '!' doesn't fall into an // optional evaluation context let bo: B? = b let b2: B = bo?.createB() // expected-error{{value of optional type 'B?' must be unwrapped to a value of type 'B'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func forgotAnyObjectBang(_ obj: AnyObject) { var a = A() a = obj // expected-error{{'AnyObject' is not convertible to 'A'}} //expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{10-10= as! A}} _ = a } func increment(_ x: inout Int) { } func forgotAmpersand() { var i = 5 increment(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{13-13=&}} var array = [1,2,3] increment(array[1]) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{13-13=&}} } func maybeFn() -> ((Int) -> Int)? { } func extraCall() { var i = 7 i = i() // expected-error{{cannot call value of non-function type 'Int'}}{{8-10=}} maybeFn()(5) // expected-error{{value of optional type '((Int) -> Int)?' must be unwrapped to a value of type '(Int) -> Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } class U { var prop1 = 0 } class T { func m1() { // <rdar://problem/17741575> let l = self.m2!.prop1 // expected-error@-1 {{method 'm2' was used as a property; add () to call it}} {{22-22=()}} } func m2() -> U! { return U() } } // Used an optional in a conditional expression class C { var a: Int = 1 } var co: C? = nil var ciuo: C! = nil if co {} // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{4-4=(}} {{6-6= != nil)}} if ciuo {} // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{4-4=(}} {{8-8= != nil)}} co ? true : false // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{1-1=(}} {{3-3= != nil)}} !co ? false : true // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{4-4= == nil)}} ciuo ? true : false // expected-error{{optional type 'C?' cannot be used as a boolean; test for '!= nil' instead}}{{1-1=(}} {{5-5= != nil)}} !ciuo ? false : true // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{6-6= == nil)}} !co // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{4-4= == nil)}} !ciuo // expected-error{{optional type 'C?' cannot be used as a boolean; test for '== nil' instead}} {{1-2=}} {{2-2=(}} {{6-6= == nil)}} // Used an integer in a conditional expression var n1: Int = 1 var n2: UInt8 = 0 var n3: Int16 = 2 if n1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{4-4=(}} {{6-6= != 0)}} if !n1 {} // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{4-5=}} {{5-5=(}} {{7-7= == 0)}} n1 ? true : false // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}} {{1-1=(}} {{3-3= != 0)}} !n1 ? false : true // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}} !n1 // expected-error {{type 'Int' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}} if n2 {} // expected-error {{type 'UInt8' cannot be used as a boolean; test for '!= 0' instead}} {{4-4=(}} {{6-6= != 0)}} !n3 // expected-error {{type 'Int16' cannot be used as a boolean; test for '== 0' instead}} {{1-2=}} {{2-2=(}} {{4-4= == 0)}} // Forgotten ! or ? var someInt = co.a // expected-error{{value of optional type 'C?' must be unwrapped to refer to member 'a' of wrapped base type 'C'}} // expected-note@-1{{chain the optional using '?' to access member 'a' only for non-'nil' base values}}{{17-17=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{17-17=!}} // SR-839 struct Q { let s: String? } let q = Q(s: nil) let a: Int? = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-error@-1 {{cannot convert value of type 'String.UTF8View?' to specified type 'Int?'}} // expected-note@-2{{chain the optional using '?'}}{{18-18=?}} let b: Int = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-error@-1 {{cannot convert value of type 'String.UTF8View' to specified type 'Int'}} // expected-note@-2{{chain the optional using '?'}}{{17-17=?}} // expected-note@-3{{force-unwrap using '!'}}{{17-17=!}} let d: Int! = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-error@-1 {{cannot convert value of type 'String.UTF8View?' to specified type 'Int?'}} // expected-note@-2{{chain the optional using '?'}}{{18-18=?}} let c = q.s.utf8 // expected-error{{value of optional type 'String?' must be unwrapped to refer to member 'utf8' of wrapped base type 'String'}} // expected-note@-1{{chain the optional using '?' to access member 'utf8' only for non-'nil' base values}}{{12-12=?}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{12-12=!}} // SR-1116 struct S1116 { var s: Int? } let a1116: [S1116] = [] var s1116 = Set(1...10).subtracting(a1116.map({ $0.s })) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{53-53= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{53-53=!}} func makeArray<T>(_ x: T) -> [T] { [x] } func sr12399(_ x: Int?) { _ = Set(0...10).subtracting(makeArray(x)) // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}} {{42-42= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} {{42-42=!}} } func moreComplexUnwrapFixes() { struct S { let value: Int let optValue: Int? = nil } struct T { let s: S let optS: S? } func takeNon(_ x: Int) -> Void {} func takeOpt(_ x: Int?) -> Void {} let s = S(value: 0) let t: T? = T(s: s, optS: nil) let os: S? = s takeOpt(os.value) // expected-error{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-1{{chain the optional using '?'}}{{13-13=?}} takeNon(os.value) // expected-error{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-1{{chain the optional using '?'}}{{13-13=?}} // expected-note@-2{{force-unwrap using '!'}}{{13-13=!}} // FIXME: Ideally we'd recurse evaluating chaining fixits instead of only offering just the unwrap of t takeOpt(t.s.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 's' of wrapped base type 'T'}} // expected-note@-1{{chain the optional using '?'}}{{12-12=?}} // expected-note@-2{{force-unwrap using '!'}}{{12-12=!}} takeOpt(t.optS.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 'optS' of wrapped base type 'T'}} // expected-note@-1{{chain the optional using '?'}}{{12-12=?}} // expected-error@-2{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-3{{chain the optional using '?'}}{{17-17=?}} takeNon(t.optS.value) // expected-error{{value of optional type 'T?' must be unwrapped to refer to member 'optS' of wrapped base type 'T'}} // expected-note@-1{{chain the optional using '?'}}{{12-12=?}} // expected-error@-2{{value of optional type 'S?' must be unwrapped to refer to member 'value' of wrapped base type 'S'}} // expected-note@-3{{chain the optional using '?'}}{{17-17=?}} // expected-note@-4{{force-unwrap using '!'}}{{17-17=!}} takeNon(os?.value) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap using '!'}}{{13-14=!}} // expected-note@-2{{coalesce}} takeNon(os?.optValue) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap using '!'}}{{11-11=(}} {{23-23=)!}} // expected-note@-2{{coalesce}} func sample(a: Int?, b: Int!) { let aa = a // expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return \}}} // expected-note@-2{{force-unwrap}} // expected-note@-3{{coalesce}} let bb = b // expected-note{{value inferred to be type 'Int?' when initialized with an implicitly unwrapped value}} // expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return \}}} // expected-note@-2{{force-unwrap}} // expected-note@-3{{coalesce}} let cc = a takeNon(aa) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} takeNon(bb) // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} _ = [].map { takeNon(cc) } // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} takeOpt(cc) } func sample2(a: Int?) -> Int { let aa = a // expected-note@-1{{short-circuit using 'guard'}}{{5-5=guard }} {{15-15= else \{ return <#default value#> \}}} // expected-note@-2{{force-unwrap}} // expected-note@-3{{coalesce}} return aa // expected-error{{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{force-unwrap}} expected-note@-1{{coalesce}} } } struct FooStruct { func a() -> Int?? { return 10 } var b: Int?? { return 15 } func c() -> Int??? { return 20 } var d: Int??? { return 25 } let e: BarStruct? = BarStruct() func f() -> Optional<Optional<Int>> { return 29 } } struct BarStruct { func a() -> Int? { return 30 } var b: Int?? { return 35 } } let thing: FooStruct? = FooStruct() let _: Int? = thing?.a() // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int? = thing?.b // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int?? = thing?.c() // expected-error {{value of optional type 'Int???' must be unwrapped to a value of type 'Int??'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int?? = thing?.d // expected-error {{value of optional type 'Int???' must be unwrapped to a value of type 'Int??'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int = thing?.e?.a() // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int? = thing?.e?.b // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} let _: Int? = thing?.f() // expected-error {{value of optional type 'Int??' must be unwrapped to a value of type 'Int?'}} // expected-note@-1{{coalesce}} // expected-note@-2{{force-unwrap}} // SR-9851 - https://bugs.swift.org/browse/SR-9851 func coalesceWithParensRootExprFix() { let optionalBool: Bool? = false if !optionalBool { } // expected-error{{value of optional type 'Bool?' must be unwrapped to a value of type 'Bool'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{7-7=(}}{{19-19= ?? <#default value#>)}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}} } func test_explicit_call_with_overloads() { func foo(_: Int) {} struct S { func foo(_: Int) -> Int { return 0 } func foo(_: Int = 32, _: String = "hello") -> Int { return 42 } } foo(S().foo) // expected-error@-1 {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{14-14=()}} } // SR-11476 func testKeyPathSubscriptArgFixes(_ fn: @escaping () -> Int) { struct S { subscript(x: Int) -> Int { x } } var i: Int? _ = \S.[i] // expected-error {{value of optional type 'Int?' must be unwrapped to a value of type 'Int'}} // expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}{{12-12= ?? <#default value#>}} // expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{12-12=!}} _ = \S.[nil] // expected-error {{'nil' is not compatible with expected argument type 'Int'}} _ = \S.[fn] // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{13-13=()}} } func sr12426(a: Any, _ str: String?) { a == str // expected-error {{binary operator '==' cannot be applied to operands of type 'Any' and 'String?'}} // expected-note@-1 {{overloads for '==' exist with these partially matching parameter lists: (CodingUserInfoKey, CodingUserInfoKey), (String, String)}} }
apache-2.0
cb0a08c772728aaf66d9bd43d31417a0
47.203857
154
0.625957
3.404943
false
false
false
false
customerly/Customerly-iOS-SDK
CustomerlySDK/Library/CyBanner.swift
1
4133
// // CyBanner.swift // Customerly // // Created by Paolo Musolino on 25/01/17. // Copyright © 2017 Customerly. All rights reserved. // import UIKit class CyBanner: CyView { @IBOutlet weak var avatarImageView: CyImageView? @IBOutlet weak var nameLabel: CyLabel? @IBOutlet weak var subtitleLabel: CyLabel? // A block to call when the user taps on the banner. var didTapBlock: (() -> ())? // A block to call when the banner is dismissed var didTapDismissed: (() -> ())? var viewBanner : CyBanner? var initialRect = CGRect(x: 15, y: -75, width: UIScreen.main.bounds.width-30, height: 75) var finalRect = CGRect(x: 15, y: 40 , width: UIScreen.main.bounds.width-30, height: 75) init(name: String?, subtitle: String? = nil, attributedSubtitle: NSAttributedString? = nil, image: UIImage? = nil){ super.init(frame: initialRect) if let banner = CyViewController.cyLoadNib(nibName: "Banner")?[0] as! CyBanner?{ viewBanner = banner viewBanner?.frame = CGRect(x: 0, y: 0, width: initialRect.width, height: initialRect.height) viewBanner?.nameLabel?.text = name viewBanner?.nameLabel?.textColor = base_color_template if subtitle != nil{ viewBanner?.subtitleLabel?.text = subtitle }else{ viewBanner?.subtitleLabel?.attributedText = attributedSubtitle } viewBanner?.subtitleLabel?.textColor = UIColor(hexString: "#666666") viewBanner?.isUserInteractionEnabled = false if viewBanner != nil && viewBanner?.avatarImageView != nil{ viewBanner?.avatarImageView?.layer.cornerRadius = viewBanner!.avatarImageView!.frame.size.width/2 viewBanner?.avatarImageView?.image = image } self.addSubview(viewBanner!) } addGestureRecognizers() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() } class func topWindow() -> UIWindow? { for window in UIApplication.shared.windows.reversed() { if window.windowLevel == UIWindow.Level.normal && !window.isHidden && window.frame != CGRect.zero { return window } } return nil } func addGestureRecognizers(){ addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTap(_:)))) let swipe = UISwipeGestureRecognizer(target: self, action: #selector(dismiss)) swipe.direction = .up addGestureRecognizer(swipe) } @objc func didTap(_ recognizer: UITapGestureRecognizer) { didTapBlock?() dismiss() } func show(view: UIView? = CyBanner.topWindow(), didTapBlock: (() -> ())? = nil){ guard let view = view else { cyPrint("CyBanner. Could not find view.") return } self.didTapBlock = didTapBlock view.addSubview(self) UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.5, options: .allowUserInteraction, animations: { self.frame = self.finalRect }) { (finished) in let dismissDelay = 4.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(1000.0 * dismissDelay))) { self.dismiss() } } } @objc func dismiss(){ UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: .allowUserInteraction, animations: { self.alpha = 0.0 self.frame = self.initialRect }) { (finished) in self.didTapDismissed?() self.removeFromSuperview() } } func dismissed(didTapDismissed: (() -> ())?){ self.didTapDismissed = didTapDismissed } }
apache-2.0
aad2af0d6a27e90a7da6ba68e3a52f9e
35.245614
164
0.593417
4.760369
false
false
false
false
MateuszKarwat/Napi
Napi/Models/Subtitle Format/Supported Subtitle Formats/SubRipSubtitleFormat.swift
1
3989
// // Created by Mateusz Karwat on 05/02/16. // Copyright © 2016 Mateusz Karwat. All rights reserved. // import Foundation /// Represents SubRip Subtitle Format. /// SubRip Subtitle Format looks like this: /// /// 2 /// 01:01:01,111 --> 02:02:02,222 /// First line of a text. /// Seconds line of a text. /// \n struct SubRipSubtitleFormat: SubtitleFormat { static let fileExtension = "srt" static let isTimeBased = true static let regexPattern = "(\\d+)\\R" + "(\\d{1,2}):(\\d{1,2}):(\\d{1,2}),(\\d{1,3})" + " +--> +" + "(\\d{1,2}):(\\d{1,2}):(\\d{1,2}),(\\d{1,3})\\R" + "((?:.+\\R?)+\\S+)" // Take all lines of text, but don't include Whitespace at the very end. static func decode(_ aString: String) -> [Subtitle] { var decodedSubtitles = [Subtitle]() self.enumerateMatches(in: aString) { match in // Extract all numbers which represent hours, minutes, etc. var timestampNumbers = [Int]() for i in 1 ... 8 { let newNumber = Int(match.capturedSubstrings[i])! timestampNumbers.append(newNumber) } let startTimestamp = timestampNumbers[0].hours + timestampNumbers[1].minutes + timestampNumbers[2].seconds + timestampNumbers[3].milliseconds let stopTimestamp = timestampNumbers[4].hours + timestampNumbers[5].minutes + timestampNumbers[6].seconds + timestampNumbers[7].milliseconds let newSubtitle = Subtitle(startTimestamp: startTimestamp, stopTimestamp: stopTimestamp, text: match.capturedSubstrings[9]) decodedSubtitles.append(newSubtitle) } return decodedSubtitles } static func encode(_ subtitles: [Subtitle]) -> [String] { var encodedSubtitles = [String]() for (index, subtitle) in subtitles.enumerated() { encodedSubtitles.append( "\(index + 1)\n" + "\(subtitle.startTimestamp.stringFormat())" + " --> " + "\(subtitle.stopTimestamp.stringFormat())\n" + "\(subtitle.text)" + "\n" ) } return encodedSubtitles } static func stringValue(for token: Token<SubtitleTokenType>) -> String? { switch token.type { case .boldStart: return "<b>" case .boldEnd: return "</b>" case .italicStart: return "<i>" case .italicEnd: return "</i>" case .underlineStart: return "<u>" case .underlineEnd: return "</u>" case .fontColorStart: return "<font color=\"\(token.values.first ?? "#FFFFFF")\">" case .fontColorEnd: return "</font>" case .whitespace: return " " case .newLine: return "\n" case .word: return "\(token.lexeme)" case .unknownCharacter: return "\(token.lexeme)" } } } fileprivate extension Timestamp { /// Returns a `String` which is in format required by SubRip Subtitle Format. func stringFormat() -> String { let minutes = self - Timestamp(value: self.numberOfFull(.hours), unit: .hours) let seconds = minutes - Timestamp(value: minutes.numberOfFull(.minutes), unit: .minutes) let milliseconds = seconds - Timestamp(value: seconds.numberOfFull(.seconds), unit: .seconds) return "\(self.numberOfFull(.hours).toString(leadingZeros: 2)):" + "\(minutes.numberOfFull(.minutes).toString(leadingZeros: 2)):" + "\(seconds.numberOfFull(.seconds).toString(leadingZeros: 2))," + "\(milliseconds.numberOfFull(.milliseconds).toString(leadingZeros: 3))" } }
mit
44b1150556737ac673ef8b1f0a9b5150
36.271028
101
0.540873
4.562929
false
false
false
false
salesawagner/WASKit
WASKitTests/Sources/Color/WASColorTests.swift
1
1753
// // WASKit // // Copyright (c) Wagner Sales (http://salesawagner.com/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import XCTest import WASKit class WASColorTests: XCTestCase { let r: UInt8 = 255 let g: UInt8 = 255 let b: UInt8 = 255 let hex = "ffffff" let invalidHex = "invalid" func testInitialization() { XCTAssertEqual(UIColor(r, g, b).WAStoUInt, UIColor.white.WAStoUInt) XCTAssertEqual(UIColor(r: r, g: g, b: b).WAStoUInt, UIColor.white.WAStoUInt) XCTAssertEqual(UIColor(grayScale: r).WAStoUInt, UIColor.white.WAStoUInt) XCTAssertEqual(UIColor(string: hex).WAStoUInt, UIColor.white.WAStoUInt) XCTAssertEqual(UIColor(string: invalidHex).WAStoUInt, UIColor.black.WAStoUInt) } }
mit
722c37c54c9febb65727e491f86246b9
41.756098
81
0.749002
3.675052
false
true
false
false
jurezove/mvvm-swift
MVVM/Car.swift
1
1839
// // Car.swift // MVVM // // Created by Jure Zove on 01/05/16. // Copyright © 2016 Jure Zove. All rights reserved. // import Foundation import RxSwift class Car { var model: String var make: String var kilowatts: Int var photoURL: String init(model: String, make: String, kilowatts: Int, photoURL: String) { self.model = model self.make = make self.kilowatts = kilowatts self.photoURL = photoURL } } class CarViewModel { private let car: Car static let horsepowerPerKilowatt = 1.34102209 let disposeBag = DisposeBag() var modelText: BehaviorSubject<String> var makeText: BehaviorSubject<String> var horsepowerText: BehaviorSubject<String> var kilowattText: BehaviorSubject<String> var titleText: BehaviorSubject<String> var photoURL: NSURL? { return NSURL(string: car.photoURL) } init(car: Car) { self.car = car modelText = BehaviorSubject<String>(value: car.model) modelText.subscribeNext { (model) in car.model = model }.addDisposableTo(disposeBag) makeText = BehaviorSubject<String>(value: car.make) makeText.subscribeNext { (make) in car.make = make }.addDisposableTo(disposeBag) titleText = BehaviorSubject<String>(value: "\(car.make) \(car.model)") [makeText, modelText].combineLatest { (carInfo) -> String in return "\(carInfo[0]) \(carInfo[1])" }.bindTo(titleText).addDisposableTo(disposeBag) horsepowerText = BehaviorSubject(value: "0") kilowattText = BehaviorSubject(value: String(car.kilowatts)) kilowattText.map({ (kilowatts) -> String in let kw = Int(kilowatts) ?? 0 let horsepower = max(Int(round(Double(kw) * CarViewModel.horsepowerPerKilowatt)), 0) return "\(horsepower) HP" }).bindTo(horsepowerText).addDisposableTo(disposeBag) } }
mit
1e2b649b624148744f9e59e263527019
26.029412
90
0.683351
3.774127
false
false
false
false
sadawi/ModelKit
ModelKit/RemoteModelStore/RequestEncoder.swift
1
2766
// // RequestEncoder.swift // APIKit // // Created by Sam Williams on 1/21/16. // Copyright © 2016 Sam Williams. All rights reserved. // // http://stackoverflow.com/questions/27794918/sending-array-of-dictionaries-with-alamofire import Foundation open class ParameterEncoder { open var escapeStrings: Bool = false open var includeNullValues: Bool = false open var nullString = "" public init(escapeStrings: Bool = false, includeNullValues:Bool = false) { self.escapeStrings = escapeStrings self.includeNullValues = includeNullValues } open func encodeParameters(_ object: AnyObject, prefix: String? = nil) -> String { if let dictionary = object as? Parameters { var results:[String] = [] for (key, value) in dictionary { if !self.valueIsNull(value) || self.includeNullValues { var prefixString: String if let prefix = prefix { prefixString = "\(prefix)[\(key)]" } else { prefixString = key } results.append(self.encodeParameters(value, prefix: prefixString)) } } return results.joined(separator: "&") } else if let array = object as? [AnyObject] { let results = array.enumerated().map { (index, value) -> String in var prefixString: String if let prefix = prefix { prefixString = "\(prefix)[\(index)]" } else { prefixString = "\(index)" } return self.encodeParameters(value, prefix: prefixString) } return results.joined(separator: "&") } else { let string = self.encodeValue(object) if let prefix = prefix { return "\(prefix)=\(string)" } else { return "\(string)" } } } open func encodeValue(_ value: AnyObject) -> String { var string:String if self.valueIsNull(value) { string = self.encodeNullValue() } else { string = "\(value)" } if self.escapeStrings { string = self.escape(string) } return string } open func valueIsNull(_ value: AnyObject?) -> Bool { return value == nil || (value as? NSNull == NSNull()) } open func encodeNullValue() -> String { return self.nullString } open func escape(_ string: String) -> String { return string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? "" } }
mit
34c2d0b7ba5d097a85ebdb16f2c0d9a2
31.916667
102
0.533092
4.964093
false
false
false
false
akhilcb/StringToHashMap
StringToHashMap/FileNameParser.swift
1
5696
// // FileNameParser.swift // StringToHashMap // // Created by Akhil Balan on 10/24/16. // Copyright © 2016 akhil. All rights reserved. // import Foundation // MARK: FileNameParserError enum implementation enum FileNameParserError : String { case InvalidFileName = "Invalid file name. Please enter a valid file name." case FileExtensionNotFound = "Could not find any file extension." case MultipleFileExtensionFound = "Found more than one file extension." case InvalidFileExtension = "Invalid file extension." case WritingFailed = "Error in writing to file." var description : String { get { return self.rawValue } } } // MARK: FileNameParser implementation class FileNameParser { init() { } //process file name text entered in text field by validating, writing to file and return output text for displaying in output view func processFileNameText(_ fileNameText: String) -> String { var displayText : String let fileNameWithExt = removeInvalidCharacters(fileNameText) let (didValidate, fileName, errorText) = validateFileName(fileNameWithExt) if didValidate { let hashMap = parseFileNameTextToHashMap(fileName!) let (didWrite, path, writeErrorText) = writeHashMapToFile(hashMap, withName: fileNameWithExt) if didWrite { displayText = finalOutputText(fileNameWithExt, withHashMap: hashMap, path: path!) } else { displayText = writeErrorText! } } else { displayText = errorText! } return displayText } //parse filename and return ordered dictionary func parseFileNameTextToHashMap(_ fileName : String) -> OrderedDictionary <String, String> { var nameArray = fileName.components(separatedBy: "_") var fileDict = OrderedDictionary <String, String> () fileDict["NAME"] = nameArray.first for i in 1..<nameArray.count { let content = nameArray[i] if content.characters.count > 0 { let index = content.index(after: content.startIndex) let key = content.substring(to: index) let val = content.substring(from: index) fileDict[key] = val } } return fileDict } //write to a file in document directory and return success/failture, path to file, error text func writeHashMapToFile(_ hashMap : OrderedDictionary <String, String>, withName name : String) -> (Bool, URL?, String?) { let fileText = "\(hashMap)" var path : URL? var didWrite = true var errorText : String? if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { path = dir.appendingPathComponent(name) do { try fileText.write(to: path!, atomically: false, encoding: String.Encoding.utf8) } catch { didWrite = false errorText = FileNameParserError.WritingFailed.description } } return (didWrite, path, errorText) } //validate file name and extension and return validFileName flag, file name and error text func validateFileName(_ fileNameWithExt: String) -> (Bool, String?, String?) { let fileNameWithExtArray = fileNameWithExt.components(separatedBy: ".") var fileName : String? var validFileName = false var displayErrorText : String? switch (fileNameWithExt, fileNameWithExtArray.count, fileNameWithExtArray.first, fileNameWithExtArray.last) { case let (fileNameWithExt, count, fileName, _) where ((fileNameWithExt == "") || (count == 2 && fileName == "")) : displayErrorText = FileNameParserError.InvalidFileName.description break case (_, 1, _, _) : displayErrorText = FileNameParserError.FileExtensionNotFound.description break case let (_, count, _, _) where count > 2 : displayErrorText = FileNameParserError.MultipleFileExtensionFound.description break case let (_, count, _, ext) where count == 2 && ext == "" : displayErrorText = FileNameParserError.InvalidFileExtension.description break default: fileName = fileNameWithExtArray.first validFileName = true } return (validFileName, fileName, displayErrorText) } //remove invalid characters from file name func removeInvalidCharacters(_ text : String) -> String { var invalidCharacters = CharacterSet(charactersIn: ":/") invalidCharacters.formUnion(CharacterSet.newlines) invalidCharacters.formUnion(CharacterSet.illegalCharacters) invalidCharacters.formUnion(CharacterSet.controlCharacters) var validText = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) validText = validText.components(separatedBy: invalidCharacters).joined(separator: "") return validText } //create final output text based on hashmap, file name and path func finalOutputText(_ fileNameWithExt : String, withHashMap hashmap : OrderedDictionary <String, String>, path : URL) -> String { let displayText = "Filename " + fileNameWithExt + " saved with contents:\n\n" + "\(hashmap)" + "\nAt path: " + "\(path)" return displayText } }
bsd-3-clause
463050d2168d8e2b45a79afd1576d282
36.966667
134
0.621422
5.219982
false
false
false
false