repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yunhan0/ChineseChess | refs/heads/master | ChineseChess/Model/Pieces/Rook.swift | mit | 1 | //
// Rook.swift
// ChineseChess
//
// Created by Yunhan Li on 5/15/17.
// Copyright © 2017 Yunhan Li. All rights reserved.
//
import Foundation
class Rook : Piece {
private var obstacleNumber: Int = 0
override func nextPossibleMoves(boardStates: [[Piece?]]) -> [Vector2] {
var ret: [Vector2] = []
// The same row
obstacleNumber = 0
for _x in stride(from: position.x - 1, through: 0, by: -1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: _x, y: position.y), boardStates) {
ret.append(Vector2(x: _x, y: position.y))
}
}
obstacleNumber = 0
for _x in stride(from: position.x + 1, to: Board.rows, by: +1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: _x, y: position.y), boardStates) {
ret.append(Vector2(x: _x, y: position.y))
}
}
// The same column
obstacleNumber = 0
for _y in stride(from: position.y - 1, through: 0, by: -1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: position.x, y: _y), boardStates) {
ret.append(Vector2(x: position.x, y: _y))
}
}
obstacleNumber = 0
for _y in stride(from: position.y + 1, to: Board.columns, by: +1) {
if (obstacleNumber == 1) {
break
}
if isValidMove(Vector2(x: position.x, y: _y), boardStates) {
ret.append(Vector2(x: position.x, y: _y))
}
}
return ret
}
override func isValidMove(_ move: Vector2, _ boardStates: [[Piece?]]) -> Bool {
if Board.isOutOfBoard(move) {
return false
}
if (obstacleNumber >= 1) {
return false
}
if let nextstate = boardStates[move.x][move.y] {
obstacleNumber += 1
if nextstate.owner == self.owner {
return false
} else {
return true
}
}
return true
}
}
| bc6ace911c52ad1986026a702f667976 | 25.032258 | 83 | 0.434944 | false | false | false | false |
sclark01/Swift_VIPER_Demo | refs/heads/master | VIPER_Demo/VIPER_DemoTests/ModulesTests/PersonDetailsTests/PresenterTests/PersonDetailsPresenterTests.swift | mit | 1 | import Foundation
import Quick
import Nimble
@testable import VIPER_Demo
class PersonDetailsPresenterTests : QuickSpec {
override func spec() {
describe("person details presenter") {
var presenter: PersonDetailsPresenter!
var mockInteractor: PersonDetailsInteractorMock!
var mockUI: PersonDetailsViewMock!
beforeEach {
presenter = PersonDetailsPresenter()
mockInteractor = PersonDetailsInteractorMock()
mockUI = PersonDetailsViewMock()
presenter.interactor = mockInteractor
presenter.userInterface = mockUI
}
it("should update view by calling get person with ID") {
let id = 10
presenter.updateViewFor(id: id)
expect(mockInteractor.getPersonByIdCalled).to(beTrue())
expect(mockInteractor.getPersonByIdCalledWithId) == id
}
it("should notify UI when a person is found") {
let personData = PersonDetailsData(person: Person(id: 1, name: "aName", phone: "aPhone", age: "anAge"))
let expectedPerson = PersonDetailsDataModel(person: personData)
presenter.got(person: personData)
expect(mockUI.calledDisplayWithPerson).toNot(beNil())
expect(mockUI.calledDisplayWithPerson) == expectedPerson
}
}
}
}
| a05d0b5d33561a8eebccac1d5dc79e66 | 32.906977 | 119 | 0.603567 | false | false | false | false |
zisko/swift | refs/heads/master | test/SILGen/external_definitions.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import ansible
var a = NSAnse(Ansible(bellsOn: NSObject()))
var anse = NSAnse
hasNoPrototype()
// CHECK-LABEL: sil @main
// -- Foreign function is referenced with C calling conv and ownership semantics
// CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @$SSo8NSObjectC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @$SSo7AnsibleC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]]
// CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
// CHECK: destroy_value [[ANSIBLE]] : $Optional<Ansible>
// -- Referencing unapplied C function goes through a thunk
// CHECK: [[NSANSE:%.*]] = function_ref @$SSo6NSAnseySo7AnsibleCSgADFTO : $@convention(thin) (@owned Optional<Ansible>) -> @owned Optional<Ansible>
// -- Referencing unprototyped C function passes no parameters
// CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
// CHECK: apply [[NOPROTO]]()
// -- Constructors for imported NSObject
// CHECK-LABEL: sil shared [serializable] @$SSo8NSObjectC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// -- Constructors for imported Ansible
// CHECK-LABEL: sil shared [serializable] @$SSo7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Optional<Any>, @thick Ansible.Type) -> @owned Optional<Ansible>
// -- Native Swift thunk for NSAnse
// CHECK: sil shared [serialized] [thunk] @$SSo6NSAnseySo7AnsibleCSgADFTO : $@convention(thin) (@owned Optional<Ansible>) -> @owned Optional<Ansible> {
// CHECK: bb0(%0 : @owned $Optional<Ansible>):
// CHECK: %1 = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: %2 = apply %1(%0) : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: destroy_value %0 : $Optional<Ansible>
// CHECK: return %2 : $Optional<Ansible>
// CHECK: }
// -- Constructor for imported Ansible was unused, should not be emitted.
// CHECK-NOT: sil {{.*}} @$SSo7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick Ansible.Type) -> @owned Ansible
| cac6090e683908a54952bab5d99e7e08 | 53.613636 | 167 | 0.671244 | false | false | false | false |
docopt/docopt.swift | refs/heads/master | Examples/Swift/naval_fate/main.swift | mit | 1 | //
// calculator_example.swift
// docopt
//
// Created by Pavel S. Mazurin on 3/9/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Docopt
let doc : String = """
Naval Fate.
Usage:
naval_fate ship new <name>...
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h | --help
naval_fate --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
var args = CommandLine.arguments
_ = args.remove(at: 0) // arguments[0] is always the program_name
let result = Docopt.parse(doc, argv: args, help: true, version: "1.0")
print("Docopt result: \(result)")
| b500342dca622cfe0da068dc3922d5ac | 24.121212 | 70 | 0.636912 | false | false | false | false |
Prosumma/CoreDataQueryInterface | refs/heads/master | Sources/CoreDataQueryInterface/QueryBuilder+Fetch.swift | mit | 1 | //
// QueryBuilder+Fetch.swift
// CoreDataQueryInterface
//
// Created by Gregory Higley on 2022-10-22.
//
import CoreData
public extension QueryBuilder {
var fetchRequest: NSFetchRequest<R> {
let fetchRequest = NSFetchRequest<R>(entityName: M.entity().name!)
fetchRequest.returnsDistinctResults = returnsDistinctResults
fetchRequest.fetchLimit = fetchLimit
fetchRequest.fetchOffset = fetchOffset
if !predicates.isEmpty {
fetchRequest.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
}
if !propertiesToFetch.isEmpty {
let properties = propertiesToFetch.map(\.asAny)
fetchRequest.propertiesToFetch = properties
}
if !propertiesToGroupBy.isEmpty {
let properties = propertiesToGroupBy.map(\.asAny)
fetchRequest.propertiesToGroupBy = properties
}
if !sortDescriptors.isEmpty {
fetchRequest.sortDescriptors = sortDescriptors
}
let resultType: NSFetchRequestResultType
switch R.self {
case is NSManagedObject.Type:
resultType = .managedObjectResultType
case is NSManagedObjectID.Type:
resultType = .managedObjectIDResultType
case is NSDictionary.Type:
resultType = .dictionaryResultType
case is NSNumber.Type:
// TODO: Figure out what the hell this is.
resultType = .countResultType // ???
default:
resultType = .managedObjectResultType
}
fetchRequest.resultType = resultType
return fetchRequest
}
func limit(_ fetchLimit: Int) -> QueryBuilder<M, R> {
var query = self
query.fetchLimit = fetchLimit
return query
}
func offset(_ fetchOffset: Int) -> QueryBuilder<M, R> {
var query = self
query.fetchOffset = fetchOffset
return query
}
func objects() -> QueryBuilder<M, M> {
.init(copying: self)
}
func ids() -> QueryBuilder<M, NSManagedObjectID> {
.init(copying: self)
}
func dictionaries() -> QueryBuilder<M, NSDictionary> {
.init(copying: self)
}
func fetch(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> [R] {
let results: [R]
if let moc = self.managedObjectContext ?? managedObjectContext {
results = try moc.fetch(fetchRequest)
} else {
results = try fetchRequest.execute()
}
return results
}
func fetchObjects(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> [M] {
try objects().fetch(managedObjectContext)
}
func fetchIDs(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> [NSManagedObjectID] {
try ids().fetch(managedObjectContext)
}
func fetchDictionaries(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> [[String: Any]] {
try dictionaries().fetch(managedObjectContext) as! [[String: Any]]
}
func fetchFirst(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> R? {
try limit(1).fetch(managedObjectContext).first
}
func count(_ managedObjectContext: NSManagedObjectContext? = nil) throws -> Int {
guard let moc = self.managedObjectContext ?? managedObjectContext else {
preconditionFailure("No NSManagedObjectContext instance on which to execute the request.")
}
return try moc.count(for: fetchRequest)
}
}
| e812f7deb130496ed8a3a07e3d1d8074 | 30.336538 | 107 | 0.699908 | false | false | false | false |
sahandnayebaziz/Dana-Hills | refs/heads/master | Dana Hills/NewsTableViewCell.swift | mit | 1 | //
// NewsTableViewCell.swift
// Dana Hills
//
// Created by Sahand Nayebaziz on 10/2/16.
// Copyright © 2016 Nayebaziz, Sahand. All rights reserved.
//
import UIKit
class NewsTableViewCell: UITableViewCell {
var titleLabel: UILabel? = nil
var publishDateLabel: UILabel? = nil
func set(forNewsArticle article: NewsArticle) {
createSubviews()
titleLabel?.text = ""
publishDateLabel?.text = ""
titleLabel?.text = article.title
publishDateLabel?.text = article.datePublished.toStringWithRelativeTime()
}
private func createSubviews() {
if titleLabel == nil {
titleLabel = UILabel()
titleLabel?.numberOfLines = 0
titleLabel!.font = UIFont.preferredFont(forTextStyle: .headline)
addSubview(titleLabel!)
}
if publishDateLabel == nil {
publishDateLabel = UILabel()
publishDateLabel!.font = UIFont.preferredFont(forTextStyle: .caption1)
publishDateLabel!.textColor = UIColor.lightGray
addSubview(publishDateLabel!)
}
titleLabel!.snp.makeConstraints { make in
make.left.equalTo(16)
make.right.equalTo(-12)
make.top.equalTo(16)
make.bottom.equalTo(publishDateLabel!.snp.top).offset(-4)
}
publishDateLabel!.snp.makeConstraints { make in
make.left.equalTo(16)
make.bottom.equalTo(-16)
}
}
}
| ae31452a6b019222596523d819a976c2 | 27.849057 | 82 | 0.59843 | false | false | false | false |
hulab/ClusterKit | refs/heads/master | Examples/Example-swift/YandexMapViewController.swift | mit | 1 | //
// YandexMapViewController.swift
// Example-swift
//
// Created by petropavel on 24/01/2019.
// Copyright © 2019 Hulab. All rights reserved.
//
import YandexMapKit
import ClusterKit
import ExampleData
class YandexMapViewController: UIViewController, YMKMapViewDataSource,
YMKMapLoadedListener,
YMKMapCameraListener,
YMKMapObjectTapListener,
YMKMapObjectDragListener {
@IBOutlet weak var mapView: YMKMapView!
private var isMapLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
mapView.dataSource = self
let map = mapView.mapWindow.map
map.setMapLoadedListenerWith(self)
map.addCameraListener(with: self)
let algorithm = CKNonHierarchicalDistanceBasedAlgorithm()
algorithm.cellSize = 200
mapView.clusterManager.algorithm = algorithm
mapView.clusterManager.marginFactor = 1
let paris = YMKPoint(latitude: 48.853, longitude: 2.35)
map.move(with: YMKCameraPosition(target: paris, zoom: 0, azimuth: 0, tilt: 0))
loadData()
}
func loadData() {
let operation = CKGeoPointOperation()
operation.setCompletionBlockWithSuccess({ (_, points) in
self.mapView.clusterManager.annotations = points
})
operation.start()
}
// MARK: YMKMapViewDataSource
func mapView(_ mapView: YMKMapView, placemarkFor cluster: CKCluster) -> YMKPlacemarkMapObject {
let point = YMKPoint(coordinate: cluster.coordinate)
let placemark: YMKPlacemarkMapObject
let mapObjects = mapView.mapWindow.map.mapObjects
if cluster.count > 1 {
placemark = mapObjects.addPlacemark(with: point, image: #imageLiteral(resourceName: "cluster"))
} else {
placemark = mapObjects.addPlacemark(with: point, image: #imageLiteral(resourceName: "marker"))
}
placemark.isDraggable = true
placemark.setDragListenerWith(self)
placemark.addTapListener(with: self)
return placemark
}
// MARK: YMKMapLoadedListener
func onMapLoaded(with statistics: YMKMapLoadStatistics) {
isMapLoaded = true
}
// MARK: - How To Update Clusters
// MARK: YMKMapCameraListener
func onCameraPositionChanged(with map: YMKMap,
cameraPosition: YMKCameraPosition,
cameraUpdateSource: YMKCameraUpdateSource,
finished: Bool) {
guard isMapLoaded, finished else {
return
}
mapView.clusterManager.updateClustersIfNeeded()
// workaround (https://github.com/yandex/mapkit-ios-demo/issues/23)
// we need to wait some time to get actual visibleRegion for clusterization
// DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
// self.mapView.clusterManager.updateClustersIfNeeded()
// }
}
// MARK: - How To Handle Selection/Deselection
// MARK: YMKMapObjectTapListener
func onMapObjectTap(with mapObject: YMKMapObject, point: YMKPoint) -> Bool {
guard let placemark = mapObject as? YMKPlacemarkMapObject,
let cluster = placemark.cluster else {
return false
}
let padding = UIEdgeInsets(top: 40, left: 20, bottom: 44, right: 20)
if cluster.count > 1 {
mapView.mapWindow.map.move(with: mapView.cameraPositionThatFits(cluster, edgePadding: padding),
animationType: YMKAnimation(type: .smooth, duration: 0.5),
cameraCallback: { completed in
if completed {
self.mapView.clusterManager.updateClustersIfNeeded()
}
})
return true
} else if let annotation = cluster.firstAnnotation {
mapView.clusterManager.selectAnnotation(annotation, animated: true)
return true
}
return false
}
// MARK: - How To Handle Drag and Drop
// MARK: YMKMapObjectDragListener
func onMapObjectDragStart(with mapObject: YMKMapObject) {
// nothing
}
func onMapObjectDrag(with mapObject: YMKMapObject, point: YMKPoint) {
// nothing
}
func onMapObjectDragEnd(with mapObject: YMKMapObject) {
guard let placemark = mapObject as? YMKPlacemarkMapObject,
let annotation = placemark.cluster?.firstAnnotation as? MKPointAnnotation else {
return
}
annotation.coordinate = placemark.geometry.coordinate
}
}
private extension YMKPoint {
convenience init(coordinate: CLLocationCoordinate2D) {
self.init(latitude: coordinate.latitude, longitude: coordinate.longitude)
}
}
| 3df53d71cbee55ec1adac796c452c92b | 29.378882 | 107 | 0.629319 | false | false | false | false |
theMonster/KAHN | refs/heads/master | Kahn/KahnTests/KahnTests.swift | mit | 1 | //
// KahnTests.swift
// KahnTests
//
// Created by Caleb Jonassaint on 12/1/14.
// Copyright (c) 2014 Caleb Jonassaint. All rights reserved.
//
import UIKit
import XCTest
import Kahn
class HTTPBin : Endpoint {
override init() {
super.init()
self.setBaseURL(NSURL(string: "https://httpbin.org")!)
}
}
let get = HTTPBin().setEndpoint("get") .GET()
let post = HTTPBin().setEndpoint("post").POST(nil)
let put = HTTPBin().setEndpoint("put").PUT(nil)
let patch = HTTPBin().setEndpoint("patch").PATCH(nil)
class KahnTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testHTTPBinUserAgent() {
let e = expectationWithDescription("user-endpoint")
HTTPBin().setEndpoint("user-agent").GETJSON() (options: nil, success: { (object) in
println((object as [String:AnyObject])["user-agent"]!)
e.fulfill()
}, failure: { () in
e.fulfill()
XCTAssert(false, "failed")
})
waitForExpectationsWithTimeout(10, handler: nil)
}
func testHTTPBinGet() {
runAnEndpoint(get)
}
func testHTTPBinPost() {
runAnEndpoint(post)
}
func testHTTPBinPut() {
runAnEndpoint(put)
}
func testHTTPBinPatch() {
runAnEndpoint(patch)
}
func runAnEndpoint(closure:Endpoint.DefaultReturn) {
let e = self.expectationWithDescription("endpoint")
closure (options: nil) { (data, response, error) -> Void in
println(NSString(data: data!, encoding: NSUTF8StringEncoding)!)
e.fulfill()
}
waitForExpectationsWithTimeout(10, handler: nil)
}
}
| fd3b8225795dc4bba4e589a691528e9a | 26.680556 | 111 | 0.610637 | false | true | false | false |
mdpianelli/ios-shopfinder | refs/heads/master | ShopFinder/ShopFinder/ShopFilterOptionsController.swift | mit | 1 | //
// ShopFilterOptions.swift
// ShopFinder
//
// Created by Marcos Pianelli on 17/07/15.
// Copyright (c) 2015 Barkala Studios. All rights reserved.
//
import UIKit
import Spring
class ShopFilterOptionsController : UIViewController {
@IBOutlet weak var modalView: SpringView!
weak var delegate : ShopListController?
@IBOutlet weak var resetButton: DesignableButton!
override func viewDidLoad() {
super.viewDidLoad()
modalView.transform = CGAffineTransformMakeTranslation(0, 300)
}
private func titleLabel(text text: String) -> UILabel {
let label = UILabel()
label.text = text
label.sizeToFit()
label.frame.origin = CGPoint(x: 12, y: 12)
return label
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
modalView.addDarkBlur()
//resetButton.makeTinted()
//modalView.insertSubview(resetButton, atIndex: 1)
//self.view.addVibrantStatusBarBackground(UIBlurEffect(style: .Light))
UIApplication.sharedApplication().sendAction("minimizeView:", to:self.delegate, from: self, forEvent: nil)
//
modalView.animate()
}
override func viewWillDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.view.removeVibrantStatusBarBackground()
}
@IBAction func resetButtonPressed(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().sendAction("maximizeView:", to:self.delegate, from: self, forEvent: nil)
}
@IBAction func closeButtonPressed(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().sendAction("maximizeView:", to:self.delegate, from: self, forEvent: nil)
}
func callSortTable(){
UIApplication.sharedApplication().sendAction("sortTable:", to:self.delegate, from: self, forEvent: nil)
resetButtonPressed(self)
}
@IBAction func sortByDistance(sender: AnyObject) {
self.delegate?.sortType = .Distance
callSortTable()
}
@IBAction func sortByRating(sender: AnyObject) {
self.delegate?.sortType = .Rating
callSortTable()
}
@IBAction func sortByReviewCount(sender: AnyObject) {
self.delegate?.sortType = .ReviewCount
callSortTable()
}
}
| 2c18137882312099b97524a2ef976391 | 24.294118 | 114 | 0.634496 | false | false | false | false |
mmrmmlrr/HandyText | refs/heads/master | HandyText/TextStyle.swift | mit | 1 | //
// TextStyle.swift
// HandyText
//
// Copyright © 2016 aleksey chernish. All rights reserved.
//
import UIKit
//TODO: generate attributes on demand to avoid recalculations
public class TextStyle {
public enum BaselineOffset {
case none
case absolute(CGFloat)
case relative(CGFloat)
}
public enum CaseTrait {
case none, capitalized, lowercase, uppercase
}
public var textAttributes: [NSAttributedString.Key: AnyObject] {
get {
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[.foregroundColor] = foregroundColor.withAlphaComponent(opacity)
attributes[.backgroundColor] = backgroundColor?.withAlphaComponent(opacity)
attributes[.strikethroughColor] = strikeThroughColor?.withAlphaComponent(opacity)
attributes[.strokeColor] = strokeColor?.withAlphaComponent(opacity)
attributes[.strokeWidth] = strokeWidth as AnyObject?
attributes[.paragraphStyle] = paragraphStyle
attributes[.font] = UIFont(name: typeface, size: size)
attributes[.ligature] = ligaturesEnabled as AnyObject?
attributes[.strikethroughStyle] = Int(strikethrough ? 1 : 0) as AnyObject?
attributes[.underlineStyle] = underlineStyle.rawValue as AnyObject?
attributes[.underlineColor] = underlineColor?.withAlphaComponent(opacity)
attributes[.shadow] = shadow
attributes[.link] = link as AnyObject?
attributes[.kern] = letterSpacing as AnyObject?
let calculatedOffset: CGFloat
switch baselineOffset {
case .absolute(let offset):
calculatedOffset = offset
case .relative(let offset):
calculatedOffset = offset * size
case .none:
calculatedOffset = 0.0
}
attributes[.baselineOffset] = calculatedOffset as AnyObject?
return attributes
}
}
public var paragraphStyle = NSMutableParagraphStyle()
/// STATE
public var font: Font
public var size: CGFloat = UIFont.preferredFont(forTextStyle: .body).pointSize
public var thickness = Font.Thickness.regular
public var caseTrait = CaseTrait.none
public var isItalic = false
public var opacity: CGFloat = 1.0
public var foregroundColor = UIColor.black
public var backgroundColor: UIColor?
public var underlineColor: UIColor?
public var strikeThroughColor: UIColor?
public var strokeColor: UIColor?
public var underlineStyle = NSUnderlineStyle(rawValue: 0)
public var strikethrough = false
public var ligaturesEnabled = false
public var strokeWidth: CGFloat = 0.0
public var shadow: NSShadow?
public var link: String?
public var baselineOffset = BaselineOffset.none
public var letterSpacing: CGFloat?
public var typeface: String {
get {
switch thickness {
case .extralight:
return isItalic ? font.extralightItalic : font.extralight
case .light:
return isItalic ? font.lightItalic : font.light
case .regular:
return isItalic ? font.italic : font.regular
case .medium:
return isItalic ? font.mediumItalic : font.medium
case .bold:
return isItalic ? font.boldItalic : font.bold
case .heavy:
return isItalic ? font.heavyItalic : font.heavy
case .extraheavy:
return isItalic ? font.extraheavyItalic : font.extraheavy
}
}
}
public enum DynamicFontStyle {
case title1, title2, title3, headline, subheadline, body, callout, footnote, caption1, caption2
var literal: String {
switch self {
case .title1:
return UIFont.TextStyle.title1.rawValue
case .title2:
return UIFont.TextStyle.title2.rawValue
case .title3:
return UIFont.TextStyle.title3.rawValue
case .headline:
return UIFont.TextStyle.headline.rawValue
case .subheadline:
return UIFont.TextStyle.subheadline.rawValue
case .body:
return UIFont.TextStyle.body.rawValue
case .callout:
return UIFont.TextStyle.callout.rawValue
case .footnote:
return UIFont.TextStyle.footnote.rawValue
case .caption1:
return UIFont.TextStyle.caption1.rawValue
case .caption2:
return UIFont.TextStyle.caption2.rawValue
}
}
}
public init(font: Font) {
self.font = font
}
public func copy() -> TextStyle {
let copy = TextStyle(font: font)
copy.size = size
copy.thickness = thickness
copy.caseTrait = caseTrait
copy.isItalic = isItalic
copy.paragraphStyle = paragraphStyle
copy.opacity = opacity
copy.foregroundColor = foregroundColor
copy.backgroundColor = backgroundColor
copy.strikeThroughColor = strikeThroughColor
copy.underlineColor = underlineColor
copy.underlineStyle = underlineStyle
copy.strikethrough = strikethrough
copy.ligaturesEnabled = ligaturesEnabled
copy.strokeColor = strokeColor
copy.strokeWidth = strokeWidth
copy.shadow = shadow
copy.link = link
copy.letterSpacing = letterSpacing
copy.baselineOffset = baselineOffset
return copy
}
}
| 3767cc8f5f489e474a4afd95efd4c135 | 34.635802 | 103 | 0.613199 | false | false | false | false |
Lohika-Mobile/css-demo-ios | refs/heads/master | CSSDemo/CommentsViewController.swift | mit | 2 | //
// CommentsViewController.swift
// CSSDemo
//
// Created by Vjacheslav Volodko on 18.07.15.
// Copyright (c) 2015 Vjacheslav Volodko. All rights reserved.
//
import UIKit
import InstagramKit
class CommentsViewController: UITableViewController {
// MARK: - Comment List
var comments: [InstagramComment] = [] {
didSet {
self.tableView.reloadData()
}
}
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 76
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentTableViewCell
cell.comment = self.comments[indexPath.row]
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| 0922875b4248afd2bc0a538ea3c38c16 | 27 | 127 | 0.668737 | false | false | false | false |
kiwisip/BadgeControl | refs/heads/master | BadgeControl/BadgeView.swift | mit | 1 | //
// BadgeView.swift
// BadgeControl
//
// Created by Robin Krenecky on 19.08.17.
// Copyright © 2017 Robin Krenecky. All rights reserved.
//
import UIKit
open class BadgeView: UIView {
// MARK: Internal properties
internal var height: CGFloat { didSet { updateUI() } }
internal var centerPoint: CGPoint { didSet { updateUI() } }
internal var text: String { didSet { updateUI() } }
internal var badgeBackgroundColor: UIColor { didSet { updateUI() } }
internal var badgeTextColor: UIColor { didSet { updateUI() } }
internal var badgeTextFont: UIFont { didSet { updateUI() } }
internal var borderWidth: CGFloat { didSet { updateUI() } }
internal var borderColor: UIColor { didSet { updateUI() } }
// MARK: Initializers
public init(height: CGFloat,
center: CGPoint,
text: String,
badgeBackgroundColor: UIColor,
badgeTextColor: UIColor,
badgeTextFont: UIFont,
borderWidth: CGFloat,
borderColor: UIColor) {
self.height = height
self.centerPoint = center
self.text = text
self.badgeBackgroundColor = badgeBackgroundColor
self.badgeTextColor = badgeTextColor
self.badgeTextFont = badgeTextFont
self.borderWidth = borderWidth
self.borderColor = borderColor
super.init(frame: CGRect(x: 0,
y: 0,
width: BadgeView.calculateWidth(height: height, borderWidth: borderWidth, text: text),
height: height))
backgroundColor = .clear
}
@available(*, unavailable, message: "Storyboard initiation is not supported.")
public required init?(coder aDecoder: NSCoder) { fatalError("Not supported") }
open override func draw(_ rect: CGRect) {
frame = CGRect(x: 0, y: 0, width: BadgeView.calculateWidth(height: height, borderWidth: borderWidth, text: text), height: height)
let height = frame.height - borderWidth
let ovalWidth = height
let rightHemisphereX = frame.width - borderWidth / 2 - height
drawOval(height, ovalWidth, rightHemisphereX)
drawText()
center = centerPoint
}
// MARK: Private methods
private static func calculateWidth(height: CGFloat, borderWidth: CGFloat, text: String) -> CGFloat {
let height = height - borderWidth * 2
let ratio = CGFloat(text.count > 0 ? text.count : 1)
return CGFloat(height + (ratio - 1) * height / 2.4) + borderWidth * 2
}
private func drawOval(_ height: CGFloat, _ ovalWidth: CGFloat, _ rightHemisphereX: CGFloat) {
var ovalPath = UIBezierPath()
addRightHemisphereArc(to: &ovalPath, rightHemisphereX, ovalWidth, height)
ovalPath.addLine(to: CGPoint(x: ovalWidth / 2, y: height + borderWidth / 2))
addLeftHemisphereArc(to: &ovalPath, frame, ovalWidth, height)
ovalPath.close()
badgeBackgroundColor.setFill()
ovalPath.fill()
borderColor.setStroke()
ovalPath.lineWidth = borderWidth
ovalPath.stroke()
}
private func addRightHemisphereArc(to path: inout UIBezierPath, _ rightHemisphereX: CGFloat, _ ovalWidth: CGFloat, _ height: CGFloat) {
let rightHemisphereRect = CGRect(x: rightHemisphereX, y: borderWidth / 2, width: ovalWidth, height: height)
path.addArc(withCenter: CGPoint(x: rightHemisphereRect.midX, y: rightHemisphereRect.midY),
radius: rightHemisphereRect.width / 2,
startAngle: -90 * CGFloat.pi / 180,
endAngle: -270 * CGFloat.pi / 180,
clockwise: true)
}
private func addLeftHemisphereArc(to path: inout UIBezierPath, _ frame: CGRect, _ ovalWidth: CGFloat, _ height: CGFloat) {
let leftHemisphereRect = CGRect(x: frame.minX + borderWidth / 2, y: frame.minY + borderWidth / 2, width: ovalWidth, height: height)
path.addArc(withCenter: CGPoint(x: leftHemisphereRect.midX, y: leftHemisphereRect.midY),
radius: leftHemisphereRect.width / 2,
startAngle: -270 * CGFloat.pi / 180,
endAngle: -90 * CGFloat.pi / 180,
clockwise: true)
}
private func drawText() {
let textRect = frame
let textTextContent = text
let textStyle = NSMutableParagraphStyle()
textStyle.alignment = .center
let textFontAttributes = [
.font: badgeTextFont,
.foregroundColor: badgeTextColor,
.paragraphStyle: textStyle,
] as [NSAttributedString.Key: Any]
let textTextHeight: CGFloat = textTextContent.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity),
options: .usesLineFragmentOrigin,
attributes: textFontAttributes,
context: nil).height
textTextContent.draw(in: CGRect(x: textRect.minX, y: textRect.minY + (textRect.height - textTextHeight) / 2,
width: textRect.width,
height: textTextHeight),
withAttributes: textFontAttributes)
}
private func updateUI() {
setNeedsDisplay()
}
}
| ac54e5aae731057ee973cc36113f903f | 37.073529 | 137 | 0.634608 | false | false | false | false |
midoks/Swift-Learning | refs/heads/master | GitHubStar/GitHubStar/GitHubStar/Controllers/ad/GuideViewController.swift | apache-2.0 | 1 | //
// GuideViewController.swift
// GitHubStar
//
// Created by midoks on 16/2/18.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
class GuideViewController: UIViewController {
var collectionView: UICollectionView?
let cellIdentifier = "GuideCell"
var pageController = UIPageControl(frame: CGRect(x: 0, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width, height: 20))
//导航视图
var imageNames = ["guide_40_1", "guide_40_2", "guide_40_3"]
//跳入正常视图
let nextButton = UIButton(frame: CGRect(x: (UIScreen.main.bounds.width - 100) * 0.5, y: UIScreen.main.bounds.height - 110, width: 100, height: 33))
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 239 / 255.0, green: 239 / 255.0, blue: 239 / 255.0, alpha: 1)
self.initView()
self.buildPageController()
self.buildNextButton()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 初始化视图 -
private func initView(){
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = UIScreen.main.bounds.size
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: layout)
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
collectionView?.isPagingEnabled = true
collectionView?.bounces = false
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
self.view.addSubview(collectionView!)
collectionView?.backgroundColor = UIColor.blue
}
//分页控制器
private func buildPageController() {
pageController.numberOfPages = self.imageNames.count
pageController.currentPage = 0
self.view.addSubview(pageController)
}
//进入下一个的按钮
private func buildNextButton(){
nextButton.setBackgroundImage(UIImage(named: "icon_next"), for: UIControlState.normal)
nextButton.addTarget(self, action: #selector(nextButtonClick), for: UIControlEvents.touchUpInside)
nextButton.isHidden = true
self.view.addSubview(nextButton)
}
//进入程序页
func nextButtonClick(){
let delegate = UIApplication.shared.delegate
delegate?.window!!.rootViewController = RootViewController()
GuideViewController.setAppOk()
}
//MARK: - 简单的判断和设置 -
static func isFristOpen() -> Bool {
let isFristOpen = UserDefaults.standard.object(forKey: "isFristOpenApp")
if isFristOpen == nil {
return true
}
return false
}
static func setAppOk(){
UserDefaults.standard.set("isFristOpenApp", forKey: "isFristOpenApp")
}
static func setAppFail(){
UserDefaults.standard.removeObject(forKey: "isFristOpenApp")
}
}
extension GuideViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageNames.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath as IndexPath)
let imageView = UIImageView(frame: UIScreen.main.bounds)
let newImage = UIImage(named: imageNames[indexPath.row])
imageView.image = newImage
imageView.contentMode = UIViewContentMode.scaleAspectFill
cell.contentView.addSubview(imageView)
if indexPath.row != imageNames.count - 1 {
nextButton.isHidden = true
}
return cell
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x == UIScreen.main.bounds.width * CGFloat(imageNames.count - 1) {
nextButton.isHidden = false
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.x != UIScreen.main.bounds.width * CGFloat(imageNames.count - 1)
&& scrollView.contentOffset.x > UIScreen.main.bounds.width * CGFloat(imageNames.count - 2) {
nextButton.isHidden = true
}
pageController.currentPage = Int(scrollView.contentOffset.x / UIScreen.main.bounds.width + 0.5)
}
}
| 8cbb512c439b982524c712c2d9ea3466 | 32.582192 | 151 | 0.657149 | false | false | false | false |
gxfeng/iOS- | refs/heads/master | ShowCell.swift | apache-2.0 | 1 | //
// ShowCell.swift
// ProjectSwift
//
// Created by ZJQ on 2016/12/23.
// Copyright © 2016年 ZJQ. All rights reserved.
//
import UIKit
class ShowCell: UITableViewCell {
var dataArray = Array<RoomModel>()
var title = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setSubViews()
}
func setSubViews() {
title = UILabel.init(frame: CGRect.init(x: 15, y: 5, width: 200, height: 15))
title.font = UIFont.systemFont(ofSize: 13)
self.contentView.addSubview(title)
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = .init(width: (UIScreen.main.bounds.size.width-3*10)/2, height: 100)
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = 5;
layout.sectionInset = .init(top: 0, left: 10, bottom: 0, right: 10)
let collectionView = UICollectionView.init(frame: .init(x: 0, y: 20, width: UIScreen.main.bounds.size.width, height: 210), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.white
self.contentView.addSubview(collectionView)
collectionView.register(DetailCollectionCell.self, forCellWithReuseIdentifier: "detailCell")
}
func sendModel(model: DetailChannelModel) {
title.text = model.title
self.dataArray = model.roomlist as! Array<RoomModel>
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension ShowCell : UICollectionViewDelegate,UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "detailCell", for: indexPath) as! DetailCollectionCell
cell.sendModel(model: self.dataArray[indexPath.item])
return cell
}
}
| 9af9861a3c84ff8d2a87a7f8532cbc0f | 30.091954 | 160 | 0.660998 | false | false | false | false |
Karumi/BothamUI | refs/heads/master | Example/Example/SeriesDetailPresenter.swift | apache-2.0 | 1 | //
// SerieDetailPresenter.swift
// Example
//
// Created by Pedro Vicente Gomez on 21/12/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
import BothamUI
class SeriesDetailPresenter: BothamPresenter {
private let seriesName: String
private weak var ui: SeriesDetailUI?
init(ui: SeriesDetailUI, seriesName: String) {
self.ui = ui
self.seriesName = seriesName
}
func viewDidLoad() {
ui?.title = seriesName.uppercased()
loadSeriesDetail()
}
private func loadSeriesDetail() {
let series = Series(name: seriesName,
coverURL: URL(string: "https://vignette3.wikia.nocookie.net/steamtradingcards/images/e/e6/Marvel_Heroes_Artwork_Iron_Man.jpg/revision/latest?cb=20130929234052"),
rating: "T",
description: "Extremis: It changes everything for Iron Man! The deadly "
+ "new technology from the imagination of Warren Ellis and Adi Granov "
+ "propels Tony Stark into the next gear as he takes on a super hero "
+ "Civil War and perhaps his greatest challenge yet as Director of "
+ "S.H.I.E.L.D.!",
comics: [
Comic(name: "Civil War: Iron Man",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/c/90/51ddaa7bb6788/portrait_incredible.jpg")),
Comic(name: "Iron Man: Execute Program",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/f/a0/4bc5ae737ec9c/portrait_incredible.jpg")),
Comic(name: "Iron Man: Extremis",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/8/80/4bc5abb727022/portrait_incredible.jpg")),
Comic(name: "Iron Man #14",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/9/40/4d2525b096dec/portrait_incredible.jpg")),
Comic(name: "Iron Man #13",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/6/e0/4d24fdc986281/portrait_incredible.jpg")),
Comic(name: "Iron Man #12",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/b/c0/4d2515cda44ae/portrait_incredible.jpg")),
Comic(name: "Iron Man #11",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/5/03/4d250b7077707/portrait_incredible.jpg")),
Comic(name: "Iron Man #10",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/3/03/4d25153f18362/portrait_incredible.jpg")),
Comic(name: "Iron Man #9",
coverURL: URL(string: "https://i.annihil.us/u/prod/marvel/i/mg/e/f0/4d24dea0ce8e1/portrait_incredible.jpg")),
Comic(name: "Iron Man #8",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/9/50/4d24e83a5b5d5/portrait_incredible.jpg")),
Comic(name: "Iron Man #7",
coverURL: URL(string: "https://i.annihil.us/u/prod/marvel/i/mg/7/20/4f8479d44fd50/portrait_incredible.jpg")),
Comic(name: "Iron Man #6",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/6/60/4f84752bb13d5/portrait_incredible.jpg")),
Comic(name: "Iron Man #5",
coverURL: URL(string: "https://i.annihil.us/u/prod/marvel/i/mg/c/60/4bb7dec0199b5/portrait_incredible.jpg")),
Comic(name: "Iron Man #4",
coverURL: URL(string: "https://x.annihil.us/u/prod/marvel/i/mg/c/70/4f7f0a8fb8c03/portrait_incredible.jpg")),
Comic(name: "Iron Man #3",
coverURL: URL(string: "https://i.annihil.us/u/prod/marvel/i/mg/9/60/4d251fee74e41/portrait_incredible.jpg"))
])
ui?.configureHeader(series)
ui?.show(items: series.comics)
}
}
| 029c38e7184103ad4114b3960877d8a7 | 54.366197 | 173 | 0.600865 | false | false | false | false |
aucl/YandexDiskKit | refs/heads/master | YandexDiskKit/YandexDiskKit/YDisk+ListFileResources.swift | bsd-2-clause | 1 | //
// YDisk+ListFileResources.swift
//
// Copyright (c) 2015, Clemens Auer
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
extension YandexDisk {
public enum FileResourceListingResult {
case Listing(items:[YandexDiskResource], limit:Int?, offset:Int? )
case Failed(NSError!)
}
/// List metainfo for files.
///
/// :param: limit Optional. The number of resources in the folder that should be described in the response (for example, for paginated output).
/// :param: offset Optional. The number of resources from the top of the list that should be skipped in the response (for example, for paginated output).
/// :param: media_type Optional. The type of files to included in the list. Each file type is detected by Disk when uploading.
/// :param: preview_size Optional. Requested size for the previews.
/// :param: preview_crop Optional. If true, preview will be cropped to square.
/// :param: sort Optional. The attribute used for sorting the list of files.
/// :param: handler Optional.
/// :returns: `ListingResult` future.
///
/// API reference:
/// `english http://api.yandex.com/disk/api/reference/all-files.xml`_,
/// `russian https://tech.yandex.ru/disk/api/reference/all-files-docpage/`_.
public func listFileResources(limit:Int?=nil, offset:Int?=nil, media_type:String?=nil, preview_size:PreviewSize?=nil, preview_crop:Bool?=nil, sort:SortKey?=nil, handler:((listing:FileResourceListingResult) -> Void)? = nil) -> Result<FileResourceListingResult> {
let result = Result<FileResourceListingResult>(handler: handler)
var url = "\(baseURL)/v1/disk/resources/files"
url.appendOptionalURLParameter("limit", value:limit)
url.appendOptionalURLParameter("media_type", value:media_type)
url.appendOptionalURLParameter("offset", value:offset)
url.appendOptionalURLParameter("preview_crop", value:preview_crop)
url.appendOptionalURLParameter("preview_size", value:preview_size)
url.appendOptionalURLParameter("sort", value:sort)
let error = { result.set(.Failed($0)) }
session.jsonTaskWithURL(url, errorHandler: error) {
(jsonRoot, response)->Void in
switch response.statusCode {
case 200:
if let items = SimpleResource.resourcesFromArray(jsonRoot["items"] as? NSArray)
{
let limit = (jsonRoot["limit"] as? NSNumber)?.integerValue
let offset = (jsonRoot["offset"] as? NSNumber)?.integerValue
return result.set(.Listing(items: items, limit: limit, offset: offset))
} else {
return error(NSError(domain: "YDisk", code: response.statusCode, userInfo:
["message":"incomplete JSON response", "json":jsonRoot]))
}
default:
return error(NSError(domain: "YDisk", code: response.statusCode, userInfo: ["response":response]))
}
}.resume()
return result
}
}
| fde3fd24fa62c16324cc9c8dc52506c3 | 50.114943 | 265 | 0.675961 | false | false | false | false |
ouch1985/IQuery | refs/heads/master | IQuery/views/FavoCell.swift | mit | 1 | //
// FavoViewCellCollectionViewCell.swift
// IQuery
//
// Created by ouchuanyu on 15/12/7.
// Copyright © 2015年 ouchuanyu.com. All rights reserved.
//
import UIKit
class FavoCell: FavoBaseCell {
// 底部的标题
var titleLabel : UILabel?
// logo图片
var logoImg : UIImageView?
// 删除按钮
var delBtn : UILabel?
// 删除按钮的高度
let delBtnSize : CGFloat = 40
override init(frame: CGRect) {
super.init(frame: frame)
let bounds = self.contentView.bounds
// 初始化标题
titleLabel = UILabel(frame: CGRectMake(0, bounds.height - txtHeight, bounds.width, txtHeight))
titleLabel!.textAlignment = NSTextAlignment.Center
self.contentView.addSubview(titleLabel!)
// 初始化LOGO
let size : CGFloat = bounds.height - txtHeight - imgPadding*2
logoImg = UIImageView(frame: CGRectMake(imgPadding + txtHeight/2, imgPadding, size, size))
logoImg?.layer.cornerRadius = 8
logoImg?.layer.masksToBounds = true
self.contentView.addSubview(logoImg!)
// 删除按钮
delBtn = UILabel(frame: CGRectMake(0, 0, bounds.width, bounds.height))
delBtn!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
delBtn!.textAlignment = NSTextAlignment.Center
delBtn!.font = UIFont.fontAwesomeOfSize(delBtnSize)
delBtn!.text = String.fontAwesomeIconWithName(FontAwesome.TimesCircle)
delBtn!.textColor = UIColor(red:0.83, green:0.33, blue:0.3, alpha:1)
delBtn!.hidden = true
self.contentView.addSubview(delBtn!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| cd9582863e39ba68c79a527ed44867c7 | 29.241379 | 102 | 0.629418 | false | false | false | false |
Bajocode/ExploringModerniOSArchitectures | refs/heads/master | Architectures/MVP/Presenter/MovieResultsPresenter.swift | mit | 1 | //
// MovieResultsPresenter.swift
// Architectures
//
// Created by Fabijan Bajo on 29/05/2017.
//
//
import Foundation
class MovieResultsPresenter: ResultsViewPresenter {
// MARK: - Properties
unowned private let view: ResultsView
private var movies = [Movie]()
var objectsCount: Int { return movies.count }
struct PresentableInstance: Transportable {
let title: String
let thumbnailURL: URL
let fullSizeURL: URL
let ratingText: String
let releaseDateText: String
}
private let releaseDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd"
return formatter
}()
// MARK: - Initializers
required init(view: ResultsView) {
self.view = view
}
// Cannot Mock because of movies private access control
convenience init(view: ResultsView, testableMovies: [Movie]) {
self.init(view: view)
movies = testableMovies
}
// MARK: - Methods
func presentableInstance(index: Int) -> Transportable {
let movie = movies[index]
let thumbnailURL = TmdbAPI.tmdbImageURL(forSize: .thumb, path: movie.posterPath)
let fullSizeURL = TmdbAPI.tmdbImageURL(forSize: .full, path: movie.posterPath)
let ratingText = String(format: "%.1f", movie.averageRating)
let dateObject = releaseDateFormatter.date(from: movie.releaseDate)
let releaseDateText = releaseDateFormatter.string(from: dateObject!)
return PresentableInstance(title: movie.title, thumbnailURL: thumbnailURL, fullSizeURL: fullSizeURL, ratingText: ratingText, releaseDateText: releaseDateText)
}
func presentNewObjects() {
DataManager.shared.fetchNewTmdbObjects(withType: .movie) { (result) in
switch result {
case let .success(parsables):
self.movies = parsables as! [Movie]
case let .failure(error):
print(error)
}
self.view.reloadCollectionData()
}
}
func presentDetail(for indexPath: IndexPath) {
let presentable = presentableInstance(index: indexPath.row) as! PresentableInstance
let vc = DetailViewController()
vc.imageURL = presentable.fullSizeURL
vc.navigationItem.title = presentable.title
view.show(vc)
}
}
// MARK: - CollectionViewConfigurable
extension MovieResultsPresenter: CollectionViewConfigurable {
// MARK: - Properties
// Required
var cellID: String { return "MovieCell" }
var widthDivisor: Double { return 2.0 }
var heightDivisor: Double { return 2.5 }
// Optional
var interItemSpacing: Double? { return 1 }
var lineSpacing: Double? { return 1 }
var bottomInset: Double? { return 49 }
}
| 3a16a0191753c22790e7d00fefc4ee21 | 29.903226 | 166 | 0.646138 | false | false | false | false |
Sage-Bionetworks/MoleMapper | refs/heads/master | MoleMapper/Charts/Classes/Renderers/RadarChartRenderer.swift | bsd-3-clause | 1 | //
// RadarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/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
import UIKit
public class RadarChartRenderer: LineScatterCandleRadarChartRenderer
{
internal weak var _chart: RadarChartView!
public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
_chart = chart
}
public override func drawData(context context: CGContext?)
{
if (_chart !== nil)
{
let radarData = _chart.data
if (radarData != nil)
{
for set in radarData!.dataSets as! [RadarChartDataSet]
{
if (set.isVisible)
{
drawDataSet(context: context, dataSet: set)
}
}
}
}
}
internal func drawDataSet(context context: CGContext?, dataSet: RadarChartDataSet)
{
CGContextSaveGState(context)
let sliceangle = _chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = _chart.factor
let center = _chart.centerOffsets
var entries = dataSet.yVals
let path = CGPathCreateMutable()
var hasMovedToPoint = false
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
let p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value - _chart.chartYMin) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle)
if (p.x.isNaN)
{
continue
}
if (!hasMovedToPoint)
{
CGPathMoveToPoint(path, nil, p.x, p.y)
hasMovedToPoint = true
}
else
{
CGPathAddLineToPoint(path, nil, p.x, p.y)
}
}
CGPathCloseSubpath(path)
// draw filled
if (dataSet.isDrawFilledEnabled)
{
CGContextSetFillColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextSetAlpha(context, dataSet.fillAlpha)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextFillPath(context)
}
// draw the line (only if filled is disabled or alpha is below 255)
if (!dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0)
{
CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor)
CGContextSetLineWidth(context, dataSet.lineWidth)
CGContextSetAlpha(context, 1.0)
CGContextBeginPath(context)
CGContextAddPath(context, path)
CGContextStrokePath(context)
}
CGContextRestoreGState(context)
}
public override func drawValues(context context: CGContext?)
{
if (_chart.data === nil)
{
return
}
let data = _chart.data!
let defaultValueFormatter = _chart.valueFormatter
let sliceangle = _chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = _chart.factor
let center = _chart.centerOffsets
let yoffset = CGFloat(5.0)
for (var i = 0, count = data.dataSetCount; i < count; i++)
{
let dataSet = data.getDataSetByIndex(i) as! RadarChartDataSet
if (!dataSet.isDrawValuesEnabled)
{
continue
}
var entries = dataSet.yVals
for (var j = 0; j < entries.count; j++)
{
let e = entries[j]
let p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle)
let valueFont = dataSet.valueFont
let valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor])
}
}
}
public override func drawExtras(context context: CGContext?)
{
drawWeb(context: context)
}
private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
internal func drawWeb(context context: CGContext?)
{
let sliceangle = _chart.sliceAngle
CGContextSaveGState(context)
// calculate the factor that is needed for transforming the value to
// pixels
let factor = _chart.factor
let rotationangle = _chart.rotationAngle
let center = _chart.centerOffsets
// draw the web lines that come from the center
CGContextSetLineWidth(context, _chart.webLineWidth)
CGContextSetStrokeColorWithColor(context, _chart.webColor.CGColor)
CGContextSetAlpha(context, _chart.webAlpha)
for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++)
{
let p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle)
_webLineSegmentsBuffer[0].x = center.x
_webLineSegmentsBuffer[0].y = center.y
_webLineSegmentsBuffer[1].x = p.x
_webLineSegmentsBuffer[1].y = p.y
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2)
}
// draw the inner-web
CGContextSetLineWidth(context, _chart.innerWebLineWidth)
CGContextSetStrokeColorWithColor(context, _chart.innerWebColor.CGColor)
CGContextSetAlpha(context, _chart.webAlpha)
let labelCount = _chart.yAxis.entryCount
for (var j = 0; j < labelCount; j++)
{
for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++)
{
let r = CGFloat(_chart.yAxis.entries[j] - _chart.chartYMin) * factor
let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle)
let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle)
_webLineSegmentsBuffer[0].x = p1.x
_webLineSegmentsBuffer[0].y = p1.y
_webLineSegmentsBuffer[1].x = p2.x
_webLineSegmentsBuffer[1].y = p2.y
CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint())
public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight])
{
if (_chart.data === nil)
{
return
}
let data = _chart.data as! RadarChartData
CGContextSaveGState(context)
CGContextSetLineWidth(context, data.highlightLineWidth)
if (data.highlightLineDashLengths != nil)
{
CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let sliceangle = _chart.sliceAngle
let factor = _chart.factor
let center = _chart.centerOffsets
for (var i = 0; i < indices.count; i++)
{
let set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! RadarChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor)
// get the index to highlight
let xIndex = indices[i].xIndex
let e = set.entryForXIndex(xIndex)
if (e === nil || e!.xIndex != xIndex)
{
continue
}
let j = set.entryIndex(entry: e!, isEqual: true)
let y = (e!.value - _chart.chartYMin)
if (y.isNaN)
{
continue
}
let p = ChartUtils.getPosition(center: center, dist: CGFloat(y) * factor,
angle: sliceangle * CGFloat(j) + _chart.rotationAngle)
_highlightPtsBuffer[0] = CGPoint(x: p.x, y: 0.0)
_highlightPtsBuffer[1] = CGPoint(x: p.x, y: viewPortHandler.chartHeight)
_highlightPtsBuffer[2] = CGPoint(x: 0.0, y: p.y)
_highlightPtsBuffer[3] = CGPoint(x: viewPortHandler.chartWidth, y: p.y)
// draw the lines
drawHighlightLines(context: context, points: _highlightPtsBuffer,
horizontal: set.isHorizontalHighlightIndicatorEnabled, vertical: set.isVerticalHighlightIndicatorEnabled)
}
CGContextRestoreGState(context)
}
} | 29a549e8e8fb6caa6f6f7f64049200cf | 33.083893 | 273 | 0.551497 | false | false | false | false |
rcspring/RCSTextField | refs/heads/master | RCSTextField/TextField/RCSTextField.swift | mit | 1 | //
// RCSTextField.swift
// unitTextField
//
// Created by Ryan Spring on 4/5/17.
// Copyright © 2017 Ryan Spring. All rights reserved.
//
import UIKit
import SnapKit
public enum RCSTextFieldValue {
case measurment(Measurement<Unit>)
case quantity(Double)
case text(String)
case nothing
}
public protocol RCSTextFieldDelegate: AnyObject {
func fieldDidComplete(field: RCSTextField)
func fieldValueDidChange(field: RCSTextField)
}
public extension RCSTextFieldDelegate {
func fieldDidComplete(field: RCSTextField) {}
func fieldValueDidChange(field: RCSTextField) {}
}
public class RCSTextField: UITextField, UITextFieldDelegate {
public internal(set) var value: RCSTextFieldValue = .text("")
@IBInspectable public var dismissButtonText: String = "DISMISS_DEFAULT_BUTTON".localized
@IBInspectable public var dismissButtonColor: UIColor = UIColor.blue
@IBOutlet public var valueDelegate: AnyObject? {
get {
return shadowDelegate
}
set {
if let delegateValue = newValue {
shadowDelegate = delegateValue as? RCSTextFieldDelegate
} else {
shadowDelegate = nil
}
}
}
weak var shadowDelegate: RCSTextFieldDelegate?
static let nForm = NumberFormatter()
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public override var delegate: UITextFieldDelegate? {
get {
return nil
}
set {}
}
override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
switch action {
case #selector(UIResponderStandardEditActions.cut(_:)):
return false
case #selector(UIResponderStandardEditActions.paste(_:)):
return false
default:
return super.canPerformAction(action, withSender: sender)
}
}
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
let confirmationView = dismissButton()
super.inputAccessoryView = confirmationView
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
guard let textL = text else {
return true
}
let newString = (textL as NSString).replacingCharacters(in: range, with: string)
value = .text(newString)
shadowDelegate?.fieldValueDidChange(field: self)
return true
}
public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
shadowDelegate?.fieldDidComplete(field: self)
}
// MARK: Private Methods
private func dismissButton() -> UIView {
let button = UIButton()
button.setTitle(dismissButtonText, for: .normal)
button.addTarget(self, action: #selector(RCSQuantityTextField.buttonPushed(_:)), for: .touchUpInside)
button.frame = CGRect(x: 0, y: 0, width: self.window!.bounds.width, height: 50)
button.backgroundColor = dismissButtonColor
let view = UIView()
view.bounds = CGRect(x: 0, y: 0, width: self.window!.bounds.width, height: 50)
view.addSubview(button)
button.snp.makeConstraints { make in
make.left.equalTo(view)
make.right.equalTo(view)
make.top.equalTo(view)
make.bottom.equalTo(view)
}
return view
}
private func setup() {
super.textAlignment = .left
super.delegate = self
}
@objc private func buttonPushed(_ sender: Any) {
self.resignFirstResponder()
}
}
| 6d6e70831d3ef82338819781f7368dea | 27.733333 | 109 | 0.640113 | false | false | false | false |
JudoPay/JudoKitObjC | refs/heads/master | JudoKitObjCExampleAppUITests/JudoKitUIDedupTests.swift | mit | 1 | //
// JudoKitUIDedupTests.swift
// JudoKitSwiftExample
//
// Copyright (c) 2016 Alternative Payments Ltd
//
// 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
class JudoKitUIDedupTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSuccessfulDedupPayment() {
let app = XCUIApplication()
app.tables.staticTexts["with default settings"].tap()
let elementsQuery = app.scrollViews.otherElements
elementsQuery.secureTextFields["Card number"].typeText("4976000000003436")
let expiryDateTextField = elementsQuery.textFields["Expiry date"]
expiryDateTextField.typeText("1220")
let cvv2TextField = elementsQuery.secureTextFields["CVV2"]
cvv2TextField.typeText("452")
app.buttons.matching(identifier: "Pay").element(boundBy: 1).tap()
let button = app.buttons["Home"]
let existsPredicate = NSPredicate(format: "exists == 1")
expectation(for: existsPredicate, evaluatedWith: button, handler: nil)
waitForExpectations(timeout: kTestCaseTimeout, handler: nil)
button.tap()
app.tables.staticTexts["with default settings"].tap()
let elementsQuery2 = app.scrollViews.otherElements
elementsQuery2.secureTextFields["Card number"].typeText("4976000000003436")
let expiryDateTextField2 = elementsQuery.textFields["Expiry date"]
expiryDateTextField2.typeText("1220")
let cvv2TextField2 = elementsQuery.secureTextFields["CVV2"]
cvv2TextField2.typeText("452")
app.buttons.matching(identifier: "Pay").element(boundBy: 1).tap()
let button2 = app.buttons["Home"]
let existsPredicate2 = NSPredicate(format: "exists == 1")
expectation(for: existsPredicate2, evaluatedWith: button2, handler: nil)
waitForExpectations(timeout: kTestCaseTimeout, handler: nil)
button2.tap()
}
}
| 6f19b5b3b0ec1555f1c2ac476faddda0 | 41.725275 | 182 | 0.681327 | false | true | false | false |
alblue/swift | refs/heads/master | test/SILGen/external_definitions.swift | apache-2.0 | 2 | // RUN: %target-swift-emit-silgen -sdk %S/Inputs %s -enable-sil-ownership -enable-objc-interop | %FileCheck %s
import ansible
var a = NSAnse(Ansible(bellsOn: NSObject()))
var anse = NSAnse
hasNoPrototype()
// CHECK-LABEL: sil @main
// -- Foreign function is referenced with C calling conv and ownership semantics
// CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @$sSo8NSObjectC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @$sSo7AnsibleC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]]
// CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
// CHECK: destroy_value [[ANSIBLE]] : $Optional<Ansible>
// -- Referencing unapplied C function goes through a thunk
// CHECK: [[NSANSE:%.*]] = function_ref @$sSo6NSAnseySo7AnsibleCSgADFTO : $@convention(thin) (@guaranteed Optional<Ansible>) -> @owned Optional<Ansible>
// -- Referencing unprototyped C function passes no parameters
// CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
// CHECK: apply [[NOPROTO]]()
// -- Constructors for imported NSObject
// CHECK-LABEL: sil shared [serializable] @$sSo8NSObjectC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick NSObject.Type) -> @owned NSObject
// -- Constructors for imported Ansible
// CHECK-LABEL: sil shared [serializable] @$sSo7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Optional<Any>, @thick Ansible.Type) -> @owned Optional<Ansible>
// -- Native Swift thunk for NSAnse
// CHECK: sil shared [serializable] [thunk] @$sSo6NSAnseySo7AnsibleCSgADFTO : $@convention(thin) (@guaranteed Optional<Ansible>) -> @owned Optional<Ansible> {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Optional<Ansible>):
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[ARG0]]
// CHECK: [[FUNC:%.*]] = function_ref @NSAnse : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: [[RESULT:%.*]] = apply [[FUNC]]([[ARG0_COPY]]) : $@convention(c) (Optional<Ansible>) -> @autoreleased Optional<Ansible>
// CHECK: destroy_value [[ARG0_COPY]] : $Optional<Ansible>
// CHECK: return [[RESULT]] : $Optional<Ansible>
// CHECK: }
// -- Constructor for imported Ansible was unused, should not be emitted.
// CHECK-NOT: sil {{.*}} @$sSo7AnsibleC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick Ansible.Type) -> @owned Ansible
| 0bb238a4ae671ef33055b710bb71f7d7 | 57.697674 | 167 | 0.665214 | false | false | false | false |
kunass2/BSSelectableView | refs/heads/master | SelectableView/Classes/SelectableView.swift | mit | 2 | //
// SelectableView.swift
// SelectableView
//
// Created by Bartłomiej Semańczyk on 06/22/2016.
// Copyright (c) 2016 Bartłomiej Semańczyk. All rights reserved.
//
open class SelectableOption: NSObject {
open var index: Int
open var identifier: String
open var title: String
open var userInfo: [AnyHashable: Any]?
open var descendantOptions = [SelectableOption]()
public init(index: Int, title: String, identifier: String, userInfo: [AnyHashable: Any]? = nil) {
self.index = index
self.identifier = identifier
self.title = title
self.userInfo = userInfo
}
}
@objc public protocol SelectableViewDelegate {
@objc optional func multiSelectableView(_ view: MultiSelectableView, tokenViewFor option: SelectableOption) -> UIView
@objc optional func singleSelectableView(_ view: SingleSelectableView, didSelect option: SelectableOption)
@objc optional func multiSelectableView(_ view: MultiSelectableView, didSelect option: SelectableOption)
@objc optional func searchSelectableView(_ view: SearchSelectableView, didSelect option: SelectableOption)
@objc optional func selectableViewDidToggleOptions(with button: UIButton, expanded: Bool)
}
let SelectableTableViewCellIdentifier = "SelectableTableViewCellIdentifier"
@IBDesignable open class SelectableView: UIView {
var fontForOption = UIFont.systemFont(ofSize: 16)
var fontForPlaceholderText = UIFont.systemFont(ofSize: 14)
@IBInspectable open var leftPaddingForPlaceholderText: Int = 0
@IBInspectable open var leftPaddingForOption: Int = 20
@IBInspectable open var heightForOption: Int = 40
@IBInspectable open var titleColorForSelectedOption: UIColor = UIColor.green
@IBInspectable open var titleColorForOption: UIColor = UIColor.black
@IBInspectable open var textColorForPlaceholderText: UIColor = UIColor.gray
@IBInspectable open var tintColorForSelectedOption: UIColor = UIColor.blue
@IBInspectable open var identifier: String = ""
@IBInspectable open var tableViewAccessibilityIdentifier: String = ""
@IBInspectable open var maxNumberOfRows: Int = 6
@IBInspectable open var placeholder: String = "" {
didSet {
(self as? MultiSelectableView)?.verticalTokenView?.setupPlaceholderLabel()
(self as? MultiSelectableView)?.horizontalTokenView?.setupPlaceholderLabel()
(self as? SingleSelectableView)?.setupLabel()
}
}
@IBInspectable open var cornerRadius: CGFloat = 3 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = true
}
}
@IBInspectable open var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable open var borderColor: UIColor = UIColor.clear {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBOutlet open var switchButton: UIButton?
@IBOutlet open var contentOptionsHeightConstraint: NSLayoutConstraint?
@IBOutlet open var contentOptionsView: UIView?
weak open var delegate: SelectableViewDelegate?
open var options = [SelectableOption]() {
didSet {
tableView.reloadData()
updateContentOptionsHeight(for: sortedOptions)
}
}
var sortedOptions: [SelectableOption] {
return options.sorted { $0.index < $1.index }
}
var tableView = UITableView()
var expanded = false {
didSet {
if let switchButton = switchButton {
delegate?.selectableViewDidToggleOptions?(with: switchButton, expanded: expanded)
}
}
}
//MARK: - Class Methods
//MARK: - Initialization
open override func awakeFromNib() {
super.awakeFromNib()
switchButton?.addTarget(self, action: #selector(switchButtonTapped), for: .touchUpInside)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.bounces = false
tableView.rowHeight = 40
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
tableView.accessibilityIdentifier = tableViewAccessibilityIdentifier
let nib = UINib(nibName: "SelectableTableViewCell", bundle: Bundle(for: SelectableTableViewCell.classForCoder()))
tableView.register(nib, forCellReuseIdentifier: SelectableTableViewCellIdentifier)
if let contentOptionsView = contentOptionsView {
contentOptionsView.addSubview(tableView)
let topConstraint = NSLayoutConstraint(item: tableView, attribute: .top, relatedBy: .equal, toItem: contentOptionsView, attribute: .top, multiplier: 1, constant: 0)
let trailingConstraint = NSLayoutConstraint(item: tableView, attribute: .trailing, relatedBy: .equal, toItem: contentOptionsView, attribute: .trailing, multiplier: 1, constant: 0)
let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .bottom, relatedBy: .equal, toItem: contentOptionsView, attribute: .bottom, multiplier: 1, constant: 0)
let leadingConstraint = NSLayoutConstraint(item: tableView, attribute: .leading, relatedBy: .equal, toItem: contentOptionsView, attribute: .leading, multiplier: 1, constant: 0)
contentOptionsView.addConstraints([topConstraint, trailingConstraint, bottomConstraint, leadingConstraint])
contentOptionsView.layoutIfNeeded()
}
(self as? MultiSelectableView)?.verticalTokenView?.reloadData()
(self as? MultiSelectableView)?.horizontalTokenView?.reloadData()
(self as? SingleSelectableView)?.setupLabel()
}
//MARK: - Deinitialization
//MARK: - Actions
//MARK: - Open
open func hideOptions() {
expanded = false
}
open func showOptions() {
expanded = true
}
//MARK: - Internal
@objc func switchButtonTapped(_ sender: UIButton) {
expanded = !expanded
}
func updateContentOptionsHeight(for options: [SelectableOption]) {
contentOptionsHeightConstraint?.constant = expanded ? CGFloat(min((options.count) * heightForOption, maxNumberOfRows * heightForOption)) : 0
}
//MARK: - Private
//MARK: - Overridden
}
| a0cc9d00e06c66f72f215661b2456ea8 | 35.060109 | 191 | 0.666465 | false | false | false | false |
Neft-io/neft | refs/heads/master | packages/neft-runtime-ios/Neft/Screen.swift | apache-2.0 | 1 | import UIKit
class Screen {
var rect: CGRect
class func register(){
App.getApp().client.onAction(.setScreenStatusBarColor) {
(reader: Reader) in
let val = reader.getString()
if val == "Light" {
UIApplication.shared.statusBarStyle = .lightContent
} else {
UIApplication.shared.statusBarStyle = .default
}
}
}
init() {
let app = App.getApp()
// SCREEN_SIZE
let mainScreen = UIScreen.main
let size = mainScreen.bounds
self.rect = size
app.client.pushAction(.screenSize, size.width, size.height)
// SCREEN_STATUSBAR_HEIGHT
let statusBarHeight = UIApplication.shared.statusBarFrame.height
app.client.pushAction(.screenStatusBarHeight, statusBarHeight)
// SCREEN_NAVIGATIONBAR_HEIGHT
if #available(iOS 11.0, *) {
let navigationBarHeight = UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0
app.client.pushAction(.screenNavigationBarHeight, navigationBarHeight)
}
}
}
| b4c8cda7967590ae6f0ff9ce9ac8a453 | 28.789474 | 104 | 0.603357 | false | false | false | false |
hirooka/chukasa-ios | refs/heads/master | chukasa-ios/src/model/database/ChukasaCoreDataOperator.swift | mit | 1 | import UIKit
import CoreData
@objc
protocol ChukasaCoreDataOperatorDelegate {
@objc optional func completeCreatingChukasaServerDestination()
@objc optional func completeUpdatingChukasaServerDestination()
@objc optional func completeCreatingChukasaPreferences()
@objc optional func completeUpdatingChukasaPreferences()
}
class ChukasaCoreDataOperator: NSObject {
var delegate: ChukasaCoreDataOperatorDelegate?
func fetch (_ entity: String, key: String, ascending: Bool) -> NSArray {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entity(forEntityName: entity, in: managedObjectContext)
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
fetchRequest.entity = entityDescription
let sortDescriptor: NSSortDescriptor = NSSortDescriptor(key: key, ascending: ascending)
let sortDescriptorArray: NSArray = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptorArray as? [NSSortDescriptor]
do {
let array = try managedObjectContext.fetch(fetchRequest)
return array as NSArray
} catch {
return NSArray()
}
}
func createChukasaServerDestination(_ chukasaServerDestination: ChukasaServerDestination){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
childManagedObjectContext.parent = managedObjectContext
childManagedObjectContext.perform { () -> Void in
let managedObject = NSEntityDescription.insertNewObject(forEntityName: "ChukasaServerDestination", into: childManagedObjectContext)
managedObject.setValue(0, forKey: "id")
managedObject.setValue(chukasaServerDestination.scheme.rawValue, forKey: "scheme")
managedObject.setValue(chukasaServerDestination.host, forKey: "host")
managedObject.setValue(chukasaServerDestination.port, forKey: "port")
managedObject.setValue(chukasaServerDestination.username, forKey: "username")
managedObject.setValue(chukasaServerDestination.password, forKey: "password")
do {
try childManagedObjectContext.save()
} catch {
//
}
managedObjectContext.perform({ () -> Void in
do {
try managedObjectContext.save()
self.delegate?.completeCreatingChukasaServerDestination!()
} catch {
//
}
})
}
}
func updateChukasaServerDestination(_ id: Int, chukasaServerDestination: ChukasaServerDestination){
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let predicateBoard = NSPredicate(format: "(id == %ld)", id)
let fetchRequestBoard: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "ChukasaServerDestination")
fetchRequestBoard.predicate = predicateBoard
do {
let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
childManagedObjectContext.parent = managedObjectContext
let chukasaServerDestinationArray = try childManagedObjectContext.fetch(fetchRequestBoard)
childManagedObjectContext.perform { () -> Void in
let updatedChukasaServerDestination = chukasaServerDestinationArray[0] as! NSManagedObject
updatedChukasaServerDestination.setValue(chukasaServerDestination.scheme.rawValue, forKey: "scheme")
updatedChukasaServerDestination.setValue(chukasaServerDestination.host, forKey: "host")
updatedChukasaServerDestination.setValue(chukasaServerDestination.port, forKey: "port")
updatedChukasaServerDestination.setValue(chukasaServerDestination.username, forKey: "username")
updatedChukasaServerDestination.setValue(chukasaServerDestination.password, forKey: "password")
do {
try childManagedObjectContext.save()
} catch {
//
}
managedObjectContext.perform({ () -> Void in
do {
try managedObjectContext.save()
self.delegate?.completeUpdatingChukasaServerDestination!()
} catch {
//
}
})
}
} catch {
}
}
func createChukasaPreferences(_ chukasaPreferences: ChukasaPreferences) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
childManagedObjectContext.parent = managedObjectContext
childManagedObjectContext.perform { () -> Void in
let managedObject = NSEntityDescription.insertNewObject(forEntityName: "ChukasaPreferences", into: childManagedObjectContext)
managedObject.setValue(0, forKey: "id")
managedObject.setValue(chukasaPreferences.canEncrypt, forKey: "canEncrypt")
managedObject.setValue(chukasaPreferences.transcodingSettings.rawValue, forKey: "transcodingSettings")
do {
try childManagedObjectContext.save()
} catch {
//
}
managedObjectContext.perform({ () -> Void in
do {
try managedObjectContext.save()
self.delegate?.completeCreatingChukasaPreferences!()
} catch {
//
}
})
}
}
func updateChukasaPreferences(_ id: Int, chukasaPreferences: ChukasaPreferences) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext
let predicateBoard = NSPredicate(format: "(id == %ld)", id)
let fetchRequestBoard:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "ChukasaPreferences")
fetchRequestBoard.predicate = predicateBoard
do {
let childManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
childManagedObjectContext.parent = managedObjectContext
let chukasaPreferencesArray = try childManagedObjectContext.fetch(fetchRequestBoard)
childManagedObjectContext.perform { () -> Void in
let updatedChukasaPreferences = chukasaPreferencesArray[0] as! NSManagedObject
updatedChukasaPreferences.setValue(chukasaPreferences.canEncrypt, forKey: "canEncrypt")
updatedChukasaPreferences.setValue(chukasaPreferences.transcodingSettings.rawValue, forKey: "transcodingSettings")
do {
try childManagedObjectContext.save()
} catch {
//
}
managedObjectContext.perform({ () -> Void in
do {
try managedObjectContext.save()
self.delegate?.completeUpdatingChukasaPreferences!()
} catch {
//
}
})
}
} catch {
}
}
}
| 2406a453ef6efdb3846a503312880cef | 42.379487 | 150 | 0.618513 | false | false | false | false |
vinivendra/jokr | refs/heads/master | jokr/Helpers/Shell.swift | apache-2.0 | 1 | import Foundation
enum Shell {
struct CommandResult {
let output: String
let error: String
let status: Int32
}
@discardableResult
static func runEnvCommand(_ command: String) -> CommandResult {
let outputPipe = Pipe()
let errorPipe = Pipe()
let arguments = command.components(separatedBy: " ")
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = arguments
task.standardOutput = outputPipe
task.standardError = errorPipe
task.launch()
task.waitUntilExit()
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let outputString = String(data: outputData, encoding: .utf8) ?? ""
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
let errorString = String(data: errorData, encoding: .utf8) ?? ""
return CommandResult(output: outputString,
error: errorString,
status: task.terminationStatus)
}
@discardableResult
static func runCommand(_ command: String) -> CommandResult {
let outputPipe = Pipe()
let errorPipe = Pipe()
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
task.standardOutput = outputPipe
task.standardError = errorPipe
task.launch()
task.waitUntilExit()
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let outputString = String(data: outputData, encoding: .utf8) ?? ""
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
let errorString = String(data: errorData, encoding: .utf8) ?? ""
return CommandResult(output: outputString,
error: errorString,
status: task.terminationStatus)
}
@discardableResult
static func runBinary(_ path: String) -> CommandResult {
let outputPipe = Pipe()
let errorPipe = Pipe()
let task = Process()
task.launchPath = path
task.standardOutput = outputPipe
task.standardError = errorPipe
task.launch()
task.waitUntilExit()
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
let outputString = String(data: outputData, encoding: .utf8) ?? ""
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
let errorString = String(data: errorData, encoding: .utf8) ?? ""
return CommandResult(output: outputString,
error: errorString,
status: task.terminationStatus)
}
}
| 9a4b3cdc762e97a6cb834bb6c2f398ee | 29.910256 | 72 | 0.699295 | false | false | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00258-swift-constraints-constraintsystem-resolveoverload.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
import Foundation
class A {
class func a() -> String {
return ""
}
class func b() {
struct c {
static let d: String = {
return self }
}
func b(c) -> <d>(() -> d) {
}
struct d<f(b: c) {
self.b = b
}
}
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
import Foundation
extension NSSet {
convenience init<T>(array: Array<T>) {
self.init()
}
}
| cc092bc64b4beb79ade56b2d19be7f26 | 22.694444 | 79 | 0.600234 | false | false | false | false |
nodes-ios/NStack | refs/heads/master | NStackSDK/NStackSDK/Classes/Logger/Logger.swift | mit | 1 | //
// Logger.swift
// NStackSDK
//
// Created by Dominik Hádl on 02/12/2016.
// Copyright © 2016 Nodes ApS. All rights reserved.
//
import Foundation
protocol LoggerType: class {
var logLevel: LogLevel { get set }
var customName: String? { get set }
var detailedOutput: Bool { get set }
func writeLogEntry(_ items: [String], level: LogLevel,
file: StaticString, line: Int, function: StaticString)
}
extension LoggerType {
func log(_ items: CustomStringConvertible...,
level: LogLevel,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: level,
file: file, line: line, function: function)
}
func logVerbose(_ items: CustomStringConvertible...,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: .verbose,
file: file, line: line, function: function)
}
func logWarning(_ items: CustomStringConvertible...,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: .warning,
file: file, line: line, function: function)
}
func logError(_ items: CustomStringConvertible...,
file: StaticString = #file,
line: Int = #line,
function: StaticString = #function) {
writeLogEntry(items.map({ $0.description }), level: .error,
file: file, line: line, function: function)
}
}
class ConsoleLogger: LoggerType {
var logLevel: LogLevel = .error
var customName: String?
var detailedOutput: Bool = false
func writeLogEntry(_ items: [String],
level: LogLevel,
file: StaticString,
line: Int,
function: StaticString) {
guard level >= logLevel, logLevel != .none else { return }
let filename = file.description.components(separatedBy: "/").last ?? "N/A"
let message = items.joined(separator: " ")
if detailedOutput {
print("[NStackSDK\(customName ?? "")] \(level.message) \(filename):\(line) – \(function) – \(message)")
} else {
print("[NStackSDK\(customName ?? "")] \(level.message) \(message)")
}
}
}
| 2ba4d83738ed3ff3d432b0eb80ab777b | 31.641026 | 115 | 0.569128 | false | false | false | false |
DrabWeb/Komikan | refs/heads/master | Komikan/Komikan/KMReaderViewController.swift | gpl-3.0 | 1 | //
// KMReaderViewController.swift
// Komikan
//
// Created by Seth on 2015-12-31.
// Copyright © 2015 DrabWeb. All rights reserved.
//
import Cocoa
import Quartz
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
class KMReaderViewController: NSViewController, NSWindowDelegate {
// The main window for the reader
var readerWindow : NSWindow = NSWindow();
/// The text field for the windows title that lets us have a white title color
@IBOutlet weak var readerWindowTitleTextField: NSTextField!
/// The view that both encapsulates the reader image views and lets you zoom in/out
@IBOutlet weak var readerImageScrollView: KMReaderScrollView!
/// The magnification gesture recognizer for zooming in and out using the Trackpad
@IBOutlet var readerMagnificationGestureRecognizer: NSMagnificationGestureRecognizer!
// The image view for the reader window
@IBOutlet weak var readerImageView: NSImageView!
// The stack view for dual page mode
@IBOutlet weak var dualPageStackView: NSStackView!
// The left page image view for dual page mode
@IBOutlet weak var leftPageReaderImageView: NSImageView!
// The right page image view for dual page mode
@IBOutlet weak var rightPageReaderImageView: NSImageView!
// The visual effect view for the reader windows titlebar
@IBOutlet weak var titlebarVisualEffectView: NSVisualEffectView!
// The view that encloses the reader panel and makes it round
@IBOutlet weak var readerPanelCornerRounding: KMReaderPanelView!
// The visual effect for the reader panel
@IBOutlet weak var readerPanelVisualEffectView: NSVisualEffectView!
// The visual effect view for the reader controls panel(Color, sharpness ETC.)
@IBOutlet weak var readerControlsPanelVisualEffectView: NSVisualEffectView!
/// The save button in the reader control panel
@IBOutlet weak var readerControlPanelSaveButton: NSButton!
// When we press the save button in the reader control panel...
@IBAction func readerControlPanelSaveButtonPressed(_ sender: AnyObject) {
// Say the controls panel is closed
readerControlsOpen = false;
// Close the controls panel
closeControlsPanel();
// Apply the new filter values to all pages(In a new thread so we dont get lots of beachballing for long manga)
Thread.detachNewThreadSelector(#selector(KMReaderViewController.updateFiltersForAllPages), toTarget: self, with: nil);
}
/// The reset button in the reader control panel
@IBOutlet weak var readerControlPanelResetButton: NSButton!
// When we press the reset button in the reader control panel...
@IBAction func readerControlPanelResetButtonPressed(_ sender: AnyObject) {
// Reset the values to default(In a new thread so we dont beachball in long manga)
Thread.detachNewThreadSelector(#selector(KMReaderViewController.resetCGValues), toTarget: self, with: nil);
}
// The slider in the control panel that controls the readers saturation
@IBOutlet weak var readerControlPanelSaturationSlider : NSSlider!
// When we interact with readerControlPanelSaturationSlider...
@IBAction func readerControlPanelSaturationSliderInteracted(_ sender: AnyObject) {
// Print to the log what value we are changing it to
print("KMReaderViewController: Changing saturation to " + String(readerControlPanelSaturationSlider.floatValue));
// Set the represented value to the represented sliders value
manga.saturation = CGFloat(readerControlPanelSaturationSlider.floatValue);
// Apply the filters to the current page
updateFiltersForCurrentPage();
}
// The slider in the control panel that controls the readers brightness
@IBOutlet weak var readerControlPanelBrightnessSlider : NSSlider!
// When we interact with readerControlPanelBrightnessSlider...
@IBAction func readerControlPanelBrightnessSliderInteracted(_ sender: AnyObject) {
// Print to the log what value we are changing it to
print("KMReaderViewController: Changing brightness to " + String(readerControlPanelBrightnessSlider.floatValue));
// Set the represented value to the represented sliders value
manga.brightness = CGFloat(readerControlPanelBrightnessSlider.floatValue);
// Apply the filters to the current page
updateFiltersForCurrentPage();
}
// The slider in the control panel that controls the readers contrast
@IBOutlet weak var readerControlPanelContrastSlider : NSSlider!
// When we interact with readerControlPanelContrastSlider...
@IBAction func readerControlPanelContrastSliderInteracted(_ sender: AnyObject) {
// Print to the log what value we are changing it to
print("KMReaderViewController: Changing contrast to " + String(readerControlPanelContrastSlider.floatValue));
// Set the represented value to the represented sliders value
manga.contrast = CGFloat(readerControlPanelContrastSlider.floatValue);
// Apply the filters to the current page
updateFiltersForCurrentPage();
}
// The slider in the control panel that controls the readers sharpness
@IBOutlet weak var readerControlPanelSharpnessSlider : NSSlider!
// When we interact with readerControlPanelSharpnessSlider...
@IBAction func readerControlPanelSharpnessSliderInteracted(_ sender: AnyObject) {
// Print to the log what value we are changing it to
print("KMReaderViewController: Changing sharpness to " + String(readerControlPanelSharpnessSlider.floatValue));
// Set the represented value to the represented sliders value
manga.sharpness = CGFloat(readerControlPanelSharpnessSlider.floatValue);
// Apply the filters to the current page
updateFiltersForCurrentPage();
}
// The button on the reader panel that lets you jump to a page
@IBOutlet weak var readerPageJumpButton: NSButton!
// When readerPageJumpButton is pressed...
@IBAction func readerPageJumpButtonPressed(_ sender: AnyObject) {
// Prompt the user to jump to a page
promptToJumpToPage();
}
/// The controller for the reader page jump view
@IBOutlet var readerPageJumpController: KMReaderPageJumpController!
// The label on the reader panel that shows what page you are on and how many pages there are
@IBOutlet weak var readerPageNumberLabel: NSTextField!
// The button on the reader panel that lets you bookmark the current page
@IBOutlet weak var readerBookmarkButton: NSButton!
// When readerBookmarkButton is pressed...
@IBAction func readerBookmarkButtonPressed(_ sender: AnyObject) {
// Bookmark the current page
bookmarkCurrentPage();
}
// Do we have the reader controls open?
var readerControlsOpen : Bool = false;
// The button on the reader panel that brings you to the settings for the reader with color controls among other things
@IBOutlet weak var readerSettingsButton: NSButton!
// When readerSettingsButton is pressed...
@IBAction func readerSettingsButtonPressed(_ sender: AnyObject) {
// Disabled for now, need to find out how to apply filters directly to an NSImage
// Say that the controls panel is open
readerControlsOpen = true;
// Open the controls panel
openControlsPanel();
}
/// The visual effect view for the background of the thumbnail page jump view
@IBOutlet weak var thumbnailPageJumpVisualEffectView: NSVisualEffectView!
// The manga we have open
var manga : KMManga = KMManga();
// The original pages for the manga
var mangaOriginalPages : [NSImage] = [NSImage()];
// Are we wanting to read in dual page mode?
var dualPage : Bool = false;
// The direction we are reading(Default Right to Left)
var dualPageDirection : KMDualPageDirection = KMDualPageDirection.rightToLeft;
// Are we fullscreen?
var isFullscreen : Bool = false;
/// Is the window in the process of closing?
var closingView : Bool = false;
// The NSTimer to handle the mouse hovering when we arent in fullscreen
var mouseHoverHandlingTimer : Timer = Timer();
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
// Style the window
styleWindow();
// Set the reader scroll views reader view controller
readerImageScrollView.readerViewController = self;
// Setup the page jump view
readerPageJumpController.setup();
// Add the magnification gesture recogniser to the reader scroll view
readerImageScrollView.addGestureRecognizer(readerMagnificationGestureRecognizer);
// Start the 0.1 second loop for the mouse hovering
mouseHoverHandlingTimer = Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(KMReaderViewController.mouseHoverHandling), userInfo: nil, repeats: true);
// Subscribe to the preferences saved notification
NotificationCenter.default.addObserver(self, selector: #selector(KMReaderViewController.reloadPreferences), name:NSNotification.Name(rawValue: "Application.PreferencesSaved"), object: nil);
// Show the reader panel and hide the controls panel
hideControlsPanelShowReaderPanel();
}
func openManga(_ openingManga : KMManga, page : Int) {
// Set the readers manga to the manga we want to open
manga = openingManga;
// Print to the log what we are opening
print("KMReaderViewController: Opening \"" + manga.title + "\"");
// Set the windows title to match the mangas name
readerWindow.title = manga.title;
// Extract the archive and get the info from it
manga.extractToTmpFolder();
// Set mangaOriginalPages to the manga's current pages
mangaOriginalPages = manga.pages;
// Load the saturation values
readerControlPanelSaturationSlider.floatValue = Float(manga.saturation);
// Load the brightness values
readerControlPanelBrightnessSlider.floatValue = Float(manga.brightness);
// Load the contrast values
readerControlPanelContrastSlider.floatValue = Float(manga.contrast);
// Load the sharpness values
readerControlPanelSharpnessSlider.floatValue = Float(manga.sharpness);
// If the color/sharpness filters are non-default...
if(manga.saturation != 1 || manga.brightness != 0 || manga.contrast != 1 || manga.sharpness != 0) {
// Apply the new filter values to all pages
updateFiltersForAllPages();
}
// Jump to the page we said to start at
jumpToPage(page, round: false);
// Resize the window to match the mangas size
fitWindowToManga();
// Center the window
readerWindow.center();
// Setup the menubar items actions
(NSApplication.shared().delegate as? AppDelegate)?.nextPageMenubarItem.action = #selector(KMReaderViewController.nextPage);
(NSApplication.shared().delegate as? AppDelegate)?.previousPageMenubarItem.action = #selector(KMReaderViewController.previousPage);
(NSApplication.shared().delegate as? AppDelegate)?.jumpToPageMenuItem.action = #selector(KMReaderViewController.promptToJumpToPage);
(NSApplication.shared().delegate as? AppDelegate)?.bookmarkCurrentPageMenuItem.action = #selector(KMReaderViewController.bookmarkCurrentPage);
(NSApplication.shared().delegate as? AppDelegate)?.dualPageMenuItem.action = #selector(KMReaderViewController.toggleDualPage);
(NSApplication.shared().delegate as? AppDelegate)?.fitWindowToPageMenuItem.action = #selector(KMReaderViewController.fitWindowToManga);
(NSApplication.shared().delegate as? AppDelegate)?.switchDualPageDirectionMenuItem.action = #selector(KMReaderViewController.switchDualPageDirection);
(NSApplication.shared().delegate as? AppDelegate)?.readerZoomInMenuItem.action = #selector(KMReaderViewController.magnifyIn);
(NSApplication.shared().delegate as? AppDelegate)?.readerZoomOutMenuItem.action = #selector(KMReaderViewController.magnifyOut);
(NSApplication.shared().delegate as? AppDelegate)?.readerResetZoomMenuItem.action = #selector(KMReaderViewController.resetMagnification);
(NSApplication.shared().delegate as? AppDelegate)?.readerOpenNotesMenuItem.action = #selector(KMReaderViewController.openNotesWindow);
(NSApplication.shared().delegate as? AppDelegate)?.readerRotateNinetyDegressLeftMenuItem.action = #selector(KMReaderViewController.rotateLeftNinetyDegrees);
(NSApplication.shared().delegate as? AppDelegate)?.readerRotateNinetyDegressRightMenuItem.action = #selector(KMReaderViewController.rotateRightNinetyDegrees);
(NSApplication.shared().delegate as? AppDelegate)?.readerResetRotationMenuItem.action = #selector(KMReaderViewController.resetRotation);
}
/// The window controller for the notes window
var notesWindowController : NSWindowController?;
/// The view controller for the notes window
var notesViewController : KMReaderNotesViewController = KMReaderNotesViewController();
/// Opens the window that lets the user edit/view the notes for this manga
func openNotesWindow() {
// If the window isnt loaded...
if(notesWindowController == nil) {
// Load the notes window controller
notesWindowController = (storyboard?.instantiateController(withIdentifier: "readerNotesWindowController") as! NSWindowController);
// Set the notes view controller to the windows view controller
notesViewController = (notesWindowController!.contentViewController as! KMReaderNotesViewController);
// Load the window into the notes view controller
notesViewController.notesWindow = notesWindowController!.window!;
// Set the notes view controller's manga
notesViewController.manga = self.manga;
}
// Load the notes window
notesWindowController!.loadWindow();
// Set the notes window to be full size
notesWindowController!.window!.styleMask.insert(NSFullSizeContentViewWindowMask);
// Hide the edit bar in the notes window
notesViewController.hideEditingBar();
// Scroll up
notesViewController.notesScrollView.pageUp(self);
// Load the notes window title
notesViewController.setWindowTitle();
// Set the notes window's delegate to the notes view controller
notesWindowController!.window!.delegate = notesViewController;
// Load the notes
notesViewController.loadNotes();
// Show the notes window
notesWindowController!.showWindow(self);
}
/// Reloads the values needed from the preferences
func reloadPreferences() {
// Set the window background color
readerWindow.backgroundColor = (NSApplication.shared().delegate as! AppDelegate).preferences.readerWindowBackgroundColor;
}
/// Resets the zoom amount
func resetMagnification() {
// Reset the reader scroll views magnification to 1
readerImageScrollView.animator().magnification = 1;
}
/// Zooms in by 10%
func magnifyIn() {
// Add 0.25 to the reader scroll views magnification
readerImageScrollView.magnification += 0.25;
}
/// Zooms out by 10%
func magnifyOut() {
// Substract 0.25 from the reader scroll views magnification
readerImageScrollView.magnification -= 0.25;
}
/// Rotates the manga left by 90 degress
func rotateLeftNinetyDegrees() {
// Rotate the pages left 90 degress
readerImageView.frameCenterRotation += 90;
dualPageStackView.frameCenterRotation += 90;
}
/// Rotates the manga right by 90 degress
func rotateRightNinetyDegrees() {
// Rotate the pages right 90 degress
readerImageView.frameCenterRotation -= 90;
dualPageStackView.frameCenterRotation -= 90;
}
/// Resets the rotation of the manga
func resetRotation() {
// Reset the rotation on the pages
readerImageView.frameCenterRotation = 0;
dualPageStackView.frameCenterRotation = 0;
}
func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize {
// Temporary fix for the image view dissapearing when rotated and the window resizes
readerImageView.frameCenterRotation = 0;
dualPageStackView.frameCenterRotation = 0;
return frameSize;
}
override func mouseUp(with theEvent: NSEvent) {
// If we arent dragging and the jump to page dialog isnt open...
if(!dragging && !pageJumpOpen) {
// If we said in the preferences to be able to drag the reader window without holding alt...
if((NSApplication.shared().delegate as! AppDelegate).preferences.dragReaderWindowByBackgroundWithoutHoldingAlt) {
// If the reader controls panel isnt open...
if(!readerControlsOpen) {
// Create a new CGEventRef, for the mouse position
let mouseEvent : CGEvent = CGEvent(source: nil)!;
// Get the mouse point onscreen from ourEvent
let mousePosition = mouseEvent.location;
// Store the titlebars frame
let titlebarFrame : NSRect = titlebarVisualEffectView.frame;
/// The mouses position on the Y
let pointY = abs(mousePosition.y - NSScreen.main()!.frame.height);
/// The mouses position where 0 0 is the bottom left of the reader window
let mousePositionFromWindow : CGPoint = NSPoint(x: mousePosition.x - readerWindow.frame.origin.x, y: pointY - readerWindow.frame.origin.y);
/// Is the mouse inside the titlebar?
var insideTitlebar : Bool = false;
// If the mouse is within the titlebar on the X...
if(mousePositionFromWindow.x > titlebarFrame.origin.x && mousePositionFromWindow.x < (titlebarFrame.origin.x + titlebarFrame.size.width)) {
// If the mouse is within the titlebar on the Y...
if(mousePositionFromWindow.y > titlebarFrame.origin.y && mousePositionFromWindow.y < (titlebarFrame.origin.y + titlebarFrame.size.height)) {
// Say the mouse is inside the titlebar
insideTitlebar = true;
}
}
// Store the reader control panels frame
let readerControlPanelFrame : NSRect = readerControlsPanelVisualEffectView.frame;
/// Is the mouse inside the reader control panel?
var insideReaderControlPanel : Bool = false;
// If the mouse is within the reader control panel on the X...
if(mousePositionFromWindow.x > readerControlPanelFrame.origin.x && mousePositionFromWindow.x < (readerControlPanelFrame.origin.x + readerControlPanelFrame.size.width)) {
// If the mouse is within the reader control panel on the Y...
if(mousePositionFromWindow.y > readerControlPanelFrame.origin.y && mousePositionFromWindow.y < (readerControlPanelFrame.origin.y + readerControlPanelFrame.size.height)) {
// Say the mouse is inside the reader control panel
insideReaderControlPanel = true;
}
}
// If we arent inside the titlebar and not inside the reader control panel...
if(!insideTitlebar && !insideReaderControlPanel) {
// If the mouse position's X(Relative to the window) is less than the window width divided by 2...
if(mousePositionFromWindow.x < (readerWindow.frame.width / 2)) {
// We clicked on the left, go to the previous page
previousPage();
}
else {
// We clicked on the right, go to the next page
nextPage();
}
}
}
else {
// Say the controls panel is closed
readerControlsOpen = false;
// Close the controls panel
closeControlsPanel();
// Apply the new filter values to all pages(In a new thread so we dont get lots of beachballing for long manga)
Thread.detachNewThreadSelector(#selector(KMReaderViewController.updateFiltersForAllPages), toTarget: self, with: nil);
}
}
else {
// If we arent holding alt...
if(theEvent.modifierFlags.rawValue != 524576 && theEvent.modifierFlags.rawValue != 524320) {
// If the reader controls panel isnt open...
if(!readerControlsOpen) {
// Create a new CGEventRef, for the mouse position
let mouseEvent : CGEvent = CGEvent(source: nil)!;
// Get the mouse point onscreen from ourEvent
let mousePosition = mouseEvent.location;
// Store the titlebars frame
let titlebarFrame : NSRect = titlebarVisualEffectView.frame;
/// The mouses position on the Y
let pointY = abs(mousePosition.y - NSScreen.main()!.frame.height);
/// The mouses position where 0 0 is the bottom left of the reader window
let mousePositionFromWindow : CGPoint = NSPoint(x: mousePosition.x - readerWindow.frame.origin.x, y: pointY - readerWindow.frame.origin.y);
/// Is the mouse inside the titlebar?
var insideTitlebar : Bool = false;
// If the mouse is within the titlebar on the X...
if(mousePositionFromWindow.x > titlebarFrame.origin.x && mousePositionFromWindow.x < (titlebarFrame.origin.x + titlebarFrame.size.width)) {
// If the mouse is within the titlebar on the Y...
if(mousePositionFromWindow.y > titlebarFrame.origin.y && mousePositionFromWindow.y < (titlebarFrame.origin.y + titlebarFrame.size.height)) {
// Say the mouse is inside the titlebar
insideTitlebar = true;
}
}
// Store the reader control panels frame
let readerControlPanelFrame : NSRect = readerControlsPanelVisualEffectView.frame;
/// Is the mouse inside the reader control panel?
var insideReaderControlPanel : Bool = false;
// If the mouse is within the reader control panel on the X...
if(mousePositionFromWindow.x > readerControlPanelFrame.origin.x && mousePositionFromWindow.x < (readerControlPanelFrame.origin.x + readerControlPanelFrame.size.width)) {
// If the mouse is within the reader control panel on the Y...
if(mousePositionFromWindow.y > readerControlPanelFrame.origin.y && mousePositionFromWindow.y < (readerControlPanelFrame.origin.y + readerControlPanelFrame.size.height)) {
// Say the mouse is inside the reader control panel
insideReaderControlPanel = true;
}
}
// If we arent inside the titlebar and not inside the reader control panel...
if(!insideTitlebar && !insideReaderControlPanel) {
// If the mouse position's X(Relative to the window) is less than the window width divided by 2...
if(mousePositionFromWindow.x < (readerWindow.frame.width / 2)) {
// We clicked on the left, go to the previous page
previousPage();
}
else {
// We clicked on the right, go to the next page
nextPage();
}
}
}
else {
// Say the controls panel is closed
readerControlsOpen = false;
// Close the controls panel
closeControlsPanel();
// Apply the new filter values to all pages(In a new thread so we dont get lots of beachballing for long manga)
Thread.detachNewThreadSelector(#selector(KMReaderViewController.updateFiltersForAllPages), toTarget: self, with: nil);
}
}
}
}
// If we arent dragging and the jump to page dialog is open...
else if(!dragging && pageJumpOpen) {
// If we said we could drag the window without holding alt...
if((NSApplication.shared().delegate as! AppDelegate).preferences.dragReaderWindowByBackgroundWithoutHoldingAlt) {
// Close the page jump view
closeJumpToPageDialog();
}
// If we said we have to hold alt while dragging the window and we are holding alt...
else if(theEvent.modifierFlags.rawValue != 524576 && theEvent.modifierFlags.rawValue != 524320) {
// Close the page jump view
closeJumpToPageDialog();
}
}
// Say we arent dragging
dragging = false;
}
/// Is the user dragging the mouse?
var dragging : Bool = false;
override func mouseDragged(with theEvent: NSEvent) {
// If we said in the preferences to be able to drag the reader window without holding alt...
if((NSApplication.shared().delegate as! AppDelegate).preferences.dragReaderWindowByBackgroundWithoutHoldingAlt) {
// Perform a window drag with the drag event
if #available(OSX 10.11, *) {
readerWindow.performDrag(with: theEvent);
} else {
// Move the window with the mouse's delta
readerWindow.setFrameOrigin(NSPoint(x: readerWindow.frame.origin.x + theEvent.deltaX, y: readerWindow.frame.origin.y - theEvent.deltaY));
};
// Say we are dragging
dragging = true;
}
else {
// If we are holding alt...
if(theEvent.modifierFlags.rawValue == 524576) {
// Perform a window drag with the drag event
if #available(OSX 10.11, *) {
readerWindow.performDrag(with: theEvent);
} else {
// Move the window with the mouse's delta
readerWindow.setFrameOrigin(NSPoint(x: readerWindow.frame.origin.x + theEvent.deltaX, y: readerWindow.frame.origin.y - theEvent.deltaY));
};
}
}
}
func switchDualPageDirection() {
// If we are reading Right to Left...
if(dualPageDirection == KMDualPageDirection.rightToLeft) {
// Switch the direction to Left to Right
dualPageDirection = KMDualPageDirection.leftToRight;
}
// If we are reading Left to Right...
else if(dualPageDirection == KMDualPageDirection.leftToRight) {
// Switch the direction to Right to Left
dualPageDirection = KMDualPageDirection.rightToLeft;
}
// Update the page
updatePage();
}
func fitWindowToManga() {
// If we are in dualPage mode...
if(dualPage && !isFullscreen) {
// Get the size of the left image
var leftImageSize : NSSize = NSSize();
// Get the size of the right image
var rightImageSize : NSSize = NSSize();
// If we add 1 to manga.currentPage and there would be an image at that index in manga.pages...
if(manga.currentPage + 1 < manga.pages.count) {
// Set leftImageSize to be the currentPage + 1's size
leftImageSize = pixelSizeOfImage(manga.pages[manga.currentPage + 1]);
}
else {
// Set leftImageSize to be the other pages size
leftImageSize = pixelSizeOfImage(manga.pages[manga.currentPage]);
}
// Set rightImageSize to be the ucrrent pages image size
rightImageSize = pixelSizeOfImage(manga.pages[manga.currentPage]);
// If the right pages height is smaller than the screen...
if(rightImageSize.height < NSScreen.main()?.frame.height) {
// Set the reader windows frame to be two times the width of the current open page
readerWindow.setFrame(NSRect(x: 0, y: 0, width: leftImageSize.width + rightImageSize.width, height: rightImageSize.height), display: false);
}
// If its larger vertically...
else {
// The height we want the window to have
let height = (NSScreen.main()?.frame.height)! - 150;
// Get the aspect ratio of the image
let aspectRatio = (leftImageSize.width + rightImageSize.width) / (rightImageSize.height);
// Figure out what the width would be if we kept the aspect ratio and set the height to the screens size
let width = aspectRatio * height;
// Set the windows size to the new size we calculated
readerWindow.setFrame(NSRect(x: 0, y: 0, width: width, height: height), display: false);
}
// Center the window
readerWindow.center();
}
else if(!dualPage && !isFullscreen) {
// If the current pages image is smaller than the screen vertically...
if(pixelSizeOfImage(readerImageView.image!).height < ((NSScreen.main()?.frame.height)! - 150)) {
// Set the reader windows frame to be the reader image views image size
readerWindow.setFrame(NSRect(x: 0, y: 0, width: pixelSizeOfImage(readerImageView.image!).width, height: pixelSizeOfImage(readerImageView.image!).height), display: false);
}
// If its larger vertically...
else {
// The height we want the window to have
let height = (NSScreen.main()?.frame.height)! - 150;
// Get the aspect ratio of the image
let aspectRatio = pixelSizeOfImage(readerImageView.image!).width / pixelSizeOfImage(readerImageView.image!).height;
// Figure out what the width would be if we kept the aspect ratio and set the height to the screens size
let width = aspectRatio * height;
// Set the windows size to the new size we calculated
readerWindow.setFrame(NSRect(x: 0, y: 0, width: width, height: height), display: false);
// Center the window
readerWindow.center();
}
// Center the window
readerWindow.center();
}
}
/// Returns the pixel size of the passed NSImage
func pixelSizeOfImage(_ image : NSImage) -> NSSize {
/// The NSBitmapImageRep to the image
let imageRep : NSBitmapImageRep = (NSBitmapImageRep(data: image.tiffRepresentation!))!;
/// The size of the iamge
let imageSize : NSSize = NSSize(width: imageRep.pixelsWide, height: imageRep.pixelsHigh);
// Return the image size
return imageSize;
}
func windowWillClose(_ notification: Notification) {
// Save the notes and close the notes window
notesWindowController?.close();
// Close the view
closeView();
}
func windowDidBecomeKey(_ notification: Notification) {
// Re-enable the next and previous menu items in case the notes popover disabled them
(NSApplication.shared().delegate as? AppDelegate)?.nextPageMenubarItem.action = #selector(KMReaderViewController.nextPage);
(NSApplication.shared().delegate as? AppDelegate)?.previousPageMenubarItem.action = #selector(KMReaderViewController.previousPage);
}
/// Call this when the window will close
func closeView() {
// Say the view is closing
closingView = true;
// Restore the manga's original pages
manga.pages = mangaOriginalPages;
// Stop the mouse hover timer
mouseHoverHandlingTimer.invalidate();
// Stop monitoring the trackpad
readerImageScrollView.removeAllMonitors();
// Unsubscribe from all notifications
NotificationCenter.default.removeObserver(self);
// Post the notification to update the percent finished
NotificationCenter.default.post(name: Notification.Name(rawValue: "KMMangaGridCollectionItem.UpdatePercentFinished"), object: manga);
// Update the grid(For some reason I have to call this function instead of the update grid one)
NotificationCenter.default.post(name: Notification.Name(rawValue: "KMEditMangaViewController.Saving"), object: manga);
// Show the cursor
NSCursor.unhide();
}
// Resets things like the Contrast, Saturation, ETC.
func resetCGValues() {
// Update the sliders
readerControlPanelSaturationSlider.floatValue = 1;
readerControlPanelBrightnessSlider.floatValue = 0;
readerControlPanelContrastSlider.floatValue = 1;
readerControlPanelSharpnessSlider.floatValue = 0;
// Reset the values
manga.saturation = 1;
manga.brightness = 0;
manga.contrast = 1;
manga.sharpness = 0;
// Update the filters
updateFiltersForCurrentPage();
}
// Opens the control panel for the user to modify the Saturation, Contrast, ETC.
func openControlsPanel() {
// Show the reader controls panel
readerControlsPanelVisualEffectView.isHidden = false;
// Animate out the reader panel
readerPanelVisualEffectView.animator().alphaValue = 0;
// Animate in the reader control panel
readerControlsPanelVisualEffectView.animator().alphaValue = 1;
// Do the 0.2 second wait to hide the reader panel and show the controls panel
Timer.scheduledTimer(timeInterval: TimeInterval(0.2), target:self, selector: #selector(KMReaderViewController.hideReaderPanelShowControlsPanel), userInfo: nil, repeats:false);
}
/// Closes the control panel for the user to modify the Saturation, Contrast, ETC.
func closeControlsPanel() {
// Animate in the reader panel
readerPanelVisualEffectView.animator().alphaValue = 1;
// Animate out the control panel
readerControlsPanelVisualEffectView.animator().alphaValue = 0;
// Do the 0.2 second wait to hide the controls panel and show the reader panel
Timer.scheduledTimer(timeInterval: TimeInterval(0.2), target:self, selector: #selector(KMReaderViewController.hideControlsPanelShowReaderPanel), userInfo: nil, repeats:false);
}
/// Hides the controls panel and shows the reader panel
func hideControlsPanelShowReaderPanel() {
// Say the controls panel is closed
readerControlsOpen = false;
// Disable all the reader control panel buttons
readerControlPanelSaturationSlider.isEnabled = false;
readerControlPanelContrastSlider.isEnabled = false;
readerControlPanelBrightnessSlider.isEnabled = false;
readerControlPanelSharpnessSlider.isEnabled = false;
readerControlPanelSaveButton.isEnabled = false;
readerControlPanelResetButton.isEnabled = false;
// Set the controls panel to be hidden
readerControlsPanelVisualEffectView.isHidden = true;
readerControlsPanelVisualEffectView.appearance = NSAppearance(named: NSAppearanceNameVibrantDark);
// For every item in the reader panel...
for (_, currentItem) in readerPanelVisualEffectView.subviews.enumerated() {
// Enable it(Cast it to a NSControl first so we can enable it)
(currentItem as! NSControl).isEnabled = true;
}
// Set the reader panel to show
readerPanelCornerRounding.isHidden = false;
}
/// Hides the reader panel and shows the control panel
func hideReaderPanelShowControlsPanel() {
// Say the controls panel is open
readerControlsOpen = true;
// Enable all the reader control panel buttons
readerControlPanelSaturationSlider.isEnabled = true;
readerControlPanelContrastSlider.isEnabled = true;
readerControlPanelBrightnessSlider.isEnabled = true;
readerControlPanelSharpnessSlider.isEnabled = true;
readerControlPanelSaveButton.isEnabled = true;
readerControlPanelResetButton.isEnabled = true;
// Set the controls panel to show
readerControlsPanelVisualEffectView.isHidden = false;
// For every item in the reader panel...
for (_, currentItem) in readerPanelVisualEffectView.subviews.enumerated() {
// Disable it(Cast it to a NSControl first so we can enable it)
(currentItem as! NSControl).isEnabled = false;
}
// Set the reader panel to be hidden
readerPanelCornerRounding.isHidden = true;
}
func toggleDualPage() {
// Toggle the dualPage bool
dualPage = !dualPage;
// Fit the window to match the mangas size
fitWindowToManga();
// If we are in dualpage mode...
if(dualPage) {
// If the current page number is even...
if(manga.currentPage % 2 == 1) {
// Subtract one from current page to make it odd
manga.currentPage = manga.currentPage - 1;
}
}
// Update the page
updatePage();
}
func isPageBookmarked(_ page : Int) -> Bool {
// Is the page bookmarked?
var bookmarked : Bool = false;
// Iterate through manga.bookmarks
for (_, bookmarksElement) in manga.bookmarks.enumerated() {
// If the current element we are iterating is equal to the page we are wanting to see if it is bookmarked...
if(bookmarksElement == page) {
// Set bookmarked to true
bookmarked = true;
}
}
// Return bookmarked
return bookmarked;
}
/// Calls bookmarkPage with the current page number
func bookmarkCurrentPage() {
// Call bookmarkPage with the current page number
bookmarkPage(manga.currentPage);
}
/// Bookmarks the current page(Starts at 0). If it is already bookmarked, it removes that bookmark
func bookmarkPage(_ page : Int) {
// A bool to say if we already bookmarked this page
var alreadyBookmarked = false;
// Iterate through mangaBookmarks
for (bookmarksIndex, bookmarksElement) in manga.bookmarks.enumerated() {
// If the current element we are iterating is equal to the page we are trying to bookmark...
if(bookmarksElement == page) {
// Remove that element
manga.bookmarks.remove(at: bookmarksIndex);
// Say it was already bookmarked
alreadyBookmarked = true;
// Print to the log that we removed that bookmark
print("KMReaderViewController: Removed bookmarked for page " + String(page + 1) + " in \"" + manga.title + "\"");
}
}
// If we didnt already bookmark this page...
if(!alreadyBookmarked) {
// Append the page we are trying to bookmark
manga.bookmarks.append(page);
// Print to the log that we are bookmarking this page
print("KMReaderViewController: Bookmarked page " + String(page + 1) + " in \"" + manga.title + "\"");
}
// Update the page page to show that the page is bookmarked
updatePage();
}
/// Is the page jump view open?
var pageJumpOpen : Bool = false;
/// The NSEvent monitor for the page jump view that listens for the escape key
var pageJumpKeyListener : AnyObject?;
// Brings up the dialog for the user to jump to a page
func promptToJumpToPage() {
// Say the page jump view is open
pageJumpOpen = true;
// Stop the mouse hover handling timer
mouseHoverHandlingTimer.invalidate();
// Show the page jump scroll view
readerPageJumpController.readerPageJumpCollectionViewScrollView.isHidden = false;
// Load the manga's pages
readerPageJumpController.loadPagesFromManga(manga);
// Scroll to the current page
readerPageJumpController.readerPageJumpCollectionView.scrollToVisible(readerPageJumpController.readerPageJumpCollectionView.frameForItem(at: manga.currentPage));
// Say we are closing the view(This is a cheap way to make sure the cursor doesnt hide)
closingView = true;
// Fade out the titlebar and reader panels
fadeOutTitlebar();
// Show the cursor
NSCursor.unhide();
// Monitor the keyboard locally
pageJumpKeyListener = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: pageJumpKeyHandler) as AnyObject?;
// Fade in the thumbnail page jump view
thumbnailPageJumpVisualEffectView.animator().alphaValue = 1;
}
/// The handler for listening for the escape key when the page jump view is up
func pageJumpKeyHandler(_ event : NSEvent) -> NSEvent {
// If we pressed the escape key and the window is frontmost...
if(event.keyCode == 53 && readerWindow.isKeyWindow) {
// Close the page jump view
closeJumpToPageDialog();
}
// Return the event
return event;
}
/// Closes the dialog that prompts the user to jump to a page, and jumps to the inputted page
func closeJumpToPageDialog() {
// Say the page jump view is no longer open
pageJumpOpen = false;
// Fade out the thumbnail page jump view
thumbnailPageJumpVisualEffectView.animator().alphaValue = 0;
// Stop listening for the escape key
NSEvent.removeMonitor(pageJumpKeyListener!);
// Say we arent closing the view(Stop the cheap tricks)
closingView = false;
// Restart the 0.1 second loop for the mouse hovering
mouseHoverHandlingTimer = Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(KMReaderViewController.mouseHoverHandling), userInfo: nil, repeats: true);
// Wait 0.2 seconds to disable the jump to page view, so the animation can finish
Timer.scheduledTimer(timeInterval: TimeInterval(0.2), target:self, selector: #selector(KMReaderViewController.disableJumpToPageDialog), userInfo: nil, repeats: false);
}
/// Disables the page jump view
func disableJumpToPageDialog() {
// Hide the page jump scroll view
readerPageJumpController.readerPageJumpCollectionViewScrollView.isHidden = true;
}
func nextPage() {
// If we are in dual page mode...
if(dualPage) {
// If we were to add 2 to mangaCurrentPage and it would be less than the openMangaPages count...
if(manga.currentPage + 2 < manga.pageCount) {
// Print to the log that we are going to the next page
print("KMReaderViewController: Loading next page in \"" + manga.title + "\"");
// Add 2 to mangaCurrentPage
manga.currentPage += 2;
// Load the new page
updatePage();
}
else {
// If we have mark as read when completed in reader enabled...
if((NSApplication.shared().delegate as! AppDelegate).preferences.markAsReadWhenCompletedInReader) {
// Print to the log that we have finished the book and are marking it as read
print("KMReaderViewController: Finished \"" + manga.title + "\", marking it as read and exiting");
// Set the mangas read variable to true
manga.read = true;
// Close the window
readerWindow.close();
}
else {
// Close the window
readerWindow.close();
}
}
}
else {
// If we were to add 1 to mangaCurrentPage and it would be less than the openMangaPages count...
if(manga.currentPage + 1 < manga.pageCount) {
// Print to the log that we are going to the next page
print("KMReaderViewController: Loading next page in \"" + manga.title + "\"");
// Add 1 to mangaCurrentPage
manga.currentPage += 1;
// Load the new page
updatePage();
}
else {
// If we have mark as read when completed in reader enabled...
if((NSApplication.shared().delegate as! AppDelegate).preferences.markAsReadWhenCompletedInReader) {
// Print to the log that we have finished the book and are marking it as read
print("KMReaderViewController: Finished \"" + manga.title + "\", marking it as read and exiting");
// Set the mangas read variable to true
manga.read = true;
// Close the window
readerWindow.close();
}
else {
// Close the window
readerWindow.close();
}
}
}
}
func previousPage() {
if(dualPage) {
// If we were to subtract 2 from mangaCurrentPage and it would be greater than 0...
if(manga.currentPage - 2 > -1) {
// Print to the log that we are going to the previous page
print("KMReaderViewController: Loading previous page in \"" + manga.title + "\"");
// Subtract 2 from mangaCurrentPage
manga.currentPage -= 2;
// Load the new page
updatePage();
}
else {
// Print to the log that there is no previous page
print("KMReaderViewController: There is no previous page in \"" + manga.title + "\"");
}
}
else {
// If we were to subtract 1 from mangaCurrentPage and it would be greater than 0...
if(manga.currentPage - 1 > -1) {
// Print to the log that we are going to the previous page
print("KMReaderViewController: Loading previous page in \"" + manga.title + "\"");
// Subtract 1 from mangaCurrentPage
manga.currentPage -= 1;
// Load the new page
updatePage();
}
else {
// Print to the log that there is no previous page
print("KMReaderViewController: There is no previous page in \"" + manga.title + "\"");
}
}
}
// The page number starts at 0, keep that in mind
func jumpToPage(_ page : Int, round : Bool) {
// See if the page we are trying to jump to is existant
if(page >= 0 && page < manga.pageCount) {
// Print to the log that we are jumping to a page
print("KMReaderViewController: Jumping to page " + String(page) + " in \"" + manga.title + "\"");
// Set the current page to the page we want to jump to
manga.currentPage = page;
// Load the new page
updatePage();
}
else {
// If we said to round off the number...
if(round) {
// Create a variable to store the page number we will round it off to
var roundedPage : Int = page;
// If roundedPage is bigger than the page count...
if(roundedPage > manga.pageCount) {
// Set roundedPage to the page count minus 1
roundedPage = manga.pageCount - 1;
}
// If roundedPage is less than 0
else if(roundedPage < 0) {
// Set roundedPage to 0
roundedPage = 0;
}
// Print to the log that we are jumping to roundedPage, and what page that is
print("KMReaderViewController: Jumping to rounded off page " + String(roundedPage) + " in \"" + manga.title + "\"");
// Set the current page to roundedPage
manga.currentPage = roundedPage;
// Load the new page
updatePage();
}
else {
// Print to the log that we cant jump to that page
print("KMReaderViewController: Cant jump to page " + String(page) + " in \"" + manga.title + "\"");
}
}
}
// Updates the manga page image view to the new page (Specified by mangaCurrentPage) and updates the reader panel labels value
func updatePage() {
// Load the new page
readerImageView.image = manga.pages[manga.currentPage];
// If we are in dual page mode...
if(dualPage) {
// If we add 1 to the current page and it wont be above the page count...
if(!(manga.currentPage + 1 < manga.pages.count)) {
// Set the label to be "(Current page + 1) / (Page count)"
readerPageNumberLabel.stringValue = String(manga.currentPage + 1) + "/" + String(manga.pageCount);
}
else {
// Set the label to be "(Current page + 1) - (Current page + 2) / (Page count)"
readerPageNumberLabel.stringValue = String(manga.currentPage + 1) + " - " + String(manga.currentPage + 2) + "/" + String(manga.pageCount);
}
}
else {
// Set the reader panels labels value
readerPageNumberLabel.stringValue = String(manga.currentPage + 1) + "/" + String(manga.pageCount);
}
// Is the current page bookmarked?
let pageBookmarked = isPageBookmarked(manga.currentPage);
// If the page is bookmarked...
if(pageBookmarked) {
// Set the manga bookmarks button to have a border
readerBookmarkButton.alphaValue = 1;
// Also add a check mark next to the bookmark menu item
(NSApplication.shared().delegate as? AppDelegate)?.bookmarkCurrentPageMenuItem.state = 1;
}
else {
// Set the manga bookmarks button alpha value to 0.2, as to indicate to the user this page is not boomarked
readerBookmarkButton.animator().alphaValue = 0.2;
// Also remove the check mark next to the bookmark menu item
(NSApplication.shared().delegate as? AppDelegate)?.bookmarkCurrentPageMenuItem.state = 0;
}
// If we are in dual page mode...
if(dualPage) {
// Hide the one page image view
readerImageView.isHidden = true;
// Show the dual page stack view for dual page mode
dualPageStackView.isHidden = false;
// If we are reading from Right to Left...
if(dualPageDirection == KMDualPageDirection.rightToLeft) {
// If we add 1 to manga.currentPage and there would be an image at that index in manga.pages...
if(manga.currentPage + 1 < manga.pages.count) {
// Set the left sides image to the current page + 1
leftPageReaderImageView.image = manga.pages[manga.currentPage + 1];
}
else {
// Set the left image views to nothing
leftPageReaderImageView.image = NSImage();
}
// Set the right sides image to the current page
rightPageReaderImageView.image = manga.pages[manga.currentPage];
}
// If we are reading from Left to Right...
else if(dualPageDirection == KMDualPageDirection.leftToRight) {
// If we add 1 to manga.currentPage and there would be an image at that index in manga.pages...
if(manga.currentPage + 1 < manga.pages.count) {
// Set the right sides image to the ucrrent page + 1
rightPageReaderImageView.image = manga.pages[manga.currentPage + 1];
}
else {
// Set the right image views to nothing
rightPageReaderImageView.image = NSImage();
}
// Set the left sides image to the current page
leftPageReaderImageView.image = manga.pages[manga.currentPage];
}
}
else {
// Show the one page image view
readerImageView.isHidden = false;
// Hide the dual page stack view
dualPageStackView.isHidden = true;
}
}
func updateFiltersForAllPages() {
// For every original page...
for(currentPageIndex, currentPage) in mangaOriginalPages.enumerated() {
// Set the current page to be the current page with the chosen filter amounts
manga.pages[currentPageIndex] = KMImageFilterUtilities().applyColorAndSharpness(currentPage, saturation: manga.saturation, brightness: manga.brightness, contrast: manga.contrast, sharpness: manga.sharpness);
}
// Update the page
updatePage();
}
func updateFiltersForCurrentPage() {
// If we arent in dual page mode...
if(!dualPage) {
// Set the current page to the current page with filters
manga.pages[manga.currentPage] = KMImageFilterUtilities().applyColorAndSharpness(mangaOriginalPages[manga.currentPage], saturation: manga.saturation, brightness: manga.brightness, contrast: manga.contrast, sharpness: manga.sharpness);
}
// If we are in dual page
else {
// If we add 1 to manga.currentPage and there would be an image at that index in manga.pages...
if(manga.currentPage + 1 < manga.pages.count) {
// Apply the filter to this image
manga.pages[manga.currentPage + 1] = KMImageFilterUtilities().applyColorAndSharpness(mangaOriginalPages[manga.currentPage + 1], saturation: manga.saturation, brightness: manga.brightness, contrast: manga.contrast, sharpness: manga.sharpness);
}
// Set the current page to the current page with filters
manga.pages[manga.currentPage] = KMImageFilterUtilities().applyColorAndSharpness(mangaOriginalPages[manga.currentPage], saturation: manga.saturation, brightness: manga.brightness, contrast: manga.contrast, sharpness: manga.sharpness);
}
// Update the page
updatePage();
}
func fadeOutTitlebarFullscreen() {
// If the view isnt closing...
if(!closingView) {
// Hide the cursor
NSCursor.hide();
}
// Set cursorHidden to true
cursorHidden = true;
// Fade out the titlebar
fadeOutTitlebar();
}
func fadeInTitlebarFullscreen() {
// Show the cursor
NSCursor.unhide();
// Set cursorHidden to false
cursorHidden = false;
// Fade in the titlebar
fadeInTitlebar();
}
// A variable to tell us where the mouse previously was
var oldMousePosition : CGPoint!;
// The NSTimer to handle fading out the panel when we dont move the mouse
var fadeTimer : Timer = Timer();
// Is the cursor hidden(Come on Apple, why isnt this part of NSCursor?)
var cursorHidden : Bool = false;
func mouseHoverHandling() {
// Are we fullscreen?
let fullscreen : Bool = readerWindow.isFullscreen();
// if we arent fullscreen...
if(!fullscreen) {
// If the titlebar visual effect view is hidden...
if(titlebarVisualEffectView.isHidden) {
// Show the titlebar visual effect view
titlebarVisualEffectView.isHidden = false;
}
}
else {
// Hide the titlebar visual effect view
titlebarVisualEffectView.isHidden = true;
// Show the window titlebar
readerWindow.standardWindowButton(NSWindowButton.closeButton)?.superview?.superview?.alphaValue = 1;
}
// Set isFullscreen to fullscreen
isFullscreen = fullscreen;
// Create a new CGEventRef, for the mouse position
let mouseEvent : CGEvent = CGEvent(source: nil)!;
// Get the mouse point onscreen from ourEvent
let mousePosition = mouseEvent.location;
// If we have moved the mouse...
if(mousePosition != oldMousePosition) {
// Stop the fade timer
fadeTimer.invalidate();
// Store the reader panels frame
let readerPanelFrame : NSRect = readerPanelCornerRounding.frame;
/// The mouses position on the Y
let pointY = abs(mousePosition.y - NSScreen.main()!.frame.height);
/// The mouses position where 0 0 is the bottom left of the reader window
let mousePositionFromWindow : CGPoint = NSPoint(x: mousePosition.x - readerWindow.frame.origin.x, y: pointY - readerWindow.frame.origin.y);
/// Is the mouse inside the reader panel?
var insideReaderPanel : Bool = false;
// If the mouse is within the reader panel on the X...
if(mousePositionFromWindow.x > readerPanelFrame.origin.x && mousePositionFromWindow.x < (readerPanelFrame.origin.x + readerPanelFrame.size.width)) {
// If the mouse is within the reader panel on the Y...
if(mousePositionFromWindow.y > readerPanelFrame.origin.y && mousePositionFromWindow.y < (readerPanelFrame.origin.y + readerPanelFrame.size.height)) {
// Say we are in the reader panel
insideReaderPanel = true;
}
}
/// Is the mouse inside the window?
var insideWindow : Bool = false;
// If the mouse is inside the window on the X...
if(mousePosition.x > readerWindow.frame.origin.x && mousePosition.x < (readerWindow.frame.origin.x + readerWindow.frame.size.width)) {
// If the mouse is inside the window on the Y...
if(pointY > readerWindow.frame.origin.y && pointY < (readerWindow.frame.origin.y + readerWindow.frame.size.height)) {
// Say we are inside the window
insideWindow = true;
}
}
// If the reader window is currently selected...
if(readerWindow.isKeyWindow) {
// Fade in the titlebar(Fullscreen mode)
fadeInTitlebarFullscreen();
}
// If the cursor isnt inside the reader panel and in fullscreen...
if(!insideReaderPanel && fullscreen) {
// Fade out the titlebar(Fullscreen mode) in one second
fadeTimer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target:self, selector: #selector(KMReaderViewController.fadeOutTitlebarFullscreen), userInfo: nil, repeats:false);
}
// If the reader window is the key window and the cursor isnt inside the reader panel and we are inside the window...
else if(readerWindow.isKeyWindow && !insideReaderPanel && insideWindow) {
// Fade out the titlebar(Fullscreen mode) in 2 seconds
fadeTimer = Timer.scheduledTimer(timeInterval: TimeInterval(2), target:self, selector: #selector(KMReaderViewController.fadeOutTitlebarFullscreen), userInfo: nil, repeats:false);
}
// If the reader window is the key window and the cursor isnt inside the reader panel and we arent inside the window...
else if(readerWindow.isKeyWindow && !insideReaderPanel && !insideWindow) {
// Fade out the titlebar(Fullscreen mode) in 0.5 seconds
fadeTimer = Timer.scheduledTimer(timeInterval: TimeInterval(0.5), target:self, selector: #selector(KMReaderViewController.fadeOutTitlebarFullscreen), userInfo: nil, repeats:false);
}
// If the reader window isnt key...
if(!readerWindow.isKeyWindow) {
// Fade out the titlebar
fadeTimer = Timer.scheduledTimer(timeInterval: TimeInterval(0), target:self, selector: #selector(KMReaderViewController.fadeOutTitlebar), userInfo: nil, repeats:false);
// Show the cursor
NSCursor.unhide();
}
}
// Set oldMousePosition to the current mouse position
oldMousePosition = mousePosition;
}
func fadeOutTitlebar() {
// Use the animator to fade out the titlebars visual effect view
titlebarVisualEffectView.animator().alphaValue = 0;
// Use the animator to fade out the windows titlebar
readerWindow.standardWindowButton(NSWindowButton.closeButton)?.superview?.superview?.animator().alphaValue = 0;
// Use the animator to fade out the reader panel
readerPanelVisualEffectView.animator().alphaValue = 0;
}
func fadeInTitlebar() {
// Use the animator to fade in the titlebars visual effect view
titlebarVisualEffectView.animator().alphaValue = 1;
// Use the animator to fade in the windows titlebar
readerWindow.standardWindowButton(NSWindowButton.closeButton)?.superview?.superview?.animator().alphaValue = 1;
// If we dont have the reader controls open...
if(!readerControlsOpen) {
// Use the animator to fade in the reader panel
readerPanelVisualEffectView.animator().alphaValue = 1;
}
}
func styleWindow() {
// Get the reader window
readerWindow = NSApplication.shared().windows.last!;
// Hide the titlebar
readerWindow.standardWindowButton(NSWindowButton.closeButton)?.superview?.superview?.alphaValue = 0;
// Hide the reader panels visual effect view
readerPanelVisualEffectView.alphaValue = 0;
// Hide the reader controls panel visual effect view
readerControlsPanelVisualEffectView.alphaValue = 0;
// Set it to have a full size content view
readerWindow.styleMask.insert(NSFullSizeContentViewWindowMask);
// Hide the titlebar background
readerWindow.titlebarAppearsTransparent = true;
// Hide the title
readerWindow.titleVisibility = NSWindowTitleVisibility.hidden;
// Create some options for the reader window title KVO
let options = NSKeyValueObservingOptions([.new, .old, .initial, .prior]);
// Subscribe to when the reader window changes its title
self.readerWindow.addObserver(self, forKeyPath: "title", options: options, context: nil);
// Set the reader windows delegate to this
readerWindow.delegate = self;
// Set the window background color
readerWindow.backgroundColor = (NSApplication.shared().delegate as! AppDelegate).preferences.readerWindowBackgroundColor;
// Set the background of the thumbnail page jump view to be dark
thumbnailPageJumpVisualEffectView.material = NSVisualEffectMaterial.dark;
// Hide the background of the thumbnail page jump view
thumbnailPageJumpVisualEffectView.alphaValue = 0;
// Unhide the background of the thumbnail page jump view(Its hidden in IB because it makes it unusable)
thumbnailPageJumpVisualEffectView.isHidden = false;
// DIsable the page jump scroll view(It stops scrolling/gestures in the reader until it is shown and hidden again)
disableJumpToPageDialog();
// For some reason it destroys these views appearances, so I have to set them
readerControlPanelSaturationSlider.superview?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark);
readerControlPanelContrastSlider.superview?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark);
readerControlPanelBrightnessSlider.superview?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark);
readerControlPanelSharpnessSlider.superview?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark);
readerControlsPanelVisualEffectView.appearance = NSAppearance(named: NSAppearanceNameVibrantDark);
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
// If the keyPath is the one for the window title...
if(keyPath == "title") {
// Update the custom title text field
readerWindowTitleTextField.stringValue = readerWindow.title;
}
}
}
| 692fb8390d1b34b943de9281acc3beb3 | 45.708305 | 258 | 0.604438 | false | false | false | false |
apegroup/APEReactiveNetworking | refs/heads/master | Example/Project/Scenes/User/Controllers/UserDetailViewController.swift | mit | 1 | //
// UserDetailViewController.swift
// Example
//
// Created by Magnus Eriksson on 2016-10-31.
// Copyright © 2016 Apegroup. All rights reserved.
//
import UIKit
import ReactiveSwift
import APEReactiveNetworking
import enum Result.NoError
import ReactiveObjC
import ReactiveObjCBridge
final class UserDetailViewController: UIViewController {
//MARK: - Properties
private var viewModel = UserDetailViewModel()
private lazy var mediaPresenter: MediaPresenter = {
return MediaPresenter { [weak self] image in
self?.viewModel.updateAvatar(image: image)
}
}()
//MARK: - IBOutlets
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var avatarImageView: UIImageView!
//MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
bindUIWithSignals()
}
private func bindUIWithSignals() {
viewModel.imageData.producer.on(value: { [weak self] data in
self?.avatarImageView.image = UIImage(data: data)
}).observe(on: UIScheduler()).start()
usernameLabel.rac_text <~ viewModel.username
viewModel.isCameraVisible.producer.on(value: { [weak self] visible in
self?.navigationItem.rightBarButtonItem = visible ? self?.cameraButton : nil
}).start()
cameraButton.rac_command = RACCommand { [weak self] _ -> RACSignal in
return RACSignal.createSignal { (subscriber: RACSubscriber!) -> RACDisposable! in
if let vc = self?.mediaPresenter.configuredImagePickerController() {
self?.present(vc, animated: true, completion: nil)
}
subscriber.sendCompleted()
return RACDisposable {}
}.deliverOnMainThread()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewModel.isActive = true
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
viewModel.isActive = false
}
//MARK: - Public
func setupViewState(_ state: UserDetailViewModel.ViewState) {
viewModel.viewState = state
}
}
| 222b68f0c87a133a64d2bd8a1c3d5c95 | 28.658228 | 93 | 0.628254 | false | false | false | false |
Michael-Lfx/SwiftArmyKnife | refs/heads/master | Extensions/Foundation+SwiftArmyKnife.swift | mit | 1 | import Foundation
import AssetsLibrary
// MARK: - Foundation
extension NSDate {
// MARK: Timestamp - 时间戳
/// **timestamp** 时间戳字符串,纯数字组成
class func dateFromTimestampString(timestamp: String) -> NSDate! {
let time = timestamp.toInt()!
let date = NSDate(timeIntervalSince1970: NSTimeInterval(time))
return date
}
class func currentLocalTimestamp() -> String! {
let timezone = NSTimeZone.systemTimeZone()
return currentTimestamp(timezone: timezone)
}
class func currentGreenwichTimestamp() -> String! {
let timezone = NSTimeZone(name: "Europe/London")!
return currentTimestamp(timezone: timezone)
}
class func currentTimestamp(#timezone: NSTimeZone) -> String! {
let date = NSDate()
return timestamp(date: date, timezone: timezone)
}
class func timestamp(#date: NSDate, timezone: NSTimeZone) -> String! {
let interval = NSTimeInterval(timezone.secondsFromGMTForDate(date))
let localeDate = date.dateByAddingTimeInterval(interval)
let timestamp = NSString.localizedStringWithFormat("%ld", Int64(localeDate.timeIntervalSince1970))
return String(timestamp)
}
class var currentDateStringWithoutTimeZoneString: String {
return dateToString(NSDate(), dateFormat: "yyyy-MM-dd HH:mm:ss")
}
static func dateToString(date: NSDate, dateFormat: String) -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = dateFormat
formatter.locale = NSLocale(localeIdentifier: NSCalendarIdentifierGregorian)
return formatter.stringFromDate(date)
}
}
extension NSObject {
/**
在主队列上延迟指定的时间执行闭包的操作,用于更新界面
:param: seconds 秒数,类型为Double
:param: closure 闭包,将在主队列上执行
*/
func delayWithSeconds(seconds: Double, closure: () -> ()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(seconds * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
extension NSUserDefaults {
static func defaultsRegisterDefaults(registrationDictionary: [NSObject : AnyObject]) -> NSUserDefaults {
NSUserDefaults.standardUserDefaults().registerDefaults(registrationDictionary)
return NSUserDefaults.standardUserDefaults()
}
static func defaultsSetValue<T: AnyObject>(value: T?, forKey defaultName: String) -> NSUserDefaults.Type {
let ud = NSUserDefaults.standardUserDefaults()
switch value {
case let realValue as Int:
ud.setInteger(realValue, forKey: defaultName)
case let realValue as Float:
ud.setFloat(realValue, forKey: defaultName)
case let realValue as Double:
ud.setDouble(realValue, forKey: defaultName)
case let realValue as Bool:
ud.setBool(realValue, forKey: defaultName)
case let realValue as NSURL:
ud.setURL(realValue, forKey: defaultName)
default:
ud.setObject(value, forKey: defaultName)
}
return self
}
static func defaultsValueForKey<T>(name: String, inout value: T?) -> NSUserDefaults.Type {
let ud = NSUserDefaults.standardUserDefaults()
switch T.self {
case is Int.Type:
value = ud.integerForKey(name) as? T
case is Float.Type:
value = ud.floatForKey(name) as? T
case is Double.Type:
value = ud.doubleForKey(name) as? T
case is Bool.Type:
value = ud.boolForKey(name) as? T
case is NSURL.Type:
value = ud.URLForKey(name) as? T
case is String.Type:
value = ud.stringForKey(name) as? T
case is NSData.Type:
value = ud.dataForKey(name) as? T
default:
value = ud.objectForKey(name) as? T
}
return self
}
static func defaultsSynchronize() -> Bool {
return NSUserDefaults.standardUserDefaults().synchronize()
}
}
extension NSBundle {
class func pathForResource(name: String, type: String?) -> String? {
return NSBundle.mainBundle().pathForResource("minus", ofType: ".png")
}
}
| af4265eeaecd1de03b7514d96056a1d5 | 30.808824 | 110 | 0.624364 | false | false | false | false |
onevcat/Rainbow | refs/heads/master | Tests/RainbowTests/ConsoleStringTests.swift | mit | 1 | //
// ConsoleStringTests.swift
// Rainbow
//
// Created by Wei Wang on 15/12/23.
//
// Copyright (c) 2018 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import Rainbow
class ConsoleStringTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
Rainbow.outputTarget = .console
Rainbow.enabled = true
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testStringColor() {
let string = "Hello Rainbow"
XCTAssertEqual(string.black, "\u{001B}[30mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.red, "\u{001B}[31mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.green, "\u{001B}[32mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.yellow, "\u{001B}[33mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.blue, "\u{001B}[34mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.magenta, "\u{001B}[35mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.cyan, "\u{001B}[36mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.white, "\u{001B}[37mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightBlack, "\u{001B}[90mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightRed, "\u{001B}[91mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightGreen, "\u{001B}[92mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightYellow, "\u{001B}[93mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightBlue, "\u{001B}[94mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightMagenta, "\u{001B}[95mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightCyan, "\u{001B}[96mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.lightWhite, "\u{001B}[97mHello Rainbow\u{001B}[0m")
}
func testString8BitColor() {
let string = "Hello Rainbow"
XCTAssertEqual(string.bit8(123), "\u{001B}[38;5;123mHello Rainbow\u{001B}[0m")
}
func testString24BitColor() {
let string = "Hello Rainbow"
XCTAssertEqual(string.bit24((10, 20, 30)), "\u{001B}[38;2;10;20;30mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.bit24(10, 20, 30), "\u{001B}[38;2;10;20;30mHello Rainbow\u{001B}[0m")
}
func testStringBackgroundColor() {
let string = "Hello Rainbow"
XCTAssertEqual(string.onBlack, "\u{001B}[40mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onRed, "\u{001B}[41mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onGreen, "\u{001B}[42mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onYellow, "\u{001B}[43mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onBlue, "\u{001B}[44mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onMagenta, "\u{001B}[45mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onCyan, "\u{001B}[46mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onWhite, "\u{001B}[47mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onLightRed, "\u{001B}[101mHello Rainbow\u{001B}[0m")
}
func testString8BitBackgroundColor() {
let string = "Hello Rainbow"
XCTAssertEqual(string.onBit8(123), "\u{001B}[48;5;123mHello Rainbow\u{001B}[0m")
}
func testString24BitBackgroundColor() {
let string = "Hello Rainbow"
XCTAssertEqual(string.onBit24((10, 20, 30)), "\u{001B}[48;2;10;20;30mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onBit24(10, 20, 30), "\u{001B}[48;2;10;20;30mHello Rainbow\u{001B}[0m")
}
func testStringStyle() {
let string = "Hello Rainbow"
XCTAssertEqual(string.bold, "\u{001B}[1mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.dim, "\u{001B}[2mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.italic, "\u{001B}[3mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.underline, "\u{001B}[4mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.blink, "\u{001B}[5mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.swap, "\u{001B}[7mHello Rainbow\u{001B}[0m")
}
func testStringMultipleModes() {
let string = "Hello Rainbow"
XCTAssertEqual(string.red.onYellow, "\u{001B}[31;43mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onYellow.red, "\u{001B}[31;43mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.green.bold, "\u{001B}[32;1mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.onWhite.dim.blink, "\u{001B}[47;2;5mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.red.blue.onWhite, "\u{001B}[34;47mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.red.blue.green.blue.blue, "\u{001B}[34mHello Rainbow\u{001B}[0m")
}
func testStringClearMode() {
let string = "Hello Rainbow"
XCTAssertEqual(string.red.clearColor, "Hello Rainbow")
XCTAssertEqual(string.onYellow.clearBackgroundColor, "Hello Rainbow")
XCTAssertEqual(string.red.clearBackgroundColor, "\u{001B}[31mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.bold.clearStyles, "Hello Rainbow")
XCTAssertEqual(string.bold.clearColor, "\u{001B}[1mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.red.clearStyles, "\u{001B}[31mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.red.bold.clearStyles, "\u{001B}[31mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.red.bold.clearColor, "\u{001B}[1mHello Rainbow\u{001B}[0m")
XCTAssertEqual(string.bold.italic.clearStyles, "Hello Rainbow")
}
func testMultipartString() {
let text1 = "Hello "
let text2 = "Rainbow"
XCTAssertEqual(text1.red + text2.yellow, "\u{001B}[31mHello \u{001B}[0m\u{001B}[33mRainbow\u{001B}[0m")
XCTAssertEqual((text1.red + text2).yellow, "\u{001B}[31mHello \u{001B}[0m\u{001B}[33mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red)\(text2)".yellow, "\u{001B}[31mHello \u{001B}[0m\u{001B}[33mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red)\(text2.blue)".yellow, "\u{001B}[31mHello \u{001B}[0m\u{001B}[34mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red)inserted \(text2.blue)".yellow, "\u{001B}[31mHello \u{001B}[0m\u{001B}[33minserted \u{001B}[0m\u{001B}[34mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red)inserted \(text2.blue.underline)".yellow.bold, "\u{001B}[31;1mHello \u{001B}[0m\u{001B}[33;1minserted \u{001B}[0m\u{001B}[34;4;1mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red)\(text2.blue)".clearColor.yellow, "\u{001B}[33mHello Rainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red)\(text2.blue)".clearStyles.yellow, "\u{001B}[31mHello \u{001B}[0m\u{001B}[34mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red.underline)\(text2.blue.dim)".bold, "\u{001B}[31;4;1mHello \u{001B}[0m\u{001B}[34;2;1mRainbow\u{001B}[0m")
XCTAssertEqual("\(text1.red.underline)\(text2.blue.dim)".clearStyles.bold, "\u{001B}[31;1mHello \u{001B}[0m\u{001B}[34;1mRainbow\u{001B}[0m")
}
func testHexColorString() {
let text = "Hello Rainbow"
XCTAssertEqual(text.hex("#afafd7"), "\u{001B}[38;5;189mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.hex("#afafd7", to: .bit24), "\u{001B}[38;2;175;175;215mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.hex(0xafafd7), "\u{001B}[38;5;189mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.hex("fff"), "\u{001B}[38;5;231mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.onHex("#afafd7"), "\u{001B}[48;5;189mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.onHex("#afafd7", to: .bit24), "\u{001B}[48;2;175;175;215mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.onHex(0xafafd7), "\u{001B}[48;5;189mHello Rainbow\u{001B}[0m")
XCTAssertEqual(text.onHex("fff"), "\u{001B}[48;5;231mHello Rainbow\u{001B}[0m")
}
}
| 391642ab6617ccf822300c1abfcd1992 | 53.757576 | 185 | 0.673935 | false | true | false | false |
walkingsmarts/ReactiveCocoa | refs/heads/master | ReactiveCocoa/AppKit/NSControl.swift | mit | 1 | import ReactiveSwift
import enum Result.NoError
import AppKit
extension NSControl: ActionMessageSending {}
extension Reactive where Base: NSControl {
/// Sets whether the control is enabled.
public var isEnabled: BindingTarget<Bool> {
return makeBindingTarget { $0.isEnabled = $1 }
}
/// Sets the value of the control with an `NSAttributedString`.
public var attributedStringValue: BindingTarget<NSAttributedString> {
return makeBindingTarget { $0.attributedStringValue = $1 }
}
/// A signal of values in `NSAttributedString`, emitted by the control.
public var attributedStringValues: Signal<NSAttributedString, NoError> {
return proxy.invoked.map { $0.attributedStringValue }
}
/// Sets the value of the control with a `Bool`.
public var boolValue: BindingTarget<Bool> {
return makeBindingTarget { $0.integerValue = $1 ? NSOnState : NSOffState }
}
/// A signal of values in `Bool`, emitted by the control.
public var boolValues: Signal<Bool, NoError> {
return proxy.invoked.map { $0.integerValue != NSOffState }
}
/// Sets the value of the control with a `Double`.
public var doubleValue: BindingTarget<Double> {
return makeBindingTarget { $0.doubleValue = $1 }
}
/// A signal of values in `Double`, emitted by the control.
public var doubleValues: Signal<Double, NoError> {
return proxy.invoked.map { $0.doubleValue }
}
/// Sets the value of the control with a `Float`.
public var floatValue: BindingTarget<Float> {
return makeBindingTarget { $0.floatValue = $1 }
}
/// A signal of values in `Float`, emitted by the control.
public var floatValues: Signal<Float, NoError> {
return proxy.invoked.map { $0.floatValue }
}
/// Sets the value of the control with an `Int32`.
public var intValue: BindingTarget<Int32> {
return makeBindingTarget { $0.intValue = $1 }
}
/// A signal of values in `Int32`, emitted by the control.
public var intValues: Signal<Int32, NoError> {
return proxy.invoked.map { $0.intValue }
}
/// Sets the value of the control with an `Int`.
public var integerValue: BindingTarget<Int> {
return makeBindingTarget { $0.integerValue = $1 }
}
/// A signal of values in `Int`, emitted by the control.
public var integerValues: Signal<Int, NoError> {
return proxy.invoked.map { $0.integerValue }
}
/// Sets the value of the control.
public var objectValue: BindingTarget<Any?> {
return makeBindingTarget { $0.objectValue = $1 }
}
/// A signal of values in `Any?`, emitted by the control.
public var objectValues: Signal<Any?, NoError> {
return proxy.invoked.map { $0.objectValue }
}
/// Sets the value of the control with a `String`.
public var stringValue: BindingTarget<String> {
return makeBindingTarget { $0.stringValue = $1 }
}
/// A signal of values in `String`, emitted by the control.
public var stringValues: Signal<String, NoError> {
return proxy.invoked.map { $0.stringValue }
}
}
| 82150bd89215adb85b9a3e00b489f190 | 29.989362 | 76 | 0.715414 | false | false | false | false |
3DprintFIT/octoprint-ios-client | refs/heads/dev | BarsAroundMe/Pods/Nimble/Sources/Nimble/Adapters/NMBExpectation.swift | apache-2.0 | 41 | import Foundation
#if _runtime(_ObjC)
internal struct ObjCMatcherWrapper: Matcher {
let matcher: NMBMatcher
func matches(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.matches(
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
func doesNotMatch(_ actualExpression: Expression<NSObject>, failureMessage: FailureMessage) -> Bool {
return matcher.doesNotMatch(
({ try! actualExpression.evaluate() }),
failureMessage: failureMessage,
location: actualExpression.location)
}
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation: NSObject {
internal let _actualBlock: () -> NSObject!
internal var _negative: Bool
internal let _file: FileString
internal let _line: UInt
internal var _timeout: TimeInterval = 1.0
public init(actualBlock: @escaping () -> NSObject!, negative: Bool, file: FileString, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
private var expectValue: Expectation<NSObject> {
return expect(_file, line: _line) {
self._actualBlock() as NSObject?
}
}
public var withTimeout: (TimeInterval) -> NMBExpectation {
return ({ timeout in self._timeout = timeout
return self
})
}
public var to: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher))
})
}
public var toWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.to(ObjCMatcherWrapper(matcher: matcher), description: description)
})
}
public var toNot: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toNot(
ObjCMatcherWrapper(matcher: matcher)
)
})
}
public var toNotWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.toNot(
ObjCMatcherWrapper(matcher: matcher), description: description
)
})
}
public var notTo: (NMBMatcher) -> Void { return toNot }
public var notToWithDescription: (NMBMatcher, String) -> Void { return toNotWithDescription }
public var toEventually: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
})
}
public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.toEventually(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
})
}
public var toEventuallyNot: (NMBMatcher) -> Void {
return ({ matcher in
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: nil
)
})
}
public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
return ({ matcher, description in
self.expectValue.toEventuallyNot(
ObjCMatcherWrapper(matcher: matcher),
timeout: self._timeout,
description: description
)
})
}
public var toNotEventually: (NMBMatcher) -> Void { return toEventuallyNot }
public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void { return toEventuallyNotWithDescription }
public class func failWithMessage(_ message: String, file: FileString, line: UInt) {
fail(message, location: SourceLocation(file: file, line: line))
}
}
#endif
| c8d1a88310abc713289e35ccbedced94 | 30.694656 | 117 | 0.607177 | false | false | false | false |
Djecksan/MobiTask | refs/heads/master | MobiTask/Helpers/Extensions/UILabel+Extension.swift | mit | 1 | //
// UILabel+Extension.swift
// MobiTask
//
// Created by Evgenyi Tyulenev on 01.08.15.
// Copyright (c) 2015 VoltMobi. All rights reserved.
//
import UIKit
extension UILabel {
func setSpacing(spacing:CGFloat?) {
self.addAttributes(spacing, nFont: nil, line: nil)
}
func setLineHeight(line:CGFloat?) {
self.addAttributes(nil, nFont: nil, line: line)
}
func addAttributes(spacing:CGFloat?, line:CGFloat?) {
self.addAttributes(spacing, nFont: nil, line: line)
}
func addAttributes(spacing:CGFloat?, nFont:UIFont?, line:CGFloat?) {
let font = nFont ?? self.font
let string = NSAttributedString(string: self.text!, attributes:[NSFontAttributeName:font!])
let attrString = NSMutableAttributedString(attributedString: string)
let paraStyle = NSMutableParagraphStyle()
paraStyle.lineSpacing = line ?? 0
paraStyle.alignment = self.textAlignment
attrString.addAttributes([NSKernAttributeName : spacing ?? 0, NSParagraphStyleAttributeName:paraStyle], range: NSRange(location: 0,length: attrString.length))
self.attributedText = attrString
}
} | 5816ec46c84b596a7545eb25da76ee20 | 29.625 | 166 | 0.654412 | false | false | false | false |
brorbw/Helium | refs/heads/master | Helium/Helium/HeliumPanelController.swift | mit | 1 | //
// HeliumPanelController.swift
// Helium
//
// Created by Jaden Geller on 4/9/15.
// Copyright (c) 2015 Jaden Geller. All rights reserved.
//
import AppKit
let optionKeyCode: UInt16 = 58
class HeliumPanelController : NSWindowController {
fileprivate var webViewController: WebViewController {
get {
return self.window?.contentViewController as! WebViewController
}
}
fileprivate var mouseOver: Bool = false
fileprivate var alpha: CGFloat = 0.6 { //default
didSet {
updateTranslucency()
}
}
fileprivate var translucencyPreference: TranslucencyPreference = .always {
didSet {
updateTranslucency()
}
}
fileprivate var translucencyEnabled: Bool = false {
didSet {
updateTranslucency()
}
}
fileprivate enum TranslucencyPreference {
case always
case mouseOver
case mouseOutside
}
fileprivate var currentlyTranslucent: Bool = false {
didSet {
if !NSApplication.shared().isActive {
panel.ignoresMouseEvents = currentlyTranslucent
}
if currentlyTranslucent {
panel.animator().alphaValue = alpha
panel.isOpaque = false
}
else {
panel.isOpaque = true
panel.animator().alphaValue = 1
}
}
}
fileprivate var panel: NSPanel! {
get {
return (self.window as! NSPanel)
}
}
// MARK: Window lifecycle
override func windowDidLoad() {
panel.isFloatingPanel = true
NotificationCenter.default.addObserver(self, selector: #selector(HeliumPanelController.didBecomeActive), name: NSNotification.Name.NSApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(HeliumPanelController.willResignActive), name: NSNotification.Name.NSApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(HeliumPanelController.didUpdateTitle(_:)), name: NSNotification.Name(rawValue: "HeliumUpdateTitle"), object: nil)
setFloatOverFullScreenApps()
if let alpha = UserDefaults.standard.object(forKey: UserSetting.opacityPercentage.userDefaultsKey) {
didUpdateAlpha(CGFloat(alpha as! Int))
}
}
// MARK : Mouse events
override func mouseEntered(with theEvent: NSEvent) {
mouseOver = true
updateTranslucency()
}
override func mouseExited(with theEvent: NSEvent) {
mouseOver = false
updateTranslucency()
}
// MARK : Translucency
fileprivate func updateTranslucency() {
currentlyTranslucent = shouldBeTranslucent()
}
fileprivate func shouldBeTranslucent() -> Bool {
/* Implicit Arguments
* - mouseOver
* - translucencyPreference
* - tranlucencyEnalbed
*/
guard translucencyEnabled else { return false }
switch translucencyPreference {
case .always:
return true
case .mouseOver:
return mouseOver
case .mouseOutside:
return !mouseOver
}
}
fileprivate func setFloatOverFullScreenApps() {
if UserDefaults.standard.bool(forKey: UserSetting.disabledFullScreenFloat.userDefaultsKey) {
panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary]
} else {
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
}
}
//MARK: IBActions
fileprivate func disabledAllMouseOverPreferences(_ allMenus: [NSMenuItem]) {
// GROSS HARD CODED
for x in allMenus.dropFirst(2) {
x.state = NSOffState
}
}
@IBAction fileprivate func alwaysPreferencePress(_ sender: NSMenuItem) {
disabledAllMouseOverPreferences(sender.menu!.items)
translucencyPreference = .always
sender.state = NSOnState
}
@IBAction fileprivate func overPreferencePress(_ sender: NSMenuItem) {
disabledAllMouseOverPreferences(sender.menu!.items)
translucencyPreference = .mouseOver
sender.state = NSOnState
}
@IBAction fileprivate func outsidePreferencePress(_ sender: NSMenuItem) {
disabledAllMouseOverPreferences(sender.menu!.items)
translucencyPreference = .mouseOutside
sender.state = NSOnState
}
@IBAction fileprivate func translucencyPress(_ sender: NSMenuItem) {
if sender.state == NSOnState {
sender.state = NSOffState
didDisableTranslucency()
}
else {
sender.state = NSOnState
didEnableTranslucency()
}
}
@IBAction fileprivate func percentagePress(_ sender: NSMenuItem) {
for button in sender.menu!.items{
(button ).state = NSOffState
}
sender.state = NSOnState
let value = sender.title.substring(to: sender.title.characters.index(sender.title.endIndex, offsetBy: -1))
if let alpha = Int(value) {
didUpdateAlpha(CGFloat(alpha))
UserDefaults.standard.set(alpha, forKey: UserSetting.opacityPercentage.userDefaultsKey)
}
}
@IBAction fileprivate func openLocationPress(_ sender: AnyObject) {
didRequestLocation()
}
@IBAction fileprivate func openFilePress(_ sender: AnyObject) {
didRequestFile()
}
@IBAction fileprivate func floatOverFullScreenAppsToggled(_ sender: NSMenuItem) {
sender.state = (sender.state == NSOnState) ? NSOffState : NSOnState
UserDefaults.standard.set((sender.state == NSOffState), forKey: UserSetting.disabledFullScreenFloat.userDefaultsKey)
setFloatOverFullScreenApps()
}
@IBAction fileprivate func hideTitle(_ sender: NSMenuItem) {
if sender.state == NSOnState {
sender.state = NSOffState
panel.styleMask = NSBorderlessWindowMask
}
else {
sender.state = NSOnState
panel.styleMask = NSWindowStyleMask(rawValue: 8345)
}
}
@IBAction func setHomePage(_ sender: AnyObject){
didRequestChangeHomepage()
}
//MARK: Actual functionality
@objc fileprivate func didUpdateTitle(_ notification: Notification) {
if let title = notification.object as? String {
panel.title = title
}
}
fileprivate func didRequestFile() {
let open = NSOpenPanel()
open.allowsMultipleSelection = false
open.canChooseFiles = true
open.canChooseDirectories = false
if open.runModal() == NSModalResponseOK {
if let url = open.url {
webViewController.loadURL(url)
}
}
}
fileprivate func didRequestLocation() {
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = "Enter Destination URL"
let urlField = NSTextField()
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
urlField.lineBreakMode = NSLineBreakMode.byTruncatingHead
urlField.usesSingleLineMode = true
alert.accessoryView = urlField
//alert.accessoryView!.becomeFirstResponder()
alert.addButton(withTitle: "Load")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!, completionHandler: { response in
if response == NSAlertFirstButtonReturn {
// Load
let text = (alert.accessoryView as! NSTextField).stringValue
self.webViewController.loadAlmostURL(text)
}
})
urlField.becomeFirstResponder()
}
func didRequestChangeHomepage(){
let alert = NSAlert()
alert.alertStyle = NSAlertStyle.informational
alert.messageText = "Enter new Home Page URL"
let urlField = NSTextField()
urlField.frame = NSRect(x: 0, y: 0, width: 300, height: 20)
urlField.lineBreakMode = NSLineBreakMode.byTruncatingHead
urlField.usesSingleLineMode = true
alert.accessoryView = urlField
alert.addButton(withTitle: "Set")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.window!, completionHandler: { response in
if response == NSAlertFirstButtonReturn {
var text = (alert.accessoryView as! NSTextField).stringValue
// Add prefix if necessary
if !(text.lowercased().hasPrefix("http://") || text.lowercased().hasPrefix("https://")) {
text = "http://" + text
}
// Save to defaults if valid. Else, use Helium default page
if self.validateURL(text) {
UserDefaults.standard.set(text, forKey: UserSetting.homePageURL.userDefaultsKey)
}
else{
UserDefaults.standard.set("https://cdn.rawgit.com/brorbw/Helium/master/helium_start.html", forKey: UserSetting.homePageURL.userDefaultsKey)
}
// Load new Home page
self.webViewController.loadAlmostURL(UserDefaults.standard.string(forKey: UserSetting.homePageURL.userDefaultsKey)!)
}
})
}
//
func validateURL (_ stringURL : String) -> Bool {
let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
return predicate.evaluate(with: stringURL)
}
@objc fileprivate func didBecomeActive() {
panel.ignoresMouseEvents = false
}
@objc fileprivate func willResignActive() {
if currentlyTranslucent {
panel.ignoresMouseEvents = true
}
}
fileprivate func didEnableTranslucency() {
translucencyEnabled = true
}
fileprivate func didDisableTranslucency() {
translucencyEnabled = false
}
fileprivate func didUpdateAlpha(_ newAlpha: CGFloat) {
alpha = newAlpha / 100
}
}
| ff205bf5303c03a7ff87cd6c4038bec2 | 31.396285 | 186 | 0.610856 | false | false | false | false |
18775134221/SwiftBase | refs/heads/develop | 02-observable-pg/challenge/Challenge1-Starter/Pods/RxSwift/RxSwift/Observables/Implementations/Do.swift | apache-2.0 | 57 | //
// Do.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class DoSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = Do<Element>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
do {
try _parent._eventHandler(event)
forwardOn(event)
if event.isStopEvent {
dispose()
}
}
catch let error {
forwardOn(.error(error))
dispose()
}
}
}
class Do<Element> : Producer<Element> {
typealias EventHandler = (Event<Element>) throws -> Void
fileprivate let _source: Observable<Element>
fileprivate let _eventHandler: EventHandler
fileprivate let _onSubscribe: (() -> ())?
fileprivate let _onDispose: (() -> ())?
init(source: Observable<Element>, eventHandler: @escaping EventHandler, onSubscribe: (() -> ())?, onDispose: (() -> ())?) {
_source = source
_eventHandler = eventHandler
_onSubscribe = onSubscribe
_onDispose = onDispose
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
_onSubscribe?()
let sink = DoSink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
let onDispose = _onDispose
let allSubscriptions = Disposables.create {
subscription.dispose()
onDispose?()
}
return (sink: sink, subscription: allSubscriptions)
}
}
| cd533348300e9ce1affd5d40b91376da | 28.666667 | 144 | 0.59069 | false | false | false | false |
anas10/Monumap | refs/heads/develop | Monumap/ViewControllers/NearbyViewController.swift | apache-2.0 | 1 | //
// NearbyViewController.swift
// Monumap
//
// Created by Anas Ait Ali on 12/03/2017.
// Copyright © 2017 Anas Ait Ali. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import MapKit
import CCHMapClusterController
class NearbyViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var mapView: MKMapView!
var viewModel: NearbyViewModel!
var viewModelConstructor: NearbyViewModelConstructorType!
var mapViewClusterModel: MapViewClusterModel!
let visibleMonuments : Variable<[Monument]> = Variable([])
private var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
viewModel = viewModelConstructor(self)
mapViewClusterModel = MapViewClusterModel(mapView: self.mapView)
mapView.delegate = self
// Fetch the monuments
viewModel.getMonuments().subscribe().disposed(by: disposeBag)
self.visibleMonuments
.asObservable()
.bind(to: collectionView.rx.items) { (collectionView, row, element) in
let indexPath = IndexPath(row: row, section: 0)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "siteCellIdentifier", for: indexPath) as! MonumentCollectionViewCell
cell.configure(monument: element)
return cell
}
.disposed(by: disposeBag)
viewModel
.dataManager
.monuments
.asObservable()
.subscribe(onNext: { monuments in
self.mapViewClusterModel.addAnnotations(monuments.map { MonumentAnnotation(monument: $0) }, withCompletionHandler: nil)
}).disposed(by: disposeBag)
}
func getVisibleMonuments(mapView: MKMapView) -> [Monument] {
return mapView
.annotations(in: mapView.visibleMapRect)
.compactMap { ($0 as? CCHMapClusterAnnotation)?.annotations as? Set<MonumentAnnotation> }
.flatMap { $0 }
.compactMap { $0.monument }
}
}
extension NearbyViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
return self.mapViewClusterModel.viewFor(annotation: annotation)
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
self.mapViewClusterModel.selectCluster(view: view)
if let monument = getMonumentFrom(view: view),
let pos = self.visibleMonuments.value.firstIndex(of: monument) {
self.collectionView
.scrollToItem(at: IndexPath(item: pos, section: 0),
at: .left,
animated: true)
} else {
print("Couldn't find monument")
}
}
func mapViewDidFinishLoadingMap(_ mapView: MKMapView) {
self.visibleMonuments.value = getVisibleMonuments(mapView: mapView)
}
func mapViewDidFailLoadingMap(_ mapView: MKMapView, withError error: Error) {
self.visibleMonuments.value = getVisibleMonuments(mapView: mapView)
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
self.visibleMonuments.value = getVisibleMonuments(mapView: mapView)
}
}
| 1e964d32f5b6e3ad6385c1115052a6ee | 31.990099 | 151 | 0.655762 | false | false | false | false |
rnystrom/GitHawk | refs/heads/master | Pods/ContextMenu/ContextMenu/CGRect+DominantCorner.swift | mit | 1 | //
// CGRect+DominantCorner.swift
// ContextMenu
//
// Created by Ryan Nystrom on 5/28/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import UIKit
extension CGRect {
func dominantCorner(in rect: CGRect) -> SourceViewCorner? {
let corners: [SourceViewCorner] = [
SourceViewCorner(rect: rect, position: .topLeft),
SourceViewCorner(rect: rect, position: .topRight),
SourceViewCorner(rect: rect, position: .bottomLeft),
SourceViewCorner(rect: rect, position: .bottomRight),
]
var maxArea: CGFloat = 0
var maxCorner: SourceViewCorner? = nil
for corner in corners {
let area = self.area(corner: corner)
if area > maxArea {
maxArea = area
maxCorner = corner
}
}
return maxCorner
}
}
| 89542d1a28a57aa6095e903727a246db | 25.787879 | 65 | 0.581448 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | Pods/SwifterSwift/Source/Extensions/Cocoa/NSAttributedStringExtensions.swift | mit | 2 | //
// NSAttributedStringExtensions.swift
// SSTests
//
// Created by Omar Albeik on 26/11/2016.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
// MARK: - Properties
public extension NSAttributedString {
#if os(iOS)
/// SwifterSwift: Bolded string.
public var bolded: NSAttributedString {
return applying(attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
/// SwifterSwift: Underlined string.
public var underlined: NSAttributedString {
return applying(attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
}
#if os(iOS)
/// SwifterSwift: Italicized string.
public var italicized: NSAttributedString {
return applying(attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
}
#endif
/// SwifterSwift: Struckthrough string.
public var struckthrough: NSAttributedString {
return applying(attributes: [NSStrikethroughStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue as Int)])
}
}
// MARK: - Methods
public extension NSAttributedString {
/// SwifterSwift: Applies given attributes to the new instance
/// of NSAttributedString initialized with self object
///
/// - Parameter attributes: Dictionary of attributes
/// - Returns: NSAttributedString with applied attributes
fileprivate func applying(attributes: [String: Any]) -> NSAttributedString {
let copy = NSMutableAttributedString(attributedString: self)
let range = (string as NSString).range(of: string)
copy.addAttributes(attributes, range: range)
return copy
}
#if os(macOS)
/// SwifterSwift: Add color to NSAttributedString.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString colored with given color.
public func colored(with color: NSColor) -> NSAttributedString {
return applying(attributes: [NSForegroundColorAttributeName: color])
}
#else
/// SwifterSwift: Add color to NSAttributedString.
///
/// - Parameter color: text color.
/// - Returns: a NSAttributedString colored with given color.
public func colored(with color: UIColor) -> NSAttributedString {
return applying(attributes: [NSForegroundColorAttributeName: color])
}
#endif
}
// MARK: - Operators
public extension NSAttributedString {
/// SwifterSwift: Add a NSAttributedString to another NSAttributedString.
///
/// - Parameters:
/// - lhs: NSAttributedString to add to.
/// - rhs: NSAttributedString to add.
public static func += (lhs: inout NSAttributedString, rhs: NSAttributedString) {
let ns = NSMutableAttributedString(attributedString: lhs)
ns.append(rhs)
lhs = ns
}
}
| 2ec7cd3661f69e4a556cd7a704e68df2 | 28.586957 | 129 | 0.747612 | false | false | false | false |
khoogheem/GenesisKit | refs/heads/master | Shared/Internal/Reachability+Internal.swift | mit | 1 | //
// Reachability+Internal.swift
// GenesisKit
//
// Created by Kevin A. Hoogheem on 10/26/14.
// Copyright (c) 2014 Kevin A. Hoogheem. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import SystemConfiguration
let ReachabilityChangedNotification = "ReachabilityChangedNotification"
/**
Internal Reachability Class to determine the reachability of network. Works much like Apple's Reachability.
Note: Does not actually check if a hostname is accepting data.. but if it could be reachable.
*/
internal class Reachability {
//TODO: Add in the Start Notifier/stop Notifier
//TODO: Make it a shared instance
let kShouldPrintReachabilityFlags = true
enum NetworkStatus {
case NotReachable
case ReachableViaWiFi
case ReachableViaWWAN
case ReachableViaEthernet
}
private var status:NetworkStatus = .NotReachable
private var reachabilityRef: SCNetworkReachability?
private var reachabilitySerialQueue: dispatch_queue_t?
private var reachabilityObject: AnyObject?
var alwaysReturnWIFIStatus: Bool = false
init(reachabilityRef: SCNetworkReachability) {
self.reachabilityRef = reachabilityRef;
}
convenience init(hostname: String) {
let ref = SCNetworkReachabilityCreateWithName(nil, (hostname as NSString).UTF8String).takeRetainedValue()
self.init(reachabilityRef: ref)
}
convenience init(hostAddress: UnsafePointer<sockaddr>) {
let ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, hostAddress).takeRetainedValue()
self.init(reachabilityRef: ref)
}
convenience init() {
var addr = sockaddr_in(sin_len: __uint8_t(sizeof(sockaddr_in)), sin_family: sa_family_t(AF_INET),
sin_port: in_port_t(0), sin_addr: in_addr(s_addr: inet_addr("0.0.0.0")), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
var sock_addr = sockaddr(sa_len: 0, sa_family: 0, sa_data: (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
memcpy(&sock_addr, &addr, Int(sizeof(sockaddr_in)))
let ref = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, &sock_addr).takeRetainedValue()
self.init(reachabilityRef: ref)
}
var currentReachabilityStatus:NetworkStatus {
if reachabilityFlags != 0 {
if alwaysReturnWIFIStatus {
status = localWiFiStatusForFlags(reachabilityFlags)
}else {
status = networkStatusForFlags(reachabilityFlags)
}
}
return status
}
func PrintReachabilityFlags(flags: SCNetworkReachabilityFlags, comment: String) {
if kShouldPrintReachabilityFlags {
#if os(iOS)
let W = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN)) ? "W" : "-"
#elseif os(OSX)
let W = "X"
#endif
let R = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable)) ? "R" : "-"
let t = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection)) ? "t" : "-"
let c = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired)) ? "c" : "-"
let C = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic)) ? "C" : "-"
let i = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired)) ? "i" : "-"
let D = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand)) ? "D" : "-"
let l = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress)) ? "l" : "-"
let d = checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect)) ? "d" : "-"
NSLog("Reachability Flag Status: \(W)\(R) \(t)\(c)\(C)\(i)\(D)\(l)\(d) Comment: \(comment)")
}
}
func localWiFiStatusForFlags(flags:SCNetworkReachabilityFlags) -> NetworkStatus {
var returnValue: NetworkStatus = .NotReachable
PrintReachabilityFlags(flags, comment: "networkStatusForWIFIFlags");
if checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable)) && checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect)) {
returnValue = .ReachableViaWiFi
}
return returnValue
}
func networkStatusForFlags(flags:SCNetworkReachabilityFlags) -> NetworkStatus {
PrintReachabilityFlags(flags, comment: "networkStatusForFlags");
var returnValue: NetworkStatus = .NotReachable
if (checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable)) == false){
// The target host is not reachable.
return returnValue
}
if checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand)) ||
checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic)) {
/*
... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
*/
if (checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable)) == false) {
/*
... and no [user] intervention is needed...
*/
returnValue = .ReachableViaWiFi;
}
}
#if os(iOS)
if ((Int(flags) & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
/*
... but WWAN connections are OK if the calling application is using the CFNetwork APIs.
*/
returnValue = .ReachableViaWWAN;
}
#elseif os(OSX)
if (checkFlag(SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable))) {
/*
... on OS lets just cheach Reacable.
*/
returnValue = .ReachableViaEthernet;
}
#endif
return returnValue
}
func connectedToNetwork() -> Bool {
PrintReachabilityFlags(reachabilityFlags, comment: "networkStatusForFlags");
var needsConnection: Bool {
return Int(reachabilityFlags) & kSCNetworkFlagsConnectionRequired == kSCNetworkFlagsConnectionRequired
}
var isReachable: Bool {
return Int(reachabilityFlags) & kSCNetworkReachabilityFlagsReachable == kSCNetworkReachabilityFlagsReachable
}
return (isReachable && !needsConnection) ? true : false
}
func isReachable() -> Bool {
switch currentReachabilityStatus {
case .NotReachable:
return false
case .ReachableViaWiFi:
fallthrough
case .ReachableViaWWAN:
fallthrough
case .ReachableViaEthernet:
return true
default:
return false
}
}
deinit {
reachabilityRef = nil
}
}
//Mark: - private
private extension Reachability {
private var reachabilityFlags: SCNetworkReachabilityFlags {
var flags: SCNetworkReachabilityFlags = 0
let gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &flags) != 0
if gotFlags {
return flags
}
return 0
}
private func checkFlag(flag: SCNetworkReachabilityFlags) -> Bool {
let iOS = false
#if os(OSX)
switch flag {
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect) != 0 {
return true
}
default:
return false
}
#else
switch flag {
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsWWAN) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsTransientConnection) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionRequired) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsInterventionRequired) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsLocalAddress) != 0 {
return true
}
case SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect):
if reachabilityFlags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsIsDirect) != 0 {
return true
}
default:
return false
}
#endif
return false
}
} | df218091b1c59eea9035ce6d5f4e4ff9 | 35.476038 | 160 | 0.760161 | false | false | false | false |
KrishMunot/swift | refs/heads/master | test/SourceKit/DocSupport/Inputs/main.swift | apache-2.0 | 3 | var globV: Int
class CC0 {
var x: Int = 0
}
class CC {
var instV: CC0
func meth() {}
func instanceFunc0(_ a: Int, b: Float) -> Int {
return 0
}
func instanceFunc1(a x: Int, b y: Float) -> Int {
return 0
}
class func smeth() {}
init() {
instV = CC0()
}
}
func +(a : CC, b: CC0) -> CC {
return a
}
struct S {
func meth() {}
static func smeth() {}
}
enum E {
case EElem
}
protocol Prot {
func protMeth(_ a: Prot)
}
func foo(_ a: CC, b: E) {
var b = b
_ = b
globV = 0
a + a.instV
a.meth()
CC.smeth()
b = E.EElem
var _: CC
class LocalCC {}
var _: LocalCC
}
typealias CCAlias = CC
extension CC : Prot {
func meth2(_ x: CCAlias) {}
func protMeth(_ a: Prot) {}
var extV : Int { return 0 }
}
class SubCC : CC {}
var globV2: SubCC
class ComputedProperty {
var value : Int {
get {
let result = 0
return result
}
set(newVal) {
// completely ignore it!
}
}
var readOnly : Int { return 0 }
}
class BC2 {
func protMeth(_ a: Prot) {}
}
class SubC2 : BC2, Prot {
override func protMeth(_ a: Prot) {}
}
class CC2 {
subscript (i : Int) -> Int {
get {
return i
}
set(vvv) {
vvv+1
}
}
}
func test1(_ cp: ComputedProperty, sub: CC2) {
var x = cp.value
x = cp.readOnly
cp.value = x
cp.value += 1
x = sub[0]
sub[0] = x
sub[0] += 1
}
struct S2 {
func sfoo() {}
}
var globReadOnly : S2 {
get {
return S2();
}
}
func test2() {
globReadOnly.sfoo()
}
class B1 {
func foo() {}
}
class SB1 : B1 {
override func foo() {
foo()
self.foo()
super.foo()
}
}
func test3(_ c: SB1, s: S2) {
test2()
c.foo()
s.sfoo()
}
func test4(_ a: inout Int) {}
protocol Prot2 {
associatedtype Element
var p : Int { get }
func foo()
}
struct S1 : Prot2 {
typealias Element = Int
var p : Int = 0
func foo() {}
}
func genfoo<T : Prot2 where T.Element == Int>(_ x: T) {}
protocol Prot3 {
func +(x: Self, y: Self)
}
| 4aec2ff4eb1efa68b51dc082dd5f9d2f | 11.851613 | 56 | 0.537149 | false | false | false | false |
russelhampton05/MenMew | refs/heads/master | App Prototypes/Menu_Server_App_Prototype_001/Menu_Server_App_Prototype_001/RTableCell.swift | mit | 1 | //
// RTableCell.swift
// Menu_Server_App_Prototype_001
//
// Created by Jon Calanio on 10/3/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import UIKit
class RTableCell: UITableViewCell {
//IBOutlets
@IBOutlet weak var tableLabel: UILabel!
@IBOutlet weak var ticketLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
loadTheme()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func loadTheme() {
//Background and Tint
self.backgroundColor = currentTheme!.primary!
self.tintColor = currentTheme!.highlight!
//Labels
tableLabel.textColor = currentTheme!.highlight!
ticketLabel.textColor = currentTheme!.highlight!
statusLabel.textColor = currentTheme!.highlight!
dateLabel.textColor = currentTheme!.highlight!
//Buttons
}
}
| b2a4adedc3c1b9f27cdad1dfd465ef0a | 25.422222 | 65 | 0.631623 | false | false | false | false |
d4rkl0rd3r3b05/Data_Structure_And_Algorithm | refs/heads/master | LeetCode_AddTwoLinkedList.swift | mit | 1 | import Foundation
public class ListNode<T> : NSObject{
var nodeValue : T
var next : ListNode?
init(value : T) {
self.nodeValue = value
}
override public var description: String {
get{
return "\(self.nodeValue)->" + (self.next != nil ? self.next!.description : "NULL")
}
}
}
public class LinkedList<T> {
public var sourceElement : ListNode<T>?
public init(array : [T]) {
var previosNode : ListNode<T>?
for currentElement in array {
if self.sourceElement == nil {
self.sourceElement = ListNode(value: currentElement)
previosNode = self.sourceElement
}
else{
previosNode?.next = ListNode(value: currentElement)
previosNode = previosNode?.next
}
}
}
public static func addTwoList(firstList : ListNode<Int>?, secondList : ListNode<Int>?) -> ListNode<Int>? {
var solutionList : ListNode<Int>?
guard firstList != nil || secondList != nil else{
return nil
}
if firstList != nil {
if secondList != nil {
let sum = (firstList!.nodeValue + secondList!.nodeValue) % 10
let carryBalance = (firstList!.nodeValue + secondList!.nodeValue) / 10
var nextNode = secondList!.next
if carryBalance > 0 {
if nextNode == nil {
nextNode = ListNode(value: carryBalance)
}else{
nextNode!.nodeValue += carryBalance
}
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: firstList!.next, secondList: nextNode)
}
else {
let sum = firstList!.nodeValue % 10
let carryBalance = firstList!.nodeValue / 10
var nextNode : ListNode<Int>?
if carryBalance > 0 {
nextNode = ListNode(value: carryBalance)
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: firstList!.next, secondList: nextNode)
}
}else {
let sum = secondList!.nodeValue % 10
let carryBalance = secondList!.nodeValue / 10
var nextNode : ListNode<Int>?
if carryBalance > 0 {
nextNode = ListNode(value: carryBalance)
}
solutionList = ListNode(value: sum)
solutionList!.next = addTwoList(firstList: nextNode, secondList: secondList!.next)
}
return solutionList
}
}
| e98ce859b113bceff4b646ed1eb58094 | 32.666667 | 110 | 0.50884 | false | false | false | false |
RaviiOS/Swift_ReusableCode | refs/heads/master | RKSwift3Plus/RKSwift3Plus/Extensions/UIDevice.swift | mit | 1 |
import Foundation
import UIKit
/**
These extensions have the intention to return if the current device has certain size or not.
*/
public extension UIDevice {
func maxScreenLength() -> CGFloat {
let bounds = UIScreen.main.bounds
return max(bounds.width, bounds.height)
}
func iPhone4() -> Bool {
return maxScreenLength() == 480
}
func iPhone5() -> Bool {
return maxScreenLength() == 568
}
func iPhone6or7() -> Bool {
return maxScreenLength() == 667
}
func iPhone6or7Plus() -> Bool {
return maxScreenLength() == 736
}
/**
Resize a font according to current device. Works for iPhone apps only. The desired font size will be multiplied by the coefficient for the corresponding current device.
All coefficients have reasonable default values.
- parameter size: Desired font size for iPhone6 Plus device type (or any other with the same size)
- parameter q6: iPhone6 coefficient
- parameter q5: iPhone5 coefficient
- parameter q4: iPhone4 coefficient
- returns: The correctly resized font size
*/
func fontSizeForDevice(_ size: CGFloat, q6: CGFloat = 0.94, q5: CGFloat = 0.86, q4: CGFloat = 0.80) -> CGFloat {
if iPhone4() {
return max(10, size * q4)
} else if iPhone5() {
return max(10, size * q5)
} else if iPhone6or7() {
return max(10, size * q6)
}
return size
}
}
/**
Scale a value for a vertical constraint constant depending on the current device. Works for iPhone apps only. All coefficients have reasonable default values for vertical constraints
- parameter value: Desired value for iPhone6 Plus device type (or any other with the same size)
- parameter q6: iPhone6 coefficient
- parameter q5: iPhone5 coefficient
- parameter q4: iPhone4 coefficient
- returns: The correctly resized constraint value
*/
public func suggestedVerticalConstraint(_ value: CGFloat, q6: CGFloat = 0.9, q5: CGFloat = 0.77, q4: CGFloat = 0.65) -> CGFloat {
if UIDevice.current.iPhone4() {
return ceil(value * q4)
} else if UIDevice.current.iPhone5() {
return ceil(value * q5)
} else if UIDevice.current.iPhone6or7() {
return ceil(value * q6)
} else {
return value
}
}
/**
Scale a value for a horizontal constraint constant depending on the current device. Works for iPhone apps only. All coefficients have reasonable default values for horizontal constraints
- parameter value: Desired value for iPhone6 Plus device type (or any other with the same size)
- parameter q6: iPhone6 coefficient
- parameter q5: iPhone5 coefficient
- parameter q4: iPhone4 coefficient
- returns: The correctly resized constraint value
*/
public func suggestedHorizontalConstraint(_ value: CGFloat, q6: CGFloat = 0.9, q5: CGFloat = 0.77, q4: CGFloat = 0.77) -> CGFloat {
if UIDevice.current.iPhone4() {
return ceil(value * q4)
} else if UIDevice.current.iPhone5() {
return ceil(value * q5)
} else if UIDevice.current.iPhone6or7() {
return ceil(value * q6)
} else {
return value
}
}
| 317ffc96db77131efcb6a03ea718db89 | 32.768421 | 187 | 0.663965 | false | false | false | false |
mchandrra/Pitch-Perfect-iOS-Swift | refs/heads/master | Pitch Perfect/RecordSoundsViewController.swift | apache-2.0 | 1 | //
// RecordSoundsViewController.swift
// Pitch Perfect
//
// Created by Sri Chandra Mallipeddi on 2/16/16.
// Copyright © 2016 Sri Chandra Mallipeddi. All rights reserved.
//
import UIKit
import AVFoundation
class RecordSoundsViewController: UIViewController, AVAudioRecorderDelegate {
@IBOutlet weak var recordingInProgress: UILabel!
@IBOutlet weak var stopButton: UIButton!
@IBOutlet weak var recordButton: UIButton!
var audioRecorder:AVAudioRecorder!
var recordedAudio:RecordedAudio!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
stopButton.hidden = true
recordButton.enabled = true
}
@IBAction func recordAudio(sender: AnyObject) {
stopButton.hidden = false
recordingInProgress.hidden = false
recordButton.enabled = false
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
//let currentDateTime = NSDate()
//let formatter = NSDateFormatter()
//formatter.dateFormat = "ddMMyyyy-HHmmss"
//let recordingName = formatter.stringFromDate(currentDateTime)+".wav"
let recordingName = "my_audio.wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)
//setup audio session
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
//Initialize and prepare the recorder
try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])
audioRecorder.delegate = self
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
if(flag){
recordedAudio = RecordedAudio()
recordedAudio.filePathUrl = recorder.url
recordedAudio.title = recorder.url.lastPathComponent
//Move to the next scene aka perform segue
self.performSegueWithIdentifier("stopRecording", sender: recordedAudio)
}else{
print("Recording was not successful")
recordButton.enabled = true
stopButton.hidden = true
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if(segue.identifier == "stopRecording") {
let playSoundsVC:PlaySoundsViewController = segue.destinationViewController as! PlaySoundsViewController
let data = sender as! RecordedAudio
playSoundsVC.receivedAudio = data
}
}
@IBAction func stopAudio(sender: AnyObject) {
recordingInProgress.hidden = true
//recordButton.enabled = true
audioRecorder.stop()
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
}
| 30b85f141d959212a7e2d19707457840 | 34.073684 | 116 | 0.666567 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | refs/heads/dev | byuSuite/Apps/YTime/controller/YTimePunchesViewController.swift | apache-2.0 | 1 | //
// YTimePunchesViewController.swift
// byuSuite
//
// Created by Eric Romrell on 5/18/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
private let DATE_FORMAT = DateFormatter.defaultDateFormat("h:mm a")
private let DELETE_DATE_FORMAT = DateFormatter.defaultDateFormat("yyyy-MM-dd")
private let HEIGHT_TO_HIDE_TOOLBAR: CGFloat = -44.0
private let PUNCH_CELL_ID = "PunchCell"
private let EXCEPTION_CELL_ID = "ExceptionCell"
private let DELETABLE_CELL_ID = "DeletableCell"
class YTimePunchesViewController: ByuTableDataViewController, UITextFieldDelegate, CLLocationManagerDelegate {
//Outlets
@IBOutlet private weak var noDataLabel: UILabel!
@IBOutlet private weak var spinner: UIActivityIndicatorView!
@IBOutlet private weak var toolbarHeightToBottomConstraint: NSLayoutConstraint!
@IBOutlet private weak var toolbar: UIToolbar!
//Public properties
var employeeRecord: Int!
var punches: [YTimePunch]!
var selectedDate: Date!
//Private properties
private var currentlyEditing: (UIDatePicker, YTimeExceptionTableViewCell?)? //The date picker and cell that the user is editing
private var punchesToSave = [YTimeExceptionTableViewCell: YTimePunch]() {
didSet {
toolbarHeightToBottomConstraint.constant = punchesToSave.count > 0 ? 0 : HEIGHT_TO_HIDE_TOOLBAR
toolbar.isHidden = punchesToSave.count == 0
}
}
private var totalHours: String?
private var locationManager: CLLocationManager?
private var punchLocation: CLLocation?
private var exceptionCellCount = 0
override func viewDidLoad() {
super.viewDidLoad()
super.title = DateFormatter.defaultDateFormat("EEE MMM d, yyyy").string(from: selectedDate)
if punches.count == 0 {
tableView.isHidden = true
noDataLabel.isHidden = false
} else {
loadTableData()
}
}
deinit {
locationManager?.delegate = nil
}
//MARK: UITableViewDataSource callbacks
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return totalHours
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = tableData.row(forIndexPath: indexPath)
if row.cellId == EXCEPTION_CELL_ID, let cell = tableData.dequeueCell(forTableView: tableView, atIndexPath: indexPath) as? YTimeExceptionTableViewCell {
//If this is an exception, load up the time proposed to correct the exception into the textfield.
cell.textField.text = DATE_FORMAT.string(fromOptional: punches[indexPath.row].punchTime)
cell.rightDetailTextLabel.text = row.detailText
return cell
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
var actions = [UITableViewRowAction]()
if tableData.cellId(forIndexPath: indexPath) == DELETABLE_CELL_ID {
actions = [UITableViewRowAction(style: .destructive, title: "Delete", handler: { (_, _) in
if let punch: YTimePunch = self.tableData.object(forIndexPath: indexPath) {
self.deletePunch(punch, indexPath: indexPath)
}
})]
}
return actions
}
//MARK: UITextFieldDelegate callbacks
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
//The text field's first super view is the cell's content view, not the cell itself
let currentCell = textField.superview?.superview as? YTimeExceptionTableViewCell
//Create a time picker and set it as the inputView of the text field
let datePicker = UIDatePicker()
datePicker.datePickerMode = .time
//Set min and max times on the time picker
if let currentCell = currentCell, let indexPath = tableView.indexPath(for: currentCell) {
let calendar = Calendar.defaultCalendar()
//Set minimumDate to startOfToday. Will be overwritten if another punch exists before the exception
datePicker.minimumDate = calendar.startOfDay(for: selectedDate)
//Set maximumDate to the end of today. Will be overwritten if another punch exists after the exception
datePicker.maximumDate = calendar.endOfDay(for: selectedDate)
//If there are punches before/after the exception, the min/max should be set to those punch times
let indexOfPunch = indexPath.row
if indexOfPunch > 0, let punchTime = punches[indexOfPunch - 1].punchTime {
datePicker.minimumDate = calendar.combine(date: selectedDate, time: punchTime)
}
if indexOfPunch < punches.count - 1, let punchTime = punches[indexOfPunch + 1].punchTime {
datePicker.maximumDate = calendar.combine(date: selectedDate, time: punchTime)
}
}
textField.inputView = datePicker
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel(sender:)))
let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let submitButton = UIBarButtonItem(title: "OK", style: .done, target: self, action: #selector(save(sender:)))
let toolbar = UIToolbar()
toolbar.items = [cancelButton, flex, submitButton]
toolbar.sizeToFit()
toolbar.tintColor = UIColor.byuToolbarTint
textField.inputAccessoryView = toolbar
currentlyEditing = (datePicker, currentCell)
return true
}
//MARK: CLLocationMangerDelegate callbacks
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
YTimeRootViewController.yTimeLocationManager(manager, didChangeAuthorization: status, for: self, deniedCompletionHandler: {
self.cancelAllPunches(self)
})
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
punchLocation = locations.last
manager.stopUpdatingLocation()
submitAllPunchesIfReady()
}
//MARK: Listeners
@objc func save(sender: Any) {
let cell = currentlyEditing?.1
//Hide the keyboard
cell?.textField.resignFirstResponder()
guard let exceptionCell = cell, let indexPath = self.tableView.indexPath(for: exceptionCell) else { return }
let punchTime = self.getPunchTime()
let exceptionPunch = self.punches[indexPath.row]
exceptionPunch.punchTime = punchTime
exceptionPunch.employeeRecord = self.employeeRecord
//Add the selected time to the textField
tableView.reloadRows(at: [indexPath], with: .automatic)
punchesToSave[exceptionCell] = exceptionPunch
}
@objc func cancel(sender: Any) {
//Just hide the keyboard
currentlyEditing?.1?.textField.resignFirstResponder()
}
@IBAction func submitAllPunches(_ sender: Any) {
if punchesToSave.count != exceptionCellCount {
super.displayAlert(title: "Submit", message: "All exceptions must be corrected before submitting.", alertHandler: nil)
} else {
//Begin getting the location for submitting the punches
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestWhenInUseAuthorization()
submitAllPunchesIfReady()
}
}
@IBAction func cancelAllPunches(_ sender: Any) {
for (cell, _) in punchesToSave {
cell.textField.text = nil
}
punchesToSave.removeAll()
}
//MARK: Private functions
private func loadTableData() {
tableData = TableData(rows: punches.map { (punch) -> Row in
let row = Row(detailText: punch.punchType)
if let time = punch.punchTime {
row.cellId = PUNCH_CELL_ID
row.text = DATE_FORMAT.string(from: time)
if let deletablePair = punch.deletablePair, deletablePair != 0 {
row.cellId = DELETABLE_CELL_ID
row.action = {
super.displayActionSheet(from: self, title: "Delete duplicate punch?", actions: [UIAlertAction(title: "Delete", style: .default, handler: { (_) in
self.deletePunch(punch, indexPath: nil)
})]) { (_) in
self.tableView.deselectSelectedRow()
}
}
row.object = punch
} else {
//Regular punch cells should not be enabled.
row.enabled = false
}
} else {
row.cellId = EXCEPTION_CELL_ID
exceptionCellCount += 1
}
return row
} )
loadTotalHours()
tableView.reloadData()
}
private func deletePunch(_ punch: YTimePunch, indexPath: IndexPath?) {
if let sequenceNumber = punch.sequenceNumber {
self.spinner.startAnimating()
YTimeClient.deletePunch(employeeRecord: self.employeeRecord.toString(), punchDate: DELETE_DATE_FORMAT.string(from: self.selectedDate), sequenceNumber: sequenceNumber, callback: { (error) in
if let error = error {
super.displayAlert(error: error)
} else {
//Both these values are nullabe. Tapping doesn't pass in indexPath and swiping does not select the row.
if let indexPath = indexPath ?? self.tableView.indexPathForSelectedRow {
//The following code helps us avoid popping back to make a new call to the service to fetch the new punches
self.tableView.beginUpdates()
self.tableView.deleteRows(at: [indexPath], with: .fade)
self.punches.remove(at: indexPath.row)
//Reset the deletablePair of the corresponding punch so that the tableView changes it to a regular punch cell
self.punches.first(where: { $0.deletablePair == punch.deletablePair })?.deletablePair = 0
self.loadTableData()
self.tableView.endUpdates()
} else {
//Popping back will reload the punches so that they will be correct if the user comes back to this date
self.popBack()
}
self.spinner.stopAnimating()
}
})
}
}
private func loadTotalHours() {
var totalInterval: TimeInterval = 0.0
let calendar = Calendar.defaultCalendar()
var inPunch: Date? = calendar.startOfDay(for: selectedDate) //Initialize to startOfDay: if the first punch is an out, we will include time from start of day in our total
for punch in punches {
//If there are any exceptions, return null so that the footer doesn't load
guard let time = punch.punchTime else { return }
if punch.clockIn {
inPunch = time
} else if let start = inPunch {
totalInterval += time.timeIntervalSince(start)
//Reset the inPunch (since it's now been totaled in)
inPunch = nil
}
}
//If the last punch was "in", add another interval from that punch until now
if let start = inPunch {
//The start date doesn't have a year, month or date attached to it (so it default to 1/1/2000). Set it to today so that the calculation works properly
guard let startDate = calendar.combine(date: selectedDate, time: start) else { return }
if selectedDate.isToday {
totalInterval += Date().timeIntervalSince(startDate)
} else {
//Only append time until end of the selectedDate and not until now
if let endOfDay = calendar.endOfDay(for: selectedDate) {
totalInterval += endOfDay.timeIntervalSince(startDate)
}
}
}
//This will turn the total into the format: 0h 00m
totalHours = String(format: "Total: %01lih %02lim", lround(floor(totalInterval / 3600)), lround(floor(totalInterval / 60)) % 60)
}
private func getPunchTime() -> Date {
//The day, month, and year come from the selected date. The hours and minute come from the date picker. Fuse the two and return the date
let cal = Calendar.current
var selectedDateComps = cal.dateComponents([.day, .month, .year, .timeZone], from: selectedDate)
let datePickerComps = cal.dateComponents([.hour, .minute], from: currentlyEditing?.0.date ?? Date())
selectedDateComps.hour = datePickerComps.hour
selectedDateComps.minute = datePickerComps.minute
selectedDateComps.second = 0
return cal.date(from: selectedDateComps) ?? Date()
}
private func submitAllPunchesIfReady() {
if punchesToSave.count > 0, let punchLocation = punchLocation {
var callbackCounter = 0
let decrementCallbackCounter: () -> Void = {
callbackCounter -= 1
if callbackCounter == 0 {
self.spinner.stopAnimating()
super.displayAlert(title: "Success", message: "The corrections were successfully submitted. Note that it may take up to a day for changes to be updated in the Y-Time system.", alertHandler: nil)
self.punchesToSave.removeAll()
}
}
//Delete the saved location, so it cannot be used later if the Location Services are turned off.
self.punchLocation = nil
self.spinner.startAnimating()
for (cell, punch) in punchesToSave {
callbackCounter += 1
//Set the punch location here to be sure the location has returned
punch.location = punchLocation
YTimeClient.createPunch(punch, callback: { (status, error) in
if status != nil {
decrementCallbackCounter()
//Manually make the cell look like a regular punch cell to avoid reloading tableData/making new service calls
cell.textField.textColor = UIColor.black
cell.textField.isEnabled = false
cell.rightDetailTextLabel.textColor = .black
} else {
super.displayAlert(error: error, message: "A server error occurred while processing one or more of the submitted corrections. Please try again later. Note that it may take up to a day before changes are updated in the Y-Time system.")
}
})
}
}
}
}
| 596628f18be7c5df2143c9a5ce1a8e79 | 39.142012 | 240 | 0.700472 | false | false | false | false |
XeresRazor/SMeaGOL | refs/heads/master | SmeagolMath/SmeagolMath/Geometry/Matrix4.swift | mit | 1 | //
// Matrix4.swift
// Smeagol
//
// Created by Green2, David on 10/5/14.
// Copyright (c) 2014 Digital Worlds. All rights reserved.
//
import Foundation
//
// MARK: - Definition and initializes -
//
public struct Matrix4 {
let m00: Float, m01: Float, m02: Float, m03: Float
let m10: Float, m11: Float, m12: Float, m13: Float
let m20: Float, m21: Float, m22: Float, m23: Float
let m30: Float, m31: Float, m32: Float, m33: Float
public static var identity: Matrix4 {
return Matrix4(
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
)
}
public init(_ m00: Float, _ m01: Float, _ m02: Float, _ m03: Float, _ m10: Float, _ m11: Float, _ m12: Float, _ m13: Float, _ m20: Float, _ m21: Float, _ m22: Float, _ m23: Float, _ m30: Float, _ m31: Float, _ m32: Float, _ m33: Float) {
self.m00 = m00
self.m01 = m01
self.m02 = m02
self.m03 = m03
self.m10 = m10
self.m11 = m11
self.m12 = m12
self.m13 = m13
self.m20 = m20
self.m21 = m21
self.m22 = m22
self.m23 = m23
self.m30 = m30
self.m31 = m31
self.m32 = m32
self.m33 = m33
}
public init(array: [Float]) {
assert(array.count == 9, "Matrix4 must be instantiated with 9 values.")
self.m00 = array[0]
self.m01 = array[1]
self.m02 = array[2]
self.m03 = array[3]
self.m10 = array[4]
self.m11 = array[5]
self.m12 = array[6]
self.m13 = array[7]
self.m20 = array[8]
self.m21 = array[9]
self.m22 = array[10]
self.m23 = array[11]
self.m30 = array[12]
self.m31 = array[13]
self.m32 = array[14]
self.m33 = array[15]
}
public init(var quaternion: Quaternion) {
quaternion = quaternion.normalize()
let x = quaternion.x
let y = quaternion.y
let z = quaternion.z
let w = quaternion.w
let _2x = x + x
let _2y = y + y
let _2z = z + z
let _2w = w + w
self.m00 = 1.0 - _2y * y - _2z * z
self.m01 = _2x * y + _2w * z
self.m02 = _2x * z - _2w * y
self.m03 = 0.0
self.m10 = _2x * y - _2w * z
self.m11 = 1.0 - _2x * x - _2z * z
self.m12 = _2y * z + _2w * x
self.m13 = 0.0
self.m20 = _2x * z + _2w * y
self.m21 = _2y * z - _2w * x
self.m22 = 1.0 - _2x * x - _2y * y
self.m23 = 0.0
self.m30 = 0.0
self.m31 = 0.0
self.m32 = 0.0
self.m33 = 1.0
}
public init(translationX: Float, translationY: Float, translationZ: Float) {
self = Matrix4.identity
self.m30 = translationX
self.m31 = translationY
self.m32 = translationZ
}
public init(scaleX: Float, scaleY: Float, scaleZ: Float) {
self = Matrix4.identity
self.m00 = scaleX
self.m11 = scaleY
self.m22 = scaleZ
}
public init(rotationAngle radians: Float, axisX x: Float, axisY y: Float, axisZ z: Float) {
let v = Vector3(x, y, z).normalize()
let _cos = cos(radians)
let _cosp = 1.0 - _cos
let _sin = sin(radians)
self = Matrix4.identity
self.m00 = _cos + _cosp * v.x * v.x
self.m01 = _cosp * v.x * v.y + v.z * _sin
self.m02 = _cosp * v.x * v.z - v.y * _sin
self.m10 = _cosp * v.x * v.y - v.z * _sin
self.m11 = _cos + _cosp * v.y * v.y
self.m12 = _cosp * v.y * v.z + v.x * _sin
self.m20 = _cosp * v.x * v.z + v.y * _sin
self.m21 = _cosp * v.y * v.z - v.y * _sin
self.m22 = _cos + _cosp * v.z * v.z
}
public init(rotationAngleAroundX radians: Float) {
let _cos = cos(radians)
let _sin = sin(radians)
self = Matrix4.identity
self.m11 = _cos
self.m12 = _sin
self.m21 = -_sin
self.m22 = _cos
}
public init(rotationAngleAroundY radians: Float) {
let _cos = cos(radians)
let _sin = sin(radians)
self = Matrix4.identity
self.m22 = _cos
self.m20 = _sin
self.m02 = -_sin
self.m00 = _cos
}
public init(rotationAngleAroundZ radians: Float) {
let _cos = cos(radians)
let _sin = sin(radians)
self = Matrix4.identity
self.m00 = _cos
self.m01 = _sin
self.m10 = -_sin
self.m11 = _cos
}
}
//
// MARK: - Convenience creators -
//
public extension Matrix4 {
public func makePerspective(verticalFOV radians: Float, aspectRatio: Float, nearZ: Float, farZ: Float) -> Matrix4 {
let _cotan = 1.0 / tan(radians / 2.0)
return Matrix4(
_cotan / aspectRatio, 0.0, 0.0, 0.0,
0.0, _cotan, 0.0, 0.0,
0.0, 0.0, (farZ + nearZ) / (nearZ - farZ), -1.0,
0.0, 0.0, (2.0 * farZ * nearZ) / (nearZ - farZ), 0.0
)
}
public func makeFrustum(left: Float, right: Float, bottom: Float, top: Float, nearZ: Float, farZ: Float) -> Matrix4 {
let ral = right + left
let rsl = right - left
let tsb = top - bottom
let tab = top + bottom
let fan = farZ + nearZ
let fsn = farZ - nearZ
return Matrix4(
2.0 * nearZ / rsl, 0.0, 0.0, 0.0,
0.0, 2.0 * nearZ / tsb, 0.0, 0.0,
ral / rsl, tab / tsb, -fan / fsn, -1.0,
0.0, 0.0, (-2.0 * farZ * nearZ) / fsn, 0.0
)
}
public func makeOrtho(left: Float, right: Float, bottom: Float, top: Float, nearZ: Float, farZ: Float) -> Matrix4 {
let ral = right + left
let rsl = right - left
let tsb = top - bottom
let tab = top + bottom
let fan = farZ + nearZ
let fsn = farZ - nearZ
return Matrix4(
2.0 / rsl, 0.0, 0.0, 0.0,
0.0, 2.0 / tsb, 0.0, 0.0,
0.0, 0.0, -2.0 / fsn, 0.0,
-ral / rsl, -tab / tsb, -fan / fsn, 1.0
)
}
public func makeLookAt(eyeX: Float, eyeY: Float, eyeZ: Float, centerX: Float, centerY: Float, centerZ: Float, upX: Float, upY: Float, upZ: Float) -> Matrix4 {
let eye = Vector3(eyeX, eyeY, eyeZ)
let center = Vector3(centerX, centerY, centerZ)
let up = Vector3(upX, upY, upZ)
let n = (eye + -center).normalize()
let u = up.cross(n).normalize()
let v = n.cross(u)
return Matrix4(
u[0], v[0], n[0], 0.0,
u[1], v[1], n[1], 0.0,
u[2], v[2], n[2], 0.0,
-u.dot(eye), -v.dot(eye), -n.dot(eye), 1.0
)
}
}
//
// MARK: - Property accessors -
//
public extension Matrix4 { // Property getters
// Array property
public subscript (index: Int) -> Float {
assert(index >= 0 && index < 16, "Index must be in the range 0...15")
switch index {
case 0:
return self.m00
case 1:
return self.m01
case 2:
return self.m02
case 3:
return self.m03
case 4:
return self.m10
case 5:
return self.m11
case 6:
return self.m12
case 7:
return self.m13
case 8:
return self.m20
case 9:
return self.m21
case 10:
return self.m22
case 11:
return self.m23
case 12:
return self.m30
case 13:
return self.m31
case 14:
return self.m32
case 15:
return self.m33
default:
fatalError("Index out of bounds accessing Matrix4")
}
}
// 2D Array property
public subscript (index: (x:Int, y:Int)) -> Float {
assert(index.x >= 0 && index.x < 4 && index.y >= 0 && index.y < 4, "Index must be in the range 0...3")
switch index {
case (0,0):
return self.m00
case (0,1):
return self.m01
case (0,2):
return self.m02
case (0,3):
return self.m03
case (1,0):
return self.m10
case (1,1):
return self.m11
case (1,2):
return self.m12
case (1,3):
return self.m13
case (2,0):
return self.m20
case (2,1):
return self.m21
case (2,2):
return self.m22
case (2,3):
return self.m23
case (3,0):
return self.m30
case (3,1):
return self.m31
case (3,2):
return self.m32
case (3,3):
return self.m33
default:
fatalError("Index out of bounds accessing Matrix4")
}
}
}
//
// MARK: - Methods -
//
public extension Matrix4 {
public func transposed() -> Matrix4 {
return Matrix4(
self.m00, self.m10, self.m20, self.m30,
self.m01, self.m11, self.m21, self.m31,
self.m02, self.m12, self.m22, self.m32,
self.m03, self.m13, self.m23, self.m33
)
}
public func inverse() -> Matrix4? {
var det: Float, invDet: Float
let det2_01_01 = m00 * m11 - m01 * m10
let det2_01_02 = m00 * m12 - m02 * m10
let det2_01_03 = m00 * m13 - m03 * m10
let det2_01_12 = m01 * m12 - m02 * m11
let det2_01_13 = m01 * m13 - m03 * m11
let det2_01_23 = m02 * m13 - m03 * m12
let det3_201_012 = m20 * det2_01_12 - m21 * det2_01_02 + m22 * det2_01_01;
let det3_201_013 = m20 * det2_01_13 - m21 * det2_01_03 + m23 * det2_01_01;
let det3_201_023 = m20 * det2_01_23 - m22 * det2_01_03 + m23 * det2_01_02;
let det3_201_123 = m21 * det2_01_23 - m22 * det2_01_13 + m23 * det2_01_12;
det = (-det3_201_123 * m30 + det3_201_023 * m31 - det3_201_013 * m32 + det3_201_012 * m33)
if ( abs(det) < 1e-14 ) {
return nil
}
invDet = 1.0 / det
// remaining 2x2 sub-determinants
let det2_03_01 = m00 * m31 - m01 * m30
let det2_03_02 = m00 * m32 - m02 * m30
let det2_03_03 = m00 * m33 - m03 * m30
let det2_03_12 = m01 * m32 - m02 * m31
let det2_03_13 = m01 * m33 - m03 * m31
let det2_03_23 = m02 * m33 - m03 * m32
let det2_13_01 = m10 * m31 - m11 * m30
let det2_13_02 = m10 * m32 - m12 * m30
let det2_13_03 = m10 * m33 - m13 * m30
let det2_13_12 = m11 * m32 - m12 * m31
let det2_13_13 = m11 * m33 - m13 * m31
let det2_13_23 = m12 * m33 - m13 * m32
// remaining 3x3 sub-determinants
let det3_203_012 = m20 * det2_03_12 - m21 * det2_03_02 + m22 * det2_03_01
let det3_203_013 = m20 * det2_03_13 - m21 * det2_03_03 + m23 * det2_03_01
let det3_203_023 = m20 * det2_03_23 - m22 * det2_03_03 + m23 * det2_03_02
let det3_203_123 = m21 * det2_03_23 - m22 * det2_03_13 + m23 * det2_03_12
let det3_213_012 = m20 * det2_13_12 - m21 * det2_13_02 + m22 * det2_13_01
let det3_213_013 = m20 * det2_13_13 - m21 * det2_13_03 + m23 * det2_13_01
let det3_213_023 = m20 * det2_13_23 - m22 * det2_13_03 + m23 * det2_13_02
let det3_213_123 = m21 * det2_13_23 - m22 * det2_13_13 + m23 * det2_13_12
let det3_301_012 = m30 * det2_01_12 - m31 * det2_01_02 + m32 * det2_01_01
let det3_301_013 = m30 * det2_01_13 - m31 * det2_01_03 + m33 * det2_01_01
let det3_301_023 = m30 * det2_01_23 - m32 * det2_01_03 + m33 * det2_01_02
let det3_301_123 = m31 * det2_01_23 - m32 * det2_01_13 + m33 * det2_01_12
let newm00 = -det3_213_123 * invDet
let newm10 = det3_213_023 * invDet
let newm20 = -det3_213_013 * invDet
let newm30 = det3_213_012 * invDet
let newm01 = det3_203_123 * invDet
let newm11 = -det3_203_023 * invDet
let newm21 = det3_203_013 * invDet
let newm31 = -det3_203_012 * invDet
let newm02 = det3_301_123 * invDet
let newm12 = -det3_301_023 * invDet
let newm22 = det3_301_013 * invDet
let newm32 = -det3_301_012 * invDet
let newm03 = -det3_201_123 * invDet
let newm13 = det3_201_023 * invDet
let newm23 = -det3_201_013 * invDet
let newm33 = det3_201_012 * invDet
return Matrix4(newm00, newm01, newm02, newm03, newm10, newm11, newm12, newm13, newm20, newm21, newm22, newm23, newm30, newm31, newm32, newm33)
/*var inverse = Array<Float>(count: 16, repeatedValue: 0.0)
inverse[0] = self.m11 * self.m22 - self.m12 * self.m21
inverse[3] = self.m12 * self.m20 - self.m10 * self.m22
inverse[6] = self.m10 * self.m21 - self.m11 * self.m20
let det: Float = self.m00 * inverse[0] + self.m01 * inverse[3] + self.m02 * inverse[6]
if abs(det) < 1e-14 {
return nil
}
let invDet = 1.0 / det
inverse[1] = self.m02 * self.m21 - self.m01 * self.m22
inverse[2] = self.m01 * self.m12 - self.m02 * self.m11
inverse[4] = self.m00 * self.m22 - self.m02 * self.m20
inverse[5] = self.m02 * self.m10 - self.m00 * self.m12
inverse[7] = self.m01 * self.m20 - self.m00 * self.m21
inverse[8] = self.m00 * self.m11 - self.m01 * self.m10
for i in 0..<9 {
inverse[i] = inverse[i] * invDet
}
return Matrix4(array: inverse)*/
}
public func matrix3() -> Matrix3 {
return Matrix3(
self.m00, self.m01, self.m02,
self.m10, self.m11, self.m12,
self.m20, self.m21, self.m22
)
}
public func matrix2() -> Matrix2 {
return Matrix2(self[0], self[1], self[4], self[5])
}
public func getRow(row: Int) -> Vector4 {
return Vector4(self[row], self[4 + row], self[6 + row], self[12 + row])
}
public func getColumn(column: Int) -> Vector4 {
let columnOffset = column * 4
return Vector4(self[columnOffset + 0], self[columnOffset + 1], self[columnOffset + 2], self[columnOffset + 3])
}
public func scaledBy(scaleX: Float, scaleY: Float, scaleZ: Float) -> Matrix4 {
return Matrix4(
self.m00 * scaleX, self.m01 * scaleX, self.m02 * scaleX, self.m03 * scaleX,
self.m10 * scaleY, self.m11 * scaleY, self.m12 * scaleY, self.m13 * scaleY,
self.m20 * scaleZ, self.m21 * scaleZ, self.m22 * scaleZ, self.m23 * scaleZ,
self.m30, self.m31, self.m32, self.m33
)
}
public func scaledBy(vector: Vector3) -> Matrix4 {
return Matrix4(
self.m00 * vector.x, self.m01 * vector.x, self.m02 * vector.x, self.m03 * vector.x,
self.m10 * vector.y, self.m11 * vector.y, self.m12 * vector.y, self.m13 * vector.y,
self.m20 * vector.z, self.m21 * vector.z, self.m22 * vector.z, self.m23 * vector.z,
self.m30, self.m31, self.m32, self.m33
)
}
public func scaledBy(vector: Vector4) -> Matrix4 {
return Matrix4(
self.m00 * vector.x, self.m01 * vector.x, self.m02 * vector.x, self.m03 * vector.x,
self.m10 * vector.y, self.m11 * vector.y, self.m12 * vector.y, self.m13 * vector.y,
self.m20 * vector.z, self.m21 * vector.z, self.m22 * vector.z, self.m23 * vector.z,
self.m30, self.m31, self.m32, self.m33
)
}
public func rotatedBy(angle radians: Float, axisX: Float, axisY: Float, axisZ: Float) -> Matrix4 {
let rm = Matrix4(rotationAngle: radians, axisX: axisX, axisY: axisY, axisZ: axisZ)
return self * rm
}
public func rotatedBy(angle radians: Float, axisVector: Vector3) -> Matrix4 {
let rm = Matrix4(rotationAngle: radians, axisX: axisVector.x, axisY: axisVector.y, axisZ: axisVector.z)
return self * rm
}
public func rotatedBy(angle radians: Float, axisVector: Vector4) -> Matrix4 {
let rm = Matrix4(rotationAngle: radians, axisX: axisVector.x, axisY: axisVector.y, axisZ: axisVector.z)
return self * rm
}
public func rotatedAroundXBy(angle radians: Float) -> Matrix4 {
let rm = Matrix4(rotationAngleAroundX: radians)
return self * rm
}
public func rotatedAroundYBy(angle radians: Float) -> Matrix4 {
let rm = Matrix4(rotationAngleAroundY: radians)
return self * rm
}
public func rotatedAroundZBy(angle radians: Float) -> Matrix4 {
let rm = Matrix4(rotationAngleAroundZ: radians)
return self * rm
}
}
//
// MARK: - Matrix/Vector multiplications
//
extension Matrix4 {
// Assumes 0 in the w component
func multiplyVector(vector: Vector3) -> Vector3 {
let v4 = self.multiplyVector(Vector4(vector.x, vector.y, vector.z, 0.0))
return Vector3(v4.x, v4.y, v4.z)
}
// Assumes 1 in the w component
func multiplyVectorWithTranslation(vector: Vector3) -> Vector3 {
let v4 = self.multiplyVector(Vector4(vector.x, vector.y, vector.z, 1.0))
return Vector3(v4.x, v4.y, v4.z)
}
// Assumes 1 in the w component and divides the resulting vector by w before returning.
func multiplyAndProjectVector(vector: Vector3) -> Vector3 {
let v4 = self.multiplyVector(Vector4(vector.x, vector.y, vector.z, 0.0))
return Vector3(v4.x, v4.y, v4.z) * (1.0 / v4.w)
}
// Assumes 0 in the w component
func multiplyVectors(inout vectors: [Vector3]) {
for i in 0 ..< vectors.count {
vectors[i] = self.multiplyVector(vectors[i])
}
}
// Assumes 1 in the w component
func multiplyVectorsWithTranslation(inout vectors: [Vector3]) {
for i in 0 ..< vectors.count {
vectors[i] = self.multiplyVectorWithTranslation(vectors[i])
}
}
// Assumes 1 in the w component and divides the resulting vector by w before returning.
func multiplyAndProjectVectors(inout vectors: [Vector3]) {
for i in 0 ..< vectors.count {
vectors[i] = self.multiplyAndProjectVector(vectors[i])
}
}
func multiplyVector(vector: Vector4) -> Vector4 {
let v = Vector4(
m00 * vector.x + m10 * vector.y + m20 * vector.z + m30 * vector.w,
m01 * vector.x + m11 * vector.y + m21 * vector.z + m31 * vector.w,
m02 * vector.x + m12 * vector.y + m22 * vector.z + m32 * vector.w,
m03 * vector.x + m13 * vector.y + m23 * vector.z + m33 * vector.w
)
return v
}
func multiplyVectors(inout vectors: [Vector4]) {
for i in 0 ..< vectors.count {
vectors[i] = self.multiplyVector(vectors[i])
}
}
}
//
// MARK: - Operators -
//
public func + (lhs: Matrix4, rhs: Matrix4) -> Matrix4 {
var newValues: [Float] = Array<Float>(count: 16, repeatedValue: 0.0)
for i in 0..<16 {
newValues[i] = lhs[i] + rhs[i]
}
return Matrix4(array: newValues)
}
public func += (inout lhs: Matrix4, rhs: Matrix4) {
var newValues: [Float] = Array<Float>(count: 16, repeatedValue: 0.0)
for i in 0..<16 {
newValues[i] = lhs[i] + rhs[i]
}
lhs = Matrix4(array: newValues)
}
public func - (lhs: Matrix4, rhs: Matrix4) -> Matrix4 {
var newValues: [Float] = Array<Float>(count: 16, repeatedValue: 0.0)
for i in 0..<16 {
newValues[i] = lhs[i] - rhs[i]
}
return Matrix4(array: newValues)
}
public func -= (inout lhs: Matrix4, rhs: Matrix4) {
var newValues: [Float] = Array<Float>(count: 16, repeatedValue: 0.0)
for i in 0..<16 {
newValues[i] = lhs[i] - rhs[i]
}
lhs = Matrix4(array: newValues)
}
public func * (lhs: Matrix4, rhs: Matrix4) -> Matrix4 {
let _00 = lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01 + lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03
let _10: Float = lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11 + lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13
let _20: Float = lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21 + lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23
let _30: Float = lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31 + lhs.m20 * rhs.m32 + lhs.m30 * rhs.m33
let _01: Float = lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01 + lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03
let _11: Float = lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11 + lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13
let _21: Float = lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21 + lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23
let _31: Float = lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31 + lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33
let _02: Float = lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01 + lhs.m22 * rhs.m02 + lhs.m32 * rhs.m03
let _12: Float = lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11 + lhs.m22 * rhs.m12 + lhs.m32 * rhs.m13
let _22: Float = lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21 + lhs.m22 * rhs.m22 + lhs.m32 * rhs.m23
let _32: Float = lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31 + lhs.m22 * rhs.m32 + lhs.m32 * rhs.m33
let _03: Float = lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01 + lhs.m23 * rhs.m02 + lhs.m33 * rhs.m03
let _13: Float = lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11 + lhs.m23 * rhs.m12 + lhs.m33 * rhs.m13
let _23: Float = lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21 + lhs.m23 * rhs.m22 + lhs.m33 * rhs.m23
let _33: Float = lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31 + lhs.m23 * rhs.m32 + lhs.m33 * rhs.m33
return Matrix4(
_00, _01, _02, _03,
_10, _11, _12, _13,
_20, _21, _22, _23,
_30, _31, _32, _33
)
}
public func *= (inout lhs: Matrix4, rhs: Matrix4) {
lhs = lhs * rhs
}
//public func * (lhs: Matrix4, rhs: Vector4) -> Vector4 {
// let x = lhs.m00 * rhs.x + lhs.m10 * rhs.y + lhs.m20 * rhs.z + lhs.m30 * rhs.w
// let y = lhs.m01 * rhs.x + lhs.m11 * rhs.y + lhs.m21 * rhs.z + lhs.m31 * rhs.w
// let z = lhs.m02 * rhs.x + lhs.m12 * rhs.y + lhs.m22 * rhs.z + lhs.m32 * rhs.w
// let w = lhs.m03 * rhs.x + lhs.m13 * rhs.y + lhs.m23 * rhs.z + lhs.m33 * rhs.w
// return Vector4(x, y, z, w)
//}
//
//public func *= (inout lhs: Vector4, rhs: Matrix4) {
//
//}
//
//public func * (lhs: Matrix4, rhs: [Vector4]) -> [Vector4] {
// var outVecs = [Vector4]()
// for i in 0 ..< rhs.count {
// outVecs.append(lhs * rhs[i])
// }
// return outVecs
//}
| 7bad75bd0f4e682583e98629db1c0ef2 | 28.278027 | 238 | 0.610201 | false | false | false | false |
manGoweb/SpecTools | refs/heads/master | Example/SpecTools/LabeledView.swift | mit | 1 | import SnapKit
import UIKit
class LabeledView: UIView {
let label: UILabel = Subviews.label
init() {
super.init(frame: .zero)
addSubviews()
setUpLayout()
}
// MARK: - Subviews
private func addSubviews() {
addSubview(label)
}
// MARK: - Layout
private func setUpLayout() {
label.snp.makeConstraints {
$0.top.trailing.lessThanOrEqualToSuperview()
$0.bottom.leading.lessThanOrEqualToSuperview()
$0.center.equalToSuperview()
}
}
// MARK: - Required initializer
required init?(coder _: NSCoder) { return nil }
}
private extension LabeledView {
enum Subviews {
static var label: UILabel {
let label = UILabel(frame: .zero)
label.textColor = .white
label.font = UIFont.systemFont(ofSize: 15.0, weight: .bold)
label.textAlignment = .center
return label
}
}
}
| 7784516bc25738443c38bf35e51dbe25 | 18.56 | 71 | 0.57362 | false | false | false | false |
httpswift/swifter | refs/heads/stable | Xcode/Sources/String+SHA1.swift | bsd-3-clause | 1 | //
// String+SHA1.swift
// Swifter
//
// Copyright 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
// swiftlint:disable identifier_name function_body_length
public struct SHA1 {
public static func hash(_ input: [UInt8]) -> [UInt8] {
// Alghorithm from: https://en.wikipedia.org/wiki/SHA-1
var message = input
var h0 = UInt32(littleEndian: 0x67452301)
var h1 = UInt32(littleEndian: 0xEFCDAB89)
var h2 = UInt32(littleEndian: 0x98BADCFE)
var h3 = UInt32(littleEndian: 0x10325476)
var h4 = UInt32(littleEndian: 0xC3D2E1F0)
// ml = message length in bits (always a multiple of the number of bits in a character).
let ml = UInt64(message.count * 8)
// append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits.
message.append(0x80)
// append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512)
let padBytesCount = ( message.count + 8 ) % 64
message.append(contentsOf: [UInt8](repeating: 0, count: 64 - padBytesCount))
// append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits.
var mlBigEndian = ml.bigEndian
withUnsafePointer(to: &mlBigEndian) {
message.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 8)))
}
// Process the message in successive 512-bit chunks ( 64 bytes chunks ):
for chunkStart in 0..<message.count/64 {
var words = [UInt32]()
let chunk = message[chunkStart*64..<chunkStart*64+64]
// break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15
for index in 0...15 {
let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>(OpaquePointer($0.baseAddress! + (index*4))).pointee})
words.append(value.bigEndian)
}
// Extend the sixteen 32-bit words into eighty 32-bit words:
for index in 16...79 {
let value: UInt32 = ((words[index-3]) ^ (words[index-8]) ^ (words[index-14]) ^ (words[index-16]))
words.append(rotateLeft(value, 1))
}
// Initialize hash value for this chunk:
var a = h0
var b = h1
var c = h2
var d = h3
var e = h4
for i in 0..<80 {
var f = UInt32(0)
var k = UInt32(0)
switch i {
case 0...19:
f = (b & c) | ((~b) & d)
k = 0x5A827999
case 20...39:
f = b ^ c ^ d
k = 0x6ED9EBA1
case 40...59:
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
case 60...79:
f = b ^ c ^ d
k = 0xCA62C1D6
default: break
}
let temp = (rotateLeft(a, 5) &+ f &+ e &+ k &+ words[i]) & 0xFFFFFFFF
e = d
d = c
c = rotateLeft(b, 30)
b = a
a = temp
}
// Add this chunk's hash to result so far:
h0 = ( h0 &+ a ) & 0xFFFFFFFF
h1 = ( h1 &+ b ) & 0xFFFFFFFF
h2 = ( h2 &+ c ) & 0xFFFFFFFF
h3 = ( h3 &+ d ) & 0xFFFFFFFF
h4 = ( h4 &+ e ) & 0xFFFFFFFF
}
// Produce the final hash value (big-endian) as a 160 bit number:
var digest = [UInt8]()
[h0, h1, h2, h3, h4].forEach { value in
var bigEndianVersion = value.bigEndian
withUnsafePointer(to: &bigEndianVersion) {
digest.append(contentsOf: Array(UnsafeBufferPointer<UInt8>(start: UnsafePointer(OpaquePointer($0)), count: 4)))
}
}
return digest
}
private static func rotateLeft(_ v: UInt32, _ n: UInt32) -> UInt32 {
return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n))
}
}
extension String {
public func sha1() -> [UInt8] {
return SHA1.hash([UInt8](self.utf8))
}
public func sha1() -> String {
return self.sha1().reduce("") { $0 + String(format: "%02x", $1) }
}
}
| 1023b17450d3c7321cb1b47135f8df96 | 31.131387 | 135 | 0.510677 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/BlockchainComponentLibrary/Sources/Examples/2 - Primitives/PrimarySegmentedControlExamples.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SwiftUI
struct PrimarySegmentedControlExamples: View {
@State var firstSelection: AnyHashable = "live"
@State var secondSelection: AnyHashable = "1m"
@State var thirdSelection: AnyHashable = "first"
@State var fourthSelection: AnyHashable = "ready"
enum Option: String {
case one
case two
case three
case four
}
@State var option: Option = .two
var body: some View {
VStack(spacing: Spacing.padding1) {
PrimarySegmentedControl(
items: [
PrimarySegmentedControl.Item(title: "Live", variant: .dot, identifier: "live"),
PrimarySegmentedControl.Item(title: "1D", identifier: "1d"),
PrimarySegmentedControl.Item(title: "1W", identifier: "1w"),
PrimarySegmentedControl.Item(title: "1M", identifier: "1m"),
PrimarySegmentedControl.Item(title: "1Y", identifier: "1y"),
PrimarySegmentedControl.Item(title: "All", identifier: "all")
],
selection: $firstSelection
)
PrimarySegmentedControl(
items: [
PrimarySegmentedControl.Item(title: "Live", variant: .dot, identifier: "live"),
PrimarySegmentedControl.Item(title: "1D", identifier: "1d"),
PrimarySegmentedControl.Item(title: "1W", identifier: "1w"),
PrimarySegmentedControl.Item(title: "1M", identifier: "1m"),
PrimarySegmentedControl.Item(title: "1Y", identifier: "1y"),
PrimarySegmentedControl.Item(title: "All", identifier: "all")
],
selection: $secondSelection
)
PrimarySegmentedControl(
items: [
PrimarySegmentedControl.Item(title: "First", identifier: "first"),
PrimarySegmentedControl.Item(title: "Second", identifier: "second"),
PrimarySegmentedControl.Item(title: "Third", identifier: "third")
],
selection: $thirdSelection
)
PrimarySegmentedControl(
items: [
PrimarySegmentedControl.Item(title: "Today", variant: .dot, identifier: "today"),
PrimarySegmentedControl.Item(title: "Tomorrow", identifier: "tomorrow"),
PrimarySegmentedControl.Item(title: "Now", identifier: "now"),
PrimarySegmentedControl.Item(title: "Ready", variant: .dot, identifier: "ready")
],
selection: $fourthSelection
)
PrimarySegmentedControl(
items: [
PrimarySegmentedControl.Item(title: Option.one.rawValue, variant: .dot, identifier: Option.one),
PrimarySegmentedControl.Item(title: Option.two.rawValue, identifier: Option.two),
PrimarySegmentedControl.Item(title: Option.three.rawValue, identifier: Option.three),
PrimarySegmentedControl.Item(title: Option.four.rawValue, variant: .dot, identifier: Option.four)
],
selection: $option
)
}
.padding(Spacing.padding())
}
}
struct PrimarySegmentedControlExamples_Previews: PreviewProvider {
static var previews: some View {
PrimarySegmentedControlExamples()
}
}
| ce864b89474873913319d93250d91a34 | 41.583333 | 117 | 0.573945 | false | false | false | false |
SamirTalwar/advent-of-code | refs/heads/main | 2018/AOC_18_2.swift | mit | 1 | let iterations = 1_000_000_000
enum Acre: CustomStringConvertible {
case openGround
case trees
case lumberyard
var description: String {
switch self {
case .openGround:
return "."
case .trees:
return "|"
case .lumberyard:
return "#"
}
}
func convert(adjacentCounts: [Acre: Int]) -> Acre {
switch self {
case .openGround:
return (adjacentCounts[.trees] ?? 0) >= 3 ? .trees : self
case .trees:
return (adjacentCounts[.lumberyard] ?? 0) >= 3 ? .lumberyard : self
case .lumberyard:
return (adjacentCounts[.lumberyard] ?? 0) >= 1 && (adjacentCounts[.trees] ?? 0) >= 1 ? self : .openGround
}
}
}
struct Grid: Equatable, CustomStringConvertible {
let values: [[Acre]]
let xRange: Range<Int>
let yRange: Range<Int>
init(_ values: [[Acre]]) {
self.values = values
xRange = 0 ..< values[0].count
yRange = 0 ..< values.count
}
var description: String {
return values.map { row in row.map { acre in acre.description }.joined() + "\n" }.joined()
}
func count(of acreType: Acre) -> Int {
return values.flatMap { row in row.filter { acre in acre == acreType } }.count
}
func iterate() -> Grid {
return Grid(yRange.map { y in
xRange.map { x in
values[y][x].convert(adjacentCounts: adjacentValueCounts(x: x, y: y))
}
})
}
private func adjacentValueCounts(x: Int, y: Int) -> [Acre: Int] {
let adjacentPositions = [
(x - 1, y - 1),
(x, y - 1),
(x + 1, y - 1),
(x - 1, y),
(x + 1, y),
(x - 1, y + 1),
(x, y + 1),
(x + 1, y + 1),
]
let adjacentValues = adjacentPositions
.filter { x, y in xRange.contains(x) && yRange.contains(y) }
.map { x, y in values[y][x] }
var counts: [Acre: Int] = [:]
for value in adjacentValues {
if let count = counts[value] {
counts[value] = count + 1
} else {
counts[value] = 1
}
}
return counts
}
}
func main() {
var past: [Grid] = []
var grid = Grid(StdIn().map { line in line.map(parseInputCharacter) })
for i in 0 ..< iterations {
grid = grid.iterate()
if let cycle = findCycle(startingWith: grid, inPast: past) {
grid = cycle[(iterations - i - 1) % cycle.count]
break
}
past.append(grid)
}
print(grid)
print(grid.count(of: .trees) * grid.count(of: .lumberyard))
}
func findCycle(startingWith grid: Grid, inPast past: [Grid]) -> [Grid]? {
for (offset, element) in past.enumerated().reversed() {
if grid == element {
return Array(past[offset ..< past.count])
}
}
return nil
}
func parseInputCharacter(_ character: Character) -> Acre {
switch character {
case ".":
return .openGround
case "|":
return .trees
case "#":
return .lumberyard
default:
fatalError("Could not parse \"\(character)\".")
}
}
| 5713c97e64fe4839825dd9424e85b09a | 26.016529 | 117 | 0.507801 | false | false | false | false |
GENG-GitHub/weibo-gd | refs/heads/master | GDWeibo/Class/Module/Home/View/GDStatusForwardCell.swift | apache-2.0 | 1 | //
// GDStatusForwardCell.swift
// GDWeibo
//
// Created by geng on 15/11/4.
// Copyright © 2015年 geng. All rights reserved.
//
import UIKit
class GDStatusForwardCell: GDStatusCell {
//MARK: - 重写父类的属性
override var status:GDStatus? {
didSet{
//设置转发的文字
let name = status?.retweeted_status?.user?.name ?? "没有名字"
let text = status?.retweeted_status?.text ?? "没有内容"
forwardLabel.text = "@\(name):\(text)"
}
}
//MARK: - 重写父类的prepareUI方法
//重写父类的方法
override func prepareUI()
{
//调用父类的方法
super.prepareUI()
//添加子控件
contentView.insertSubview(backBtn, belowSubview: pictureView)
contentView.addSubview(forwardLabel)
//设置背景View的约束
backBtn.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: nil ,offset:CGPoint(x: -8, y: 8))
backBtn.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
//设置转发微博文字的约束
forwardLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: backBtn, size: nil, offset: CGPoint(x: 8, y: 8))
// 宽度约束
contentView.addConstraint(NSLayoutConstraint(item: forwardLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: UIScreen.mainScreen().bounds.width - 2 * 8))
//pictureView的约束
// 在内容标签的左下位置,距离右r边为8,宽高为290, 290
let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: forwardLabel, size: CGSize(width: 290, height: 290), offset: CGPoint(x: 0, y: 8))
// 获取配图视图的宽度约束
pictureViewWidthCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
// 获取配图视图的高度约束
pictureViewHeightCon = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
}
//MARK: - 懒加载控件
private lazy var forwardLabel: UILabel = {
//创建label
let label = UILabel()
//设置属性
label.numberOfLines = 0
return label
}()
private lazy var backBtn: UIButton = {
//创建按钮
let btn = UIButton()
//设置属性
btn.backgroundColor = UIColor(white: 0.93, alpha: 1)
return btn
}()
}
| 1c5e224373311619cfe9ba8aa72754a3 | 28.481928 | 271 | 0.60237 | false | false | false | false |
benlangmuir/swift | refs/heads/master | test/Interop/SwiftToCxx/initializers/init-in-cxx.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Init -clang-header-expose-public-decls -emit-clang-header-path %t/inits.h
// RUN: %FileCheck %s < %t/inits.h
// RUN: %check-interop-cxx-header-in-clang(%t/inits.h -Wno-unused-function)
// CHECK: SWIFT_EXTERN struct swift_interop_returnStub_Init_uint32_t_0_4 $s4Init16FirstSmallStructVACycfC(void) SWIFT_NOEXCEPT SWIFT_CALL; // init()
// CHECK-NEXT: SWIFT_EXTERN struct swift_interop_returnStub_Init_uint32_t_0_4 $s4Init16FirstSmallStructVyACSicfC(ptrdiff_t x) SWIFT_NOEXCEPT SWIFT_CALL; // init(_:)
// CHECK: SWIFT_EXTERN void $s4Init11LargeStructVACycfC(SWIFT_INDIRECT_RESULT void * _Nonnull) SWIFT_NOEXCEPT SWIFT_CALL; // init()
// CHECK-NEXT: SWIFT_EXTERN void $s4Init11LargeStructV1x1yACSi_AA010FirstSmallC0VtcfC(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, struct swift_interop_passStub_Init_uint32_t_0_4 y) SWIFT_NOEXCEPT SWIFT_CALL; // init(x:y:)
// CHECK: SWIFT_EXTERN struct swift_interop_returnStub_Init_[[PTRENC:void_ptr_0_[0-9]]] $s4Init28StructWithRefCountStoredPropVACycfC(void) SWIFT_NOEXCEPT SWIFT_CALL; // init()
// CHECK-NEXT: SWIFT_EXTERN struct swift_interop_returnStub_Init_[[PTRENC]] $s4Init28StructWithRefCountStoredPropV1xACSi_tcfC(ptrdiff_t x) SWIFT_NOEXCEPT SWIFT_CALL; // init(x:)
public struct FirstSmallStruct {
public let x: UInt32
public init() {
x = 42
}
public init(_ x: Int) {
self.x = UInt32(x)
}
private init(_ y: Float) {
fatalError("nope")
}
}
// CHECK: class FirstSmallStruct final {
// CHECK-NEXT: public:
// CHECK: inline FirstSmallStruct(FirstSmallStruct &&) = default;
// CHECK-NEXT: inline uint32_t getX() const;
// CHECK-NEXT: static inline FirstSmallStruct init();
// CHECK-NEXT: static inline FirstSmallStruct init(swift::Int x);
// CHECK-NEXT: private:
public struct LargeStruct {
public let x1, x2, x3, x4, x5, x6: Int
public init () {
x1 = 0
x2 = 0
x3 = 0
x4 = 0
x5 = 0
x6 = 0
}
public init(x: Int, y: FirstSmallStruct) {
x1 = x
x2 = Int(y.x)
x3 = -x
x4 = 0
x5 = 11
x6 = x * Int(y.x)
}
}
// CHECK: class LargeStruct final {
// CHECK: inline swift::Int getX6() const;
// CHECK-NEXT: static inline LargeStruct init();
// CHECK-NEXT: static inline LargeStruct init(swift::Int x, const FirstSmallStruct& y);
// CHECK-NEXT: private:
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
public init() {
storedRef = RefCountedClass(x: -1)
}
public init(x: Int) {
storedRef = RefCountedClass(x: x)
}
}
// CHECK: static inline StructWithRefCountStoredProp init();
// CHECK-NEXT: static inline StructWithRefCountStoredProp init(swift::Int x);
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s4Init16FirstSmallStructV1xs6UInt32Vvg(_impl::swift_interop_passDirect_Init_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct FirstSmallStruct::init() {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_uint32_t_0_4(result, _impl::$s4Init16FirstSmallStructVACycfC());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct FirstSmallStruct::init(swift::Int x) {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_uint32_t_0_4(result, _impl::$s4Init16FirstSmallStructVyACSicfC(x));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline LargeStruct LargeStruct::init() {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s4Init11LargeStructVACycfC(result);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::init(swift::Int x, const FirstSmallStruct& y) {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s4Init11LargeStructV1x1yACSi_AA010FirstSmallC0VtcfC(result, x, _impl::swift_interop_passDirect_Init_uint32_t_0_4(_impl::_impl_FirstSmallStruct::getOpaquePointer(y)));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline StructWithRefCountStoredProp StructWithRefCountStoredProp::init() {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_[[PTRENC]](result, _impl::$s4Init28StructWithRefCountStoredPropVACycfC());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline StructWithRefCountStoredProp StructWithRefCountStoredProp::init(swift::Int x) {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_[[PTRENC]](result, _impl::$s4Init28StructWithRefCountStoredPropV1xACSi_tcfC(x));
// CHECK-NEXT: });
// CHECK-NEXT: }
| 8cc8eb3e6d09acc3655dba9b6da6e5c6 | 40.015267 | 229 | 0.687326 | false | false | false | false |
Onetaway/iOS8-day-by-day | refs/heads/master | 18-split-view-controller/NinjaWeapons/NinjaWeapons/Weapon.swift | apache-2.0 | 3 | //
// Copyright 2014 Scott Logic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
struct Weapon {
let name: String
let partOfSpeech: String
let alternative: String
let detail: String
let imageName: String
var image: UIImage {
return UIImage(named: imageName)
}
init(dictionary: [String:String]) {
name = dictionary["name"]!
partOfSpeech = dictionary["partOfSpeech"]!
alternative = dictionary["alternative"]!
detail = dictionary["detail"]!
imageName = dictionary["image"]!
}
}
class WeaponProvider {
private(set) var weapons = [Weapon]()
convenience init() {
// Default name
self.init(plistNamed: "WeaponCollection")
}
init(plistNamed: String) {
self.weapons = self.loadWeaponsFromPListNamed(plistNamed)
}
private func loadWeaponsFromPListNamed(plistName: String) -> [Weapon] {
let path = NSBundle.mainBundle().pathForResource(plistName, ofType: "plist")
let rawArray = NSArray(contentsOfFile: path!)
var weaponCollection = [Weapon]()
for rawWeapon in rawArray as [[String:String]] {
weaponCollection.append(Weapon(dictionary: rawWeapon))
}
return weaponCollection
}
}
| 3bc25e0e1c5ccb0be7dfc5010bada25d | 26.532258 | 80 | 0.705917 | false | false | false | false |
SoySauceLab/CollectionKit | refs/heads/master | CollectionKitTests/ComposedHeaderProviderSpec.swift | mit | 1 | //
// ComposedHeaderProviderSpec.swift
// CollectionKitTests
//
// Created by Luke Zhao on 2018-10-17.
// Copyright © 2018 lkzhao. All rights reserved.
//
@testable import CollectionKit
import Quick
import Nimble
class ComposedHeaderProviderSpec: QuickSpec {
override func spec() {
describe("ComposedHeaderProvider") {
let headerViewSource = ClosureViewSource(viewUpdater: { (view: UILabel, data: HeaderData, index) in
view.text = "header \(data.index)"
})
let headerSizeSource = ClosureSizeSource(sizeSource: { (_, data: HeaderData, collectionSize) in
return CGSize(width: collectionSize.width, height: 50)
})
it("support all the initialization methods") {
let collectionView = CollectionView()
let provider1 = SimpleTestProvider(data: [1, 2, 3, 4])
let provider2 = SimpleTestProvider(data: ["a", "b"])
let provider3 = SimpleTestProvider(data: ["hello", "collectionKit"])
collectionView.provider =
ComposedHeaderProvider(headerViewSource: { (headerView: UILabel, data, index) in },
headerSizeSource: { _, _, collectionSize in return CGSize(width: collectionSize.width, height: 50) },
sections: [provider1, provider2, provider3])
collectionView.provider =
ComposedHeaderProvider(headerViewSource: { (headerView: UILabel, data, index) in },
headerSizeSource: headerSizeSource,
sections: [provider1, provider2, provider3])
collectionView.provider =
ComposedHeaderProvider(headerViewSource: headerViewSource,
headerSizeSource: { _, _, collectionSize in return CGSize(width: collectionSize.width, height: 50) },
sections: [provider1, provider2, provider3])
collectionView.provider =
ComposedHeaderProvider(headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider1, provider2, provider3])
}
it("combines multiple provider") {
let provider1 = SimpleTestProvider(data: [1, 2, 3, 4])
let provider2 = SimpleTestProvider(data: ["a", "b"])
let provider3 = SimpleTestProvider(data: ["hello", "collectionKit"])
let composer = ComposedHeaderProvider(headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider1, provider2, provider3])
let collectionView = CollectionView(provider: composer)
collectionView.frame = CGRect(x: 0, y: 0, width: 300, height: 500)
collectionView.layoutIfNeeded()
expect(collectionView.visibleCells.count) == 11
expect((collectionView.subviews[1] as! UILabel).text) == "1"
expect((collectionView.subviews[6] as! UILabel).text) == "a"
expect((collectionView.subviews[9] as! UILabel).text) == "hello"
}
it("supports nesting") {
let provider1 = SimpleTestProvider(data: [1, 2, 3, 4])
let provider2 = SimpleTestProvider(data: ["a", "b"])
let provider3 = SimpleTestProvider(data: ["hello", "collectionKit"])
let provider4 = SimpleTestProvider(data: [])
let provider5 = SimpleTestProvider(data: [5.0])
let composer = ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [
ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [
ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider1, provider2]
),
provider3
]),
ComposedProvider(),
ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider4, provider5]
)
]
)
let collectionView = CollectionView(provider: composer)
collectionView.frame = CGRect(x: 0, y: 0, width: 300, height: 700)
collectionView.layoutIfNeeded()
expect(collectionView.visibleCells.count) == 18
expect((collectionView.subviews as! [UILabel]).map({ $0.text! })) == [
"header 0",
"header 0",
"header 0",
"1",
"2",
"3",
"4",
"header 1",
"a",
"b",
"header 1",
"hello",
"collectionKit",
"header 1",
"header 2",
"header 0",
"header 1",
"5.0",
]
}
it("triggers reload") {
let provider1 = SimpleTestProvider(data: [1, 2, 3, 4])
let provider2 = SimpleTestProvider(data: ["a", "b"])
let provider3 = SimpleTestProvider(data: ["hello", "collectionKit"])
let composer = ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider1, provider2, provider3]
)
let collectionView = CollectionView(provider: composer)
collectionView.frame = CGRect(x: 0, y: 0, width: 300, height: 500)
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 1
composer.sections = [provider2]
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 2
expect(collectionView.visibleCells.count) == 3
expect((collectionView.subviews[0] as! UILabel).text) == "header 0"
expect((collectionView.subviews[1] as! UILabel).text) == "a"
expect((collectionView.subviews[2] as! UILabel).text) == "b"
composer.animator = ScaleAnimator()
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 3
provider2.data = ["b"]
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 4
expect(collectionView.visibleCells.count) == 2
expect((collectionView.subviews[1] as! UILabel).text) == "b"
provider1.data = [3, 4, 5] // provider1 is not a section anymore, shouldnt trigger reload
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 4
expect((collectionView.subviews[0] as! UILabel).frame) == CGRect(x: 0, y: 0, width: 300, height: 50)
composer.headerSizeSource = ClosureSizeSource(sizeSource: { (index, data, maxSize) -> CGSize in
return CGSize(width: 50, height: 50)
})
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 4 // shouldn't trigger reload, but should layout
expect((collectionView.subviews[0] as! UILabel).frame) == CGRect(x: 0, y: 0, width: 50, height: 50)
composer.headerViewSource = ClosureViewSource(viewUpdater: { (view, data, index) in })
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 5
}
it("shouldn't reload when it doesn't need to") {
let provider1 = SimpleTestProvider(data: [1, 2, 3, 4])
let provider2 = SimpleTestProvider(data: ["a", "b"])
let provider3 = SimpleTestProvider(data: ["hello", "collectionKit"])
let composer = ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider1, provider2, provider3]
)
let collectionView = CollectionView(provider: composer)
collectionView.frame = CGRect(x: 0, y: 0, width: 300, height: 500)
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 1
expect(collectionView.subviews[1].frame.origin) == CGPoint(x: 0, y: 50)
expect(collectionView.subviews[2].frame.origin) == CGPoint(x: 50, y: 50)
provider1.sizeSource = ClosureSizeSource(sizeSource: { _, _, _ in
return CGSize(width: 30, height: 30)
})
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 1
expect(collectionView.subviews[1].frame.origin) == CGPoint(x: 0, y: 50)
expect(collectionView.subviews[2].frame.origin) == CGPoint(x: 30, y: 50)
// changing layout shouldn't reload, but will invalidate layout
provider1.layout = FlowLayout(justifyContent: .spaceBetween)
collectionView.layoutIfNeeded()
expect(collectionView.reloadCount) == 1
expect(collectionView.subviews[1].frame.origin) == CGPoint(x: 0, y: 50)
expect(collectionView.subviews[2].frame.origin) != CGPoint(x: 30, y: 50)
// changing layout shouldn't reload, but will invalidate layout
provider1.layout = FlowLayout()
composer.layout = FlowLayout(justifyContent: .center)
collectionView.layoutIfNeeded()
print(collectionView.subviews.map({ $0.frame }))
expect(collectionView.reloadCount) == 1
expect(collectionView.subviews[1].frame.origin) != CGPoint(x: 0, y: 50)
}
it("support tap") {
var lastTappedText: String?
let provider1 = SimpleTestProvider(data: [1, 2, 3, 4])
let provider2 = SimpleTestProvider(data: ["a", "b"])
let tapProvider = BasicProvider(
dataSource: [11, 12],
viewSource: {
(label: UILabel, data: Int, index: Int) in
label.text = "\(data)"
},
sizeSource: { (index: Int, data: Int, collectionSize: CGSize) -> CGSize in
return CGSize(width: 50, height: 50)
},
tapHandler: { context in
lastTappedText = context.view.text
}
)
let composer = ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [
ComposedHeaderProvider(
headerViewSource: headerViewSource,
headerSizeSource: headerSizeSource,
sections: [provider1,
provider2]),
tapProvider
]
)
let collectionView = CollectionView(provider: composer)
collectionView.frame = CGRect(x: 0, y: 0, width: 200, height: 500)
collectionView.layoutIfNeeded()
UITapGestureRecognizer.testLocation = CGPoint(x: 10, y: 310)
collectionView.tap(gesture: collectionView.tapGestureRecognizer)
UITapGestureRecognizer.testLocation = nil
expect(lastTappedText) == "11"
}
}
}
}
| d8a4ece87b17c19a2ccbbccfa2ea5dcf | 42.162698 | 134 | 0.603567 | false | true | false | false |
huangboju/Moots | refs/heads/master | Examples/Lumia/Lumia/Component/Transitions/PhotoTransitioning/AssetViewController.swift | mit | 1 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The AssetViewController is a basic view controller created to display a grid of photos or a one-up presentation of a single photo.
*/
import UIKit
import Photos
private let reuseIdentifier = "Cell"
enum AssetLayoutStyle {
case grid
case oneUp
private func itemSize(inBoundingSize size: CGSize) -> (itemSize: CGSize, lineSpacing: Int) {
var length = 0
let w = Int(size.width)
var spacing = 1
for i in 1...3 {
for n in 4...8 {
let x = w - ((n-1) * i)
if x % n == 0 && (x/n) > length {
length = x/n
spacing = i
}
}
}
return (CGSize(width: length, height: length), spacing)
}
func recalculate(layout: UICollectionViewFlowLayout, inBoundingSize size: CGSize) {
switch self {
case .grid:
layout.minimumLineSpacing = 1
layout.minimumInteritemSpacing = 1
layout.sectionInset = UIEdgeInsets.zero
let itemInfo = self.itemSize(inBoundingSize: size)
layout.minimumLineSpacing = CGFloat(itemInfo.lineSpacing)
layout.itemSize = itemInfo.itemSize
case .oneUp:
layout.minimumLineSpacing = 40
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
layout.scrollDirection = .horizontal;
layout.itemSize = size
}
}
}
class AssetViewController: UICollectionViewController, UICollectionViewDataSourcePrefetching {
let layoutStyle: AssetLayoutStyle
let fetchResult: PHFetchResult<PHAsset>
let imageManager: PHCachingImageManager
let queue: DispatchQueue
var assetSize: CGSize = CGSize.zero
var transitioningAsset: PHAsset?
var sizeTransitionIndexPath: IndexPath?
// MARK: Initializers
init(layoutStyle: AssetLayoutStyle, fetchResult: PHFetchResult<PHAsset>? = nil, imageManager: PHCachingImageManager? = nil) {
self.layoutStyle = layoutStyle
if let fetchResult = fetchResult {
self.fetchResult = fetchResult
} else {
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
self.fetchResult = PHAsset.fetchAssets(with: options)
}
if let imageManager = imageManager {
self.imageManager = imageManager
} else {
self.imageManager = PHCachingImageManager()
}
queue = DispatchQueue(label: "com.photo.prewarm", qos: .default, attributes: [.concurrent], autoreleaseFrequency: .inherit, target: nil)
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Private
private var flowLayout: UICollectionViewFlowLayout {
return collectionViewLayout as! UICollectionViewFlowLayout
}
private func recalculateItemSize(inBoundingSize size: CGSize) {
layoutStyle.recalculate(layout: flowLayout, inBoundingSize: size)
let itemSize = flowLayout.itemSize
let scale = UIScreen.main.scale
assetSize = CGSize(width: itemSize.width * scale, height: itemSize.height * scale);
}
// MARK:
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
view.clipsToBounds = true
if let collectionView = self.collectionView {
collectionView.register(AssetCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.isPrefetchingEnabled = true
collectionView.prefetchDataSource = self
collectionView.backgroundColor = UIColor.clear
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
recalculateItemSize(inBoundingSize: self.view.bounds.size)
switch layoutStyle {
case .grid:
title = "All Photos"
case .oneUp:
collectionView.contentInsetAdjustmentBehavior = .never
self.collectionView?.isPagingEnabled = true
self.collectionView?.frame = view.frame.insetBy(dx: -20.0, dy: 0.0)
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
recalculateItemSize(inBoundingSize: size)
if view.window == nil {
view.frame = CGRect(origin: view.frame.origin, size: size)
view.layoutIfNeeded()
} else {
let indexPath = self.collectionView?.indexPathsForVisibleItems.last
coordinator.animate(alongsideTransition: { ctx in
self.collectionView?.layoutIfNeeded()
}, completion: { _ in
if self.layoutStyle == .oneUp, let indexPath = indexPath {
self.collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
}
})
}
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchResult.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! AssetCell
if layoutStyle == .oneUp {
cell.imageView.contentMode = .scaleAspectFit;
}
let asset = fetchResult.object(at: indexPath.item)
cell.assetIdentifier = asset.localIdentifier
let options = PHImageRequestOptions()
options.deliveryMode = .opportunistic
options.isNetworkAccessAllowed = true
self.imageManager.requestImage(for: asset, targetSize: self.assetSize, contentMode: .aspectFit, options: options) { (result, info) in
if (cell.assetIdentifier == asset.localIdentifier) {
cell.imageView.image = result
}
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if layoutStyle == .grid {
let assetViewController = AssetViewController(layoutStyle: .oneUp, fetchResult: fetchResult, imageManager: imageManager)
assetViewController.flowLayout.itemSize = view.bounds.size
assetViewController.transitioningAsset = fetchResult.object(at: indexPath.item)
navigationController?.pushViewController(assetViewController, animated: true)
}
}
override func collectionView(_ collectionView: UICollectionView, targetContentOffsetForProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard layoutStyle == .oneUp, let indexPath = collectionView.indexPathsForVisibleItems.last, let layoutAttributes = flowLayout.layoutAttributesForItem(at: indexPath) else {
return proposedContentOffset
}
return CGPoint(x: layoutAttributes.center.x - (layoutAttributes.size.width / 2.0) - (flowLayout.minimumLineSpacing / 2.0), y: 0)
}
// MARK: UICollectionViewDataSourcePrefetching
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
queue.async {
self.imageManager.startCachingImages(for: indexPaths.map{self.fetchResult.object(at: $0.item)}, targetSize: self.assetSize, contentMode: .aspectFill, options: nil)
}
}
func collectionView(_ collectionView: UICollectionView, cancelPrefetchingForItemsAt indexPaths: [IndexPath]) {
queue.async {
self.imageManager.stopCachingImages(for: indexPaths.map{self.fetchResult.object(at: $0.item)}, targetSize: self.assetSize, contentMode: .aspectFill, options: nil)
}
}
}
| d7490f79705a52953f5dc14e63369b33 | 38.302326 | 179 | 0.649112 | false | false | false | false |
srochiramani/Movies | refs/heads/master | Movies/Movies/MoviesTableViewController.swift | apache-2.0 | 1 | //
// MoviesTableViewController.swift
// Movies
//
// Created by Sunny Rochiramani on 5/5/15.
// Copyright (c) 2015 Codepath. All rights reserved.
//
import UIKit
class MoviesTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let instructorKey = "dagqdghwaq3e3mxyrp7kmmj5"
var movies : [NSDictionary]?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var errorMessageLabel: UILabel!
var pullToRefresh : UIRefreshControl!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
self.tableView.delegate = self
self.errorMessageLabel.hidden = true
self.pullToRefresh = UIRefreshControl()
self.pullToRefresh.addTarget(self, action: "onRefresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.insertSubview(self.pullToRefresh, atIndex: 0)
showInitialLoadingIndicator()
fetchLatestMovies()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if movies != nil {
return movies!.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MovieTableCell", forIndexPath: indexPath) as! MovieTableViewCell
let movie = self.movies![indexPath.row]
cell.titleLabel?.text = movie["title"] as? String
cell.synopsisLabel.text = movie["synopsis"] as? String
let posterUrl = NSURL(string: movie.valueForKeyPath("posters.thumbnail") as! String)!
cell.posterImageView.setImageWithURL(posterUrl)
let audienceScore = movie.valueForKeyPath("ratings.audience_score")!
cell.userReviewScoreLabel.text = audienceScore.stringValue + "%"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let cell = sender as! MovieTableViewCell
let indexPath = tableView.indexPathForCell(cell)!
let movie = self.movies![indexPath.row]
let movieDetailsViewController = segue.destinationViewController as! MoviesDetailViewController
movieDetailsViewController.movie = movie
}
func fetchLatestMovies() {
let url = NSURL(string: "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=" + instructorKey)!
let request = NSURLRequest(URL: url)
let queue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
let httpResponse = response as! NSHTTPURLResponse
println("response: \(response) + error: \(error)")
if (data != nil) {
var jsonResult: NSDictionary? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as? NSDictionary
println("AsSynchronous\(jsonResult)")
if (jsonResult != nil) {
let errorMessage = jsonResult!["error"] as? String
if (errorMessage != nil) {
self.showErrorMessage("Error: " + errorMessage!)
} else {
self.movies = jsonResult!["movies"] as! [NSDictionary]?
println("movies size: \(self.movies!.count)")
self.tableView.reloadData()
self.hideInitialLoadingIndicator()
}
}
}
self.pullToRefresh.endRefreshing()
})
}
func onRefresh() {
self.fetchLatestMovies()
}
func showInitialLoadingIndicator() {
self.loadingIndicator.hidden = false
self.loadingIndicator.startAnimating()
self.tableView.hidden = true
}
func hideInitialLoadingIndicator() {
self.loadingIndicator.stopAnimating()
self.loadingIndicator.hidden = true
self.tableView.hidden = false
}
func showErrorMessage(error : String) {
self.errorMessageLabel.text = error
self.errorMessageLabel.hidden = false
self.tableView.hidden = true
self.loadingIndicator.hidden = true
}
}
| ae87a0e865d94480891601748070d8bf | 34.862319 | 160 | 0.631643 | false | false | false | false |
shahabc/ProjectNexus | refs/heads/master | Mobile Buy SDK Sample Apps/Advanced App - ObjC/Pods/CKWaveCollectionViewTransition/Classes/Extensions/UICollectionViewExtension.swift | mit | 1 | //
// UICollectionViewExtension.swift
// CKWaveCollectionViewTransition
//
// Created by Salvation on 7/21/15.
// Copyright (c) 2015 CezaryKopacz. All rights reserved.
//
import UIKit
extension UICollectionView {
func numberOfVisibleRowsAndColumn() -> (rows: Int, columns: Int) {
var rows = 1
var columns = 0
var currentWidth: CGFloat = 0.0
let visibleCells = self.visibleCells
for cell in visibleCells {
if (currentWidth + cell.frame.size.width) < self.frame.size.width {
currentWidth += cell.frame.size.width
if rows == 1 { //we only care about first row
columns += 1
}
} else {
rows += 1
currentWidth = cell.frame.size.width
}
}
return (rows, columns)
}
}
| f8b3664c8864db51659ab97a3fd945de | 23.763158 | 79 | 0.512221 | false | false | false | false |
CoderYLiu/30DaysOfSwift | refs/heads/master | Project 02 - CustomFont/CustomFont/ViewController.swift | mit | 1 | //
// ViewController.swift
// CustomFont <https://github.com/DeveloperLY/30DaysOfSwift>
//
// Created by Liu Y on 16/4/8.
// Copyright © 2016年 DeveloperLY. All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var changeFontButton: UIButton!
@IBOutlet weak var fontTableView: UITableView!
var data = ["30 Days Swift", "这些字体特别适合打「奋斗」和「理想」", "谢谢「造字工房」,本案例不涉及商业使用", "使用到造字工房劲黑体,致黑体,童心体", "呵呵,再见🤗 See you next Project", "简书:DeveloperLY"]
var fontNames = ["MFTongXin_Noncommercial-Regular", "MFJinHei_Noncommercial-Regular", "MFZhiHei_Noncommercial-Regular", "Gaspar Regular"]
var fontRowIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
for family in UIFont.familyNames {
for font in UIFont.fontNames(forFamilyName: family) {
print(font)
}
}
changeFontButton.layer.cornerRadius = 55;
fontTableView.rowHeight = 50;
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
@IBAction func changeFontDidClick(_ sender: UIButton) {
fontRowIndex = (fontRowIndex + 1) % 4
fontTableView.reloadData()
}
// MARK: - <UITableViewDataSource>
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = fontTableView.dequeueReusableCell(withIdentifier: "FontCell", for: indexPath)
let text = data[indexPath.row]
cell.textLabel?.text = text;
cell.textLabel?.textColor = UIColor.white
cell.textLabel?.font = UIFont(name:self.fontNames[fontRowIndex], size: 16.0)
return cell;
}
}
| 6d8bc0b6ce0abc7d24cda2c4fa4402cd | 30.279412 | 148 | 0.647861 | false | false | false | false |
tkester/swift-algorithm-club | refs/heads/master | Depth-First Search/DepthFirstSearch.playground/Sources/Graph.swift | mit | 1 | public class Graph: CustomStringConvertible, Equatable {
public private(set) var nodes: [Node]
public init() {
self.nodes = []
}
public func addNode(_ label: String) -> Node {
let node = Node(label)
nodes.append(node)
return node
}
public func addEdge(_ source: Node, neighbor: Node) {
let edge = Edge(neighbor)
source.neighbors.append(edge)
}
public var description: String {
var description = ""
for node in nodes {
if !node.neighbors.isEmpty {
description += "[node: \(node.label) edges: \(node.neighbors.map { $0.neighbor.label})]"
}
}
return description
}
public func findNodeWithLabel(_ label: String) -> Node {
return nodes.filter { $0.label == label }.first!
}
public func duplicate() -> Graph {
let duplicated = Graph()
for node in nodes {
duplicated.addNode(node.label)
}
for node in nodes {
for edge in node.neighbors {
let source = duplicated.findNodeWithLabel(node.label)
let neighbour = duplicated.findNodeWithLabel(edge.neighbor.label)
duplicated.addEdge(source, neighbor: neighbour)
}
}
return duplicated
}
}
public func == (_ lhs: Graph, rhs: Graph) -> Bool {
return lhs.nodes == rhs.nodes
}
| d8c29bd948d453e5103dd4f199e661bb | 22.745455 | 96 | 0.616386 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Foundation/Extensions/UITabBarItem+Conveniences.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public struct TabItemContent {
let title: String
let image: String
let selectedImage: String
let accessibility: Accessibility
public init(
title: String,
image: String,
selectedImage: String,
accessibility: Accessibility
) {
self.title = title
self.image = image
self.selectedImage = selectedImage
self.accessibility = accessibility
}
}
extension UITabBarItem {
public convenience init(with content: TabItemContent) {
self.init(
title: content.title,
image: UIImage(named: content.image),
selectedImage: UIImage(named: content.selectedImage)
)
accessibilityIdentifier = content.accessibility.id
}
}
| 8378206830ef1de4e5e58202b90a40d8 | 24.575758 | 64 | 0.645735 | false | false | false | false |
tattn/SPAJAM2017-Final | refs/heads/master | SPAJAM2017Final/Utility/Extension/UIColor+.swift | mit | 1 | //
// UIColor+.swift
// HackathonStarter
//
// Created by 田中 達也 on 2016/06/30.
// Copyright © 2016年 tattn. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let g = CGFloat((hex & 0x00FF00) >> 8) / 255.0
let b = CGFloat(hex & 0x0000FF) / 255.0
self.init(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
convenience init?(rgbHexString: String, alpha: CGFloat = 1.0) {
let scanner = Scanner(string: rgbHexString.replacingOccurrences(of: "#", with: ""))
var rgbHex: UInt32 = 0
guard scanner.scanHexInt32(&rgbHex) else {
return nil
}
self.init(hex: Int(rgbHex), alpha: alpha)
}
@nonobjc
convenience init(red: Int, green: Int, blue: Int, alpha: Double = 1.0) {
self.init(red: CGFloat(red) / 255, green: CGFloat(green) / 255, blue: CGFloat(blue) / 255, alpha: CGFloat(alpha))
}
}
| 7324826b60d9c6e18a5bfef02b5788f6 | 27.971429 | 121 | 0.593688 | false | false | false | false |
Flinesoft/BartyCrouch | refs/heads/main | Demo/Untouched/Demo/BartyCrouch.swift | mit | 1 | //
// This file is required in order for the `transform` task of the translation helper tool BartyCrouch to work.
// See here for more details: https://github.com/Flinesoft/BartyCrouch
//
import Foundation
enum BartyCrouch {
enum SupportedLanguage: String {
// TODO: remove unsupported languages from the following cases list & add any missing languages
case arabic = "ar"
case chineseSimplified = "zh-Hans"
case chineseTraditional = "zh-Hant"
case english = "en"
case french = "fr"
case german = "de"
case hindi = "hi"
case italian = "it"
case japanese = "ja"
case korean = "ko"
case malay = "ms"
case portuguese = "pt-BR"
case russian = "ru"
case spanish = "es"
case turkish = "tr"
}
static func translate(key: String, translations: [SupportedLanguage: String], comment: String? = nil) -> String {
let typeName = String(describing: BartyCrouch.self)
let methodName = #function
print(
"Warning: [BartyCrouch]",
"Untransformed \(typeName).\(methodName) method call found with key '\(key)' and base translations '\(translations)'.",
"Please ensure that BartyCrouch is installed and configured correctly."
)
// fall back in case something goes wrong with BartyCrouch transformation
return "BC: TRANSFORMATION FAILED!"
}
}
| d5a14bf9489e8098794bb90b42fc2ade | 34.487805 | 131 | 0.62268 | false | false | false | false |
wangwugang1314/weiBoSwift | refs/heads/master | weiBoSwift/weiBoSwift/Classes/Main/Controller/YBTabBarController.swift | apache-2.0 | 1 | //
// YBTabBarController.swift
// weiBoSwift
//
// Created by MAC on 15/11/25.
// Copyright © 2015年 MAC. All rights reserved.
//
import UIKit
class YBTabBarController: UITabBarController {
//MARK: - 属性animated
//MARK: - ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// 准备UI
prepareUI()
// 设置渲染颜色
tabBar.tintColor = UIColor.orangeColor()
// 设置背景颜色
tabBar.backgroundColor = UIColor(patternImage: UIImage(named: "tabbar_background")!)
}
///
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// 添加中间按钮
addCenterBut()
}
// MARK: - 准备UI
private func prepareUI(){
// 首页
creatController(YBHomeController(), title: "首页", imageName: "tabbar_home")
// 消息
creatController(YBMessageController(), title: "消息", imageName: "tabbar_message_center")
// 占位
creatController(UIViewController(), title: "", imageName: "")
// 发现
creatController(YBDiscoverController(), title: "发现", imageName: "tabbar_discover")
// 我
creatController(YBMeController(), title: "我", imageName: "tabbar_profile")
}
/// 添加中间按钮
private func addCenterBut(){
// 创建按钮
let but = UIButton(frame: CGRect(x: UIScreen.width() * 0.4, y: 0, width: UIScreen.width() * 0.2 + 2, height: tabBar.viewHeight))
// 设置背景图片
but.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
but.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
but.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
but.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
// 添加
tabBar.addSubview(but)
// 设置点击事件
but.addTarget(self, action: "centerButClick", forControlEvents: UIControlEvents.TouchUpInside)
}
/// 根据指定的名称图片创建控制器
private func creatController(controller: UIViewController, title: String?, imageName: String?) {
// 创建导航控制器
let navC = YBBaseNavigationController(rootViewController: controller)
if title?.characters.count > 0 {
navC.tabBarItem.title = title
navC.tabBarItem.setTitleTextAttributes([NSUnderlineStyleAttributeName : 1], forState: UIControlState.Normal)
// 设置图片
navC.tabBarItem.image = UIImage(named: imageName!)
}
// 添加到tabBar控制器
addChildViewController(navC)
}
// MARK: - 按钮点击事件
@objc private func centerButClick(){
let nav = UINavigationController(rootViewController: YBSendViewController())
presentViewController(nav, animated: true, completion: nil)
}
// 对象销毁
// deinit{
// print("\(self) - 销毁")
// }
}
| 34902edc26fd895546464c2127e7cad7 | 32.75 | 136 | 0.628956 | false | false | false | false |
alexth/VIPER-test | refs/heads/master | ViperTest/ViperTest/Flows/Master/MasterInteractor.swift | mit | 1 | //
// MasterInteractor.swift
// ViperTest
//
// Created by Alex Golub on 10/29/16.
// Copyright (c) 2016 Alex Golub. All rights reserved.
//
import UIKit
import CoreData
protocol MasterInteractorInput: MasterViewControllerOutput {
}
protocol MasterInteractorOutput {
}
final class MasterInteractor: MasterInteractorInput {
var output: MasterInteractorOutput!
fileprivate var dataSource: FetchedTableViewDataSource!
init(withDataSource dataSource: FetchedTableViewDataSource = FetchedTableViewDataSource()) {
self.dataSource = dataSource
}
func setupDataSourceWith(tableView: UITableView) {
dataSource.tableView = tableView
dataSource.tableView.dataSource = dataSource
}
// MARK: Business logic
func insertNewObject() {
dataSource.insertNewObject()
}
func deleteObjectAt(indexPath: IndexPath) {
dataSource.deleteObjectAt(indexPath: indexPath)
}
func eventAt(indexPath: IndexPath) -> Event {
return dataSource.eventAt(indexPath: indexPath)
}
}
extension MasterInteractor: ViperInteractor {
convenience init(withOutput: ViperPresenter) {
self.init()
self.output = withOutput as! MasterInteractorOutput
}
}
| 4ad8b696f2b0f6656151d1574ca686f7 | 23.352941 | 96 | 0.719002 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/Interpreter/algorithms.swift | apache-2.0 | 32 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
func fib() {
var (a, b) = (0, 1)
while b < 10 {
print(b)
(a, b) = (b, a+b)
}
}
fib()
// CHECK: 1
// CHECK: 1
// CHECK: 2
// CHECK: 3
// CHECK: 5
// CHECK: 8
// From: <rdar://problem/17796401>
// FIXME: <rdar://problem/21993692> type checker too slow
let two_oneA = [1, 2, 3, 4].lazy.reversed()
let two_one = Array(two_oneA.filter { $0 % 2 == 0 }.map { $0 / 2 })
print(two_one)
// CHECK: [2, 1]
// rdar://problem/18208283
func flatten<Element, Seq: Sequence, InnerSequence: Sequence
where Seq.Iterator.Element == InnerSequence, InnerSequence.Iterator.Element == Element> (_ outerSequence: Seq) -> [Element] {
var result = [Element]()
for innerSequence in outerSequence {
result.append(contentsOf: innerSequence)
}
return result
}
// CHECK: [1, 2, 3, 4, 5, 6]
let flat = flatten([[1,2,3], [4,5,6]])
print(flat)
// rdar://problem/19416848
func observe<T:Sequence, V where V == T.Iterator.Element>(_ g:T) { }
observe(["a":1])
| e946bcb9f5cf025e53ae0aa26e53c905 | 22.133333 | 132 | 0.615754 | false | false | false | false |
anhnc55/fantastic-swift-library | refs/heads/master | Example/Pods/Material/Sources/iOS/MaterialAnimation.swift | mit | 2 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(MaterialAnimationDelegate)
public protocol MaterialAnimationDelegate : MaterialDelegate {
optional func materialAnimationDidStart(animation: CAAnimation)
optional func materialAnimationDidStop(animation: CAAnimation, finished flag: Bool)
}
public typealias MaterialAnimationFillModeType = String
public enum MaterialAnimationFillMode {
case Forwards
case Backwards
case Both
case Removed
}
/**
:name: MaterialAnimationFillModeToValue
*/
public func MaterialAnimationFillModeToValue(mode: MaterialAnimationFillMode) -> MaterialAnimationFillModeType {
switch mode {
case .Forwards:
return kCAFillModeForwards
case .Backwards:
return kCAFillModeBackwards
case .Both:
return kCAFillModeBoth
case .Removed:
return kCAFillModeRemoved
}
}
public typealias MaterialAnimationDelayCancelBlock = (cancel : Bool) -> Void
public struct MaterialAnimation {
/// Delay helper method.
public static func delay(time: NSTimeInterval, completion: ()-> Void) -> MaterialAnimationDelayCancelBlock? {
func dispatch_later(completion: ()-> Void) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), completion)
}
var cancelable: MaterialAnimationDelayCancelBlock?
let delayed: MaterialAnimationDelayCancelBlock = { (cancel: Bool) in
if !cancel {
dispatch_async(dispatch_get_main_queue(), completion)
}
cancelable = nil
}
cancelable = delayed
dispatch_later {
cancelable?(cancel: false)
}
return cancelable;
}
/**
:name: delayCancel
*/
public static func delayCancel(completion: MaterialAnimationDelayCancelBlock?) {
completion?(cancel: true)
}
/**
:name: animationDisabled
*/
public static func animationDisabled(animations: (() -> Void)) {
animateWithDuration(0, animations: animations)
}
/**
:name: animateWithDuration
*/
public static func animateWithDuration(duration: CFTimeInterval, animations: (() -> Void), completion: (() -> Void)? = nil) {
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setCompletionBlock(completion)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut))
animations()
CATransaction.commit()
}
/**
:name: animationGroup
*/
public static func animationGroup(animations: Array<CAAnimation>, duration: CFTimeInterval = 0.5) -> CAAnimationGroup {
let group: CAAnimationGroup = CAAnimationGroup()
group.fillMode = MaterialAnimationFillModeToValue(.Forwards)
group.removedOnCompletion = false
group.animations = animations
group.duration = duration
group.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
return group
}
/**
:name: animateWithDelay
*/
public static func animateWithDelay(delay d: CFTimeInterval, duration: CFTimeInterval, animations: (() -> Void), completion: (() -> Void)? = nil) {
delay(d) {
animateWithDuration(duration, animations: animations, completion: completion)
}
}
}
| 79a30210fbb8ba49a36d059e7ff39970 | 32.057143 | 148 | 0.766638 | false | false | false | false |
crazypoo/PTools | refs/heads/main | Pods/Instructions/Sources/Instructions/Views/CoachMarkView.swift | mit | 2 | // Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
// swiftlint:disable force_cast
/// The actual coach mark that will be displayed.
class CoachMarkView: UIView {
// MARK: - Internal properties
/// The body of the coach mark (likely to contain some text).
let bodyView: CoachMarkBodyView
/// The arrow view, note that the arrow view is not mandatory.
private(set) var arrowView: CoachMarkArrowView?
/// The arrow orientation (where it will sit relative to the body view, i.e.
/// above or below.)
private(set) var arrowOrientation: CoachMarkArrowOrientation?
/// The offset (in case the arrow is required to overlap the body)
var arrowOffset: CGFloat = 0.0
/// The control used to get to the next coach mark.
var nextControl: UIControl? {
return bodyView.nextControl
}
// MARK: - Private properties
private var bodyUIView: UIView { return bodyView as! UIView }
private var arrowUIView: UIView? { return arrowView as? UIView }
private var innerConstraints = CoachMarkViewConstraints()
private let coachMarkLayoutHelper: CoachMarkInnerLayoutHelper
// MARK: - Initialization
/// Allocate and initliaze the coach mark view, with the given subviews.
///
/// - Parameter bodyView: the mandatory body view
/// - Parameter arrowView: the optional arrow view
/// - Parameter arrowOrientation: the arrow orientation, either .Top or .Bottom
/// - Parameter arrowOffset: the arrow offset (in case the arrow is required
/// to overlap the body) - a positive number
/// will make the arrow overlap.
/// - Parameter coachMarkInnerLayoutHelper: auto-layout constraints helper.
init(bodyView: UIView & CoachMarkBodyView,
arrowView: (UIView & CoachMarkArrowView)? = nil,
arrowOrientation: CoachMarkArrowOrientation? = nil, arrowOffset: CGFloat? = nil,
coachMarkInnerLayoutHelper: CoachMarkInnerLayoutHelper) {
self.bodyView = bodyView
self.arrowView = arrowView
self.arrowOrientation = arrowOrientation
self.coachMarkLayoutHelper = coachMarkInnerLayoutHelper
if let arrowOffset = arrowOffset {
self.arrowOffset = arrowOffset
}
super.init(frame: CGRect.zero)
self.bodyView.highlightArrowDelegate = self
self.layoutViewComposition()
}
required init?(coder aDecoder: NSCoder) {
fatalError(ErrorMessage.Fatal.doesNotSupportNSCoding)
}
// MARK: - Internal Method
//TODO: Better documentation
/// Change the arrow horizontal position to the given position.
/// `position` is relative to:
/// - `.Leading`: `offset` is relative to the leading edge of the overlay;
/// - `.Center`: `offset` is relative to the center of the overlay;
/// - `.Trailing`: `offset` is relative to the trailing edge of the overlay.
///
/// - Parameter position: arrow position
/// - Parameter offset: arrow offset
func changeArrowPosition(to position: ArrowPosition, offset: CGFloat) {
guard let arrowUIView = arrowUIView else { return }
if innerConstraints.arrowXposition != nil {
self.removeConstraint(innerConstraints.arrowXposition!)
}
innerConstraints.arrowXposition = coachMarkLayoutHelper.horizontalArrowConstraints(
for: (bodyView: bodyUIView, arrowView: arrowUIView), withPosition: position,
horizontalOffset: offset)
innerConstraints.arrowXposition?.isActive = true
}
// MARK: - Private Method
/// Layout the body view and the arrow view together.
private func layoutViewComposition() {
translatesAutoresizingMaskIntoConstraints = false
self.addSubview(bodyUIView)
self.addConstraints(bodyUIView.makeConstraintToFillSuperviewHorizontally())
if let arrowUIView = arrowUIView, let arrowOrientation = self.arrowOrientation {
self.addSubview(arrowUIView)
innerConstraints.arrowXposition = coachMarkLayoutHelper.horizontalArrowConstraints(
for: (bodyView: bodyUIView, arrowView: arrowUIView), withPosition: .center,
horizontalOffset: 0)
innerConstraints.arrowXposition?.isActive = true
self.addConstraints(coachMarkLayoutHelper.verticalConstraints(
for: (bodyView: bodyUIView, arrowView: arrowUIView), in: self,
withProperties: (orientation: arrowOrientation, verticalArrowOffset: arrowOffset)
))
} else {
bodyUIView.topAnchor.constraint(equalTo: topAnchor).isActive = true
bodyUIView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
}
// MARK: - Protocol conformance | CoachMarkBodyHighlightArrowDelegate
extension CoachMarkView: CoachMarkBodyHighlightArrowDelegate {
func highlightArrow(_ highlighted: Bool) {
self.arrowView?.isHighlighted = highlighted
}
}
private struct CoachMarkViewConstraints {
/// The horizontal position of the arrow, likely to be at the center of the
/// cutout path.
var arrowXposition: NSLayoutConstraint?
/// The constraint making the body stick to its parent.
var bodyStickToParent: NSLayoutConstraint?
init () { }
}
| 71b7dbd4e4488731c6acc4823f816188 | 37.716312 | 97 | 0.682909 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | refs/heads/master | the-blue-alliance-ios/View Controllers/Teams/TeamsContainerViewController.swift | mit | 1 | import CoreData
import Firebase
import MyTBAKit
import Photos
import TBAData
import TBAKit
import UIKit
class TeamsContainerViewController: ContainerViewController {
private(set) var myTBA: MyTBA
private(set) var pasteboard: UIPasteboard?
private(set) var photoLibrary: PHPhotoLibrary?
private(set) var searchService: SearchService
private(set) var statusService: StatusService
private(set) var urlOpener: URLOpener
var searchController: UISearchController!
private(set) var teamsViewController: TeamsViewController!
// MARK: - Init
init(myTBA: MyTBA, pasteboard: UIPasteboard? = nil, photoLibrary: PHPhotoLibrary? = nil, searchService: SearchService, statusService: StatusService, urlOpener: URLOpener, dependencies: Dependencies) {
self.myTBA = myTBA
self.pasteboard = pasteboard
self.photoLibrary = photoLibrary
self.searchService = searchService
self.statusService = statusService
self.urlOpener = urlOpener
teamsViewController = TeamsViewController(refreshProvider: searchService, showSearch: false, dependencies: dependencies)
super.init(viewControllers: [teamsViewController], dependencies: dependencies)
title = RootType.teams.title
tabBarItem.image = RootType.teams.icon
teamsViewController.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Only show Search in container view on iPhone
if UIDevice.isPhone {
setupSearchController()
}
}
}
extension TeamsContainerViewController: TeamsViewControllerDelegate, SearchContainer, SearchContainerDelegate, SearchViewControllerDelegate {}
| be314e712c2b720da49d3ff639d367b0 | 30.40678 | 204 | 0.728009 | false | false | false | false |
Dormmate/DORMLibrary | refs/heads/master | Example/DORM/TabbarItem_Example2.swift | mit | 1 | //
// TabbarItem_Example2.swift
// DORM
//
// Created by Dormmate on 2017. 5. 4..
// Copyright © 2017 Dormmate. All rights reserved.
//
import UIKit
// 탭바를 사용한다면 탭바 아이템으로 사용하는 뷰이다.
// If you use tabbar, it is view for tabbar item
class TabbarItem_Example2: UIViewController {
public var id : Int?
let label = UILabel()
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
viewInit()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewInit(){
self.label.frame = CGRect(x: 50, y: 200, width: 50, height: 50)
self.label.textColor = UIColor.black
self.view.addSubview(label)
button.frame = CGRect(x: 127.5, y: 300, width: 100, height: 50)
button.setTitle("next page", for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
self.view.addSubview(button)
}
func backButtonAction(){
self.navigationController?.popVC(animated: true)
}
}
| 3036a812bfdeffa14ec43c698456d36e | 24.510638 | 71 | 0.613845 | false | false | false | false |
SimonGetTrick/RWPickFlavor | refs/heads/master | RWPickFlavor/PickFlavorViewController.swift | mit | 1 | //
// ViewController.swift
// IceCreamShop
//
// Created by Joshua Greene on 2/8/15.
// Copyright (c) 2015 Razeware, LLC. All rights reserved.
//
import UIKit
import Alamofire
import MBProgressHUD
public class PickFlavorViewController: UIViewController, UICollectionViewDelegate {
// MARK: Instance Variables
var flavors: [Flavor] = [] {
didSet {
pickFlavorDataSource?.flavors = flavors
}
}
private var pickFlavorDataSource: PickFlavorDataSource? {
return collectionView?.dataSource as! PickFlavorDataSource?
}
private let flavorFactory = FlavorFactory()
// MARK: Outlets
@IBOutlet var contentView: UIView!
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var iceCreamView: IceCreamView!
@IBOutlet var label: UILabel!
// MARK: View Lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
loadFlavors()
}
private func loadFlavors() {
// Implement this
let urlString = "http://www.raywenderlich.com/downloads/Flavors.plist"
showLoadingHUD() // <-- Add this line
// 1
Alamofire.request(.GET, urlString, encoding: .PropertyList(.XMLFormat_v1_0, 0))
.responsePropertyList { [unowned self] request, response, array, error in
self.hideLoadingHUD() // <-- And this line
// 2
if let error = error {
println("Error: \(error)")
// 3
} else if let array = array as? [[String: String]] {
// 4
if array.isEmpty {
println("No flavors were found!")
// 5
} else {
self.flavors = self.flavorFactory.flavorsFromDictionaryArray(array)
self.collectionView.reloadData()
self.selectFirstFlavor()
}
}
}
}
private func showLoadingHUD() {
let hud = MBProgressHUD.showHUDAddedTo(contentView, animated: true)
hud.labelText = "Loading..."
}
private func hideLoadingHUD() {
MBProgressHUD.hideAllHUDsForView(contentView, animated: true)
}
private func selectFirstFlavor() {
if let flavor = flavors.first {
updateWithFlavor(flavor)
}
}
// MARK: UICollectionViewDelegate
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let flavor = flavors[indexPath.row]
updateWithFlavor(flavor)
}
// MARK: Internal
private func updateWithFlavor(flavor: Flavor) {
iceCreamView.updateWithFlavor(flavor)
label.text = flavor.name
}
}
| a90a8c4824dda898ddaf0290ff0ddbb5 | 23.8 | 113 | 0.638633 | false | false | false | false |
DanielAsher/VIPER-SWIFT | refs/heads/master | Carthage/Checkouts/RxSwift/scripts/validate-headers.swift | apache-2.0 | 7 | #!/usr/bin/swift
//
// validate-headers.swift
// scripts
//
// Created by Krunoslav Zaher on 12/26/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Validates that all headers are in this standard form
//
// {file}.swift
// Project
//
// Created by {Author} on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
Only Project is not checked yet, but it will be soon.
*/
let fileManager = NSFileManager.defaultManager()
let allowedExtensions = [
".swift",
".h",
".m",
]
let excludedRootPaths = [
".git",
"build",
"Rx.playground"
]
let excludePaths = [
"AllTests/main.swift",
"RxExample/Services/Reachability.swift",
"RxCocoaTests/RxTests-"
]
func isExtensionIncluded(path: String) -> Bool {
return (allowedExtensions.map { path.hasSuffix($0) }).reduce(false) { $0 || $1 }
}
let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let identifier = "(?:\\w|\\+|\\_|\\.|-)+"
let fileLine = try NSRegularExpression(pattern: "// (\(identifier))", options: [])
let projectLine = try NSRegularExpression(pattern: "// (\(identifier))", options: [])
let createdBy = try NSRegularExpression(pattern: "// Created by .* on \\d+/\\d+/\\d+\\.", options: [])
let copyrightLine = try NSRegularExpression(pattern: "// Copyright © (\\d+) Krunoslav Zaher. All rights reserved.", options: [])
func validateRegexMatches(regularExpression: NSRegularExpression, content: String) -> ([String], Bool) {
let range = NSRange(location: 0, length: content.characters.count)
let matches = regularExpression.matchesInString(content, options: [], range: range)
if matches.count == 0 {
print("ERROR: line `\(content)` is invalid: \(regularExpression.pattern)")
return ([], false)
}
for m in matches {
if m.numberOfRanges == 0 || !NSEqualRanges(m.range, range) {
print("ERROR: line `\(content)` is invalid: \(regularExpression.pattern)")
return ([], false)
}
}
return (matches[0 ..< matches.count].flatMap { m -> [String] in
return (1 ..< m.numberOfRanges).map { index in
return (content as NSString).substringWithRange(m.rangeAtIndex(index))
}
}, true)
}
func validateHeader(path: String) throws -> Bool {
let contents = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
let rawLines = contents.componentsSeparatedByString("\n")
var lines = rawLines.map { $0.stringByTrimmingCharactersInSet(whitespace) }
if (lines.first ?? "").hasPrefix("#") || (lines.first ?? "").hasPrefix("// This file is autogenerated.") {
lines.removeAtIndex(0)
}
if lines.count < 8 {
print("ERROR: Number of lines is less then 8, so the header can't be correct")
return false
}
for i in 0 ..< 7 {
if !lines[i].hasPrefix("//") {
print("ERROR: Line [\(i + 1)] (\(lines[i])) isn't prefixed with //")
return false
}
}
if lines[0] != "//" {
print("ERROR: Line[1] First line should be `//`")
return false
}
let (parsedFileLine, isValidFilename) = validateRegexMatches(fileLine, content: lines[1])
if !isValidFilename {
print("ERROR: Line[2] Filename line should match `\(fileLine.pattern)`")
return false
}
let fileNameInFile = parsedFileLine.first ?? ""
if fileNameInFile != (path as NSString).lastPathComponent {
print("ERROR: Line[2] invalid file name `\(fileNameInFile)`, correct content is `\((path as NSString).lastPathComponent)`")
return false
}
let (_, isValidProject) = validateRegexMatches(projectLine, content: lines[2])
if !isValidProject {
print("ERROR: Line[3] Line not maching \(projectLine.pattern)")
return false
}
if lines[3] != "//" {
print("ERROR: Line[4] Line should be `//`")
return false
}
let (_, isValidCreatedBy) = validateRegexMatches(createdBy, content: lines[4])
if !isValidCreatedBy {
print("ERROR: Line[5] Line not matching \(createdBy.pattern)")
return false
}
let (year, isValidCopyright) = validateRegexMatches(copyrightLine, content: lines[5])
if !isValidCopyright {
print("ERROR: Line[6] Line not matching \(copyrightLine.pattern)")
return false
}
if year.first == nil || !(2015...2016).contains(Int(year.first!) ?? 0) {
print("ERROR: Line[6] Wrong copyright year \(year.first ?? "?") instead of 2015...2016")
return false
}
if lines[6] != "//" {
print("ERROR: Line[7] Line not matching \(copyrightLine.pattern)")
return false
}
if lines[7] != "" {
print("ERROR: Line[8] Should be blank and not `\(lines[7])`")
return false
}
return true
}
func verifyAll(root: String) throws -> Bool {
return try fileManager.subpathsOfDirectoryAtPath(root).map { file -> Bool in
let excluded = excludePaths.map { file.hasPrefix($0) }.reduce(false) { $0 || $1 }
if excluded {
return true
}
if !isExtensionIncluded(file) {
return true
}
//print("Validating \(file)")
let isValid = try validateHeader("\(root)/\(file)")
if !isValid {
print(" while Validating \(file)")
}
return isValid
}.reduce(true) { $0 && $1 }
}
let allValid = try fileManager.contentsOfDirectoryAtPath(".").map { rootDir -> Bool in
if excludedRootPaths.contains(rootDir) {
print("Skipping \(rootDir)")
return true
}
return try verifyAll(rootDir)
}.reduce(true) { $0 && $1 }
if !allValid {
exit(-1)
} | 311837c85cdde538924301aca42974a9 | 28 | 131 | 0.612437 | false | false | false | false |
cc001/learnSwiftBySmallProjects | refs/heads/master | 10-SpotifyVideoBackground/SpotifyVideoBackground/ViewController.swift | mit | 1 | //
// ViewController.swift
// SpotifyVideoBackground
//
// Created by 陈闯 on 2016/12/20.
// Copyright © 2016年 CC. All rights reserved.
//
import UIKit
class ViewController: VideoSplashViewController {
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
setupVideoBackground()
}
func setupVideoBackground() {
let url = URL(fileURLWithPath: Bundle.main.path(forResource: "moments", ofType: "mp4")!)
videoFrame = view.frame
fillMode = .resizeAspectFill
alwaysRepeat = true
sound = true
startTime = 2.0
alpha = 0.8
contentURL = url
view.isUserInteractionEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 7750d1cbff4a21608df98ddc37dc2866 | 23.142857 | 106 | 0.629438 | false | false | false | false |
Sephiroth87/C-swifty4 | refs/heads/master | C64/Files/SaveState.swift | mit | 1 | //
// SaveState.swift
// C64
//
// Created by Fabio Ritrovato on 07/06/2016.
// Copyright © 2016 orange in a day. All rights reserved.
//
public final class SaveState {
private(set) public var data: [UInt8]
private(set) internal var cpuState: CPUState
private(set) internal var memoryState: C64MemoryState
private(set) internal var cia1State: CIAState
private(set) internal var cia2State: CIAState
private(set) internal var vicState: VICState
internal init(c64: C64) {
cpuState = c64.cpu.state
memoryState = c64.memory.state
cia1State = c64.cia1.state
cia2State = c64.cia2.state
vicState = c64.vic.state
let states: [BinaryConvertible] = [cpuState, memoryState, cia1State, cia2State, vicState]
data = states.flatMap { $0.dump() }
}
public init(data: [UInt8]) {
self.data = data
let dump = BinaryDump(data: data)
cpuState = dump.next()
memoryState = dump.next()
cia1State = dump.next()
cia2State = dump.next()
vicState = dump.next()
}
}
| 4de59417459b0a6e86f91ceb794ba960 | 28.289474 | 97 | 0.627134 | false | false | false | false |
VincenzoFreeman/CATransition | refs/heads/master | CATransition/Classes/PhotoBrowser/PhotosBrowserViewController.swift | mit | 1 | //
// PhotosBrowserViewController.swift
// CATransition
//
// Created by wenzhiji on 16/4/28.
// Copyright © 2016年 Manager. All rights reserved.
//
import UIKit
class PhotosBrowserViewController: UIViewController {
private let photosCell = "photosCell"
var indexPath : NSIndexPath?
var shops : [ShopItem]?
// MARK:- 懒加载属性
private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotosBrowserCollectionLayout())
private lazy var closeButton = UIButton(title: "关 闭", backgroundColor: UIColor.darkGrayColor(), fontSize: 14.0)
private lazy var saveButton = UIButton(title: "保 存", backgroundColor: UIColor.darkGrayColor(), fontSize: 14.0)
override func loadView() {
super.loadView()
view.frame.size.width += 15
}
override func viewDidLoad() {
super.viewDidLoad()
/// 添加子控件
setupSubViews()
// 添加数据源代理
collectionView.dataSource = self
collectionView.delegate = self
// 注册cell
collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: photosCell)
// collectionView 滚动到相应的位置
collectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: .Left, animated: false)
}
}
// MARK:- 添加子控件
extension PhotosBrowserViewController{
func setupSubViews(){
view.addSubview(collectionView)
view.addSubview(closeButton)
view.addSubview(saveButton)
// 设置子控件frame
collectionView.frame = UIScreen.mainScreen().bounds
let buttonW : CGFloat = 90
let buttonH : CGFloat = 32
let closeButtonX : CGFloat = 20
let closeButtonY = UIScreen.mainScreen().bounds.height - buttonH - closeButtonX
let saveButtonX = UIScreen.mainScreen().bounds.width - buttonW - closeButtonX
closeButton.frame = CGRectMake(closeButtonX, closeButtonY, buttonW, buttonH)
saveButton.frame = CGRectMake(saveButtonX, closeButtonY, buttonW, buttonH)
// 监听按钮点击
closeButton.addTarget(self, action: "dismissButtonClick", forControlEvents: .TouchUpInside)
saveButton.addTarget(self, action: "saveButtonClick", forControlEvents: .TouchUpInside)
}
}
// MARK:- 实现监听点击方法
extension PhotosBrowserViewController{
@objc private func dismissButtonClick(){
dismissViewControllerAnimated(true, completion: nil)
}
@objc private func saveButtonClick(){
// 取出cell显示的图片
let cell = collectionView.visibleCells().first as! PhotoBrowserCell
guard let image = cell.imageView.image else {
return
}
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
// MARK:- 实现监数据源代理方法
extension PhotosBrowserViewController : UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 有值就执行前面的count,没有值就是0
return shops?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photosCell, forIndexPath: indexPath) as! PhotoBrowserCell
cell.shop = shops?[indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
dismissButtonClick()
}
}
| 8b25e3e9cacf86f2bbc7f1e2074069d6 | 38.25 | 130 | 0.705559 | false | false | false | false |
NottingHack/instrumentation-lighting | refs/heads/main | Sources/nh-lighting/MySQL/MySQLService.swift | mit | 1 | //
// MySQLService.swift
// instrumentation-lighting
//
// Created by Matt Lloyd on 21/09/2017.
//
//
import PerfectLib
import MariaDB
import Foundation
//MARK: -
class MySQLService {
private let host: String
private let user: String
private let password: String
private let database: String
let client = MySQL()
init(host: String, user: String, password: String, database: String) {
self.host = host
self.user = user
self.password = password
self.database = database
let _ = client.setOption(.MYSQL_SET_CHARSET_NAME, "utf8")
}
func loadModels() -> Bool {
guard client.connect(host: host, user: user, password: password, db: database) else {
Log.info(message: "Failure connecting to data server \(host)")
Log.info(message: client.errorMessage())
return false
}
lighting = Lighting()
defer {
client.close() // defer ensures we close our db connection at the end of this request
}
guard loadBuildings(),
loadFloors(),
loadRooms(),
loadLights(),
loadControllers(),
loadOutputChannels(),
loadInputChannels(),
loadPatterns(),
loadLightPatterns() else {
Log.critical(message: "Falied to load Model")
return false
}
Log.info(message: "MySQL loaded model")
return true
}
func load(_ select: String, callback: (MySQL.Results.Element) -> ()) -> Bool {
guard client.query(statement: select) else {
Log.error(message: client.errorMessage())
return false
}
let results = client.storeResults()!
results.forEachRow(callback: callback)
results.close()
return true
}
func loadBuildings() -> Bool {
let select = "SELECT id, name FROM buildings"
return load(select) { (row) in
guard let id = Int(row[0]!),
let name = row[1] else {
return
}
lighting.buildings.append(Building(id: id, name: name))
}
}
func loadFloors() -> Bool {
let select = "SELECT id, name, level, building_id FROM floors"
return load(select) { (row) in
guard let id = Int(row[0]!),
let name = row[1],
let level = Int(row[2]!),
let buildingId = Int(row[3]!) else {
return
}
lighting.floors.append(Floor(id: id, name: name, level: level, buildingId: buildingId))
}
}
func loadRooms() -> Bool {
let select = "SELECT id, name, floor_id FROM rooms"
return load(select) { (row) in
guard let id = Int(row[0]!),
let name = row[1],
let floorId = Int(row[2]!) else {
return
}
lighting.rooms.append(Room(id: id, name: name, floorId: floorId))
}
}
func loadLights() -> Bool {
let select = "SELECT id, name, room_id, output_channel_id FROM lights"
return load(select) { (row) in
guard let id = Int(row[0]!),
let name = row[1],
let roomId = Int(row[2]!),
let outputChannelId = Int(row[3]!) else {
return
}
lighting.lights.append(Light(id: id, name: name, roomId: roomId, outputChannelId: outputChannelId))
}
}
func loadControllers() -> Bool {
let select = "SELECT id, name, room_id FROM lighting_controllers"
return load(select) { (row) in
guard let id = Int(row[0]!),
let name = row[1],
let roomId = Int(row[2]!) else {
return
}
lighting.controllers.append(Controller(id: id, name: name, roomId: roomId))
}
}
func loadOutputChannels() -> Bool {
let select = "SELECT id, channel, controller_id FROM lighting_output_channels"
return load(select) { (row) in
guard let id = Int(row[0]!),
let channel = Int(row[1]!),
let controllerId = Int(row[2]!) else {
return
}
lighting.outputChannels.append(OutputChannel(id: id, channel: channel, controllerId: controllerId))
}
}
func loadInputChannels() -> Bool {
let select = "SELECT id, channel, controller_id, pattern_id, statefull FROM lighting_input_channels"
return load(select) { (row) in
guard let id = Int(row[0]!),
let channel = Int(row[1]!),
let controllerId = Int(row[2]!),
let statefull = Int(row[4]!) else {
return
}
var patternId: Int?
if let patternString = row[3] {
patternId = Int(patternString)
}
lighting.inputChannels.append(InputChannel(id: id, channel: channel, controllerId: controllerId, patternId: patternId, statefull: statefull == 1))
if !inputChannelStateTracking.keys.contains(id) {
// only add the id tracking if its not allready therey
// this way we keep state over DB reload
inputChannelStateTracking[id] = false
}
}
}
func loadPatterns() -> Bool {
let select = "SELECT id, name, next_pattern_id, timeout FROM lighting_patterns"
return load(select) { (row) in
guard let id = Int(row[0]!),
let name = row[1] else {
return
}
var nextPatternId: Int?
if let nextPatternString = row[2] {
nextPatternId = Int(nextPatternString)
}
var timeout: Int?
if let timeoutString = row[3] {
timeout = Int(timeoutString)
}
lighting.patterns.append(Pattern(id: id, name: name, nextPatternId: nextPatternId, timeout: timeout))
}
}
func loadLightPatterns() -> Bool {
let select = "SELECT pattern_id, light_id, state FROM light_lighting_pattern"
return load(select) { (row) in
guard let lightId = Int(row[1]!),
let patternId = Int(row[0]!),
let state = ChannelState(rawValue: row[2]!) else {
return
}
lighting.lightPatterns.append(LigthPattern(lightId: lightId, patternId: patternId, state: state))
}
}
}
| e1434eb9c69fe6cd1a73583b272835cd | 25.408072 | 152 | 0.597385 | false | false | false | false |
Alexiuce/Tip-for-day | refs/heads/master | Example/Pods/NVActivityIndicatorView/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotate.swift | apache-2.0 | 9 | //
// NVActivityIndicatorBallClipRotate.swift
// NVActivityIndicatorView
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// 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
class NVActivityIndicatorAnimationBallClipRotate: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 0.75
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.6, 1]
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.values = [0, Double.pi, 2 * Double.pi]
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = NVActivityIndicatorShape.ringThirdFour.layerWith(size: CGSize(width: size.width, height: size.height), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| 175b9de247c8608db21f17d4f05dcf19 | 39.955224 | 137 | 0.701166 | false | false | false | false |
paulstringer/TicTacToe | refs/heads/master | TicTacToe/TicTacToeBoard.swift | mit | 1 | import Foundation
public enum BoardPosition: Int {
case topLeft = 0
case topMiddle = 1
case topRight = 2
case middleLeft = 3
case middle = 4
case middleRight = 5
case bottomLeft = 6
case bottomMiddle = 7
case bottomRight = 8
}
enum BoardMarker {
case none
case nought
case cross
}
enum BoardError: Error {
case positionTaken
case invalidMove
}
typealias BoardLine = [BoardPosition]
struct TicTacToeBoard: GameBoard {
fileprivate static let NewBoard: [BoardMarker] = [.none, .none, .none, .none, .none, .none, .none, .none, .none]
//MARK: Game Board
var markers: [BoardMarker]
var lastTurn: BoardPosition?
var winningLine: BoardLine? {
get {
return BoardAnalyzer.victory(self).line
}
}
init(markers: [BoardMarker] = TicTacToeBoard.NewBoard) {
self.markers = markers
self.lastTurn = BoardAnalyzer.lastPlayedPosition(self)
}
//MARK: Board Actions
mutating func takeTurnAtPosition(_ position:BoardPosition) throws {
let marker = BoardAnalyzer.nextMarker(self)
try canAddMarker(marker, atPosition: position)
lastTurn = position
markers[position.rawValue] = marker
}
//MARK: Private
fileprivate func canAddMarker(_ marker: BoardMarker, atPosition position: BoardPosition) throws {
guard BoardAnalyzer.isEmpty(self, position: position) else {
throw BoardError.positionTaken
}
guard BoardAnalyzer.nextMarker(self) == marker else {
throw BoardError.invalidMove
}
}
}
| 0353393784ff278c734d8ae614c1fe78 | 21.089744 | 116 | 0.612885 | false | false | false | false |
cdmx/MiniMancera | refs/heads/master | miniMancera/Model/Main/Abstract/MPerkFactory.swift | mit | 1 | import Foundation
class MPerkFactory
{
class func factoryPerks() -> [MPerkProtocol]
{
let perkReformaCrossing:MPerkReformaCrossing = MPerkReformaCrossing()
let perkPollutedGarden:MPerkPollutedGarden = MPerkPollutedGarden()
let perkWhistlesVsZombies:MPerkWhistlesVsZombies = MPerkWhistlesVsZombies()
// let perkTamalesOaxaquenos:MPerkTamalesOaxaquenos = MPerkTamalesOaxaquenos()
let perks:[MPerkProtocol] = [
perkReformaCrossing,
perkPollutedGarden,
perkWhistlesVsZombies,
// perkTamalesOaxaquenos
]
return perks
}
}
| 1177baebfd93f7bb9287f03cfc71a76c | 29.904762 | 85 | 0.670262 | false | false | false | false |
JGiola/swift | refs/heads/main | test/AutoDiff/Sema/differentiable_attr_type_checking.swift | apache-2.0 | 7 | // RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s
// RUN: %target-swift-frontend-typecheck -enable-testing -verify -disable-availability-checking %s
import _Differentiation
// Dummy `Differentiable`-conforming type.
public struct DummyTangentVector: Differentiable & AdditiveArithmetic {
public static var zero: Self { Self() }
public static func + (_: Self, _: Self) -> Self { Self() }
public static func - (_: Self, _: Self) -> Self { Self() }
public typealias TangentVector = Self
}
@differentiable(reverse) // expected-error {{'@differentiable' attribute cannot be applied to this declaration}}
let globalConst: Float = 1
@differentiable(reverse) // expected-error {{'@differentiable' attribute cannot be applied to this declaration}}
var globalVar: Float = 1
func testLocalVariables() {
// expected-error @+1 {{'_' has no parameters to differentiate with respect to}}
@differentiable(reverse)
var getter: Float {
return 1
}
// expected-error @+1 {{'_' has no parameters to differentiate with respect to}}
@differentiable(reverse)
var getterSetter: Float {
get { return 1 }
set {}
}
}
@differentiable(reverse) // expected-error {{'@differentiable' attribute cannot be applied to this declaration}}
protocol P {}
@differentiable(reverse) // ok!
func no_jvp_or_vjp(_ x: Float) -> Float {
return x * x
}
// Test duplicate `@differentiable` attributes.
@differentiable(reverse) // expected-error {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(reverse) // expected-note {{other attribute declared here}}
func dupe_attributes(arg: Float) -> Float { return arg }
@differentiable(reverse, wrt: arg1)
@differentiable(reverse, wrt: arg2) // expected-error {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(reverse, wrt: arg2) // expected-note {{other attribute declared here}}
func dupe_attributes(arg1: Float, arg2: Float) -> Float { return arg1 }
struct ComputedPropertyDupeAttributes<T: Differentiable>: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
var value: T
@differentiable(reverse) // expected-note {{other attribute declared here}}
var computed1: T {
@differentiable(reverse) // expected-error {{duplicate '@differentiable' attribute with same parameters}}
get { value }
set { value = newValue }
}
// TODO(TF-482): Remove diagnostics when `@differentiable` attributes are
// also uniqued based on generic requirements.
@differentiable(reverse where T == Float) // expected-error {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(reverse where T == Double) // expected-note {{other attribute declared here}}
var computed2: T {
get { value }
set { value = newValue }
}
}
// Test TF-568.
protocol WrtOnlySelfProtocol: Differentiable {
@differentiable(reverse)
var computedProperty: Float { get }
@differentiable(reverse)
func method() -> Float
}
class Class: Differentiable {
typealias TangentVector = DummyTangentVector
func move(by _: TangentVector) {}
}
@differentiable(reverse, wrt: x)
func invalidDiffWrtClass(_ x: Class) -> Class {
return x
}
protocol Proto {}
// expected-error @+1 {{can only differentiate functions with results that conform to 'Differentiable', but 'any Proto' does not conform to 'Differentiable'}}
@differentiable(reverse, wrt: x)
func invalidDiffWrtExistential(_ x: Proto) -> Proto {
return x
}
// expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '@differentiable(reverse) (Float) -> Float' does not conform to 'Differentiable'}}
@differentiable(reverse, wrt: fn)
func invalidDiffWrtFunction(_ fn: @differentiable(reverse) (Float) -> Float) -> Float {
return fn(.pi)
}
// expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}}
@differentiable(reverse)
func invalidDiffNoParams() -> Float {
return 1
}
// expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}}
@differentiable(reverse)
func invalidDiffVoidResult(x: Float) {}
// Test static methods.
struct StaticMethod {
// expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}}
@differentiable(reverse)
static func invalidDiffNoParams() -> Float {
return 1
}
// expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}}
@differentiable(reverse)
static func invalidDiffVoidResult(x: Float) {}
}
// Test instance methods.
struct InstanceMethod {
// expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}}
@differentiable(reverse)
func invalidDiffNoParams() -> Float {
return 1
}
// expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}}
@differentiable(reverse)
func invalidDiffVoidResult(x: Float) {}
}
// Test instance methods for a `Differentiable` type.
struct DifferentiableInstanceMethod: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
@differentiable(reverse) // ok
func noParams() -> Float {
return 1
}
}
// Test subscript methods.
struct SubscriptMethod: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
@differentiable(reverse) // ok
subscript(implicitGetter x: Float) -> Float {
return x
}
@differentiable(reverse) // ok
subscript(implicitGetterSetter x: Float) -> Float {
get { return x }
set {}
}
subscript(explicit x: Float) -> Float {
@differentiable(reverse) // ok
get { return x }
@differentiable(reverse)
set {}
}
subscript(x: Float, y: Float) -> Float {
@differentiable(reverse) // ok
get { return x + y }
@differentiable(reverse)
set {}
}
}
// expected-error @+3 {{type 'Scalar' constrained to non-protocol, non-class type 'Float'}}
// expected-error @+2 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
// expected-note @+1 {{use 'Scalar == Float' to require 'Scalar' to be 'Float'}}
@differentiable(reverse where Scalar: Float)
func invalidRequirementConformance<Scalar>(x: Scalar) -> Scalar {
return x
}
// expected-error @+1 {{'@differentiable' attribute does not yet support layout requirements}}
@differentiable(reverse where T: AnyObject)
func invalidAnyObjectRequirement<T: Differentiable>(x: T) -> T {
return x
}
// expected-error @+1 {{'@differentiable' attribute does not yet support layout requirements}}
@differentiable(reverse where Scalar: _Trivial)
func invalidRequirementLayout<Scalar>(x: Scalar) -> Scalar {
return x
}
// expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
@differentiable(reverse)
func missingConformance<T>(_ x: T) -> T {
return x
}
protocol ProtocolRequirements: Differentiable {
// expected-note @+2 {{protocol requires initializer 'init(x:y:)' with type '(x: Float, y: Float)'}}
@differentiable(reverse)
init(x: Float, y: Float)
// expected-note @+2 {{protocol requires initializer 'init(x:y:)' with type '(x: Float, y: Int)'}}
@differentiable(reverse, wrt: x)
init(x: Float, y: Int)
// expected-note @+2 {{protocol requires function 'amb(x:y:)' with type '(Float, Float) -> Float';}}
@differentiable(reverse)
func amb(x: Float, y: Float) -> Float
// expected-note @+2 {{protocol requires function 'amb(x:y:)' with type '(Float, Int) -> Float';}}
@differentiable(reverse, wrt: x)
func amb(x: Float, y: Int) -> Float
// expected-note @+3 {{protocol requires function 'f1'}}
// expected-note @+2 {{overridden declaration is here}}
@differentiable(reverse, wrt: (self, x))
func f1(_ x: Float) -> Float
// expected-note @+2 {{protocol requires function 'f2'}}
@differentiable(reverse, wrt: (self, x, y))
func f2(_ x: Float, _ y: Float) -> Float
}
protocol ProtocolRequirementsRefined: ProtocolRequirements {
// expected-error @+1 {{overriding declaration is missing attribute '@differentiable(reverse)'}}
func f1(_ x: Float) -> Float
}
// Test missing `@differentiable` attribute for internal protocol witnesses.
// No errors expected; internal `@differentiable` attributes are created.
struct InternalDiffAttrConformance: ProtocolRequirements {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
var x: Float
var y: Float
init(x: Float, y: Float) {
self.x = x
self.y = y
}
init(x: Float, y: Int) {
self.x = x
self.y = Float(y)
}
func amb(x: Float, y: Float) -> Float {
return x
}
func amb(x: Float, y: Int) -> Float {
return x
}
func f1(_ x: Float) -> Float {
return x
}
@differentiable(reverse, wrt: (self, x))
func f2(_ x: Float, _ y: Float) -> Float {
return x + y
}
}
// Test missing `@differentiable` attribute for public protocol witnesses. Errors expected.
// expected-error @+1 {{does not conform to protocol 'ProtocolRequirements'}}
public struct PublicDiffAttrConformance: ProtocolRequirements {
public typealias TangentVector = DummyTangentVector
public mutating func move(by _: TangentVector) {}
var x: Float
var y: Float
// FIXME(TF-284): Fix unexpected diagnostic.
// expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse) }}
// expected-note @+1 {{candidate has non-matching type '(x: Float, y: Float)'}}
public init(x: Float, y: Float) {
self.x = x
self.y = y
}
// FIXME(TF-284): Fix unexpected diagnostic.
// expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse) }}
// expected-note @+1 {{candidate has non-matching type '(x: Float, y: Int)'}}
public init(x: Float, y: Int) {
self.x = x
self.y = Float(y)
}
// expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse) }}
// expected-note @+1 {{candidate has non-matching type '(Float, Float) -> Float'}}
public func amb(x: Float, y: Float) -> Float {
return x
}
// expected-note @+2 {{candidate is missing explicit '@differentiable(reverse, wrt: x)' attribute to satisfy requirement}} {{10-10=@differentiable(reverse, wrt: x) }}
// expected-note @+1 {{candidate has non-matching type '(Float, Int) -> Float'}}
public func amb(x: Float, y: Int) -> Float {
return x
}
// expected-note @+1 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}}
public func f1(_ x: Float) -> Float {
return x
}
// expected-note @+2 {{candidate is missing explicit '@differentiable(reverse)' attribute to satisfy requirement}}
@differentiable(reverse, wrt: (self, x))
public func f2(_ x: Float, _ y: Float) -> Float {
return x + y
}
}
protocol ProtocolRequirementsWithDefault_NoConformingTypes {
@differentiable(reverse)
func f1(_ x: Float) -> Float
}
extension ProtocolRequirementsWithDefault_NoConformingTypes {
// TODO(TF-650): It would be nice to diagnose protocol default implementation
// with missing `@differentiable` attribute.
func f1(_ x: Float) -> Float { x }
}
protocol ProtocolRequirementsWithDefault {
@differentiable(reverse)
func f1(_ x: Float) -> Float
}
extension ProtocolRequirementsWithDefault {
func f1(_ x: Float) -> Float { x }
}
struct DiffAttrConformanceErrors2: ProtocolRequirementsWithDefault {
func f1(_ x: Float) -> Float { x }
}
protocol NotRefiningDiffable {
@differentiable(reverse, wrt: x)
func a(_ x: Float) -> Float
}
struct CertainlyNotDiffableWrtSelf: NotRefiningDiffable {
func a(_ x: Float) -> Float { return x * 5.0 }
}
protocol TF285: Differentiable {
@differentiable(reverse, wrt: (x, y))
@differentiable(reverse, wrt: x)
func foo(x: Float, y: Float) -> Float
}
struct TF285MissingOneDiffAttr: TF285 {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
// Requirement is missing the required `@differentiable(reverse, wrt: (x, y))` attribute.
// Since `TF285MissingOneDiffAttr.foo` is internal, the attribute is implicitly created.
@differentiable(reverse, wrt: x)
func foo(x: Float, y: Float) -> Float {
return x
}
}
// TF-521: Test invalid `@differentiable` attribute due to invalid
// `Differentiable` conformance (`TangentVector` does not conform to
// `AdditiveArithmetic`).
struct TF_521<T: FloatingPoint> {
var real: T
var imaginary: T
// expected-error @+1 {{can only differentiate functions with results that conform to 'Differentiable', but 'TF_521<T>' does not conform to 'Differentiable'}}
@differentiable(reverse where T: Differentiable, T == T.TangentVector)
init(real: T = 0, imaginary: T = 0) {
self.real = real
self.imaginary = imaginary
}
}
// expected-error @+1 {{type 'TF_521<T>' does not conform to protocol 'Differentiable'}}
extension TF_521: Differentiable where T: Differentiable {
// expected-note @+1 {{possibly intended match 'TF_521<T>.TangentVector' (aka 'TF_521<T>') does not conform to 'AdditiveArithmetic'}}
typealias TangentVector = TF_521
}
// expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable(reverse) (Float, Float) -> TF_521<Float> = { r, i in
TF_521(real: r, imaginary: i)
}
// expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable(reverse) (_, _) -> TF_521<Float> = { (r: Float, i: Float) in
TF_521(real: r, imaginary: i)
}
// expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable(reverse) (Float, Float) -> _ = { r, i in
TF_521(real: r, imaginary: i)
}
// TF-296: Infer `@differentiable` wrt parameters to be to all parameters that conform to `Differentiable`.
@differentiable(reverse)
func infer1(_ a: Float, _ b: Int) -> Float {
return a + Float(b)
}
@differentiable(reverse)
func infer2(_ fn: @differentiable(reverse) (Float) -> Float, x: Float) -> Float {
return fn(x)
}
struct DiffableStruct: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
var a: Float
@differentiable(reverse)
func fn(_ b: Float, _ c: Int) -> Float {
return a + b + Float(c)
}
}
struct NonDiffableStruct {
var a: Float
@differentiable(reverse)
func fn(_ b: Float) -> Float {
return a + b
}
}
// Index based 'wrt:'
struct NumberWrtStruct: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
var a, b: Float
@differentiable(reverse, wrt: 0) // ok
@differentiable(reverse, wrt: 1) // ok
func foo1(_ x: Float, _ y: Float) -> Float {
return a*x + b*y
}
@differentiable(reverse, wrt: -1) // expected-error {{expected a parameter, which can be a function parameter name, parameter index, or 'self'}}
@differentiable(reverse, wrt: (1, x)) // expected-error {{parameters must be specified in original order}}
func foo2(_ x: Float, _ y: Float) -> Float {
return a*x + b*y
}
@differentiable(reverse, wrt: (x, 1)) // ok
@differentiable(reverse, wrt: (0)) // ok
static func staticFoo1(_ x: Float, _ y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (1, 1)) // expected-error {{parameters must be specified in original order}}
@differentiable(reverse, wrt: (2)) // expected-error {{parameter index is larger than total number of parameters}}
static func staticFoo2(_ x: Float, _ y: Float) -> Float {
return x + y
}
}
@differentiable(reverse, wrt: y) // ok
func two1(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (x, y)) // ok
func two2(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (0, y)) // ok
func two3(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (x, 1)) // ok
func two4(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (0, 1)) // ok
func two5(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: 2) // expected-error {{parameter index is larger than total number of parameters}}
func two6(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (1, 0)) // expected-error {{parameters must be specified in original order}}
func two7(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (1, x)) // expected-error {{parameters must be specified in original order}}
func two8(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(reverse, wrt: (y, 0)) // expected-error {{parameters must be specified in original order}}
func two9(x: Float, y: Float) -> Float {
return x + y
}
// Inout 'wrt:' arguments.
@differentiable(reverse, wrt: y)
func inout1(x: Float, y: inout Float) -> Void {
let _ = x + y
}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(reverse, wrt: y)
func inout2(x: Float, y: inout Float) -> Float {
let _ = x + y
}
// Test refining protocol requirements with `@differentiable` attribute.
public protocol Distribution {
associatedtype Value
func logProbability(of value: Value) -> Float
}
public protocol DifferentiableDistribution: Differentiable, Distribution {
// expected-note @+2 {{overridden declaration is here}}
@differentiable(reverse, wrt: self)
func logProbability(of value: Value) -> Float
}
// Adding a more general `@differentiable` attribute.
public protocol DoubleDifferentiableDistribution: DifferentiableDistribution
where Value: Differentiable {
// expected-error @+1 {{overriding declaration is missing attribute '@differentiable(reverse, wrt: self)'}} {{3-3=@differentiable(reverse, wrt: self) }}
func logProbability(of value: Value) -> Float
}
// Test failure to satisfy protocol requirement's `@differentiable` attribute.
public protocol HasRequirement {
@differentiable(reverse)
// expected-note @+1 {{protocol requires function 'requirement' with type '<T> (T, T) -> T'; do you want to add a stub?}}
func requirement<T: Differentiable>(_ x: T, _ y: T) -> T
}
// expected-error @+1 {{type 'AttemptsToSatisfyRequirement' does not conform to protocol 'HasRequirement'}}
public struct AttemptsToSatisfyRequirement: HasRequirement {
// This `@differentiable` attribute does not satisfy the requirement because
// it is more constrained than the requirement's `@differentiable` attribute.
@differentiable(reverse where T: CustomStringConvertible)
// expected-note @+1 {{candidate is missing explicit '@differentiable(reverse, wrt: (x, y))' attribute to satisfy requirement}}
public func requirement<T: Differentiable>(_ x: T, _ y: T) -> T { x }
}
// Test protocol requirement `@differentiable` attribute unsupported features.
protocol ProtocolRequirementUnsupported: Differentiable {
associatedtype Scalar
// expected-error @+1 {{'@differentiable' attribute on protocol requirement cannot specify 'where' clause}}
@differentiable(reverse where Scalar: Differentiable)
func unsupportedWhereClause(value: Scalar) -> Float
}
extension ProtocolRequirementUnsupported {
func dfoo(_ x: Float) -> (Float, (Float) -> Float) {
(x, { $0 })
}
}
// Classes.
class Super: Differentiable {
typealias TangentVector = DummyTangentVector
func move(by _: TangentVector) {}
var base: Float
// expected-error @+1 {{'@differentiable' attribute cannot be declared on 'init' in a non-final class; consider making 'Super' final}}
@differentiable(reverse)
init(base: Float) {
self.base = base
}
// NOTE(TF-1040): `@differentiable` attribute on class methods currently
// does two orthogonal things:
// - Requests derivative generation for the class method.
// - Adds JVP/VJP vtable entries for the class method.
// There's currently no way using `@differentiable` to do only one of the
// above.
@differentiable(reverse)
func testClassMethod(_ x: Float) -> Float { x }
@differentiable(reverse)
final func testFinalMethod(_ x: Float) -> Float { x }
@differentiable(reverse)
static func testStaticMethod(_ x: Float) -> Float { x }
@differentiable(reverse, wrt: (self, x))
@differentiable(reverse, wrt: x)
// expected-note @+1 2 {{overridden declaration is here}}
func testMissingAttributes(_ x: Float) -> Float { x }
@differentiable(reverse, wrt: x)
func testSuperclassDerivatives(_ x: Float) -> Float { x }
// Test duplicate attributes with different derivative generic signatures.
// expected-error @+1 {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(reverse, wrt: x where T: Differentiable)
// expected-note @+1 {{other attribute declared here}}
@differentiable(reverse, wrt: x)
func instanceMethod<T>(_ x: Float, y: T) -> Float { x }
// expected-error @+1 {{'@differentiable' attribute cannot be declared on class members returning 'Self'}}
@differentiable(reverse)
func dynamicSelfResult() -> Self { self }
// expected-error @+1 {{'@differentiable' attribute cannot be declared on class members returning 'Self'}}
@differentiable(reverse)
var testDynamicSelfProperty: Self { self }
// TODO(TF-632): Fix "'TangentVector' is not a member type of 'Self'" diagnostic.
// The underlying error should appear instead:
// "covariant 'Self' can only appear at the top level of method result type".
// expected-error @+1 2 {{'TangentVector' is not a member type of type 'Self'}}
func vjpDynamicSelfResult() -> (Self, (Self.TangentVector) -> Self.TangentVector) {
return (self, { $0 })
}
}
class Sub: Super {
// expected-error @+2 {{overriding declaration is missing attribute '@differentiable(reverse, wrt: x)'}}
// expected-error @+1 {{overriding declaration is missing attribute '@differentiable(reverse)'}}
override func testMissingAttributes(_ x: Float) -> Float { x }
}
final class FinalClass: Differentiable {
typealias TangentVector = DummyTangentVector
func move(by _: TangentVector) {}
var base: Float
@differentiable(reverse)
init(base: Float) {
self.base = base
}
}
// Test `inout` parameters.
@differentiable(reverse, wrt: y)
func inoutVoid(x: Float, y: inout Float) {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(reverse)
func multipleSemanticResults(_ x: inout Float) -> Float { x }
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(reverse, wrt: y)
func swap(x: inout Float, y: inout Float) {}
struct InoutParameters: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
}
extension InoutParameters {
@differentiable(reverse)
static func staticMethod(_ lhs: inout Self, rhs: Self) {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(reverse)
static func multipleSemanticResults(_ lhs: inout Self, rhs: Self) -> Self {}
}
extension InoutParameters {
@differentiable(reverse)
mutating func mutatingMethod(_ other: Self) {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(reverse)
mutating func mutatingMethod(_ other: Self) -> Self {}
}
// Test accessors: `set`, `_read`, `_modify`.
struct Accessors: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(by _: TangentVector) {}
var stored: Float
var computed: Float {
@differentiable(reverse)
set { stored = newValue }
// `_read` is a coroutine: `(Self) -> () -> ()`.
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable(reverse)
_read { yield stored }
// `_modify` is a coroutine: `(inout Self) -> () -> ()`.
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable(reverse)
_modify { yield &stored }
}
}
// expected-error @+1 {{cannot differentiate functions returning opaque result types}}
@differentiable(reverse)
func opaqueResult(_ x: Float) -> some Differentiable { x }
// Test the function tupling conversion with @differentiable.
func tuplify<Ts, U>(_ fn: @escaping (Ts) -> U) -> (Ts) -> U { fn }
func tuplifyDifferentiable<Ts : Differentiable, U>(_ fn: @escaping @differentiable(reverse) (Ts) -> U) -> @differentiable(reverse) (Ts) -> U { fn }
func testTupling(withoutNoDerivative: @escaping @differentiable(reverse) (Float, Float) -> Float,
withNoDerivative: @escaping @differentiable(reverse) (Float, @noDerivative Float) -> Float) {
// We support tupling of differentiable functions as long as they drop @differentiable.
let _: ((Float, Float)) -> Float = tuplify(withoutNoDerivative)
let fn1 = tuplify(withoutNoDerivative)
_ = fn1((0, 0))
// In this case we also drop @noDerivative.
let _: ((Float, Float)) -> Float = tuplify(withNoDerivative)
let fn2 = tuplify(withNoDerivative)
_ = fn2((0, 0))
// We do not support tupling into an @differentiable function.
let _ = tuplifyDifferentiable(withoutNoDerivative) // expected-error {{cannot convert value of type '@differentiable(reverse) (Float, Float) -> Float' to expected argument type '@differentiable(reverse) (Float) -> Float'}}
let _ = tuplifyDifferentiable(withNoDerivative) // expected-error {{cannot convert value of type '@differentiable(reverse) (Float, @noDerivative Float) -> Float' to expected argument type '@differentiable(reverse) (Float) -> Float'}}
}
| e2683882ebfa8b6c4a89f8fc8e18fbbd | 33.976 | 235 | 0.701357 | false | false | false | false |
HarukaMa/iina | refs/heads/master | iina/MainWindowMenuActions.swift | gpl-3.0 | 1 | //
// MainWindowMenuActions.swift
// iina
//
// Created by lhc on 25/12/2016.
// Copyright © 2016 lhc. All rights reserved.
//
import Cocoa
// MARK: - Menu Actions
extension MainWindowController {
@IBAction func menuTogglePause(_ sender: NSMenuItem) {
playerCore.togglePause(!playerCore.info.isPaused)
}
@IBAction func menuStop(_ sender: NSMenuItem) {
// FIXME: handle stop
playerCore.stop()
displayOSD(.stop)
}
@IBAction func menuStep(_ sender: NSMenuItem) {
if sender.tag == 0 { // -> 5s
playerCore.seek(relativeSecond: 5, option: .relative)
} else if sender.tag == 1 { // <- 5s
playerCore.seek(relativeSecond: -5, option: .relative)
}
}
@IBAction func menuStepFrame(_ sender: NSMenuItem) {
if !playerCore.info.isPaused {
playerCore.togglePause(true)
}
if sender.tag == 0 { // -> 1f
playerCore.frameStep(backwards: false)
} else if sender.tag == 1 { // <- 1f
playerCore.frameStep(backwards: true)
}
}
@IBAction func menuJumpToBegin(_ sender: NSMenuItem) {
playerCore.seek(absoluteSecond: 0)
}
@IBAction func menuJumpTo(_ sender: NSMenuItem) {
let _ = Utility.quickPromptPanel(messageText: "Jump to:", informativeText: "Example: 20:35") { input in
if let vt = VideoTime(input) {
self.playerCore.seek(absoluteSecond: Double(vt.second))
}
}
}
@IBAction func menuSnapshot(_ sender: NSMenuItem) {
playerCore.screenShot()
}
@IBAction func menuABLoop(_ sender: NSMenuItem) {
playerCore.abLoop()
}
@IBAction func menuFileLoop(_ sender: NSMenuItem) {
playerCore.toggleFileLoop()
}
@IBAction func menuPlaylistLoop(_ sender: NSMenuItem) {
playerCore.togglePlaylistLoop()
}
@IBAction func menuPlaylistItem(_ sender: NSMenuItem) {
let index = sender.tag
playerCore.playFileInPlaylist(index)
}
@IBAction func menuShowPlaylistPanel(_ sender: NSMenuItem) {
if sideBarStatus == .hidden || sideBarStatus == .settings {
playlistView.pleaseSwitchToTab(.playlist)
playlistButtonAction(sender)
} else {
if playlistView.currentTab != .playlist {
playlistView.pleaseSwitchToTab(.playlist)
} else {
playlistButtonAction(sender)
}
}
}
@IBAction func menuShowChaptersPanel(_ sender: NSMenuItem) {
if sideBarStatus == .hidden || sideBarStatus == .settings {
playlistView.pleaseSwitchToTab(.chapters)
playlistButtonAction(sender)
} else {
if playlistView.currentTab != .chapters {
playlistView.pleaseSwitchToTab(.chapters)
} else {
playlistButtonAction(sender)
}
}
}
@IBAction func menuChapterSwitch(_ sender: NSMenuItem) {
let index = sender.tag
playerCore.playChapter(index)
let chapter = playerCore.info.chapters[index]
displayOSD(.chapter(chapter.title))
}
@IBAction func menuShowVideoQuickSettings(_ sender: NSMenuItem) {
if sideBarStatus == .hidden || sideBarStatus == .playlist {
quickSettingView.pleaseSwitchToTab(.video)
settingsButtonAction(sender)
} else {
if quickSettingView.currentTab != .video {
quickSettingView.pleaseSwitchToTab(.video)
} else {
settingsButtonAction(sender)
}
}
}
@IBAction func menuShowAudioQuickSettings(_ sender: NSMenuItem) {
if sideBarStatus == .hidden || sideBarStatus == .playlist {
quickSettingView.pleaseSwitchToTab(.audio)
settingsButtonAction(sender)
} else {
if quickSettingView.currentTab != .audio {
quickSettingView.pleaseSwitchToTab(.audio)
} else {
settingsButtonAction(sender)
}
}
}
@IBAction func menuShowSubQuickSettings(_ sender: NSMenuItem) {
if sideBarStatus == .hidden || sideBarStatus == .playlist {
quickSettingView.pleaseSwitchToTab(.sub)
settingsButtonAction(sender)
} else {
if quickSettingView.currentTab != .sub {
quickSettingView.pleaseSwitchToTab(.sub)
} else {
settingsButtonAction(sender)
}
}
}
@IBAction func menuChangeTrack(_ sender: NSMenuItem) {
if let trackObj = sender.representedObject as? (MPVTrack, MPVTrack.TrackType) {
playerCore.setTrack(trackObj.0.id, forType: trackObj.1)
} else if let trackObj = sender.representedObject as? MPVTrack {
playerCore.setTrack(trackObj.id, forType: trackObj.type)
}
}
@IBAction func menuChangeAspect(_ sender: NSMenuItem) {
if let aspectStr = sender.representedObject as? String {
playerCore.setVideoAspect(aspectStr)
displayOSD(.aspect(aspectStr))
} else {
Utility.log("Unknown aspect in menuChangeAspect(): \(sender.representedObject.debugDescription)")
}
}
@IBAction func menuChangeCrop(_ sender: NSMenuItem) {
if let cropStr = sender.representedObject as? String {
playerCore.setCrop(fromString: cropStr)
} else {
Utility.log("sender.representedObject is not a string in menuChangeCrop()")
}
}
@IBAction func menuChangeRotation(_ sender: NSMenuItem) {
if let rotationInt = sender.representedObject as? Int {
playerCore.setVideoRotate(rotationInt)
}
}
@IBAction func menuToggleFlip(_ sender: NSMenuItem) {
if playerCore.info.flipFilter == nil {
playerCore.setFlip(true)
} else {
playerCore.setFlip(false)
}
}
@IBAction func menuToggleMirror(_ sender: NSMenuItem) {
if playerCore.info.mirrorFilter == nil {
playerCore.setMirror(true)
} else {
playerCore.setMirror(false)
}
}
@IBAction func menuToggleDeinterlace(_ sender: NSMenuItem) {
playerCore.toggleDeinterlace(sender.state != NSOnState)
}
@IBAction func menuChangeWindowSize(_ sender: NSMenuItem) {
// -1: normal(non-retina), same as 1 when on non-retina screen
// 0: half
// 1: normal
// 2: double
// 3: fit screen
// 10: smaller size
// 11: bigger size
let size = sender.tag
guard let w = window, var vw = playerCore.info.displayWidth, var vh = playerCore.info.displayHeight else { return }
if vw == 0 { vw = AppData.widthWhenNoVideo }
if vh == 0 { vh = AppData.heightWhenNoVideo }
var retinaSize = w.convertFromBacking(NSMakeRect(w.frame.origin.x, w.frame.origin.y, CGFloat(vw), CGFloat(vh)))
let screenFrame = NSScreen.main()!.visibleFrame
let newFrame: NSRect
let sizeMap: [CGFloat] = [0.5, 1, 2]
let scaleStep: CGFloat = 25
switch size {
// scale
case 0, 1, 2:
retinaSize.size.width *= sizeMap[size]
retinaSize.size.height *= sizeMap[size]
if retinaSize.size.width > screenFrame.size.width || retinaSize.size.height > screenFrame.size.height {
newFrame = w.frame.centeredResize(to: w.frame.size.shrink(toSize: screenFrame.size)).constrain(in: screenFrame)
} else {
newFrame = w.frame.centeredResize(to: retinaSize.size.satisfyMinSizeWithSameAspectRatio(minSize)).constrain(in: screenFrame)
}
// fit screen
case 3:
w.center()
newFrame = w.frame.centeredResize(to: w.frame.size.shrink(toSize: screenFrame.size))
// bigger size
case 10, 11:
let newWidth = w.frame.width + scaleStep * (size == 10 ? -1 : 1)
let newHeight = newWidth / (w.aspectRatio.width / w.aspectRatio.height)
newFrame = w.frame.centeredResize(to: NSSize(width: newWidth, height: newHeight).satisfyMinSizeWithSameAspectRatio(minSize))
default:
return
}
w.setFrame(newFrame, display: true, animate: true)
}
@IBAction func menuAlwaysOnTop(_ sender: AnyObject) {
isOntop = !isOntop
setWindowFloatingOnTop(isOntop)
}
@available(macOS 10.12, *)
@IBAction func menuTogglePIP(_ sender: NSMenuItem) {
if !isInPIP {
enterPIP()
} else {
exitPIP(manually: true)
}
}
@IBAction func menuToggleFullScreen(_ sender: NSMenuItem) {
toggleWindowFullScreen()
}
@IBAction func menuChangeVolume(_ sender: NSMenuItem) {
if let volumeDelta = sender.representedObject as? Int {
let newVolume = Double(volumeDelta) + playerCore.info.volume
playerCore.setVolume(newVolume, constrain: false)
} else {
Utility.log("sender.representedObject is not int in menuChangeVolume()")
}
}
@IBAction func menuToggleMute(_ sender: NSMenuItem) {
playerCore.toogleMute(nil)
}
@IBAction func menuChangeAudioDelay(_ sender: NSMenuItem) {
if let delayDelta = sender.representedObject as? Double {
let newDelay = playerCore.info.audioDelay + delayDelta
playerCore.setAudioDelay(newDelay)
} else {
Utility.log("sender.representedObject is not Double in menuChangeAudioDelay()")
}
}
@IBAction func menuResetAudioDelay(_ sender: NSMenuItem) {
playerCore.setAudioDelay(0)
}
@IBAction func menuLoadExternalSub(_ sender: NSMenuItem) {
let _ = Utility.quickOpenPanel(title: "Load external subtitle file", isDir: false) { url in
self.playerCore.loadExternalSubFile(url)
}
}
@IBAction func menuChangeSubDelay(_ sender: NSMenuItem) {
if let delayDelta = sender.representedObject as? Double {
let newDelay = playerCore.info.subDelay + delayDelta
playerCore.setSubDelay(newDelay)
} else {
Utility.log("sender.representedObject is not Double in menuChangeSubDelay()")
}
}
@IBAction func menuChangeSubScale(_ sender: NSMenuItem) {
if sender.tag == 0 {
playerCore.setSubScale(1)
return
}
// FIXME: better refactor this part
let amount = sender.tag > 0 ? 0.1 : -0.1
let currentScale = playerCore.mpvController.getDouble(MPVOption.Subtitles.subScale)
let displayValue = currentScale >= 1 ? currentScale : -1/currentScale
let truncated = round(displayValue * 100) / 100
var newTruncated = truncated + amount
// range for this value should be (~, -1), (1, ~)
if newTruncated > 0 && newTruncated < 1 || newTruncated > -1 && newTruncated < 0 {
newTruncated = -truncated + amount
}
playerCore.setSubScale(abs(newTruncated > 0 ? newTruncated : 1 / newTruncated))
}
@IBAction func menuResetSubDelay(_ sender: NSMenuItem) {
playerCore.setSubDelay(0)
}
@IBAction func menuSetSubEncoding(_ sender: NSMenuItem) {
playerCore.setSubEncoding((sender.representedObject as? String) ?? "auto")
}
@IBAction func menuSubFont(_ sender: NSMenuItem) {
Utility.quickFontPickerWindow() {
self.playerCore.setSubFont($0 ?? "")
}
}
@IBAction func menuFindOnlineSub(_ sender: NSMenuItem) {
guard let url = playerCore.info.currentURL else { return }
OnlineSubtitle.getSub(forFile: url) { subtitles in
// send osd in main thread
self.playerCore.sendOSD(.foundSub(subtitles.count))
// download them
for sub in subtitles {
sub.download { result in
switch result {
case .ok(let url):
Utility.log("Saved subtitle to \(url.path)")
self.playerCore.loadExternalSubFile(url)
self.playerCore.sendOSD(.downloadedSub(url.lastPathComponent))
self.playerCore.info.haveDownloadedSub = true
case .failed:
self.playerCore.sendOSD(.networkError)
}
}
}
}
}
@IBAction func saveDownloadedSub(_ sender: NSMenuItem) {
let selected = playerCore.info.subTracks.filter { $0.id == playerCore.info.sid }
guard let currURL = playerCore.info.currentURL else { return }
guard selected.count > 0 else {
Utility.showAlert("sub.no_selected")
return
}
let sub = selected[0]
// make sure it's a downloaded sub
guard let path = sub.externalFilename, path.contains("/var/") else {
Utility.showAlert("sub.no_selected")
return
}
let subURL = URL(fileURLWithPath: path)
let subFileName = subURL.lastPathComponent
let destURL = currURL.deletingLastPathComponent().appendingPathComponent(subFileName, isDirectory: false)
do {
try FileManager.default.copyItem(at: subURL, to: destURL)
displayOSD(.savedSub)
} catch let error as NSError {
Utility.showAlert("error_saving_file", arguments: ["subtitle",
error.localizedDescription])
}
}
@IBAction func menuShowInspector(_ sender: AnyObject) {
let inspector = (NSApp.delegate as! AppDelegate).inspector
inspector.showWindow(self)
inspector.updateInfo()
}
@IBAction func menuSavePlaylist(_ sender: NSMenuItem) {
let _ = Utility.quickSavePanel(title: "Save to playlist", types: ["m3u8"]) {
(url) in if url.isFileURL {
var playlist = ""
for item in playerCore.info.playlist {
playlist.append((item.filename + "\n"))
}
do {
try playlist.write(to: url, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
Utility.showAlert("error_saving_file", arguments: ["subtitle",
error.localizedDescription])
}
}
}
}
@IBAction func menuDeleteCurrentFile(_ sender: NSMenuItem) {
guard let url = playerCore.info.currentURL else { return }
do {
let index = playerCore.mpvController.getInt(MPVProperty.playlistPos)
playerCore.playlistRemove(index)
try FileManager.default.trashItem(at: url, resultingItemURL: nil)
} catch let error {
Utility.showAlert("playlist.error_deleting", arguments: [error.localizedDescription])
}
}
}
| b60f6e6fcdd3410abc74ae28a0d9a487 | 31.104265 | 132 | 0.662755 | false | false | false | false |
robert-hatfield/PicFeed | refs/heads/master | PicFeed/PicFeed/GalleryViewController.swift | mit | 1 | //
// GalleryViewController.swift
// PicFeed
//
// Created by Robert Hatfield on 3/29/17.
// Copyright © 2017 Robert Hatfield. All rights reserved.
//
import UIKit
class GalleryViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var allPosts = [Post]() {
didSet {
self.collectionView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.collectionViewLayout = GalleryCollectionViewLayout(columns: 2)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
update()
}
func update() {
CloudKit.shared.getPosts { (posts) in
if let posts = posts {
self.allPosts = posts
}
}
}
}
//MARK: UICollectionViewDataSource Extension
extension GalleryViewController : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GalleryCell.identifier, for: indexPath) as! GalleryCell
cell.post = self.allPosts[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allPosts.count
}
}
| e88c4c0e9b25f4fded0eb63d20d2cb6b | 24.45 | 130 | 0.642436 | false | false | false | false |
4oby/TableTop-Ambience | refs/heads/master | TableTop Ambience/SoundPadItem.swift | gpl-3.0 | 1 | //
// SoundPadItem.swift
// TableTop Ambience
//
// Created by Victor Cebanu on 8/23/16.
// Copyright © 2016 Victor Cebanu. All rights reserved.
//
import Foundation
private enum EncodeDictionaryAttributes: String {
case fileAddress = "fileAddress"
case icon = "icon"
case name = "name"
case autoRepeat = "autoRepeat"
case volume = "volume"
}
struct SoundPadItem {
let fileAddress: String
let icon: String
let name: String
let autoRepeat: Bool
let volume: Float
init(fileAddress: String, icon: String, name: String, autoRepeat: Bool = false, volume: Float = 0.5) {
self.fileAddress = fileAddress
self.icon = icon
self.name = name
self.autoRepeat = autoRepeat
self.volume = volume
}
init(dictionary: Dictionary<String, Any>) {
self.fileAddress = dictionary[EncodeDictionaryAttributes.fileAddress.rawValue] as? String ?? ""
self.icon = dictionary[EncodeDictionaryAttributes.icon.rawValue] as? String ?? ""
self.name = dictionary[EncodeDictionaryAttributes.name.rawValue] as? String ?? ""
self.autoRepeat = dictionary[EncodeDictionaryAttributes.autoRepeat.rawValue] as? Bool ?? false
self.volume = dictionary[EncodeDictionaryAttributes.volume.rawValue] as? Float ?? 0.5
}
init(fileAddress: String) { //utility init
self.fileAddress = fileAddress
self.icon = ""
self.name = URL(fileURLWithPath: fileAddress).deletingPathExtension().lastPathComponent
self.autoRepeat = false
self.volume = 0.5
}
}
//MARK: - Saving Utility
extension SoundPadItem {
func encode() -> Dictionary<String, Any> {
var dictionary = Dictionary<String, Any>()
dictionary[EncodeDictionaryAttributes.fileAddress.rawValue] = self.fileAddress
dictionary[EncodeDictionaryAttributes.icon.rawValue] = self.icon
dictionary[EncodeDictionaryAttributes.name.rawValue] = self.name
dictionary[EncodeDictionaryAttributes.autoRepeat.rawValue] = self.autoRepeat
dictionary[EncodeDictionaryAttributes.volume.rawValue] = self.volume
return dictionary
}
}
//MARK: - Editing Utility
extension SoundPadItem {
func setVolume(volume: Float) -> SoundPadItem {
return SoundPadItem(fileAddress: self.fileAddress,
icon: self.icon,
name: self.name,
autoRepeat: self.autoRepeat,
volume: volume)
}
func setAutoRepeat(autoRepeat: Bool) -> SoundPadItem {
return SoundPadItem(fileAddress: self.fileAddress,
icon: self.icon,
name: self.name,
autoRepeat: autoRepeat,
volume: self.volume)
}
}
| 09610232868622677ef97d043021bd3c | 33.345238 | 106 | 0.630849 | false | false | false | false |
SwiftKitz/Appz | refs/heads/master | Appz/AppzTests/AppsTests/Camera360Tests.swift | mit | 1 | //
// Camera360Tests.swift
// Appz
//
// Created by Mariam AlJamea on 1/27/16.
// Copyright © 2016 kitz. All rights reserved.
//
import XCTest
@testable import Appz
class Camera360Tests: XCTestCase {
let appCaller = ApplicationCallerMock()
func testConfiguration() {
let camera360 = Applications.Camera360()
XCTAssertEqual(camera360.scheme, "camera360:")
XCTAssertEqual(camera360.fallbackURL, "https://www.camera360.com/production/?production=camera360&platform=ios")
}
func testOpen() {
let action = Applications.Camera360.Action.open
XCTAssertEqual(action.paths.app.pathComponents, ["app"])
XCTAssertEqual(action.paths.app.queryParameters, [:])
XCTAssertEqual(action.paths.web, Path())
}
}
| 0ec800e7d7afdc7db6aad6c2770bd4a1 | 25.322581 | 120 | 0.656863 | false | true | false | false |
sunnychan626/project-window | refs/heads/master | Pods/SwiftState/Sources/StateMachine.swift | apache-2.0 | 1 | //
// StateMachine.swift
// SwiftState
//
// Created by Yasuhiro Inami on 2015-12-05.
// Copyright © 2015 Yasuhiro Inami. All rights reserved.
//
///
/// State-machine which can `tryState()` (state-driven) as well as `tryEvent()` (event-driven).
///
/// - Note:
/// Use `NoEvent` type to ignore event-handlings whenever necessary.
///
public final class StateMachine<S: StateType, E: EventType>: Machine<S, E>
{
/// Closure-based routes for `tryState()`.
/// - Returns: Multiple `toState`s from single `fromState`, similar to `.State0 => [.State1, .State2]`
public typealias StateRouteMapping = (fromState: S, userInfo: Any?) -> [S]?
private lazy var _routes: _RouteDict = [:]
private lazy var _routeMappings: [String : StateRouteMapping] = [:] // NOTE: `StateRouteMapping`, not `RouteMapping`
/// `tryState()`-based handler collection.
private lazy var _handlers: [Transition<S> : [_HandlerInfo<S, E>]] = [:]
//--------------------------------------------------
// MARK: - Init
//--------------------------------------------------
public override init(state: S, initClosure: (StateMachine -> ())? = nil)
{
super.init(state: state, initClosure: { machine in
initClosure?(machine as! StateMachine<S, E>) // swiftlint:disable:this force_cast
return
})
}
public override func configure(closure: StateMachine -> ())
{
closure(self)
}
//--------------------------------------------------
// MARK: - hasRoute
//--------------------------------------------------
/// Check for added routes & routeMappings.
/// - Note: This method also checks for event-based-routes.
public func hasRoute(transition: Transition<S>, userInfo: Any? = nil) -> Bool
{
guard let fromState = transition.fromState.rawValue,
toState = transition.toState.rawValue else
{
assertionFailure("State = `.Any` is not supported for `hasRoute()` (always returns `false`)")
return false
}
return self.hasRoute(fromState: fromState, toState: toState, userInfo: userInfo)
}
/// Check for added routes & routeMappings.
/// - Note: This method also checks for event-based-routes.
public func hasRoute(fromState fromState: S, toState: S, userInfo: Any? = nil) -> Bool
{
if self._hasRouteInDict(fromState: fromState, toState: toState, userInfo: userInfo) {
return true
}
if self._hasRouteMappingInDict(fromState: fromState, toState: toState, userInfo: userInfo) != nil {
return true
}
// look for all event-based-routes
return super._hasRoute(event: nil, fromState: fromState, toState: toState, userInfo: userInfo)
}
/// Check for `_routes`.
private func _hasRouteInDict(fromState fromState: S, toState: S, userInfo: Any? = nil) -> Bool
{
let validTransitions = _validTransitions(fromState: fromState, toState: toState)
for validTransition in validTransitions {
// check for `_routes
if let keyConditionDict = self._routes[validTransition] {
for (_, condition) in keyConditionDict {
if _canPassCondition(condition, forEvent: nil, fromState: fromState, toState: toState, userInfo: userInfo) {
return true
}
}
}
}
return false
}
/// Check for `_routeMappings`.
private func _hasRouteMappingInDict(fromState fromState: S, toState: S, userInfo: Any? = nil) -> S?
{
for mapping in self._routeMappings.values {
if let preferredToStates = mapping(fromState: fromState, userInfo: userInfo) {
return preferredToStates.contains(toState) ? toState : nil
}
}
return nil
}
//--------------------------------------------------
// MARK: - tryState
//--------------------------------------------------
/// - Note: This method also checks for event-based-routes.
public func canTryState(toState: S, userInfo: Any? = nil) -> Bool
{
return self.hasRoute(fromState: self.state, toState: toState, userInfo: userInfo)
}
/// - Note: This method also tries state-change for event-based-routes.
public func tryState(toState: S, userInfo: Any? = nil) -> Bool
{
let fromState = self.state
if self.canTryState(toState, userInfo: userInfo) {
// collect valid handlers before updating state
let validHandlerInfos = self._validHandlerInfos(fromState: fromState, toState: toState)
// update state
self._state = toState
//
// Perform validHandlers after updating state.
//
// NOTE:
// Instead of using before/after handlers as seen in many other StateMachine libraries,
// SwiftState uses `order` value to perform handlers in 'fine-grained' order,
// only after state has been updated. (Any problem?)
//
for handlerInfo in validHandlerInfos {
handlerInfo.handler(Context(event: nil, fromState: fromState, toState: toState, userInfo: userInfo))
}
return true
}
else {
for handlerInfo in self._errorHandlers {
handlerInfo.handler(Context(event: nil, fromState: fromState, toState: toState, userInfo: userInfo))
}
}
return false
}
private func _validHandlerInfos(fromState fromState: S, toState: S) -> [_HandlerInfo<S, E>]
{
var validHandlerInfos: [_HandlerInfo<S, E>] = []
let validTransitions = _validTransitions(fromState: fromState, toState: toState)
for validTransition in validTransitions {
if let handlerInfos = self._handlers[validTransition] {
for handlerInfo in handlerInfos {
validHandlerInfos += [handlerInfo]
}
}
}
validHandlerInfos.sortInPlace { info1, info2 in
return info1.order < info2.order
}
return validHandlerInfos
}
//--------------------------------------------------
// MARK: - Route
//--------------------------------------------------
// MARK: addRoute (no-event)
public func addRoute(transition: Transition<S>, condition: Condition? = nil) -> Disposable
{
let route = Route(transition: transition, condition: condition)
return self.addRoute(route)
}
public func addRoute(route: Route<S, E>) -> Disposable
{
let transition = route.transition
let condition = route.condition
if self._routes[transition] == nil {
self._routes[transition] = [:]
}
let key = _createUniqueString()
var keyConditionDict = self._routes[transition]!
keyConditionDict[key] = condition
self._routes[transition] = keyConditionDict
let _routeID = _RouteID(event: Optional<Event<E>>.None, transition: transition, key: key)
return ActionDisposable { [weak self] in
self?._removeRoute(_routeID)
}
}
// MARK: addRoute (no-event) + conditional handler
public func addRoute(transition: Transition<S>, condition: Condition? = nil, handler: Handler) -> Disposable
{
let route = Route(transition: transition, condition: condition)
return self.addRoute(route, handler: handler)
}
public func addRoute(route: Route<S, E>, handler: Handler) -> Disposable
{
let transition = route.transition
let condition = route.condition
let routeDisposable = self.addRoute(transition, condition: condition)
let handlerDisposable = self.addHandler(transition) { context in
if _canPassCondition(condition, forEvent: nil, fromState: context.fromState, toState: context.toState, userInfo: context.userInfo) {
handler(context)
}
}
return ActionDisposable {
routeDisposable.dispose()
handlerDisposable.dispose()
}
}
// MARK: removeRoute
private func _removeRoute(_routeID: _RouteID<S, E>) -> Bool
{
guard _routeID.event == nil else {
return false
}
let transition = _routeID.transition
guard let keyConditionDict_ = self._routes[transition] else {
return false
}
var keyConditionDict = keyConditionDict_
let removed = keyConditionDict.removeValueForKey(_routeID.key) != nil
if keyConditionDict.isEmpty == false {
self._routes[transition] = keyConditionDict
}
else {
self._routes[transition] = nil
}
return removed
}
//--------------------------------------------------
// MARK: - Handler
//--------------------------------------------------
// MARK: addHandler (no-event)
/// Add `handler` that is called when `tryState()` succeeds for target `transition`.
/// - Note: `handler` will not be invoked for `tryEvent()`.
public func addHandler(transition: Transition<S>, order: HandlerOrder = _defaultOrder, handler: Handler) -> Disposable
{
if self._handlers[transition] == nil {
self._handlers[transition] = []
}
let key = _createUniqueString()
var handlerInfos = self._handlers[transition]!
let newHandlerInfo = _HandlerInfo<S, E>(order: order, key: key, handler: handler)
_insertHandlerIntoArray(&handlerInfos, newHandlerInfo: newHandlerInfo)
self._handlers[transition] = handlerInfos
let handlerID = _HandlerID<S, E>(event: nil, transition: transition, key: key)
return ActionDisposable { [weak self] in
self?._removeHandler(handlerID)
}
}
// MARK: removeHandler
private func _removeHandler(handlerID: _HandlerID<S, E>) -> Bool
{
if let transition = handlerID.transition {
if let handlerInfos_ = self._handlers[transition] {
var handlerInfos = handlerInfos_
if _removeHandlerFromArray(&handlerInfos, removingHandlerID: handlerID) {
self._handlers[transition] = handlerInfos
return true
}
}
}
return false
}
// MARK: addAnyHandler (event-based & state-based)
/// Add `handler` that is called when either `tryEvent()` or `tryState()` succeeds for target `transition`.
public func addAnyHandler(transition: Transition<S>, order: HandlerOrder = _defaultOrder, handler: Handler) -> Disposable
{
let disposable1 = self.addHandler(transition, order: order, handler: handler)
let disposable2 = self.addHandler(event: .Any, order: order) { context in
if (transition.fromState == .Any || transition.fromState == context.fromState) &&
(transition.toState == .Any || transition.toState == context.toState)
{
handler(context)
}
}
return ActionDisposable {
disposable1.dispose()
disposable2.dispose()
}
}
//--------------------------------------------------
// MARK: - RouteChain
//--------------------------------------------------
//
// NOTE:
// `RouteChain` allows to register `handler` which will be invoked
// only when state-based-transitions in `RouteChain` succeeded continuously.
//
// MARK: addRouteChain + conditional handler
public func addRouteChain(chain: TransitionChain<S>, condition: Condition? = nil, handler: Handler) -> Disposable
{
let routeChain = RouteChain(transitionChain: chain, condition: condition)
return self.addRouteChain(routeChain, handler: handler)
}
public func addRouteChain(chain: RouteChain<S, E>, handler: Handler) -> Disposable
{
let routeDisposables = chain.routes.map { self.addRoute($0) }
let handlerDisposable = self.addChainHandler(chain, handler: handler)
return ActionDisposable {
routeDisposables.forEach { $0.dispose() }
handlerDisposable.dispose()
}
}
// MARK: addChainHandler
public func addChainHandler(chain: TransitionChain<S>, order: HandlerOrder = _defaultOrder, handler: Handler) -> Disposable
{
return self.addChainHandler(RouteChain(transitionChain: chain), order: order, handler: handler)
}
public func addChainHandler(chain: RouteChain<S, E>, order: HandlerOrder = _defaultOrder, handler: Handler) -> Disposable
{
return self._addChainHandler(chain, order: order, handler: handler, isError: false)
}
// MARK: addChainErrorHandler
public func addChainErrorHandler(chain: TransitionChain<S>, order: HandlerOrder = _defaultOrder, handler: Handler) -> Disposable
{
return self.addChainErrorHandler(RouteChain(transitionChain: chain), order: order, handler: handler)
}
public func addChainErrorHandler(chain: RouteChain<S, E>, order: HandlerOrder = _defaultOrder, handler: Handler) -> Disposable
{
return self._addChainHandler(chain, order: order, handler: handler, isError: true)
}
private func _addChainHandler(chain: RouteChain<S, E>, order: HandlerOrder = _defaultOrder, handler: Handler, isError: Bool) -> Disposable
{
var handlerDisposables: [Disposable] = []
var shouldStop = true
var shouldIncrementChainingCount = true
var chainingCount = 0
var allCount = 0
// reset count on 1st route
let firstRoute = chain.routes.first!
var handlerDisposable = self.addHandler(firstRoute.transition) { context in
if _canPassCondition(firstRoute.condition, forEvent: nil, fromState: context.fromState, toState: context.toState, userInfo: context.userInfo) {
if shouldStop {
shouldStop = false
chainingCount = 0
allCount = 0
}
}
}
handlerDisposables += [handlerDisposable]
// increment chainingCount on every route
for route in chain.routes {
handlerDisposable = self.addHandler(route.transition) { context in
// skip duplicated transition handlers e.g. chain = 0 => 1 => 0 => 1 & transiting 0 => 1
if !shouldIncrementChainingCount { return }
if _canPassCondition(route.condition, forEvent: nil, fromState: context.fromState, toState: context.toState, userInfo: context.userInfo) {
if !shouldStop {
chainingCount++
shouldIncrementChainingCount = false
}
}
}
handlerDisposables += [handlerDisposable]
}
// increment allCount (+ invoke chainErrorHandler) on any routes
handlerDisposable = self.addHandler(.Any => .Any, order: 150) { context in
shouldIncrementChainingCount = true
if !shouldStop {
allCount++
}
if chainingCount < allCount {
shouldStop = true
if isError {
handler(context)
}
}
}
handlerDisposables += [handlerDisposable]
// invoke chainHandler on last route
let lastRoute = chain.routes.last!
handlerDisposable = self.addHandler(lastRoute.transition, order: 200) { context in
if _canPassCondition(lastRoute.condition, forEvent: nil, fromState: context.fromState, toState: context.toState, userInfo: context.userInfo) {
if chainingCount == allCount && chainingCount == chain.routes.count && chainingCount == chain.routes.count {
shouldStop = true
if !isError {
handler(context)
}
}
}
}
handlerDisposables += [handlerDisposable]
return ActionDisposable {
handlerDisposables.forEach { $0.dispose() }
}
}
//--------------------------------------------------
// MARK: - StateRouteMapping
//--------------------------------------------------
// MARK: addStateRouteMapping
public func addStateRouteMapping(routeMapping: StateRouteMapping) -> Disposable
{
let key = _createUniqueString()
self._routeMappings[key] = routeMapping
let routeMappingID = _RouteMappingID(key: key)
return ActionDisposable { [weak self] in
self?._removeStateRouteMapping(routeMappingID)
}
}
// MARK: addStateRouteMapping + conditional handler
public func addStateRouteMapping(routeMapping: StateRouteMapping, handler: Handler) -> Disposable
{
let routeDisposable = self.addStateRouteMapping(routeMapping)
let handlerDisposable = self.addHandler(.Any => .Any) { context in
guard context.event == nil else { return }
guard let preferredToStates = routeMapping(fromState: context.fromState, userInfo: context.userInfo)
where preferredToStates.contains(context.toState) else
{
return
}
handler(context)
}
return ActionDisposable {
routeDisposable.dispose()
handlerDisposable.dispose()
}
}
// MARK: removeStateRouteMapping
private func _removeStateRouteMapping(routeMappingID: _RouteMappingID) -> Bool
{
if self._routeMappings[routeMappingID.key] != nil {
self._routeMappings[routeMappingID.key] = nil
return true
}
else {
return false
}
}
}
//--------------------------------------------------
// MARK: - Custom Operators
//--------------------------------------------------
// MARK: `<-` (tryState)
infix operator <- { associativity left }
public func <- <S: StateType, E: EventType>(machine: StateMachine<S, E>, state: S) -> StateMachine<S, E>
{
machine.tryState(state)
return machine
}
public func <- <S: StateType, E: EventType>(machine: StateMachine<S, E>, tuple: (S, Any?)) -> StateMachine<S, E>
{
machine.tryState(tuple.0, userInfo: tuple.1)
return machine
}
| d84432065113e11af3743f81925a9084 | 33.353704 | 155 | 0.579376 | false | false | false | false |
zilaiyedaren/MLSwiftBasic | refs/heads/master | MLSwiftBasic/Classes/PhotoBrowser/MLPhotoBrowserPhotoScrollView.swift | mit | 1 | //
// MLPhotoBrowserPhotoScrollView.swift
// MLSwiftBasic
//
// Created by 张磊 on 15/8/31.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
import Kingfisher
@objc protocol MLPhotoBrowserPhotoScrollViewDelegate: NSObjectProtocol{
func photoBrowserPhotoScrollViewDidSingleClick()
}
class MLPhotoBrowserPhotoScrollView: UIScrollView,MLPhotoBrowserPhotoViewDelegate,MLPhotoPickerBrowserPhotoImageViewDelegate,UIActionSheetDelegate {
var photoImageView:MLPhotoBrowserPhotoImageView?
var isHiddenShowSheet:Bool?
var photo:MLPhotoBrowser?{
willSet{
var thumbImage = newValue!.thumbImage
if (thumbImage == nil) {
self.photoImageView!.image = newValue?.toView?.image
thumbImage = self.photoImageView!.image
}else{
self.photoImageView!.image = thumbImage;
}
self.photoImageView!.contentMode = .ScaleAspectFit;
self.photoImageView!.frame = ZLPhotoRect.setMaxMinZoomScalesForCurrentBoundWithImageView(self.photoImageView!)
// if (self.photoImageView.image == nil) {
// [self setProgress:0.01];
// }
// 网络URL
self.photoImageView!.kf_setImageWithURL(newValue!.photoURL!, placeholderImage: thumbImage, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
}, completionHandler: { (image, error, cacheType, imageURL) -> () in
if ((image) != nil) {
self.photoImageView!.image = image
self.displayImage()
}else{
self.photoImageView?.removeScaleBigTap()
}
})
}
}
var sheet:UIActionSheet?
weak var photoScrollViewDelegate:MLPhotoBrowserPhotoScrollViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupInit()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupInit(){
var tapView = MLPhotoBrowserPhotoView(frame: self.bounds)
tapView.delegate = self
tapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
tapView.backgroundColor = UIColor.blackColor()
self.addSubview(tapView)
photoImageView = MLPhotoBrowserPhotoImageView(frame: self.bounds)
photoImageView!.delegate = self
photoImageView?.userInteractionEnabled = true
photoImageView!.autoresizingMask = .FlexibleWidth | .FlexibleHeight
photoImageView!.backgroundColor = UIColor.blackColor()
self.addSubview(photoImageView!)
// Setup
self.backgroundColor = UIColor.blackColor()
self.delegate = self
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.decelerationRate = UIScrollViewDecelerationRateFast
self.autoresizingMask = .FlexibleWidth | .FlexibleHeight;
var longGesture = UILongPressGestureRecognizer(target: self, action: "longGesture:")
self.addGestureRecognizer(longGesture)
}
func displayImage(){
// Reset
self.maximumZoomScale = 1
self.minimumZoomScale = 1
self.zoomScale = 1
self.contentSize = CGSizeMake(0, 0)
// Get image from browser as it handles ordering of fetching
var img = photoImageView?.image
if img != nil {
photoImageView?.hidden = false
// Set ImageView Frame
// Sizes
var boundsSize = self.bounds.size
var imageSize = photoImageView!.image!.size
var xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise
var yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise
var minScale:CGFloat = min(xScale, yScale);
if (xScale >= 1 && yScale >= 1) {
minScale = min(xScale, yScale);
}
var frameToCenter = CGRectZero;
if (minScale >= 3) {
minScale = 3;
}
photoImageView?.frame = CGRectMake(0, 0, imageSize.width * minScale, imageSize.height * minScale)
self.maximumZoomScale = 3
self.minimumZoomScale = 1.0
self.zoomScale = 1.0
}
self.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen
var boundsSize = self.bounds.size
var frameToCenter = photoImageView!.frame
// Horizontally
if (frameToCenter.size.width < boundsSize.width) {
frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2.0);
} else {
frameToCenter.origin.x = 0;
}
// Vertically
if (frameToCenter.size.height < boundsSize.height) {
frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2.0);
} else {
frameToCenter.origin.y = 0;
}
// Center
if (!CGRectEqualToRect(photoImageView!.frame, frameToCenter)){
photoImageView!.frame = frameToCenter;
}
}
// MARK:: Tap Detection
func handleDoubleTap(touchPoint:CGPoint){
// Zoom
if (self.zoomScale != self.minimumZoomScale) {
// Zoom out
self.setZoomScale(self.minimumZoomScale, animated: true)
self.contentSize = CGSizeMake(self.frame.size.width, 0)
} else {
// Zoom in to twice the size
var newZoomScale = ((self.maximumZoomScale + self.minimumZoomScale) / 2)
var xsize = self.bounds.size.width / newZoomScale
var ysize = self.bounds.size.height / newZoomScale
self.zoomToRect(CGRectMake(touchPoint.x - xsize/2.0, touchPoint.y - ysize/2, xsize, ysize), animated: true)
}
}
func photoPickerBrowserPhotoViewDoubleTapDetected(touch:UITouch) {
var touchX = touch.locationInView(touch.view).x;
var touchY = touch.locationInView(touch.view).y;
touchX *= 1/self.zoomScale;
touchY *= 1/self.zoomScale;
touchX += self.contentOffset.x;
touchY += self.contentOffset.y;
self.handleDoubleTap(CGPointMake(touchX, touchY))
}
func photoPickerBrowserPhotoImageViewSingleTapDetected(touch: UITouch) {
self.disMissTap(nil)
}
func disMissTap(tap:UITapGestureRecognizer?){
if self.photoScrollViewDelegate?.respondsToSelector("photoBrowserPhotoScrollViewDidSingleClick") == true {
self.photoScrollViewDelegate?.photoBrowserPhotoScrollViewDidSingleClick()
}
}
func longGesture(gesture:UILongPressGestureRecognizer){
if gesture.state == .Began{
if self.isHiddenShowSheet == false{
self.sheet = UIActionSheet(title: "提示", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil)
self.sheet?.showInView(self)
}
}
}
// Image View
func photoPickerBrowserPhotoImageViewDoubleTapDetected(touch: UITouch) {
self.handleDoubleTap(touch.locationInView(touch.view))
}
func photoPickerBrowserPhotoViewSingleTapDetected(touch: UITouch) {
self.disMissTap(nil)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return photoImageView
}
func scrollViewDidZoom(scrollView: UIScrollView) {
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
@objc protocol MLPhotoBrowserPhotoViewDelegate: NSObjectProtocol {
func photoPickerBrowserPhotoViewSingleTapDetected(touch:UITouch)
func photoPickerBrowserPhotoViewDoubleTapDetected(touch:UITouch)
}
class MLPhotoBrowserPhotoView: UIView {
var delegate:MLPhotoBrowserPhotoViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.addGesture()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addGesture(){
// 双击放大
var scaleBigTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
scaleBigTap.numberOfTapsRequired = 2
scaleBigTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(scaleBigTap)
// 单击缩小
var disMissTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
disMissTap.numberOfTapsRequired = 1
disMissTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(disMissTap)
// 只能有一个手势存在
disMissTap.requireGestureRecognizerToFail(scaleBigTap)
}
func handleDoubleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoViewDoubleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoViewDoubleTapDetected(touch)
}
}
func handleSingleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoViewSingleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoViewSingleTapDetected(touch)
}
}
}
@objc protocol MLPhotoBrowserPhotoImageViewDelegate: NSObjectProtocol {
func photoPickerBrowserPhotoImageViewSingleTapDetected(touch:UITouch)
func photoPickerBrowserPhotoImageViewDoubleTapDetected(touch:UITouch)
}
class MLPhotoBrowserPhotoImageView: UIImageView {
var scaleBigTap:UITapGestureRecognizer?
var delegate:MLPhotoPickerBrowserPhotoImageViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.addGesture()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func removeScaleBigTap(){
self.scaleBigTap?.removeTarget(self, action: "handleDoubleTap:")
}
func addGesture(){
// 双击放大
var scaleBigTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
scaleBigTap.numberOfTapsRequired = 2
scaleBigTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(scaleBigTap)
self.scaleBigTap = scaleBigTap
// 单击缩小
var disMissTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
disMissTap.numberOfTapsRequired = 1
disMissTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(disMissTap)
// 只能有一个手势存在
disMissTap.requireGestureRecognizerToFail(scaleBigTap)
}
func handleDoubleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoImageViewDoubleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoImageViewDoubleTapDetected(touch)
}
}
func handleSingleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoImageViewSingleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoImageViewSingleTapDetected(touch)
}
}
}
| 58e4aac89e6ffa800d8db0ae59843602 | 35.087774 | 170 | 0.640375 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Layers/Display KML network links/DisplayKMLNetworkLinksViewController.swift | apache-2.0 | 1 | // Copyright 2018 Esri.
//
// 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 ArcGIS
class DisplayKMLNetworkLinksViewController: UIViewController {
@IBOutlet weak var sceneView: AGSSceneView!
/// The controller shown in a popover after tapping "View Messages"
private weak var messageViewController: KMLNetworkMessagesViewController?
private var messageText = "Network Link Messages:\n\n" {
didSet {
updatePopoverForMessage()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["DisplayKMLNetworkLinksViewController"]
// instantiate a scene using labeled imagery basemap
let scene = AGSScene(basemapStyle: .arcGISImagery)
// set the view's scene
sceneView.scene = scene
// create and set a viewpoint centered on the data coverage
let viewpoint = AGSViewpoint(center: AGSPoint(x: 8.150526, y: 50.472421, spatialReference: .wgs84()), scale: 10000000)
sceneView.setViewpoint(viewpoint)
/// The URL of a KML file with network links
let datasetURL = URL(string: "https://www.arcgis.com/sharing/rest/content/items/600748d4464442288f6db8a4ba27dc95/data")!
/// The KML dataset with network links
let kmlDataset = AGSKMLDataset(url: datasetURL)
// register to receive the network link messages
kmlDataset.networkLinkMessageHandler = { [weak self] (_, message) in
// run UI updates on the main thread
DispatchQueue.main.async {
// append the message to the prior messages
self?.messageText += "\(message)\n\n"
}
}
/// The layer used to display the KML data
let kmlLayer = AGSKMLLayer(kmlDataset: kmlDataset)
// add the layer to the scene
scene.operationalLayers.add(kmlLayer)
}
private func updatePopoverForMessage() {
// updates the text shown in the text view with the message text
messageViewController?.textView?.text = messageText
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// The popovover segue is triggered via storyboard connections, so set it up here.
if let controller = segue.destination as? KMLNetworkMessagesViewController {
controller.presentationController?.delegate = self
controller.preferredContentSize = CGSize(width: 300, height: 300)
// load the view so the text view can be accessed now
controller.loadViewIfNeeded()
// retain a reference to the controller so the text view can be updated from `updatePopoverForMessage()`
messageViewController = controller
// set the initial message
updatePopoverForMessage()
}
}
}
extension DisplayKMLNetworkLinksViewController: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
// show as this as a popover even on small displays
return .none
}
}
class KMLNetworkMessagesViewController: UIViewController {
@IBOutlet var textView: UITextView!
}
| 0280a8141439b82db57b9462ff395762 | 41.688172 | 142 | 0.682116 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/VideoAvatarModalController.swift | gpl-2.0 | 1 | //
// VideoAvatarModalController.swift
// Telegram
//
// Created by Mikhail Filimonov on 11/06/2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
import AVKit
import SwiftSignalKit
private var magicNumber: CGFloat {
return 8 / 370
}
private final class VideoAvatarKeyFramePreviewView: Control {
private let imageView: ImageView = ImageView()
private let flash: View = View()
fileprivate var keyFrame: CGFloat?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(imageView)
addSubview(flash)
flash.backgroundColor = .white
flash.frame = bounds
imageView.frame = bounds
imageView.animates = true
layout()
}
func update(with image: CGImage?, value: CGFloat?, animated: Bool, completion: @escaping(Bool)->Void) {
imageView.image = image
self.keyFrame = value
if animated {
flash.layer?.animateAlpha(from: 1, to: 0, duration: 0.8, timingFunction: .easeIn, removeOnCompletion: false, completion: { [weak self] completed in
self?.flash.removeFromSuperview()
completion(completed)
})
} else {
flash.removeFromSuperview()
}
}
override func layout() {
super.layout()
imageView.frame = bounds
layer?.cornerRadius = frame.width / 2
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private final class VideoAvatarModalView : View {
private var avPlayer: AVPlayerView
private var videoSize: NSSize = .zero
private let playerContainer: View = View()
private var keyFramePreview: VideoAvatarKeyFramePreviewView?
private var keyFrameDotView: View?
private let controls: View = View()
fileprivate let ok: TitleButton = TitleButton()
fileprivate let cancel: TitleButton = TitleButton()
fileprivate let scrubberView: VideoEditorScrubblerControl = VideoEditorScrubblerControl(frame: .zero)
fileprivate let selectionRectView: SelectionRectView
private let descView: TextView = TextView()
required init(frame frameRect: NSRect) {
selectionRectView = SelectionRectView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height))
avPlayer = AVPlayerView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height))
super.init(frame: frameRect)
playerContainer.addSubview(avPlayer)
avPlayer.controlsStyle = .none
playerContainer.addSubview(selectionRectView)
controls.addSubview(scrubberView)
selectionRectView.isCircleCap = true
selectionRectView.dimensions = .square
addSubview(playerContainer)
addSubview(controls)
self.addSubview(ok)
self.addSubview(cancel)
addSubview(descView)
descView.userInteractionEnabled = false
descView.isSelectable = false
descView.disableBackgroundDrawing = true
cancel.set(background: .grayText, for: .Normal)
ok.set(background: .accent, for: .Normal)
cancel.set(background: NSColor.grayText.withAlphaComponent(0.8), for: .Highlight)
ok.set(background: NSColor.accent.highlighted, for: .Highlight)
cancel.set(color: .white, for: .Normal)
cancel.set(text: strings().videoAvatarButtonCancel, for: .Normal)
ok.set(color: .white, for: .Normal)
ok.set(text: strings().videoAvatarButtonSet, for: .Normal)
_ = cancel.sizeToFit(.zero, NSMakeSize(80, 20), thatFit: true)
_ = ok.sizeToFit(.zero, NSMakeSize(80, 20), thatFit: true)
cancel.layer?.cornerRadius = .cornerRadius
ok.layer?.cornerRadius = .cornerRadius
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowColor = NSColor.black.withAlphaComponent(0.2)
shadow.shadowOffset = NSMakeSize(0, 2)
self.cancel.shadow = shadow
self.ok.shadow = shadow
// cancel.set(image: NSImage(named: "Icon_VideoPlayer_Close")!.precomposed(.white), for: .Normal)
// ok.set(image: NSImage(named: "Icon_SaveEditedMessage")!.precomposed(.accent), for: .Normal)
setFrameSize(frame.size)
layout()
}
func updateKeyFrameImage(_ image: CGImage?) {
keyFramePreview?.update(with: image, value: keyFramePreview?.keyFrame, animated: false, completion: { _ in })
}
func setKeyFrame(value: CGFloat?, highRes: CGImage? = nil, lowRes: CGImage? = nil, animated: Bool, completion: @escaping(Bool)->Void = { _ in}, moveToCurrentKeyFrame: @escaping(CGFloat)->Void = { _ in }) -> Void {
if let keyFramePreview = self.keyFramePreview {
self.keyFramePreview = nil
keyFramePreview.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak keyFramePreview] _ in
keyFramePreview?.removeFromSuperview()
})
}
if let keyFrameDotView = self.keyFrameDotView {
self.keyFrameDotView = nil
keyFrameDotView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak keyFrameDotView] _ in
keyFrameDotView?.removeFromSuperview()
})
}
if let value = value {
let point = self.convert(selectionRectView.selectedRect.origin, from: selectionRectView)
let size = selectionRectView.selectedRect.size
let keyFramePreview = VideoAvatarKeyFramePreviewView(frame: CGRect(origin: point, size: size))
keyFramePreview.set(handler: { _ in
moveToCurrentKeyFrame(value)
}, for: .Click)
keyFramePreview.update(with: highRes, value: value, animated: animated, completion: { [weak self, weak keyFramePreview] completed in
if !completed {
keyFramePreview?.removeFromSuperview()
completion(completed)
return
}
guard let `self` = self, let keyFramePreview = keyFramePreview else {
return
}
let keyFrameDotView = View()
self.addSubview(keyFrameDotView)
keyFrameDotView.backgroundColor = .white
keyFrameDotView.layer?.cornerRadius = 3
let point = NSMakePoint(self.controls.frame.minX + self.scrubberView.frame.minX + value * self.scrubberView.frame.width - 15 + 2, self.controls.frame.maxY - self.scrubberView.frame.height - 30 - 14)
keyFrameDotView.frame = NSMakeRect(self.controls.frame.minX + self.scrubberView.frame.minX + (value * self.scrubberView.frame.width) - 3 + 2, self.controls.frame.maxY - self.scrubberView.frame.height - 10, 6, 6)
keyFramePreview.layer?.animateScale(from: 1, to: 30 / keyFramePreview.frame.width, duration: 0.23, removeOnCompletion: false)
keyFramePreview.layer?.animatePosition(from: keyFramePreview.frame.origin, to: point, duration: 0.3, removeOnCompletion: false, completion: { [weak self, weak keyFramePreview, weak keyFrameDotView] complete in
keyFramePreview?.update(with: lowRes, value: value, animated: false, completion: { _ in })
keyFramePreview?.frame = CGRect(origin: point, size: NSMakeSize(30, 30))
keyFramePreview?.layer?.removeAllAnimations()
self?.keyFrameDotView = keyFrameDotView
self?.keyFramePreview = keyFramePreview
if !complete {
keyFrameDotView?.removeFromSuperview()
keyFramePreview?.removeFromSuperview()
}
completion(complete)
})
keyFrameDotView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
})
self.addSubview(keyFramePreview)
}
}
var playerSize: NSSize {
return playerContainer.frame.size
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
}
private var localize: String?
func update(_ player: AVPlayer, localize: String, size: NSSize) {
self.avPlayer.player = player
self.videoSize = size
self.localize = localize
setFrameSize(frame.size)
layout()
let size = NSMakeSize(200, 200).aspectFitted(playerContainer.frame.size)
let rect = playerContainer.focus(size)
selectionRectView.minimumSize = size.aspectFitted(NSMakeSize(150, 150))
selectionRectView.applyRect(rect, force: true, dimensions: .square)
}
func play() {
self.avPlayer.player?.play()
}
func stop() {
self.avPlayer.player?.pause()
self.avPlayer.player = nil
}
override func setFrameSize(_ newSize: NSSize) {
let oldSize = self.frame.size
super.setFrameSize(newSize)
let videoContainerSize = videoSize.aspectFitted(NSMakeSize(frame.width, frame.height - 200))
let oldVideoContainerSize = playerContainer.frame.size
playerContainer.setFrameSize(videoContainerSize)
if oldSize != newSize, oldSize != NSZeroSize, inLiveResize {
let multiplier = NSMakeSize(videoContainerSize.width / oldVideoContainerSize.width, videoContainerSize.height / oldVideoContainerSize.height)
selectionRectView.applyRect(selectionRectView.selectedRect.apply(multiplier: multiplier))
}
avPlayer.frame = playerContainer.bounds
selectionRectView.frame = playerContainer.bounds
controls.setFrameSize(NSMakeSize(370, 44))
scrubberView.setFrameSize(controls.frame.size)
if let localize = localize {
let descLayout = TextViewLayout.init(.initialize(string: localize, color: .white, font: .normal(.text)), maximumNumberOfLines: 1)
descLayout.measure(width: frame.width)
descView.update(descLayout)
}
}
override func layout() {
super.layout()
playerContainer.centerX(y: floorToScreenPixels(backingScaleFactor, (frame.height - 184) - playerContainer.frame.height) / 2)
controls.centerX(y: frame.height - controls.frame.height - 100)
scrubberView.centerX(y: controls.frame.height - scrubberView.frame.height)
ok.centerX(y: frame.height - ok.frame.height - 30, addition: 7 + ok.frame.width / 2)
cancel.centerX(y: frame.height - cancel.frame.height - 30, addition: -(7 + cancel.frame.width / 2))
descView.centerX(y: controls.frame.maxY + 15)
if let keyFramePreview = keyFramePreview, let keyFrameDotView = keyFrameDotView, let value = keyFramePreview.keyFrame {
let point = NSMakePoint(self.controls.frame.minX + self.scrubberView.frame.minX + value * self.scrubberView.frame.width - 15 + 2, self.controls.frame.maxY - self.scrubberView.frame.height - 30 - 14)
keyFrameDotView.frame = NSMakeRect(self.controls.frame.minX + self.scrubberView.frame.minX + (value * self.scrubberView.frame.width) - 3 + 2, self.controls.frame.maxY - self.scrubberView.frame.height - 10, 6, 6)
keyFramePreview.frame = CGRect(origin: point, size: NSMakeSize(30, 30))
}
}
}
enum VideoAvatarGeneratorState : Equatable {
case start(thumb: String)
case progress(Float)
case complete(thumb: String, video: String, keyFrame: Double?)
case error
}
class VideoAvatarModalController: ModalViewController {
private let context: AccountContext
fileprivate let videoSize: NSSize
fileprivate let player: AVPlayer
fileprivate let item: AVPlayerItem
fileprivate let asset: AVComposition
fileprivate let track: AVAssetTrack
fileprivate var appliedKeyFrame: CGFloat? = nil
private let updateThumbsDisposable = MetaDisposable()
private let rectDisposable = MetaDisposable()
private let valuesDisposable = MetaDisposable()
private let keyFrameGeneratorDisposable = MetaDisposable()
fileprivate let scrubberValues:Atomic<VideoScrubberValues> = Atomic(value: VideoScrubberValues(movePos: 0, keyFrame: nil, leftTrim: 0, rightTrim: 1.0, minDist: 0, maxDist: 1, paused: true, suspended: false))
fileprivate let _scrubberValuesSignal: ValuePromise<VideoScrubberValues> = ValuePromise(ignoreRepeated: true)
var scrubberValuesSignal: Signal<VideoScrubberValues, NoError> {
return _scrubberValuesSignal.get() |> deliverOnMainQueue
}
fileprivate func updateValues(_ f: (VideoScrubberValues)->VideoScrubberValues) {
_scrubberValuesSignal.set(scrubberValues.modify(f))
}
private var firstTime: Bool = true
private var timeObserverToken: Any?
var completeState: Signal<VideoAvatarGeneratorState, NoError> {
return state.get()
}
private var state: Promise<VideoAvatarGeneratorState> = Promise()
private let localize: String
private let quality: String
private let holder: AVAsset
init(context: AccountContext, asset: AVComposition, track: AVAssetTrack, localize: String, quality: String, holder: AVAsset) {
self.context = context
self.asset = asset
self.track = track
self.holder = holder
self.quality = quality
let size = track.naturalSize.applying(track.preferredTransform)
self.videoSize = NSMakeSize(abs(size.width), abs(size.height))
self.item = AVPlayerItem(asset: asset)
self.player = AVPlayer(playerItem: item)
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = videoSize
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: self.asset.duration)
let transform1: CGAffineTransform = track.preferredTransform
transformer.setTransform(transform1, at: CMTime.zero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
self.item.videoComposition = videoComposition
self.localize = localize
super.init(frame: CGRect(origin: .zero, size: context.window.contentView!.frame.size - NSMakeSize(20, 20)))
self.bar = .init(height: 0)
}
override open func measure(size: NSSize) {
if let contentSize = self.modal?.window.contentView?.frame.size {
self.modal?.resize(with: contentSize - NSMakeSize(20, 20), animated: false)
}
}
func updateSize(_ animated: Bool) {
if let contentSize = self.modal?.window.contentView?.frame.size {
self.modal?.resize(with: contentSize - NSMakeSize(20, 20), animated: animated)
}
}
override var dynamicSize: Bool {
return true
}
override var background: NSColor {
return .clear
}
override var containerBackground: NSColor {
return .clear
}
override var isVisualEffectBackground: Bool {
return true
}
override func viewClass() -> AnyClass {
return VideoAvatarModalView.self
}
private var genericView: VideoAvatarModalView {
return self.view as! VideoAvatarModalView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
player.pause()
if let timeObserverToken = timeObserverToken {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
override func returnKeyAction() -> KeyHandlerResult {
self.state.set(generateVideo(asset, composition: self.currentVideoComposition(), quality: self.quality, values: self.scrubberValues.with { $0 }))
close()
return .invoked
}
private func currentVideoComposition() -> AVVideoComposition {
let size = self.videoSize
let naturalSize = self.asset.naturalSize
enum Orientation {
case up, down, right, left
}
func orientation(for track: AVAssetTrack) -> Orientation {
let t = track.preferredTransform
if(t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0) {
return .up
} else if(t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0) {
return .down
} else if(t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0) {
return .right
} else if(t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0) {
return .left
} else {
return .up
}
}
func roundSize(_ numToRound: CGFloat) -> CGFloat {
let numToRound = Int(numToRound)
let remainder = numToRound % 16;
if (remainder == 0) {
return CGFloat(numToRound)
}
return CGFloat((numToRound - 16) + (16 - remainder));
}
let rotation: Orientation = orientation(for: track)
var selectedRect = self.genericView.selectionRectView.selectedRect
let viewSize = self.genericView.playerSize
let coefficient = NSMakeSize(size.width / viewSize.width, size.height / viewSize.height)
selectedRect = selectedRect.apply(multiplier: coefficient)
selectedRect.size = NSMakeSize(min(selectedRect.width, selectedRect.height), min(selectedRect.width, selectedRect.height))
let videoComposition = AVMutableVideoComposition()
videoComposition.renderSize = NSMakeSize(roundSize(selectedRect.width), roundSize(selectedRect.height))
videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: track)
let instruction = AVMutableVideoCompositionInstruction()
instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: self.asset.duration)
let point = selectedRect.origin
var finalTransform: CGAffineTransform = CGAffineTransform.identity
switch rotation {
case .down:
finalTransform = finalTransform
.translatedBy(x: -point.x, y: naturalSize.width - point.y)
.rotated(by: -.pi / 2)
case .left:
finalTransform = finalTransform
.translatedBy(x: naturalSize.width - point.x, y: naturalSize.height - point.y)
.rotated(by: .pi)
case .right:
finalTransform = finalTransform
.translatedBy(x: -point.x, y: -point.y)
.rotated(by: 0)
case .up:
finalTransform = finalTransform
.translatedBy(x: naturalSize.height - point.x, y: -point.y)
.rotated(by: .pi / 2)
}
transformer.setTransform(finalTransform, at: CMTime.zero)
instruction.layerInstructions = [transformer]
videoComposition.instructions = [instruction]
return videoComposition
}
deinit {
rectDisposable.dispose()
updateThumbsDisposable.dispose()
valuesDisposable.dispose()
keyFrameGeneratorDisposable.dispose()
NotificationCenter.default.removeObserver(self.item)
if let timeObserverToken = timeObserverToken {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
private var generatedRect: NSRect? = nil
private func updateUserInterface(_ firstTime: Bool) {
let size = NSMakeSize(genericView.scrubberView.frame.height, genericView.scrubberView.frame.height)
let signal = generateVideoScrubberThumbs(for: asset, composition: currentVideoComposition(), size: size, count: Int(ceil(genericView.scrubberView.frame.width / size.width)), gradually: true, blur: true)
|> delay(0.2, queue: .concurrentDefaultQueue())
let duration = CMTimeGetSeconds(asset.duration)
let keyFrame = scrubberValues.with { $0.keyFrame }
let keyFrameSignal: Signal<CGImage?, NoError>
if let keyFrame = keyFrame {
keyFrameSignal = generateVideoAvatarPreview(for: asset, composition: self.currentVideoComposition(), highSize: genericView.selectionRectView.selectedRect.size, lowSize: NSMakeSize(30, 30), at: Double(keyFrame) * duration)
|> delay(0.2, queue: .concurrentDefaultQueue())
|> map { $0.0 }
} else {
keyFrameSignal = .single(nil)
}
var selectedRect = self.genericView.selectionRectView.selectedRect
let viewSize = self.genericView.playerSize
let coefficient = NSMakeSize(size.width / viewSize.width, size.height / viewSize.height)
selectedRect = selectedRect.apply(multiplier: coefficient)
if generatedRect != selectedRect {
updateThumbsDisposable.set(combineLatest(queue: .mainQueue(), signal, keyFrameSignal).start(next: { [weak self] images, keyFrame in
self?.genericView.scrubberView.render(images.0, size: size)
self?.genericView.updateKeyFrameImage(keyFrame)
if self?.firstTime == true {
self?.firstTime = !images.1
}
self?.generatedRect = selectedRect
}))
}
}
private func applyValuesToPlayer(_ values: VideoScrubberValues) {
if values.movePos > values.rightTrim - (magicNumber + (magicNumber / 2)), !values.paused {
play()
}
if values.paused {
player.rate = 0
seekToNormal(values)
player.pause()
} else if player.rate == 0, !values.paused {
player.rate = 1
play()
}
if let keyFrame = values.keyFrame, appliedKeyFrame != keyFrame {
self.runKeyFrameUpdater(keyFrame)
seekToNormal(values)
} else if appliedKeyFrame != nil && values.keyFrame == nil {
self.genericView.setKeyFrame(value: nil, animated: true)
self.appliedKeyFrame = nil
}
}
@discardableResult private func seekToNormal(_ values: VideoScrubberValues) -> CGFloat? {
let duration = CMTimeGetSeconds(asset.duration)
if values.suspended {
self.player.seek(to: CMTimeMakeWithSeconds(TimeInterval(values.movePos) * duration, preferredTimescale: 1000), toleranceBefore: .zero, toleranceAfter: .zero)
return values.keyFrame
} else {
self.player.seek(to: CMTimeMakeWithSeconds(TimeInterval(values.leftTrim + magicNumber) * duration, preferredTimescale: 1000), toleranceBefore: .zero, toleranceAfter: .zero)
return nil
}
}
private func play() {
player.pause()
let duration = CMTimeGetSeconds(asset.duration)
if let timeObserverToken = timeObserverToken {
player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
_ = self.scrubberValues.modify { values in
let values = values.withUpdatedPaused(false)
if let result = self.seekToNormal(values) {
return values.withUpdatedMove(result)
} else {
return values.withUpdatedMove(values.leftTrim)
}
}
let timeScale = CMTimeScale(NSEC_PER_SEC)
let time = CMTime(seconds: 0.016 * 2, preferredTimescale: timeScale)
timeObserverToken = player.addPeriodicTimeObserver(forInterval: time, queue: .main) { [weak self] time in
self?.updateValues { current in
if !current.suspended {
return current.withUpdatedMove(CGFloat(CMTimeGetSeconds(time) / duration))
} else {
return current
}
}
}
self.player.play()
}
private func runKeyFrameUpdater(_ keyFrame: CGFloat) {
let duration = CMTimeGetSeconds(asset.duration)
let size = genericView.selectionRectView.selectedRect.size
let signal = generateVideoAvatarPreview(for: self.asset, composition: self.currentVideoComposition(), highSize: size, lowSize: NSMakeSize(30, 30), at: Double(keyFrame) * duration)
|> deliverOnMainQueue
keyFrameGeneratorDisposable.set(signal.start(next: { [weak self] highRes, lowRes in
self?.genericView.setKeyFrame(value: keyFrame, highRes: highRes, lowRes: lowRes, animated: true, completion: { [weak self] completed in
if completed {
self?.updateValues {
$0.withUpdatedPaused(false)
.withUpdatedMove(keyFrame)
}
self?.updateValues {
$0.withUpdatedSuspended(false)
}
} else {
self?.updateValues {
$0.withUpdatedSuspended(false)
.withUpdatedPaused(false)
}
}
}, moveToCurrentKeyFrame: { [weak self] keyFrame in
self?.updateValues {
$0.withUpdatedSuspended(true)
.withUpdatedMove(keyFrame)
}
self?.updateValues { [weak self] values in
self?.seekToNormal(values)
return values
}
self?.updateValues {
$0.withUpdatedSuspended(false)
}
})
self?.appliedKeyFrame = keyFrame
}))
}
override var closable: Bool {
return false
}
override func viewDidLoad() {
super.viewDidLoad()
genericView.update(self.player, localize: self.localize, size: self.videoSize)
genericView.cancel.set(handler: { [weak self] _ in
self?.close()
}, for: .Click)
genericView.ok.set(handler: { [weak self] _ in
_ = self?.returnKeyAction()
}, for: .Click)
let duration = CMTimeGetSeconds(asset.duration)
let scrubberSize = genericView.scrubberView.frame.width
let valueSec = (scrubberSize / CGFloat(duration)) / scrubberSize
self.updateValues { values in
return values.withUpdatedMinDist(valueSec).withUpdatedMaxDist(valueSec * 10.0).withUpdatedrightTrim(min(1, valueSec * 10.0))
}
genericView.scrubberView.updateValues = { [weak self] values in
self?.updateValues { _ in
return values
}
}
rectDisposable.set(genericView.selectionRectView.updatedRect.start(next: { [weak self] rect in
self?.genericView.selectionRectView.applyRect(rect, force: true, dimensions: .square)
self?.updateUserInterface(self?.firstTime ?? false)
}))
valuesDisposable.set(self.scrubberValuesSignal.start(next: { [weak self] values in
self?.genericView.scrubberView.apply(values: values)
self?.applyValuesToPlayer(values)
}))
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.item, queue: .main) { [weak self] _ in
self?.play()
}
play()
readyOnce()
}
}
func selectVideoAvatar(context: AccountContext, path: String, localize: String, quality: String = AVAssetExportPresetMediumQuality, signal:@escaping(Signal<VideoAvatarGeneratorState, NoError>)->Void) {
let asset = AVURLAsset(url: URL(fileURLWithPath: path))
let track = asset.tracks(withMediaType: .video).first
if let track = track {
let composition = AVMutableComposition()
guard let compositionVideoTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) else {
return
}
do {
try compositionVideoTrack.insertTimeRange(CMTimeRangeMake(start: .zero, duration: asset.duration), of: track, at: .zero)
let controller = VideoAvatarModalController(context: context, asset: composition, track: track, localize: localize, quality: quality, holder: asset)
showModal(with: controller, for: context.window)
signal(controller.completeState)
} catch {
}
}
}
private func generateVideo(_ asset: AVComposition, composition: AVVideoComposition, quality: String, values: VideoScrubberValues) -> Signal<VideoAvatarGeneratorState, NoError> {
return Signal { subscriber in
let exportSession = AVAssetExportSession(asset: asset, presetName: quality)!
exportSession.outputFileType = .mp4
exportSession.shouldOptimizeForNetworkUse = true
let videoPath = NSTemporaryDirectory() + "\(arc4random()).mp4"
let thumbPath = NSTemporaryDirectory() + "\(arc4random()).jpg"
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.maximumSize = CGSize(width: 640, height: 640)
imageGenerator.appliesPreferredTrackTransform = true
imageGenerator.requestedTimeToleranceBefore = .zero
imageGenerator.requestedTimeToleranceAfter = .zero
imageGenerator.videoComposition = composition
let image = try? imageGenerator.copyCGImage(at: CMTimeMakeWithSeconds(Double(values.keyFrame ?? values.leftTrim) * asset.duration.seconds, preferredTimescale: 1000), actualTime: nil)
if let image = image {
let options = NSMutableDictionary()
options.setValue(640 as NSNumber, forKey: kCGImageDestinationImageMaxPixelSize as String)
options.setValue(true as NSNumber, forKey: kCGImageSourceCreateThumbnailWithTransform as String)
let colorQuality: Float = 0.3
options.setObject(colorQuality as NSNumber, forKey: kCGImageDestinationLossyCompressionQuality as NSString)
let mutableData: CFMutableData = NSMutableData() as CFMutableData
let colorDestination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, options)!
CGImageDestinationSetProperties(colorDestination, nil)
CGImageDestinationAddImage(colorDestination, image, options as CFDictionary)
CGImageDestinationFinalize(colorDestination)
try? (mutableData as Data).write(to: URL(fileURLWithPath: thumbPath))
subscriber.putNext(.start(thumb: thumbPath))
}
exportSession.outputURL = URL(fileURLWithPath: videoPath)
exportSession.videoComposition = composition
let wholeDuration = CMTimeGetSeconds(asset.duration)
let from = TimeInterval(values.leftTrim) * wholeDuration
let to = TimeInterval(values.rightTrim) * wholeDuration
let start = CMTimeMakeWithSeconds(from, preferredTimescale: 1000)
let duration = CMTimeMakeWithSeconds(to - from, preferredTimescale: 1000)
if #available(OSX 10.14, *) {
exportSession.fileLengthLimit = 2 * 1024 * 1024
}
let timer = SwiftSignalKit.Timer(timeout: 0.05, repeat: true, completion: {
subscriber.putNext(.progress(exportSession.progress))
}, queue: .concurrentBackgroundQueue())
exportSession.timeRange = CMTimeRangeMake(start: start, duration: duration)
exportSession.exportAsynchronously(completionHandler: { [weak exportSession] in
timer.invalidate()
if let exportSession = exportSession, exportSession.status == .completed, exportSession.error == nil {
subscriber.putNext(.complete(thumb: thumbPath, video: videoPath, keyFrame: values.keyFrame != nil ? Double(values.keyFrame!) * asset.duration.seconds : nil))
subscriber.putCompletion()
} else {
subscriber.putNext(.error)
subscriber.putCompletion()
}
})
timer.start()
return ActionDisposable {
exportSession.cancelExport()
timer.invalidate()
}
} |> runOn(.concurrentBackgroundQueue())
}
/*
- (NSImageOrientation)getVideoOrientationFromAsset:(AVAsset *)asset
{
AVAssetTrack *videoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
CGSize size = [videoTrack naturalSize];
CGAffineTransform txf = [videoTrack preferredTransform];
if (size.width == txf.tx && size.height == txf.ty)
return NSImageOrientationLeft; //return UIInterfaceOrientationLandscapeLeft;
else if (txf.tx == 0 && txf.ty == 0)
return NSImageOrientationRight; //return UIInterfaceOrientationLandscapeRight;
else if (txf.tx == 0 && txf.ty == size.width)
return NSImageOrientationDown; //return UIInterfaceOrientationPortraitUpsideDown;
else
return NSImageOrientationUp; //return UIInterfaceOrientationPortrait;
}
*/
| aea57f7c143291b573cbe30bf0d80080 | 38.754305 | 233 | 0.619072 | false | false | false | false |
nlsteers/learning-ios | refs/heads/master | Cat Age/Cat Age/ViewController.swift | mit | 1 | //
// ViewController.swift
// Cat Age
//
// Created by Nathaniel Steers on 13/10/2015.
// Copyright © 2015 nlsteers. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var catAge: UILabel!
@IBOutlet weak var textField1: UITextField!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBAction func submitAge(sender: AnyObject) {
print("button pressed")
var age = Int(textField1.text!)!
age = age * 7
label1.hidden = false
catAge.text = String(age)
label2.hidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
print("Hello World")
label1.hidden = true
label2.hidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| c13877d48dfb2e26cd0702603e9351d8 | 20.232558 | 51 | 0.601314 | false | false | false | false |
zeroc-ice/ice-demos | refs/heads/3.7 | swift/Chat/views/MessageView.swift | gpl-2.0 | 1 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import InputBarAccessoryView
import MessageKit
import PromiseKit
import SwiftUI
final class MessageSwiftUIVC: MessagesViewController {
// MARK: - Public properties
var client: Client!
// MARK: - Overriding UIViewController methods
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,
selector: #selector(handleKeyboardDidShow(_:)),
name: UIResponder.keyboardDidShowNotification, object: nil)
if let conn = client.router!.ice_getCachedConnection() {
conn.setACM(timeout: client.acmTimeout, close: nil, heartbeat: .HeartbeatAlways)
do {
try conn.setCloseCallback { _ in
// Dispatch the connection close callback to the main thread in order to modify the UI in a thread
// safe manner.
DispatchQueue.main.async {
self.closed()
}
}
} catch {}
}
// Register the chat callback.
firstly {
client.session!.setCallbackAsync(client.callbackProxy)
}.catch { err in
let alert = UIAlertController(title: "Error",
message: err.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.parent?.present(alert, animated: true, completion: nil)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Because SwiftUI wont automatically make our controller the first responder, we need to do it on viewDidAppear
becomeFirstResponder()
messagesCollectionView.scrollToLastItem(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let logoutButton = UIBarButtonItem(title: "Logout", style: .done, target: self, action: #selector(logout(_:)))
parent?.navigationItem.leftBarButtonItem = logoutButton
parent?.navigationItem.setHidesBackButton(true, animated: true)
let usersText = "\(client.users.count) " + (client.users.count > 1 ? "Users" : "User")
let usersButton = UIBarButtonItem(title: usersText,
style: .plain,
target: self,
action: #selector(showUsers(_:)))
parent?.navigationItem.rightBarButtonItem = usersButton
}
// MARK: - Public functions
@objc func showUsers(_: UIBarButtonItem) {
let swiftUIView = UsersView(users: client?.users ?? [])
let hostingController = UIHostingController(rootView: swiftUIView)
present(hostingController, animated: true, completion: nil)
}
// MARK: - Private functions
private func closed() {
// The session is invalid, clear.
if client.session != nil, let controller = navigationController {
client.session = nil
client.router = nil
controller.popToRootViewController(animated: true)
client.destroySession()
// Open an alert with just an OK button
let alert = UIAlertController(title: "Error",
message: "Lost connection with session!\n",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
parent?.present(alert, animated: true, completion: nil)
}
}
@objc private func logout(_: UIBarButtonItem) {
view.endEditing(true)
client?.destroySession()
if let controller = navigationController {
dismiss(animated: true, completion: nil)
view.endEditing(true)
controller.popViewController(animated: true)
}
}
// TODO: - Work around for issue in message kit involving `messagesCollectionView.scrollToLastItem`
// Information about issue can be found at https://github.com/MessageKit/MessageKit/issues/1503
@objc private func handleKeyboardDidShow(_: Notification) {
messagesCollectionView.contentInset.bottom = 0
}
}
struct MessagesView: UIViewControllerRepresentable {
@EnvironmentObject var client: Client
@State private var initialized = false
func makeUIViewController(context: Context) -> MessageSwiftUIVC {
let messagesVC = MessageSwiftUIVC()
messagesVC.client = client
messagesVC.messagesCollectionView.messagesDisplayDelegate = context.coordinator
messagesVC.messagesCollectionView.messagesLayoutDelegate = context.coordinator
messagesVC.messagesCollectionView.messagesDataSource = context.coordinator
messagesVC.messageInputBar.delegate = context.coordinator
messagesVC.scrollsToBottomOnKeyboardBeginsEditing = true
messagesVC.scrollsToLastItemOnKeyboardBeginsEditing = true
messagesVC.showMessageTimestampOnSwipeLeft = true // default false
messagesVC.messageInputBar.inputTextView.placeholder = "Message"
return messagesVC
}
func updateUIViewController(_ uiViewController: MessageSwiftUIVC, context _: Context) {
let usersText = "\(client.users.count) " + (client.users.count > 1 ? "Users" : "User")
let usersButton = UIBarButtonItem(title: usersText,
style: .plain,
target: self,
action: #selector(uiViewController.showUsers(_:)))
uiViewController.parent?.navigationItem.rightBarButtonItem = usersButton
uiViewController.messagesCollectionView.reloadData()
scrollToBottom(uiViewController)
}
func makeCoordinator() -> Coordinator {
return Coordinator(self, client: client)
}
final class Coordinator {
let formatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .medium
return formatter
}()
var parent: MessagesView
var client: Client
init(_ parent: MessagesView, client: Client) {
self.client = client
self.parent = parent
}
}
private func scrollToBottom(_ uiViewController: MessagesViewController) {
DispatchQueue.main.async {
// The initialized state variable allows us to start at the bottom with the initial messages without seeing
// the initial scroll flash by
uiViewController.messagesCollectionView.scrollToLastItem(animated: self.initialized)
self.initialized = true
}
}
private func isLastSectionVisible(_ uiViewController: MessagesViewController) -> Bool {
guard !$client.messages.isEmpty else { return false }
let lastIndexPath = IndexPath(item: 0, section: $client.messages.count - 1)
return uiViewController.messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
}
}
extension MessagesView.Coordinator: MessagesDataSource {
func currentSender() -> SenderType {
return client.currentUser
}
func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
return client.messages[indexPath.section]
}
func numberOfSections(in _: MessagesCollectionView) -> Int {
return client.messages.count
}
func messageTopLabelAttributedText(for message: MessageType, at _: IndexPath) -> NSAttributedString? {
let name = message.sender.displayName
let font = UIFont.preferredFont(forTextStyle: .caption1)
return NSAttributedString(string: name,
attributes: [NSAttributedString.Key.font: font])
}
func messageBottomLabelAttributedText(for message: MessageType, at _: IndexPath) -> NSAttributedString? {
let dateString = formatter.string(from: message.sentDate)
let font = UIFont.preferredFont(forTextStyle: .caption2)
return NSAttributedString(string: dateString,
attributes: [NSAttributedString.Key.font: font])
}
func messageTimestampLabelAttributedText(for message: MessageType, at _: IndexPath) -> NSAttributedString? {
let sentDate = message.sentDate
let sentDateString = MessageKitDateFormatter.shared.string(from: sentDate)
let timeLabelFont: UIFont = .boldSystemFont(ofSize: 10)
let timeLabelColor: UIColor = .systemGray
return NSAttributedString(string: sentDateString,
attributes: [NSAttributedString.Key.font: timeLabelFont,
NSAttributedString.Key.foregroundColor: timeLabelColor])
}
}
extension MessagesView.Coordinator: InputBarAccessoryViewDelegate {
func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith _: String) {
let text = inputBar.inputTextView.text ?? ""
inputBar.inputTextView.text = String()
inputBar.invalidatePlugins()
inputBar.sendButton.startAnimating()
inputBar.inputTextView.placeholder = "Sending"
DispatchQueue.global(qos: .default).async {
self.client.session?.sendAsync(text).catch { error in
let viewController = inputBar.superview?.window?.rootViewController
let alert = UIAlertController(title: "Error",
message: error.localizedDescription,
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
viewController?.present(alert, animated: true, completion: nil)
}.finally {
inputBar.sendButton.stopAnimating()
inputBar.inputTextView.placeholder = "Message"
}
}
}
}
extension MessagesView.Coordinator: MessagesLayoutDelegate, MessagesDisplayDelegate {
func configureAvatarView(_ avatarView: AvatarView,
for message: MessageType,
at _: IndexPath,
in _: MessagesCollectionView)
{
let name = message.sender.displayName
let avatar = Avatar(image: nil, initials: "\(name.first ?? "A")")
avatarView.set(avatar: avatar)
}
func backgroundColor(for message: MessageType, at _: IndexPath, in view: MessagesCollectionView) -> UIColor {
let lightMode = view.traitCollection.userInterfaceStyle == .light
let secondaryColor: UIColor = lightMode ? .secondaryLight : .secondaryDark
return isFromCurrentSender(message: message) ? .primaryColor : secondaryColor
}
func messageStyle(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
let tail: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft
return .bubbleTail(tail, .curved)
}
func cellTopLabelHeight(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> CGFloat {
return 18
}
func cellBottomLabelHeight(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> CGFloat {
return 17
}
func messageTopLabelHeight(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> CGFloat {
return 20
}
func messageBottomLabelHeight(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> CGFloat {
return 16
}
}
extension UIColor {
static let primaryColor = UIColor(red: 0.27, green: 0.50, blue: 0.82, alpha: 1.0)
static let secondaryLight = UIColor(red: 230 / 255,
green: 230 / 255,
blue: 230 / 255,
alpha: 1)
static let secondaryDark = UIColor(red: 38 / 255,
green: 37 / 255,
blue: 41 / 255,
alpha: 1)
}
| 23be5132ac84be7e308f8d69661cc08b | 41.917241 | 120 | 0.62028 | false | false | false | false |
rudkx/swift | refs/heads/main | test/Constraints/result_builder_pairwise_build_block.swift | apache-2.0 | 1 | // RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-pairwise-build-block) | %FileCheck %s
// REQUIRES: executable_test
// TODO: This test is for the old method name `buildBlock(combining:into:)`. Delete this file once
// clients have moved to `buildPartialBlock`.
struct Values<T> {
var values: T
init(values: T) {
self.values = values
}
func map<R>(_ f: (T) -> R) -> Values<R> {
.init(values: f(values))
}
}
@resultBuilder
enum NestedTupleBuilder {
static func buildBlock<T>(_ x: T) -> Values<T> {
.init(values: x)
}
static func buildBlock<T, U>(
combining next: U, into combined: Values<T>
) -> Values<(T, U)> {
.init(values: (combined.values, next))
}
}
extension Values {
init(@NestedTupleBuilder nested values: () -> Self) {
self = values()
}
}
let nestedValues = Values(nested: {
1
"2"
3.0
"yes"
})
print(nestedValues)
// CHECK: Values<(((Int, String), Double), String)>(values: (((1, "2"), 3.0), "yes"))
@resultBuilder
enum FlatTupleBuilder {
static func buildExpression<T>(_ x: T) -> Values<T> {
.init(values: x)
}
static func buildBlock<T>(_ x: Values<T>) -> Values<T> {
.init(values: x.values)
}
static func buildBlock<T, N>(
combining new: Values<N>,
into combined: Values<T>
) -> Values<(T, N)> {
.init(values: (combined.values, new.values))
}
static func buildBlock<T0, T1, N>(
combining new: Values<N>,
into combined: Values<(T0, T1)>
) -> Values<(T0, T1, N)> {
.init(values: (combined.values.0, combined.values.1, new.values))
}
static func buildBlock<T0, T1, T2, N>(
combining new: Values<N>,
into combined: Values<(T0, T1, T2)>
) -> Values<(T0, T1, T2, N)> {
.init(values: (combined.values.0, combined.values.1, combined.values.2, new.values))
}
static func buildBlock<T0, T1, T2, T3, N>(
combining new: Values<N>,
into combined: Values<(T0, T1, T2, T3)>
) -> Values<(T0, T1, T2, T3, N)> {
.init(values: (combined.values.0, combined.values.1, combined.values.2, combined.values.3, new.values))
}
static func buildBlock(_ x: Never...) -> Values<()> {
assert(x.isEmpty, "I should never be called unless it's nullary")
return .init(values: ())
}
static func buildEither<T>(first: T) -> T {
first
}
static func buildEither<T>(second: T) -> T {
second
}
static func buildOptional<T>(_ x: Values<T>?) -> Values<T?> {
x?.map { $0 } ?? .init(values: nil)
}
static func buildLimitedAvailability<T>(_ x: Values<T>) -> Values<T> {
x
}
}
extension Values {
init(@FlatTupleBuilder flat values: () -> Self) {
self = values()
}
}
let flatValues0 = Values(flat: {})
print(flatValues0)
// CHECK: Values<()>(values: ())
let flatValues1 = Values(flat: {
1
"2"
3.0
})
print(flatValues1)
// CHECK: Values<(Int, String, Double)>(values: (1, "2", 3.0))
let flatValues2 = Values(flat: {
1
"2"
let y = 3.0 + 4.0
#if false
"not gonna happen"
#endif
if true {
"yes"
} else {
"no"
}
#warning("Beware of pairwise block building")
#if true
if false {
"nah"
}
if #available(*) {
5.0
}
#endif
})
print(flatValues2)
// CHECK: Values<(Int, String, String, Optional<String>, Optional<Double>)>(values: (1, "2", "yes", nil, Optional(5.0)))
struct Nil: CustomStringConvertible {
var description: String {
"nil"
}
}
struct Cons<Head, Tail>: CustomStringConvertible {
var head: Head
var tail: Tail
var description: String {
"(cons \(String(reflecting: head)) \(tail))"
}
}
@resultBuilder
enum ListBuilder {
static func buildBlock() -> Nil {
Nil()
}
static func buildBlock<T>(_ x: T) -> Cons<T, Nil> {
.init(head: x, tail: Nil())
}
static func buildBlock<New, T>(combining new: New, into combined: T) -> Cons<New, T> {
.init(head: new, tail: combined)
}
static func buildBlock<T>(_ x: T...) -> [T] {
fatalError("I should never be called!")
}
}
func list<T>(@ListBuilder f: () -> T) -> T {
f()
}
let list0 = list {}
print(list0)
// CHECK: nil
let list1 = list { "1" }
print(list1)
// Check: (cons 1 nil)
let list2 = list {
1
2
}
print(list2)
// CHECK: (cons 2 (cons 1 nil))
let list3 = list {
1
list {
2.0
"3"
}
"4"
}
print(list3)
// CHECK: (cons "4" (cons (cons "3" (cons 2.0 nil)) (cons 1 nil)))
| 653139d1e5463337d7597553c5d51919 | 19.5 | 120 | 0.600092 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Services/LikeUserHelpers.swift | gpl-2.0 | 1 | import Foundation
/// Helper class for creating LikeUser objects.
/// Used by PostService and CommentService when fetching likes for posts/comments.
///
@objc class LikeUserHelper: NSObject {
@objc class func createOrUpdateFrom(remoteUser: RemoteLikeUser, context: NSManagedObjectContext) -> LikeUser {
let liker = likeUser(for: remoteUser, context: context) ?? LikeUser(context: context)
liker.userID = remoteUser.userID.int64Value
liker.username = remoteUser.username
liker.displayName = remoteUser.displayName
liker.primaryBlogID = remoteUser.primaryBlogID?.int64Value ?? 0
liker.avatarUrl = remoteUser.avatarURL
liker.bio = remoteUser.bio ?? ""
liker.dateLikedString = remoteUser.dateLiked ?? ""
liker.dateLiked = DateUtils.date(fromISOString: liker.dateLikedString)
liker.likedSiteID = remoteUser.likedSiteID?.int64Value ?? 0
liker.likedPostID = remoteUser.likedPostID?.int64Value ?? 0
liker.likedCommentID = remoteUser.likedCommentID?.int64Value ?? 0
liker.preferredBlog = createPreferredBlogFrom(remotePreferredBlog: remoteUser.preferredBlog, forUser: liker, context: context)
liker.dateFetched = Date()
return liker
}
class func likeUser(for remoteUser: RemoteLikeUser, context: NSManagedObjectContext) -> LikeUser? {
let userID = remoteUser.userID ?? 0
let siteID = remoteUser.likedSiteID ?? 0
let postID = remoteUser.likedPostID ?? 0
let commentID = remoteUser.likedCommentID ?? 0
let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser>
request.predicate = NSPredicate(format: "userID = %@ AND likedSiteID = %@ AND likedPostID = %@ AND likedCommentID = %@",
userID, siteID, postID, commentID)
return try? context.fetch(request).first
}
private class func createPreferredBlogFrom(remotePreferredBlog: RemoteLikeUserPreferredBlog?,
forUser user: LikeUser,
context: NSManagedObjectContext) -> LikeUserPreferredBlog? {
guard let remotePreferredBlog = remotePreferredBlog,
let preferredBlog = user.preferredBlog ?? NSEntityDescription.insertNewObject(forEntityName: "LikeUserPreferredBlog", into: context) as? LikeUserPreferredBlog else {
return nil
}
preferredBlog.blogUrl = remotePreferredBlog.blogUrl
preferredBlog.blogName = remotePreferredBlog.blogName
preferredBlog.iconUrl = remotePreferredBlog.iconUrl
preferredBlog.blogID = remotePreferredBlog.blogID?.int64Value ?? 0
preferredBlog.user = user
return preferredBlog
}
class func purgeStaleLikes() {
let derivedContext = ContextManager.shared.newDerivedContext()
derivedContext.perform {
purgeStaleLikes(fromContext: derivedContext)
ContextManager.shared.save(derivedContext)
}
}
// Delete all LikeUsers that were last fetched at least 7 days ago.
private class func purgeStaleLikes(fromContext context: NSManagedObjectContext) {
guard let staleDate = Calendar.current.date(byAdding: .day, value: -7, to: Date()) else {
DDLogError("Error creating date to purge stale Likes.")
return
}
let request = LikeUser.fetchRequest() as NSFetchRequest<LikeUser>
request.predicate = NSPredicate(format: "dateFetched <= %@", staleDate as CVarArg)
do {
let users = try context.fetch(request)
users.forEach { context.delete($0) }
} catch {
DDLogError("Error fetching Like Users: \(error)")
}
}
}
| 37e7ccd78cc48ac3c69daf2de5345050 | 43.619048 | 179 | 0.673426 | false | false | false | false |
anicolaspp/rate-my-meetings-ios | refs/heads/master | RateMyMeetings/NewTeamViewController.swift | mit | 1 | //
// NewTeamViewController.swift
// RateMyMeetings
//
// Created by Nicolas Perez on 11/23/15.
// Copyright © 2015 Nicolas Perez. All rights reserved.
//
import UIKit
class NewTeamViewController: UIViewController {
let teamRepository: ICompanyRepository? = nil
var user: User?
@IBOutlet weak var domainLabel: UILabel!
@IBOutlet weak var ownerLabel: UILabel!
@IBOutlet weak var teamNameField: UITextField!
var delegate: TeamDelegate?
override func viewDidLoad() {
super.viewDidLoad()
ownerLabel.text = user?.email
domainLabel.text = user?.email!.componentsSeparatedByString("@")[1]
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func createNewTeamButton(sender: AnyObject) {
// Register user
// Create new team and login
let team = teamRepository!.team(teamNameField.text!, shouldBeCreateWithOwner: self.user!)
self.delegate?.didCreateTeam(team)
// Return control to login page to login
// let newUser = userRepository?.register("company", email: "email", password: "password")
// let newTeam = teamRepository?.team("teamName", shouldBeCreateWithOwner: newUser!)
// Use Delegate to return control
}
}
extension NewTeamViewController : UITextFieldDelegate {
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if (string.containsString("@")) {
return false
}
if (textField.text!.characters.count + string.characters.count > 25) {
return false
}
return true
}
}
| 1d2f312c4f599041b2d62a6dc9cfa076 | 27.555556 | 132 | 0.640078 | false | false | false | false |
AfricanSwift/TUIKit | refs/heads/master | TUIKit/Source/Ansi/Ansi+Window.swift | mit | 1 | //
// File: Ansi+Window.swift
// Created by: African Swift
import Darwin
// MARK: -
// MARK: Window manipulation (from dtterm, as well as extensions) -
public extension Ansi
{
/// Window manipulation (from dtterm, as well as extensions).
public enum Window
{
/// Move window to x,y
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - returns: Ansi
public static func move(x: Int, y: Int) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)3;\(x);\(y)t")
}
/// Resize window to pixel: height/width
///
/// - parameters:
/// - width: Int
/// - height: Int
/// - returns: Ansi
public static func resize(width: Int, height: Int) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)4;\(height);\(width)t")
}
/// Resize text area to character: width/height
///
/// - parameters:
/// - width: Int
/// - height: Int
/// - returns: Ansi
public static func resizeTextArea(width: Int, height: Int) -> Ansi
{
return Ansi("\(Ansi.C1.CSI)8;\(height);\(width)t")
}
/// De-iconify window
///
/// - returns: Ansi
public static func deIconify() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)1t")
}
/// Iconify window
///
/// - returns: Ansi
public static func iconify() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)2t")
}
/// Raise window to front of stacking order
///
/// - returns: Ansi
public static func raise() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)5t")
}
/// Lower window to bottom of stacking order
///
/// - returns: Ansi
public static func lower() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)6t")
}
/// Refresh the xterm window
///
/// - returns: Ansi
public static func refresh() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)7t")
}
/// Restore maximized window
///
/// - returns: Ansi
public static func restore() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)9;0t")
}
/// Maximize window
///
/// - returns: Ansi
public static func maximize() -> Ansi
{
return Ansi("\(Ansi.C1.CSI)9;1t")
}
}
}
// MARK: -
// MARK: Window Report -
public extension Ansi.Window
{
/// Window Reports: state, position, pixelSize, ...
public enum Report
{
/// __State__
///
/// - **open**: window is open (non-iconified)
/// - **iconified**: window is iconified
/// - **indeterminate**: unknown state
public enum State
{
case open, iconified, indeterminate
}
private static let stateCommand = Ansi.Terminal.Command(
request: Ansi("\(Ansi.C1.CSI)11t"),
response: "\u{1B}[#t")
/// Report xterm window state
/// - If window is open (non-iconified), it returns CSI 1 t .
/// - If window is iconified, it returns CSI 2 t
///
/// - returns: Ansi.Window.Report.State
public static func state() -> State
{
guard let response = Ansi.Terminal.responseTTY(command: stateCommand)
else { return .indeterminate }
let value = response
.replacingOccurrences(of: Ansi.C1.CSI, with: "")
.replacingOccurrences(of: "t", with: "")
switch value
{
case "1":
return State.open
case "2":
return State.iconified
default:
return State.indeterminate
}
}
private static let positionCommand = Ansi.Terminal.Command(
request: Ansi("\(Ansi.C1.CSI)13t"),
response: "\u{1B}[3;#;#t")
/// Report window position
/// Result is CSI 3 ; x ; y t
///
/// - returns: TUIVec2?
public static func position() -> TUIVec2?
{
guard let response = Ansi.Terminal.responseTTY(command: positionCommand)
else { return nil }
let values = response
.replacingOccurrences(of: Ansi.C1.CSI, with: "")
.replacingOccurrences(of: "t", with: "")
.characters.split(separator: ";").map {String($0)}
return TUIVec2(x: Int(values[1]) ?? 0, y: Int(values[2]) ?? 0)
}
private static let pixelSizeCommand = Ansi.Terminal.Command(
request: Ansi("\(Ansi.C1.CSI)14t"),
response: "\u{1B}[4;#;#t")
/// Report window in pixels
/// Result is CSI 4 ; height ; width t
///
/// - returns: TUISize?
public static func pixelSize() -> TUISize?
{
guard let response = Ansi.Terminal.responseTTY(command: pixelSizeCommand)
else { return nil }
let values = response
.replacingOccurrences(of: Ansi.C1.CSI, with: "")
.replacingOccurrences(of: "t", with: "")
.characters.split(separator: ";").map {String($0)}
return TUISize(width: Int(values[2]) ?? 0, height: Int(values[1]) ?? 0)
}
private static let characterTextAreaSizeCommand = Ansi.Terminal.Command(
request: Ansi("\(Ansi.C1.CSI)18t"),
response: "\u{1B}[8;#;#t")
// Report the size of the text area in characters.
/// Result is CSI 8 ; height ; width t
///
/// - returns: TUISIze?
public static func characterTextAreaSize() -> TUISize?
{
guard let response = Ansi.Terminal.responseTTY(command: characterTextAreaSizeCommand)
else { return nil }
let values = response
.replacingOccurrences(of: Ansi.C1.CSI, with: "")
.replacingOccurrences(of: "t", with: "")
.characters.split(separator: ";").map {String($0)}
return TUISize(width: Int(values[2]) ?? 0, height: Int(values[1]) ?? 0)
}
private static let characterScreenSizeCommand = Ansi.Terminal.Command(
request: Ansi("\(Ansi.C1.CSI)19t"),
response: "\u{1B}[9;#;#t")
// Report screen size in characters
/// Result is CSI 9 ; height ; width t
///
/// - returns: TUISize?
public static func characterScreenSize() -> TUISize?
{
guard let response = Ansi.Terminal.responseTTY(command: characterScreenSizeCommand)
else { return nil }
let values = response
.replacingOccurrences(of: Ansi.C1.CSI, with: "")
.replacingOccurrences(of: "t", with: "")
.characters.split(separator: ";").map {String($0)}
return TUISize(width: Int(values[2]) ?? 0, height: Int(values[1]) ?? 0)
}
}
}
// MARK: -
// MARK: Operating System Controls -
public extension Ansi.Window
{
public enum OSC
{
/// Change Icon Name and Window Title
///
/// - parameters:
/// - name: String
/// - returns: Ansi
public static func iconNameAndTitle(name: String) -> Ansi
{
return Ansi("\(Ansi.C1.OSC)0;\(name)\(Ansi.C0.BEL)")
}
/// Change Icon Name
///
/// - parameters:
/// - name: String
/// - returns: Ansi
public static func iconName(name: String) -> Ansi
{
return Ansi("\(Ansi.C1.OSC)1;\(name)\(Ansi.C0.BEL)")
}
/// Change Window Title
///
/// - parameters:
/// - title: String
/// - returns: Ansi
public static func windowTitle(title: String) -> Ansi
{
return Ansi("\(Ansi.C1.OSC)2;\(title)\(Ansi.C0.BEL)")
}
}
}
| c0c491ee1415ee80c3e6a848be2340a2 | 26.307985 | 91 | 0.559176 | false | false | false | false |
FotiosTragopoulos/Core-Geometry | refs/heads/master | Core Geometry/Tri1ViewLine.swift | apache-2.0 | 1 | //
// Tri1ViewLine.swift
// Core Geometry
//
// Created by Fotios Tragopoulos on 14/01/2017.
// Copyright © 2017 Fotios Tragopoulos. All rights reserved.
//
import UIKit
class Tri1ViewLine: UIView {
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let myShadowOffset = CGSize (width: 10, height: 10)
context?.setShadow (offset: myShadowOffset, blur: 8)
context?.saveGState()
context?.setLineWidth(3.0)
context?.setStrokeColor(UIColor.red.cgColor)
let xView = viewWithTag(13)?.alignmentRect(forFrame: rect).midX
let yView = viewWithTag(13)?.alignmentRect(forFrame: rect).midY
let width = self.viewWithTag(13)?.frame.size.width
let height = self.viewWithTag(13)?.frame.size.height
let size = CGSize(width: width! * 0.6, height: height! * 0.4)
let linePlacementX = CGFloat(size.width/2)
let linePlacementY = CGFloat(size.height/2)
context?.move(to: CGPoint(x: (xView! - linePlacementX + 30), y: (yView! - linePlacementY)))
context?.addLine(to: CGPoint(x: (xView! - linePlacementX + 30), y: (yView! + linePlacementY)))
let dashArray:[CGFloat] = [10, 4]
context?.setLineDash(phase: 3, lengths: dashArray)
context?.strokePath()
context?.restoreGState()
self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil)
}
}
| 1220376de4113dd37260d5cd2738e0ba | 37.133333 | 219 | 0.634033 | false | false | false | false |
CaseyApps/HackingWithSwift | refs/heads/master | project36/Project36/GameScene.swift | unlicense | 24 | //
// GameScene.swift
// Project36
//
// Created by Hudzilla on 19/09/2015.
// Copyright (c) 2015 Paul Hudson. All rights reserved.
//
import GameplayKit
import SpriteKit
enum GameState {
case ShowingLogo
case Playing
case Dead
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var player: SKSpriteNode!
var scoreLabel: SKLabelNode!
var backgroundMusic: SKAudioNode!
var logo: SKSpriteNode!
var gameOver: SKSpriteNode!
var gameState = GameState.ShowingLogo
var score = 0 {
didSet {
scoreLabel.text = "SCORE: \(score)"
}
}
override func didMoveToView(view: SKView) {
createPlayer()
createSky()
createBackground()
createGround()
createScore()
createLogos()
physicsWorld.gravity = CGVectorMake(0.0, -5.0)
physicsWorld.contactDelegate = self
backgroundMusic = SKAudioNode(fileNamed: "music.m4a")
addChild(backgroundMusic)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
switch gameState {
case .ShowingLogo:
gameState = .Playing
let fadeOut = SKAction.fadeOutWithDuration(0.5)
let remove = SKAction.removeFromParent()
let wait = SKAction.waitForDuration(0.5)
let activatePlayer = SKAction.runBlock { [unowned self] in
self.player.physicsBody?.dynamic = true
self.initRocks()
}
let sequence = SKAction.sequence([fadeOut, wait, activatePlayer, remove])
logo.runAction(sequence)
case .Playing:
player.physicsBody?.velocity = CGVectorMake(0, 0)
player.physicsBody?.applyImpulse(CGVectorMake(0, 20))
case .Dead:
let scene = GameScene(fileNamed: "GameScene")!
scene.scaleMode = .ResizeFill
let transition = SKTransition.moveInWithDirection(SKTransitionDirection.Right, duration: 1)
self.view?.presentScene(scene, transition: transition)
}
}
override func update(currentTime: CFTimeInterval) {
guard player != nil else { return }
let value = player.physicsBody!.velocity.dy * 0.001
let rotate = SKAction.rotateToAngle(value, duration: 0.1)
player.runAction(rotate)
}
func createPlayer() {
let playerTexture = SKTexture(imageNamed: "player-1")
player = SKSpriteNode(texture: playerTexture)
player.zPosition = 10
player.position = CGPoint(x: frame.width / 6, y: frame.height * 0.75)
addChild(player)
player.physicsBody = SKPhysicsBody(texture: playerTexture, size: playerTexture.size())
player.physicsBody!.contactTestBitMask = player.physicsBody!.collisionBitMask
player.physicsBody?.dynamic = false
player.physicsBody?.collisionBitMask = 0
let frame2 = SKTexture(imageNamed: "player-2")
let frame3 = SKTexture(imageNamed: "player-3")
let animation = SKAction.animateWithTextures([playerTexture, frame2, frame3, frame2], timePerFrame: 0.01)
let runForever = SKAction.repeatActionForever(animation)
player.runAction(runForever)
}
func createSky() {
let topSky = SKSpriteNode(color: UIColor(hue: 0.55, saturation: 0.14, brightness: 0.97, alpha: 1), size: CGSize(width: frame.width, height: frame.height * 0.67))
topSky.anchorPoint = CGPoint(x: 0.5, y: 1)
let bottomSky = SKSpriteNode(color: UIColor(hue: 0.55, saturation: 0.16, brightness: 0.96, alpha: 1), size: CGSize(width: frame.width, height: frame.height * 0.33))
topSky.anchorPoint = CGPoint(x: 0.5, y: 1)
topSky.position = CGPoint(x: CGRectGetMidX(frame), y: frame.size.height)
bottomSky.position = CGPoint(x: CGRectGetMidX(frame), y: bottomSky.frame.height / 2)
addChild(topSky)
addChild(bottomSky)
bottomSky.zPosition = -40
topSky.zPosition = -40
}
func createBackground() {
let backgroundTexture = SKTexture(imageNamed: "background")
for i in 0 ... 1 {
let background = SKSpriteNode(texture: backgroundTexture)
background.zPosition = -30
background.anchorPoint = CGPointZero
background.position = CGPoint(x: (backgroundTexture.size().width * CGFloat(i)) - CGFloat(1 * i), y: 100)
let moveLeft = SKAction.moveByX(-backgroundTexture.size().width, y: 0, duration: 20)
let moveReset = SKAction.moveByX(backgroundTexture.size().width, y: 0, duration: 0)
let moveLoop = SKAction.sequence([moveLeft, moveReset])
let moveForever = SKAction.repeatActionForever(moveLoop)
background.runAction(moveForever)
addChild(background)
}
}
func createGround() {
let groundTexture = SKTexture(imageNamed: "ground")
for i in 0 ... 1 {
let ground = SKSpriteNode(texture: groundTexture)
ground.zPosition = -10
ground.position = CGPoint(x: (groundTexture.size().width / 2.0 + (groundTexture.size().width * CGFloat(i))), y: groundTexture.size().height / 2)
ground.physicsBody = SKPhysicsBody(texture: ground.texture!, size: ground.texture!.size())
ground.physicsBody?.dynamic = false
addChild(ground)
let moveLeft = SKAction.moveByX(-groundTexture.size().width, y: 0, duration: 5)
let moveReset = SKAction.moveByX(groundTexture.size().width, y: 0, duration: 0)
let moveLoop = SKAction.sequence([moveLeft, moveReset])
let moveForever = SKAction.repeatActionForever(moveLoop)
ground.runAction(moveForever)
}
}
func createRocks() {
// 1
let rockTexture = SKTexture(imageNamed: "rock")
let topRock = SKSpriteNode(texture: rockTexture)
topRock.physicsBody = SKPhysicsBody(texture: rockTexture, size: rockTexture.size())
topRock.physicsBody?.dynamic = false
topRock.zRotation = CGFloat(M_PI)
topRock.xScale = -1.0
let bottomRock = SKSpriteNode(texture: rockTexture)
bottomRock.physicsBody = SKPhysicsBody(texture: rockTexture, size: rockTexture.size())
bottomRock.physicsBody?.dynamic = false
topRock.zPosition = -20
bottomRock.zPosition = -20
// 2
let rockCollision = SKSpriteNode(color: UIColor.clearColor(), size: CGSize(width: 32, height: frame.height))
rockCollision.physicsBody = SKPhysicsBody(rectangleOfSize: rockCollision.size)
rockCollision.physicsBody?.dynamic = false
rockCollision.name = "scoreDetect"
addChild(topRock)
addChild(bottomRock)
addChild(rockCollision)
// 3
let xPosition = frame.width + topRock.frame.width
let max = Int(frame.height / 3)
let rand = GKRandomDistribution(lowestValue: -100, highestValue: max)
let yPosition = CGFloat(rand.nextInt())
// this next value affects the width of the gap between rocks
// make it smaller to make your game harder – if you're feeling evil!
let rockDistance: CGFloat = 70
// 4
topRock.position = CGPoint(x: xPosition, y: yPosition + topRock.size.height + rockDistance)
bottomRock.position = CGPoint(x: xPosition, y: yPosition - rockDistance)
rockCollision.position = CGPoint(x: xPosition + (rockCollision.size.width * 2), y: CGRectGetMidY(frame))
let endPosition = frame.width + (topRock.frame.width * 2)
let moveAction = SKAction.moveByX(-endPosition, y: 0, duration: 5.8)
let moveSequence = SKAction.sequence([moveAction, SKAction.removeFromParent()])
topRock.runAction(moveSequence)
bottomRock.runAction(moveSequence)
rockCollision.runAction(moveSequence)
}
func initRocks() {
let create = SKAction.runBlock { [unowned self] in
self.createRocks()
}
let wait = SKAction.waitForDuration(3)
let sequence = SKAction.sequence([create, wait])
let repeatForever = SKAction.repeatActionForever(sequence)
runAction(repeatForever)
}
func createScore() {
scoreLabel = SKLabelNode(fontNamed: "Optima-ExtraBlack")
scoreLabel.fontSize = 24
scoreLabel.position = CGPointMake(CGRectGetMaxX(frame) - 20, CGRectGetMaxY(frame) - 40)
scoreLabel.horizontalAlignmentMode = .Right
scoreLabel.text = "SCORE: 0"
scoreLabel.fontColor = UIColor.blackColor()
addChild(scoreLabel)
}
func createLogos() {
logo = SKSpriteNode(imageNamed: "logo")
logo.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
addChild(logo)
gameOver = SKSpriteNode(imageNamed: "gameover")
gameOver.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame))
gameOver.alpha = 0
addChild(gameOver)
}
func didBeginContact(contact: SKPhysicsContact) {
if contact.bodyA.node?.name == "scoreDetect" || contact.bodyB.node?.name == "scoreDetect" {
if contact.bodyA.node == player {
contact.bodyB.node?.removeFromParent()
} else {
contact.bodyA.node?.removeFromParent()
}
let sound = SKAction.playSoundFileNamed("coin.wav", waitForCompletion: false)
runAction(sound)
++score
return
}
if contact.bodyA.node == player || contact.bodyB.node == player {
if let explosion = SKEmitterNode(fileNamed: "PlayerExplosion.sks") {
explosion.position = player.position
addChild(explosion)
}
let sound = SKAction.playSoundFileNamed("explosion.wav", waitForCompletion: false)
runAction(sound)
gameOver.alpha = 1
gameState = .Dead
backgroundMusic.runAction(SKAction.stop())
player.removeFromParent()
speed = 0
}
}
} | eaa5638260ad5246a28946f5302ba05f | 29.358621 | 166 | 0.728842 | false | false | false | false |
SuEric/SVU_iOS | refs/heads/master | SVU/AlumnoViewController.swift | gpl-3.0 | 1 | //
// ViewController.swift
// SVU
//
// Created by Eric García on 12/10/15.
// Copyright © 2015 Eric García. All rights reserved.
//
import UIKit
class AlumnoViewController: UIViewController {
@IBOutlet weak var matricula: UITextField!
@IBOutlet weak var password: UITextField!
var firstLaunch : Bool!
var registered : Bool!
override func viewDidLoad() {
super.viewDidLoad()
/*
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "Registered")
*/
firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
registered = NSUserDefaults.standardUserDefaults().boolForKey("Registered")
if firstLaunch == false && registered == true {
print("Ya está registrado y no es primera vez que arranca");
self.performSegueWithIdentifier("ingreso_alumno", sender: self)
}
else {
print("Registrate")
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "FirstLaunch")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registroButtonClicked(sender: AnyObject) {
let str_matricula = matricula.text
let str_password = password.text
print("Matrícula: \(str_matricula), Contraseña: \(str_password)")
if str_matricula?.isEmpty == false && str_password?.isEmpty == false {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "Registered")
self.performSegueWithIdentifier("ingreso_alumno", sender: self)
let alert = UIAlertController(title: "Registro exitoso", message: "Usuario registrado correctamente", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cerrar", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
else {
let alert = UIAlertController(title: "Faltan campos", message: "Favor de ingresar más campos", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cerrar", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "ingreso_alumno" {
if firstLaunch == false && registered == true {
return true
}
}
return false
}
}
| f238fd56ae0c700d4e5c4caddfec19cd | 36.302632 | 159 | 0.64515 | false | false | false | false |
apple/swift-nio | refs/heads/main | Sources/NIOCore/BSDSocketAPI.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(Windows)
import ucrt
import let WinSDK.IPPROTO_IP
import let WinSDK.IPPROTO_IPV6
import let WinSDK.IPPROTO_TCP
import let WinSDK.IP_ADD_MEMBERSHIP
import let WinSDK.IP_DROP_MEMBERSHIP
import let WinSDK.IP_MULTICAST_IF
import let WinSDK.IP_MULTICAST_LOOP
import let WinSDK.IP_MULTICAST_TTL
import let WinSDK.IPV6_JOIN_GROUP
import let WinSDK.IPV6_LEAVE_GROUP
import let WinSDK.IPV6_MULTICAST_HOPS
import let WinSDK.IPV6_MULTICAST_IF
import let WinSDK.IPV6_MULTICAST_LOOP
import let WinSDK.IPV6_V6ONLY
import let WinSDK.AF_INET
import let WinSDK.AF_INET6
import let WinSDK.AF_UNIX
import let WinSDK.PF_INET
import let WinSDK.PF_INET6
import let WinSDK.PF_UNIX
import let WinSDK.SO_ERROR
import let WinSDK.SO_KEEPALIVE
import let WinSDK.SO_LINGER
import let WinSDK.SO_RCVBUF
import let WinSDK.SO_RCVTIMEO
import let WinSDK.SO_REUSEADDR
import let WinSDK.SOL_SOCKET
import let WinSDK.TCP_NODELAY
import struct WinSDK.SOCKET
import func WinSDK.inet_ntop
import func WinSDK.inet_pton
import func WinSDK.GetLastError
import func WinSDK.WSAGetLastError
internal typealias socklen_t = ucrt.size_t
#elseif os(Linux) || os(Android)
import Glibc
import CNIOLinux
private let sysInet_ntop: @convention(c) (CInt, UnsafeRawPointer?, UnsafeMutablePointer<CChar>?, socklen_t) -> UnsafePointer<CChar>? = inet_ntop
private let sysInet_pton: @convention(c) (CInt, UnsafePointer<CChar>?, UnsafeMutableRawPointer?) -> CInt = inet_pton
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
private let sysInet_ntop: @convention(c) (CInt, UnsafeRawPointer?, UnsafeMutablePointer<CChar>?, socklen_t) -> UnsafePointer<CChar>? = inet_ntop
private let sysInet_pton: @convention(c) (CInt, UnsafePointer<CChar>?, UnsafeMutableRawPointer?) -> CInt = inet_pton
#endif
#if os(Android)
let IFF_BROADCAST: CUnsignedInt = numericCast(SwiftGlibc.IFF_BROADCAST.rawValue)
let IFF_POINTOPOINT: CUnsignedInt = numericCast(SwiftGlibc.IFF_POINTOPOINT.rawValue)
let IFF_MULTICAST: CUnsignedInt = numericCast(SwiftGlibc.IFF_MULTICAST.rawValue)
#if arch(arm)
let SO_RCVTIMEO = SO_RCVTIMEO_OLD
let SO_TIMESTAMP = SO_TIMESTAMP_OLD
#endif
#elseif os(Linux)
// Work around SO_TIMESTAMP/SO_RCVTIMEO being awkwardly defined in glibc.
let SO_TIMESTAMP = CNIOLinux_SO_TIMESTAMP
let SO_RCVTIMEO = CNIOLinux_SO_RCVTIMEO
#endif
public enum NIOBSDSocket {
#if os(Windows)
public typealias Handle = SOCKET
#else
public typealias Handle = CInt
#endif
}
extension NIOBSDSocket {
/// Specifies the addressing scheme that the socket can use.
public struct AddressFamily: RawRepresentable, Sendable {
public typealias RawValue = CInt
public var rawValue: RawValue
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
}
extension NIOBSDSocket.AddressFamily: Equatable {
}
extension NIOBSDSocket.AddressFamily: Hashable {
}
extension NIOBSDSocket {
/// Specifies the type of protocol that the socket can use.
public struct ProtocolFamily: RawRepresentable, Sendable {
public typealias RawValue = CInt
public var rawValue: RawValue
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
}
extension NIOBSDSocket.ProtocolFamily: Equatable {
}
extension NIOBSDSocket.ProtocolFamily: Hashable {
}
extension NIOBSDSocket {
/// Defines socket option levels.
public struct OptionLevel: RawRepresentable, Sendable {
public typealias RawValue = CInt
public var rawValue: RawValue
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
}
extension NIOBSDSocket.OptionLevel: Equatable {
}
extension NIOBSDSocket.OptionLevel: Hashable {
}
extension NIOBSDSocket {
/// Defines configuration option names.
public struct Option: RawRepresentable, Sendable {
public typealias RawValue = CInt
public var rawValue: RawValue
public init(rawValue: RawValue) {
self.rawValue = rawValue
}
}
}
extension NIOBSDSocket.Option: Equatable {
}
extension NIOBSDSocket.Option: Hashable {
}
// Address Family
extension NIOBSDSocket.AddressFamily {
/// Address for IP version 4.
public static let inet: NIOBSDSocket.AddressFamily =
NIOBSDSocket.AddressFamily(rawValue: AF_INET)
/// Address for IP version 6.
public static let inet6: NIOBSDSocket.AddressFamily =
NIOBSDSocket.AddressFamily(rawValue: AF_INET6)
/// Unix local to host address.
public static let unix: NIOBSDSocket.AddressFamily =
NIOBSDSocket.AddressFamily(rawValue: AF_UNIX)
}
// Protocol Family
extension NIOBSDSocket.ProtocolFamily {
/// IP network 4 protocol.
public static let inet: NIOBSDSocket.ProtocolFamily =
NIOBSDSocket.ProtocolFamily(rawValue: PF_INET)
/// IP network 6 protocol.
public static let inet6: NIOBSDSocket.ProtocolFamily =
NIOBSDSocket.ProtocolFamily(rawValue: PF_INET6)
/// UNIX local to the host.
public static let unix: NIOBSDSocket.ProtocolFamily =
NIOBSDSocket.ProtocolFamily(rawValue: PF_UNIX)
}
#if !os(Windows)
extension NIOBSDSocket.ProtocolFamily {
/// UNIX local to the host, alias for `PF_UNIX` (`.unix`)
public static let local: NIOBSDSocket.ProtocolFamily =
NIOBSDSocket.ProtocolFamily(rawValue: PF_LOCAL)
}
#endif
// Option Level
extension NIOBSDSocket.OptionLevel {
/// Socket options that apply only to IP sockets.
#if os(Linux) || os(Android)
public static let ip: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: CInt(IPPROTO_IP))
#else
public static let ip: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: IPPROTO_IP)
#endif
/// Socket options that apply only to IPv6 sockets.
#if os(Linux) || os(Android)
public static let ipv6: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: CInt(IPPROTO_IPV6))
#elseif os(Windows)
public static let ipv6: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: IPPROTO_IPV6.rawValue)
#else
public static let ipv6: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: IPPROTO_IPV6)
#endif
/// Socket options that apply only to TCP sockets.
#if os(Linux) || os(Android)
public static let tcp: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: CInt(IPPROTO_TCP))
#elseif os(Windows)
public static let tcp: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: IPPROTO_TCP.rawValue)
#else
public static let tcp: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: IPPROTO_TCP)
#endif
/// Socket options that apply to MPTCP sockets.
///
/// These only work on Linux currently.
public static let mptcp = NIOBSDSocket.OptionLevel(rawValue: 284)
/// Socket options that apply to all sockets.
public static let socket: NIOBSDSocket.OptionLevel =
NIOBSDSocket.OptionLevel(rawValue: SOL_SOCKET)
}
// IPv4 Options
extension NIOBSDSocket.Option {
/// Add a multicast group membership.
public static let ip_add_membership: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IP_ADD_MEMBERSHIP)
/// Drop a multicast group membership.
public static let ip_drop_membership: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IP_DROP_MEMBERSHIP)
/// Set the interface for outgoing multicast packets.
public static let ip_multicast_if: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IP_MULTICAST_IF)
/// Control multicast loopback.
public static let ip_multicast_loop: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IP_MULTICAST_LOOP)
/// Control multicast time-to-live.
public static let ip_multicast_ttl: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IP_MULTICAST_TTL)
}
// IPv6 Options
extension NIOBSDSocket.Option {
/// Add an IPv6 group membership.
public static let ipv6_join_group: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IPV6_JOIN_GROUP)
/// Drop an IPv6 group membership.
public static let ipv6_leave_group: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IPV6_LEAVE_GROUP)
/// Specify the maximum number of router hops for an IPv6 packet.
public static let ipv6_multicast_hops: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IPV6_MULTICAST_HOPS)
/// Set the interface for outgoing multicast packets.
public static let ipv6_multicast_if: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IPV6_MULTICAST_IF)
/// Control multicast loopback.
public static let ipv6_multicast_loop: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IPV6_MULTICAST_LOOP)
/// Indicates if a socket created for the `AF_INET6` address family is
/// restricted to IPv6 only.
public static let ipv6_v6only: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: IPV6_V6ONLY)
}
// TCP Options
extension NIOBSDSocket.Option {
/// Disables the Nagle algorithm for send coalescing.
public static let tcp_nodelay: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: TCP_NODELAY)
}
#if os(Linux) || os(FreeBSD) || os(Android)
extension NIOBSDSocket.Option {
/// Get information about the TCP connection.
public static let tcp_info: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: TCP_INFO)
}
#endif
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
extension NIOBSDSocket.Option {
/// Get information about the TCP connection.
public static let tcp_connection_info: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: TCP_CONNECTION_INFO)
}
#endif
// MPTCP options
//
// These values are hardcoded as they're fairly new, and not available in all
// header files yet.
extension NIOBSDSocket.Option {
/// Get info about an MPTCP connection
public static let mptcp_info = NIOBSDSocket.Option(rawValue: 1)
}
// Socket Options
extension NIOBSDSocket.Option {
/// Get the error status and clear.
public static let so_error: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_ERROR)
/// Use keep-alives.
public static let so_keepalive: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_KEEPALIVE)
/// Linger on close if unsent data is present.
public static let so_linger: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_LINGER)
/// Specifies the total per-socket buffer space reserved for receives.
public static let so_rcvbuf: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_RCVBUF)
/// Specifies the receive timeout.
public static let so_rcvtimeo: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_RCVTIMEO)
/// Allows the socket to be bound to an address that is already in use.
public static let so_reuseaddr: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_REUSEADDR)
}
#if !os(Windows)
extension NIOBSDSocket.Option {
/// Indicate when to generate timestamps.
public static let so_timestamp: NIOBSDSocket.Option =
NIOBSDSocket.Option(rawValue: SO_TIMESTAMP)
}
#endif
extension NIOBSDSocket {
// Sadly this was defined on BSDSocket, and we need it for SocketAddress.
@inline(never)
internal static func inet_pton(addressFamily: NIOBSDSocket.AddressFamily, addressDescription: UnsafePointer<CChar>, address: UnsafeMutableRawPointer) throws {
#if os(Windows)
// TODO(compnerd) use `InetPtonW` to ensure that we handle unicode properly
switch WinSDK.inet_pton(addressFamily.rawValue, addressDescription, address) {
case 0: throw IOError(errnoCode: EINVAL, reason: "inet_pton")
case 1: return
default: throw IOError(winsock: WSAGetLastError(), reason: "inet_pton")
}
#else
switch sysInet_pton(CInt(addressFamily.rawValue), addressDescription, address) {
case 0: throw IOError(errnoCode: EINVAL, reason: #function)
case 1: return
default: throw IOError(errnoCode: errno, reason: #function)
}
#endif
}
@discardableResult
@inline(never)
internal static func inet_ntop(addressFamily: NIOBSDSocket.AddressFamily, addressBytes: UnsafeRawPointer, addressDescription: UnsafeMutablePointer<CChar>, addressDescriptionLength: socklen_t) throws -> UnsafePointer<CChar> {
#if os(Windows)
// TODO(compnerd) use `InetNtopW` to ensure that we handle unicode properly
guard let result = WinSDK.inet_ntop(addressFamily.rawValue, addressBytes,
addressDescription,
Int(addressDescriptionLength)) else {
throw IOError(windows: GetLastError(), reason: "inet_ntop")
}
return result
#else
switch sysInet_ntop(CInt(addressFamily.rawValue), addressBytes, addressDescription, addressDescriptionLength) {
case .none: throw IOError(errnoCode: errno, reason: #function)
case .some(let ptr): return ptr
}
#endif
}
}
| 79a7e842c694cefc9c4d1c74bdfa64ab | 33.325926 | 228 | 0.696806 | false | false | false | false |
ChrisXu1221/accountTest | refs/heads/master | Demo/Demo/AccountCellViewModel.swift | mit | 1 | //
// AccountCellViewModel.swift
// Demo
//
// Created by Chris Xu on 09/08/2016.
// Copyright © 2016 CXCreation. All rights reserved.
//
import UIKit
class AccountCellViewModel: ViewModeling {
private(set) var account: Account!
var didViewExpand: Bool = false
init(account: Account) {
self.account = account
}
func balanceAttributedText() -> NSAttributedString? {
if let balanceText = text(withBalance: Float(account.balance/1000), currencyCode: account.currencyCode) {
let attributedText = NSMutableAttributedString(string: balanceText)
// set up fonts
let normalFont = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium)
let smallFont = UIFont.systemFontOfSize(12, weight: UIFontWeightMedium)
attributedText.addAttributes([NSFontAttributeName: normalFont], range: NSMakeRange(0, balanceText.characters.count))
let rangeOfLastTwoDigits = NSMakeRange(balanceText.characters.count - 2, 2)
attributedText.addAttributes([NSFontAttributeName: smallFont], range: rangeOfLastTwoDigits)
// move the last two digits up
let offset = normalFont.capHeight - smallFont.capHeight
attributedText.addAttributes([NSBaselineOffsetAttributeName: offset], range: rangeOfLastTwoDigits)
return attributedText
}
return nil
}
private func text(withBalance balance: Float, currencyCode code: String) -> String? {
let formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.currencyGroupingSeparator = "."
formatter.usesGroupingSeparator = true
formatter.currencyCode = code
return formatter.stringFromNumber(balance)
}
} | 04d972a02f425836ec3813688f684f15 | 37.25 | 128 | 0.671935 | false | false | false | false |
Subsets and Splits