repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ioan-chera/DoomMakerSwift
DoomMakerSwift/Geom.swift
1
9961
/* DoomMaker Copyright (C) 2017 Ioan Chera This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation /// PI representation let π = Double.pi let πf = Float.pi enum Geom { /// Checks if a line clips a rectangle, using Cohen-Sutherland's algorithm /// https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm static func lineClipsRect(_ pp0: NSPoint, _ pp1: NSPoint, rect: NSRect) -> Bool { let inside = 0 let left = 1 let right = 2 let bottom = 4 let top = 8 func computeOutCode(_ p: NSPoint) -> Int { var code = inside if p.x < rect.minX { code |= left } else if p.x > rect.maxX { code |= right } if p.y < rect.minY { code |= bottom } else if p.y > rect.maxY { code |= top } return code } var p0 = pp0 var p1 = pp1 var outcode0 = computeOutCode(p0) var outcode1 = computeOutCode(p1) while true { if (outcode0 | outcode1) == 0 { return true } if (outcode0 & outcode1) != 0 { return false } let outcodeOut = outcode0 != 0 ? outcode0 : outcode1 let p: NSPoint if (outcodeOut & top) != 0 { p = NSPoint(x: p0.x + (p1.x - p0.x) * (rect.maxY - p0.y) / (p1.y - p0.y), y: rect.maxY) } else if (outcodeOut & bottom) != 0 { p = NSPoint(x: p0.x + (p1.x - p0.x) * (rect.minY - p0.y) / (p1.y - p0.y), y: rect.minY) } else if (outcodeOut & right) != 0 { p = NSPoint(x: rect.maxX, y: p0.y + (p1.y - p0.y) * (rect.maxX - p0.x) / (p1.x - p0.x)) } else if (outcodeOut & left) != 0 { p = NSPoint(x: rect.minX, y: p0.y + (p1.y - p0.y) * (rect.minX - p0.x) / (p1.x - p0.x)) } else { assert(false) // should never happen p = NSPoint() } if outcodeOut == outcode0 { p0 = p outcode0 = computeOutCode(p0) } else { p1 = p outcode1 = computeOutCode(p1) } } } /// /// Finds projection of point /// static func projection(point: NSPoint, linep1: NSPoint, linep2: NSPoint) -> NSPoint { let x = point.x let y = point.y let x1 = linep1.x let y1 = linep1.y let dx = linep2.x - x1 let dy = linep2.y - y1 let dxsq = dx * dx let dysq = dy * dy let deltax = -x * dxsq - x1 * dysq + (y1 - y) * dx * dy let deltay = -y * dysq - y1 * dxsq + (x1 - x) * dy * dx let delta = -dxsq - dysq if delta != 0 { return NSPoint(x: deltax / delta, y: deltay / delta) } return linep1 // if not possible, just return one point } /// /// Find intersection point /// static func intersection(p00: NSPoint, p01: NSPoint, p10: NSPoint, p11: NSPoint) -> NSPoint? { let divisor = (p00.x - p01.x) * (p10.y - p11.y) - (p00.y - p01.y) * (p10.x - p11.x) if divisor == 0 { return nil } let fact1 = p00.x * p01.y - p00.y * p01.x let fact2 = p10.x * p11.y - p10.y * p11.x let d1 = fact1 * (p10.x - p11.x) - (p00.x - p01.x) * fact2 let d2 = fact1 * (p10.y - p11.y) - (p00.y - p01.y) * fact2 return NSPoint(x: d1 / divisor, y: d2 / divisor) } } /// NSPoint addition func + (left: NSPoint, right: NSPoint) -> NSPoint { return NSPoint(x: left.x + right.x, y: left.y + right.y) } /// NSPoint-NSSize addition func + (left: NSPoint, right: NSSize) -> NSPoint { return NSPoint(x: left.x + right.width, y: left.y + right.height) } /// NSPoint subtraction func - (left: NSPoint, right: NSPoint) -> NSPoint { return NSPoint(x: left.x - right.x, y: left.y - right.y) } /// NSPoint-NSSize subtraction func - (left: NSPoint, right: NSSize) -> NSPoint { return NSPoint(x: left.x - right.width, y: left.y - right.height) } /// NSPoint-CGFloat division func / (left: NSPoint, right: CGFloat) -> NSPoint { return NSPoint(x: left.x / right, y: left.y / right) } /// NSPoint-Double division func / (left: NSPoint, right: Double) -> NSPoint { return left / CGFloat(right) } /// NSPoint-CGFloat multiplication func * (left: NSPoint, right: CGFloat) -> NSPoint { return NSPoint(x: left.x * right, y: left.y * right) } /// NSPoint-Double multiplication func * (left: NSPoint, right: Double) -> NSPoint { return left * CGFloat(right) } func * (left: NSPoint, right: NSPoint) -> CGFloat { return left.x * right.x + left.y * right.y } /// floor applied to NSPoint elements func floor(_ point: NSPoint) -> NSPoint { return NSPoint(x: floor(point.x), y: floor(point.y)) } /// ceil applied to NSPoint elements func ceil(_ point: NSPoint) -> NSPoint { return NSPoint(x: ceil(point.x), y: ceil(point.y)) } /// Distance operator infix operator <-> : MultiplicationPrecedence /// Additions to the NSPoint structure extension NSPoint { /// Applies rotation to the 2D NSPoint vector func rotated(_ degrees: Float) -> NSPoint { let rad = degrees / 180 * πf let nx = Float(x) * cos(rad) - Float(y) * sin(rad) let ny = Float(x) * sin(rad) + Float(y) * cos(rad) return NSPoint(x: CGFloat(nx), y: CGFloat(ny)) } init(item: DraggedItem) { self.init(x: Int(item.x), y: Int(item.y)) } init(x: Int16, y: Int16) { self.init(x: Int(x), y: Int(y)) } static func <-> (left: NSPoint, right: NSPoint) -> CGFloat { return sqrt(pow(left.x - right.x, 2) + pow(left.y - right.y, 2)) } func distanceToLine(point1 p1: NSPoint, point2 p2: NSPoint) -> CGFloat { // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Cartesian_coordinates return abs((p2.y - p1.y) * x - (p2.x - p1.x) * y + p2.x * p1.y - p2.y * p1.x) / (p1 <-> p2) } func distanceToSegment(point1 p1: NSPoint, point2 p2: NSPoint) -> CGFloat { if (p1 - self) * (p2 - p1) >= 0 { return self <-> p1 } if (self - p2) * (p2 - p1) >= 0 { return self <-> p2 } return distanceToLine(point1: p1, point2: p2) } func withinRoundedRect(_ rect: NSRect, radius: CGFloat) -> Bool { if x >= rect.minX && x < rect.maxX && y >= rect.minY - radius && y < rect.maxY + radius { return true } if x < rect.minX && x >= rect.minX - radius { if y >= rect.minY && y < rect.maxY { return true } if y >= rect.minY - radius && y < rect.minY { return self <-> NSPoint(x: rect.minX, y: rect.minY) <= radius } if y >= rect.maxY && y < rect.maxY + radius { return self <-> NSPoint(x: rect.minX, y: rect.maxY) <= radius } return false } if x >= rect.maxX && x < rect.maxX + radius { if y >= rect.minY && y < rect.maxY { return true } if y >= rect.minY - radius && y < rect.minY { return self <-> NSPoint(x: rect.maxX, y: rect.minY) <= radius } if y >= rect.maxY && y < rect.maxY + radius { return self <-> NSPoint(x: rect.maxX, y: rect.maxY) <= radius } return false } return false } /// Cross product's Z func drill(_ point: NSPoint) -> CGFloat { return x * point.y - point.x * y } } /// NSRect additions extension NSRect { /// Modifies this NSRect by adding the point to this as to a bounding box mutating func pointAdd(_ point: NSPoint) { if point.x > self.maxX { self.size.width = point.x - self.minX } else if point.x < self.minX { self.size.width = self.maxX - point.x self.origin.x = point.x } if point.y > self.maxY { self.size.height = point.y - self.minY } else if point.y < self.minY { self.size.height = self.maxY - point.y self.origin.y = point.y } } init(point1: NSPoint, point2: NSPoint) { self.init() self.origin = point1 self.size = NSSize() pointAdd(point2) } } infix operator /• : MultiplicationPrecedence func /• (left: CGFloat, right: CGFloat) -> CGFloat { return round(left / right) * right } func /• (left: Float, right: Float) -> Float { return round(left / right) * right } func /• (left: NSPoint, right: CGFloat) -> NSPoint { return NSPoint(x: left.x /• right, y: left.y /• right) } // // For line relative position // enum Side { case front case back init(_ value: Int) { self = value == 0 ? .front : .back } init(_ value: Bool) { self = value ? .back : .front } } prefix func ! (right: Side) -> Side { return right == .front ? .back : .front } func anglemod(_ angle: Double) -> Double { var res = angle while res < -π { res += 2 * π } while res >= π { res -= 2 * π } return res }
gpl-3.0
4608253f97504d4256cb726faf9f54ad
29.218845
103
0.532287
3.434197
false
false
false
false
victorchee/TableView
TableView/TableView/ViewController.swift
1
2941
// // ViewController.swift // TableView // // Created by qihaijun on 11/10/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class ViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Normally, a cell’s height is determined by the table view delegate’s tableView:heightForRowAtIndexPath: method. To enable self-sizing table view cells, you must set the table view’s rowHeight property to UITableViewAutomaticDimension. You must also assign a value to the estimatedRowHeight property. As soon as both of these properties are set, the system uses Auto Layout to calculate the row’s actual height. tableView.estimatedRowHeight = 44.0 // tableView.rowHeight = UITableViewAutomaticDimension let blurEffect = UIBlurEffect(style: .Dark) let vibrancyEffect = UIVibrancyEffect(forBlurEffect: blurEffect) let enableVibrancy = true if enableVibrancy { tableView.separatorEffect = vibrancyEffect } else { tableView.separatorEffect = blurEffect } } // MARK: - DataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell cell.label.text = "Cell \(indexPath.row)" cell.label.font = cell.label.font.fontWithSize(CGFloat(indexPath.row+1)*4.0) if indexPath.row % 2 == 0 { cell.contentView.backgroundColor = UIColor.lightGrayColor() } else { cell.contentView.backgroundColor = UIColor.whiteColor() } return cell } // MARK: - Delegate override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let destructiveAction = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "Destruct") { (action, indexPath) -> Void in print("Destruct \(indexPath)") } let defaultAction = UITableViewRowAction(style: .Default, title: "Default") { (action, indexPath) -> Void in print("Default \(indexPath)") } defaultAction.backgroundColor = UIColor.orangeColor() let normalAction = UITableViewRowAction(style: .Normal, title: "Normal") { (action, indexPath) -> Void in print("Normal \(indexPath)") } normalAction.backgroundEffect = UIBlurEffect(style: .Dark) return [destructiveAction, defaultAction, normalAction] } }
mit
c1146262385bd32ab90d5d8db79d164f
40.885714
422
0.671214
5.379817
false
false
false
false
VojtaStavik/ProtocolUI
ProtocolUITests/TransluentTRUEProtocolTest.swift
1
1729
// // TransluentTRUEProtocolTest.swift // ProtocolUI // // Created by STRV on 20/08/15. // Copyright © 2015 Vojta Stavik. All rights reserved. // import XCTest @testable import ProtocolUI class TransluentTRUEProtocolTest: XCTestCase { typealias CurrentTestProtocol = TransluentTRUE typealias CurrentTestValueType = Bool static let testValue : CurrentTestValueType = true func testUINavigationBar() { class TestView : UINavigationBar, CurrentTestProtocol { } let test1 = TestView() test1.applyProtocolUIAppearance() XCTAssertEqual(test1.translucent, self.dynamicType.testValue) let test2 = TestView() test2.prepareForInterfaceBuilder() XCTAssertEqual(test2.translucent, self.dynamicType.testValue) } func testUIToolbar() { class TestView : UIToolbar, CurrentTestProtocol { } let test1 = TestView() test1.applyProtocolUIAppearance() XCTAssertEqual(test1.translucent, self.dynamicType.testValue) let test2 = TestView() test2.prepareForInterfaceBuilder() XCTAssertEqual(test2.translucent, self.dynamicType.testValue) } func testUITabBar() { class TestView : UITabBar, CurrentTestProtocol { } let test1 = TestView() test1.applyProtocolUIAppearance() XCTAssertEqual(test1.translucent, self.dynamicType.testValue) let test2 = TestView() test2.prepareForInterfaceBuilder() XCTAssertEqual(test2.translucent, self.dynamicType.testValue) } }
mit
e34c4703323b35d3771d0a8f57f3223e
26
69
0.627315
5.468354
false
true
false
false
bit6/bit6-ios-sdk
CoreSamples/Bit6FullDemo-Swift/Bit6ChatDemo-Swift/ChatsTableViewController.swift
1
12646
// // ChatsTableViewController.swift // Bit6ChatDemo-Swift // // Created by Carlos Thurber Boaventura on 07/08/14. // Copyright (c) 2014 Bit6. All rights reserved. // import UIKit import MobileCoreServices import Bit6 class ChatsTableViewController: UITableViewController, UITextFieldDelegate { var conversation : Bit6Conversation! { didSet { Bit6.setCurrentConversation(conversation) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.messagesChangedNotification(_:)), name: Bit6MessagesChangedNotification, object: self.conversation) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.groupsChangedNotification(_:)), name: Bit6GroupsChangedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.typingBeginNotification(_:)), name: Bit6TypingDidBeginRtNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(ChatsTableViewController.typingEndNotification(_:)), name: Bit6TypingDidEndRtNotification, object: nil) } } var scroll : Bool var _messages : [Bit6Message]! var messages : [Bit6Message] { get { if _messages != nil{ return _messages } else { _messages = self.conversation.messages return _messages } } set { _messages = newValue } } @IBOutlet var typingBarButtonItem: UIBarButtonItem! required init?(coder aDecoder: NSCoder) { self.scroll = false super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() if let userIdentity = Bit6.session().activeIdentity { self.navigationItem.prompt = "Logged as \(userIdentity.uri)" } let callItem = UIBarButtonItem(image:UIImage(named:"bit6ui_phone"), style:.Plain, target:self, action:#selector(ChatsTableViewController.call)) self.navigationItem.rightBarButtonItem = callItem if let typingAddress = self.conversation.typingAddress { self.typingBarButtonItem.title = "\(typingAddress.uri) is typing..." } else { self.typingBarButtonItem.title = nil; } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setToolbarHidden(false, animated: true) if !self.scroll { self.scroll = true self.tableView.reloadData() self.tableView.setContentOffset(CGPointMake(0, CGFloat.max), animated: false) } } deinit { Bit6.setCurrentConversation(nil) NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - TableView override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { return self.messages.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let message = self.messages[indexPath.row] var cell : UITableViewCell if message.incoming { cell = tableView.dequeueReusableCellWithIdentifier("textInCell")! } else { cell = tableView.dequeueReusableCellWithIdentifier("textOutCell")! } return cell } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let message = self.messages[indexPath.row] if let textLabel = cell.viewWithTag(1) as? UILabel { textLabel.text = ChatsTableViewController.textContentForMessage(message) } if let detailTextLabel = cell.viewWithTag(2) as? UILabel { if message.type == .Call { detailTextLabel.text = "" } else { switch message.status { case .New : detailTextLabel.text = "" case .Sending : detailTextLabel.text = "Sending" case .Sent : detailTextLabel.text = "Sent" case .Failed : detailTextLabel.text = "Failed" case .Delivered : detailTextLabel.text = "Delivered" case .Read : detailTextLabel.text = "Read" } } } } // MARK: - Calls //WARNING: change to Bit6CallMediaModeMix to enable recording during a call static let callMediaMode = Bit6CallMediaModeP2P func call() { let actionSheet = UIAlertController(title:nil, message: nil, preferredStyle: .ActionSheet) actionSheet.addAction(UIAlertAction(title: "Audio Call", style: .Default, handler:{(action :UIAlertAction) in Bit6.startCallTo(self.conversation.address, streams:[.Audio], mediaMode:ChatsTableViewController.callMediaMode, offnet: false) })) actionSheet.addAction(UIAlertAction(title: "Video Call", style: .Default, handler:{(action :UIAlertAction) in Bit6.startCallTo(self.conversation.address, streams:[.Audio,.Video], mediaMode:ChatsTableViewController.callMediaMode, offnet: false) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:nil)) self.navigationController?.presentViewController(actionSheet, animated: true, completion:nil) } // MARK: - Send Text @IBAction func touchedComposeButton(sender : UIBarButtonItem) { if !self.canChat() { let alert = UIAlertController(title:"You have left this group", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action :UIAlertAction) in })) self.navigationController?.presentViewController(alert, animated: true, completion:nil) return; } let alert = UIAlertController(title:"Type the message", message: nil, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:{(action :UIAlertAction) in })) alert.addAction(UIAlertAction(title: "Done", style: .Default, handler:{(action :UIAlertAction) in let msgTextField = alert.textFields![0] guard let text = msgTextField.text else { return } self.sendTextMsg(text) })) alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in textField.placeholder = "Message" textField.delegate = self }) self.navigationController?.presentViewController(alert, animated: true, completion:nil) } func sendTextMsg(msg : NSString){ if msg.length > 0 { let message = Bit6OutgoingMessage(destination:self.conversation.address) message.content = msg as String message.sendWithCompletionHandler{ (response, error) in if error == nil { NSLog("Message Sent") } else { NSLog("Message Failed with Error: \(error?.localizedDescription)") } } } } // MARK: - Typing func typingBeginNotification(notification:NSNotification) { let userInfo = notification.userInfo! let fromAddress = userInfo[Bit6FromKey] as! Bit6Address let convervationAddress = notification.object as! Bit6Address if convervationAddress == self.conversation.address { self.typingBarButtonItem.title = "\(fromAddress.uri) is typing..." } } func typingEndNotification(notification:NSNotification) { let convervationAddress = notification.object as! Bit6Address if convervationAddress == self.conversation.address { self.typingBarButtonItem.title = nil } } // MARK: - Data Source changes //here we listen to changes in group members and group title func groupsChangedNotification(notification:NSNotification) { let userInfo = notification.userInfo! let object = userInfo[Bit6ObjectKey] as! Bit6Group let change = userInfo[Bit6ChangeKey] as! String if change == Bit6UpdatedKey && object.address == self.conversation.address { self.title = ConversationsViewController.titleForConversation(self.conversation) } } func messagesChangedNotification(notification:NSNotification) { var userInfo = notification.userInfo! let object = userInfo[Bit6ObjectKey] as! Bit6Message let change = userInfo[Bit6ChangeKey] as! String if change == Bit6AddedKey { let indexPath = NSIndexPath(forRow: self.messages.count, inSection: 0) self.messages.append(object) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic) self.scrollToBottomAnimated(true) } else if change == Bit6UpdatedKey { if let indexPath = findMessage(object) { let cell = self.tableView.cellForRowAtIndexPath(indexPath) if cell != nil { self.tableView(self.tableView, willDisplayCell:cell!, forRowAtIndexPath:indexPath) } } } else if change == Bit6DeletedKey { if let indexPath = findMessage(object) { self.messages.removeAtIndex(indexPath.row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic) } } } func findMessage(message:Bit6Message) -> NSIndexPath? { for x in (0..<self.messages.count).reverse() { if self.messages[x].isEqual(message) { return NSIndexPath(forRow:x, inSection:0) } } return nil } // MARK: - func scrollToBottomAnimated(animated:Bool){ if self.messages.count>0 { let section = 0 let row = self.tableView(self.tableView, numberOfRowsInSection: section)-1 let scrollIndexPath = NSIndexPath(forRow: row, inSection: section) self.tableView.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated) } } // MARK: - UITextFieldDelegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { Bit6.typingBeginToAddress(self.conversation.address) return true } // MARK: - Helpers func canChat() -> Bool { if let group = Bit6Group(conversation:self.conversation) { if group.hasLeft { return false } } return true } class func textContentForMessage(message:Bit6Message) -> String? { if message.type == .Call { var showDuration = false var status = "" switch message.callStatus { case .Answer: status = "Answer"; showDuration = true; case .Missed: status = "Missed"; case .Failed: status = "Failed"; case .NoAnswer: status = "No Answer"; } var channels = [String]() if message.callHasChannel(.Audio) { channels.append("Audio") } if message.callHasChannel(.Video) { channels.append("Video"); } if message.callHasChannel(.Data) { channels.append("Data"); } let channel = channels.joinWithSeparator(" + ") if showDuration { return "\(channel) Call - \(message.callDuration!.description)s" } else { return "\(channel) Call (\(status))" } } else if message.type == .Location { return "Location" } else if message.type == .Attachments { return "Attachment" } else { return message.content; } } }
mit
14d4df7d6f0cef72149e90341a708104
36.085044
210
0.603511
5.315679
false
false
false
false
tkremenek/swift
test/Sema/availability_nonoverlapping.swift
13
11256
// RUN: not %target-swift-frontend -typecheck %s -swift-version 4 2> %t.4.txt // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-4 %s < %t.4.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.4.txt // RUN: not %target-swift-frontend -typecheck %s -swift-version 5 2> %t.5.txt // RUN: %FileCheck -check-prefix=CHECK -check-prefix=CHECK-5 %s < %t.5.txt // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t.5.txt class NonOptToOpt { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonOptToOpt() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class NonOptToOptReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonOptToOptReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class OptToNonOpt { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = OptToNonOpt() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class OptToNonOptReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = OptToNonOptReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class NoChange { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class NoChangeReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class OptToOpt { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class OptToOptReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init?() {} @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init!() {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init()' } class ThreeWayA { @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayB { @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayC { @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayD { @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayE { @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class ThreeWayF { @available(swift, introduced: 5.0, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.0) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class DisjointThreeWay { @available(swift, obsoleted: 5.0) public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 5.1, obsoleted: 6.0) public init?() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, introduced: 6.1) public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } class OverlappingVersions { @available(swift, obsoleted: 6.0) public init(a: ()) {} @available(swift 5.0) public init?(a: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(a:)' @available(swift 5.0) public init?(b: ()) {} @available(swift, obsoleted: 5.1) public init(b: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(b:)' public init(c: ()) {} @available(swift 5.0) public init?(c: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c:)' @available(swift 5.0) public init(c2: ()) {} public init?(c2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(c2:)' @available(swift, obsoleted: 5.0) public init(d: ()) {} public init?(d: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d:)' public init(d2: ()) {} @available(swift, obsoleted: 5.0) public init?(d2: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(d2:)' @available(swift, obsoleted: 5.0) public init(e: ()) {} @available(swift 5.0) public init?(e: ()) {} @available(swift 5.0) public init!(e: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(e:)' @available(swift, obsoleted: 5.0) public init(f: ()) {} @available(swift 5.0) public init?(f: ()) {} @available(swift, obsoleted: 5.0) public init!(f: ()) {} // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'init(f:)' } class NonThrowingToThrowing { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonThrowingToThrowing() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = NonThrowingToThrowing.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class NonThrowingToThrowingReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = NonThrowingToThrowingReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = NonThrowingToThrowingReversed.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class ThrowingToNonThrowing { @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = ThrowingToNonThrowing() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = ThrowingToNonThrowing.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class ThrowingToNonThrowingReversed { @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public init() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public init() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public static func foo() {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public static func foo() throws {} // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = ThrowingToNonThrowingReversed() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 _ = ThrowingToNonThrowingReversed.foo() // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0 class ChangePropertyType { // We don't allow this for stored properties. @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public var stored: Int16 = 0 @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public var stored: Int8 = 0 // CHECK: :[[@LINE]]:{{.+}} error: invalid redeclaration of 'stored' // OK for computed properties. @available(swift 5.0) @available(*, deprecated, message: "yes 5.0") public var computed: Int16 { get { } set { } } @available(swift, obsoleted: 5.0) @available(*, deprecated, message: "not 5.0") public var computed: Int8 { get { } set { } } // NEGATIVE-NOT: :[[@LINE]]:{{.+}}error } _ = ChangePropertyType().computed // CHECK-4: :[[@LINE-1]]:{{.+}} not 5.0 // CHECK-5: :[[@LINE-2]]:{{.+}} yes 5.0
apache-2.0
b23a2ee209669215775a89e8bda7092b
29.923077
98
0.592928
3.468721
false
false
false
false
movem3nt/StreamBaseKit
StreamBaseKit/UnionStream.swift
2
4286
// // UnionStream.swift // StreamBaseKit // // Created by Steve Farrell on 8/31/15. // Copyright (c) 2015 Movem3nt, Inc. All rights reserved. // import Foundation /** Compose a stream out of other streams. Some example use cases are: - Placeholders - Multiple Firebase queries in one view It's ok for the keys to overlap, and for different substreams to have different types. The sort order of the first stream is used by the union stream. (The sort orders of the other streams is ignored.) */ public class UnionStream { private let sources: [StreamBase] // TODO StreamBaseProtocol private let delegates: [UnionStreamDelegate] private var timer: NSTimer? private var numStreamsFinished: Int? = 0 private var union = KeyedArray<BaseItem>() private var error: NSError? private var comparator: StreamBase.Comparator { get { return sources[0].comparator } } /** The delegate to notify as the merged stream is updated. */ weak public var delegate: StreamBaseDelegate? /** Construct a union stream from other streams. The sort order of the first substream is used for the union. :param: sources The substreams. */ public init(sources: StreamBase...) { precondition(sources.count > 0) self.sources = sources delegates = sources.map{ UnionStreamDelegate(source: $0) } for (s, d) in zip(sources, delegates) { d.union = self s.delegate = d } } private func update() { var newUnion = [BaseItem]() var seen = Set<String>() for source in sources { for item in source { if !seen.contains(item.key!) { newUnion.append(item) seen.insert(item.key!) } } } newUnion.sortInPlace(comparator) StreamBase.applyBatch(union, batch: newUnion, delegate: delegate) if numStreamsFinished == sources.count { numStreamsFinished = nil delegate?.streamDidFinishInitialLoad(error) } } func needsUpdate() { timer?.invalidate() timer = NSTimer.schedule(delay: 0.1) { [weak self] timer in self?.update() } } func didFinishInitialLoad(error: NSError?) { if let e = error where self.error == nil { self.error = e // Any additional errors are ignored. } numStreamsFinished?++ needsUpdate() } func changed(t: BaseItem) { if let row = union.find(t.key!) { delegate?.streamItemsChanged([NSIndexPath(forRow: row, inSection: 0)]) } } } extension UnionStream : Indexable { public typealias Index = Int public var startIndex: Index { return union.startIndex } public var endIndex: Index { return union.startIndex } public subscript(i: Index) -> BaseItem { return union[i] } } extension UnionStream : CollectionType { } extension UnionStream : StreamBaseProtocol { public func find(key: String) -> BaseItem? { if let row = union.find(key) { return union[row] } return nil } public func findIndexPath(key: String) -> NSIndexPath? { if let row = union.find(key) { return NSIndexPath(forRow: row, inSection: 0) } return nil } } private class UnionStreamDelegate: StreamBaseDelegate { weak var source: StreamBase? weak var union: UnionStream? init(source: StreamBase) { self.source = source } func streamWillChange() { } func streamDidChange() { union?.needsUpdate() } func streamItemsAdded(paths: [NSIndexPath]) { } func streamItemsDeleted(paths: [NSIndexPath]) { } func streamItemsChanged(paths: [NSIndexPath]) { for path in paths { if let t = source?[path.row] { union?.changed(t) } } } func streamDidFinishInitialLoad(error: NSError?) { union?.didFinishInitialLoad(error) } }
mit
ed82ec9457e9bd5a280941c185621f1e
24.825301
94
0.580495
4.583957
false
false
false
false
alienorb/Vectorized
Vectorized/Parser/SVGPathCommand.swift
1
11308
//--------------------------------------------------------------------------------------- // The MIT License (MIT) // // Created by Arthur Evstifeev on 5/29/12. // Modified by Michael Redig 9/28/14 // Ported to Swift by Brian Christensen <brian@alienorb.com> // // Copyright (c) 2012 Arthur Evstifeev // Copyright (c) 2014 Michael Redig // Copyright (c) 2015 Seedling // Copyright (c) 2016 Alien Orb Software LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //--------------------------------------------------------------------------------------- import Foundation import CoreGraphics internal enum CommandType: Int { case Absolute case Relative } internal protocol SVGPathCommand { func processCommandString(commandString: String, withPrevCommand: String, forPath: SVGBezierPath, factoryIdentifier: String) } internal class SVGPathCommandImpl: SVGPathCommand { static let paramRegex = try! NSRegularExpression(pattern: "[-+]?[0-9]*\\.?[0-9]+", options: []) var prevCommand: String? func parametersForCommand(commandString: String) -> [CGFloat] { let matches = SVGPathCommandImpl.paramRegex.matchesInString(commandString, options: [], range: NSRange(location: 0, length: commandString.characters.count)) var results: [CGFloat] = [] for match in matches { let paramString = (commandString as NSString).substringWithRange(match.range) if let value = Float(paramString) { results.append(CGFloat(value)) } } return results } func isAbsoluteCommand(commandLetter: String) -> Bool { return commandLetter == commandLetter.uppercaseString } func processCommandString(commandString: String, withPrevCommand prevCommand: String, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { self.prevCommand = prevCommand let commandLetter = commandString.substringToIndex(commandString.startIndex.advancedBy(1)) let params = parametersForCommand(commandString) let commandType: CommandType = isAbsoluteCommand(commandLetter) ? .Absolute : .Relative performWithParams(params, commandType: commandType, forPath: path, factoryIdentifier: identifier) } func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { fatalError("You must override \(#function) in a subclass") } } internal class SVGMoveCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.moveToPoint(CGPoint(x: params[0], y: params[1])) } else { path.moveToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGLineToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addLineToPoint(CGPoint(x: params[0], y: params[1])) } else { path.addLineToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGHorizontalLineToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addLineToPoint(CGPoint(x: params[0], y: path.currentPoint.y)) } else { path.addLineToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y)) } } } internal class SVGVerticalLineToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addLineToPoint(CGPoint(x: path.currentPoint.x, y: params[0])) } else { path.addLineToPoint(CGPoint(x: path.currentPoint.x, y: path.currentPoint.y + params[0])) } } } internal class SVGCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addCurveToPoint(CGPoint(x: params[4], y: params[5]), controlPoint1: CGPoint(x: params[0], y: params[1]), controlPoint2: CGPoint(x: params[2], y: params[3])) } else { path.addCurveToPoint(CGPoint(x: path.currentPoint.x + params[4], y: path.currentPoint.y + params[5]), controlPoint1: CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1]), controlPoint2: CGPoint(x: path.currentPoint.x + params[2], y: path.currentPoint.y + params[3])) } } } internal class SVGSmoothCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { var firstControlPoint = path.currentPoint if let prevCommand = prevCommand { if prevCommand.characters.count > 0 { let prevCommandType = prevCommand.substringToIndex(prevCommand.startIndex.advancedBy(1)) let prevCommandTypeLowercase = prevCommandType.lowercaseString let isAbsolute = prevCommandType != prevCommandTypeLowercase if prevCommandTypeLowercase == "c" || prevCommandTypeLowercase == "s" { let prevParams = parametersForCommand(prevCommand) if prevCommandTypeLowercase == "c" { if isAbsolute { firstControlPoint = CGPoint(x: -1 * prevParams[2] + 2 * path.currentPoint.x, y: -1 * prevParams[3] + 2 * path.currentPoint.y) } else { let oldCurrentPoint = CGPoint(x: path.currentPoint.x - prevParams[4], y: path.currentPoint.y - prevParams[5]) firstControlPoint = CGPoint(x: -1 * (prevParams[2] + oldCurrentPoint.x) + 2 * path.currentPoint.x, y: -1 * (prevParams[3] + oldCurrentPoint.y) + 2 * path.currentPoint.y) } } else { if isAbsolute { firstControlPoint = CGPoint(x: -1 * prevParams[0] + 2 * path.currentPoint.x, y: -1 * prevParams[1] + 2 * path.currentPoint.y) } else { let oldCurrentPoint = CGPoint(x: path.currentPoint.x - prevParams[2], y: path.currentPoint.y - prevParams[3]) firstControlPoint = CGPoint(x: -1 * (prevParams[0] + oldCurrentPoint.x) + 2 * path.currentPoint.x, y: -1 * (prevParams[1] + oldCurrentPoint.y) + 2 * path.currentPoint.y) } } } } } if type == .Absolute { path.addCurveToPoint(CGPoint(x: params[2], y: params[3]), controlPoint1: CGPoint(x: firstControlPoint.x, y: firstControlPoint.y), controlPoint2: CGPoint(x: params[0], y: params[1])) } else { path.addCurveToPoint(CGPoint(x: path.currentPoint.x + params[2], y: path.currentPoint.y + params[3]), controlPoint1: CGPoint(x: firstControlPoint.x, y: firstControlPoint.y), controlPoint2: CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGQuadraticCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { if type == .Absolute { path.addQuadCurveToPoint(CGPoint(x: params[2], y: params[3]), controlPoint: CGPoint(x: params[0], y: params[1])) } else { path.addQuadCurveToPoint(CGPoint(x: path.currentPoint.x + params[2], y: path.currentPoint.y + params[3]), controlPoint: CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1])) } } } internal class SVGSmoothQuadraticCurveToCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { var firstControlPoint = path.currentPoint if let prevCommand = prevCommand { if prevCommand.characters.count > 0 { let prevCommandType = prevCommand.substringToIndex(prevCommand.startIndex.advancedBy(1)) let prevCommandTypeLowercase = prevCommandType.lowercaseString let isAbsolute = prevCommandType != prevCommandTypeLowercase if prevCommandTypeLowercase == "q" { let prevParams = parametersForCommand(prevCommand) if isAbsolute { firstControlPoint = CGPoint(x: -1 * prevParams[0] + 2 * path.currentPoint.x, y: -1 * prevParams[1] + 2 * path.currentPoint.y) } else { let oldCurrentPoint = CGPoint(x: path.currentPoint.x - prevParams[2], y: path.currentPoint.y - prevParams[3]) firstControlPoint = CGPoint(x: -1 * (prevParams[0] + oldCurrentPoint.x) + 2 * path.currentPoint.x, y: -1 * (prevParams[1] + oldCurrentPoint.y) + 2 * path.currentPoint.y) } } } } if type == .Absolute { path.addQuadCurveToPoint(CGPoint(x: params[0], y: params[1]), controlPoint: firstControlPoint) } else { path.addQuadCurveToPoint(CGPoint(x: path.currentPoint.x + params[0], y: path.currentPoint.y + params[1]), controlPoint: firstControlPoint) } } } internal class SVGClosePathCommand: SVGPathCommandImpl { override func performWithParams(params: [CGFloat], commandType type: CommandType, forPath path: SVGBezierPath, factoryIdentifier identifier: String) { path.closePath() } } internal class SVGPathCommandFactory { static let defaultFactory = SVGPathCommandFactory() static var factories: [String: SVGPathCommandFactory] = [:] private var commands: [String: SVGPathCommand] = [:] class func factoryWithIdentifier(identifier: String) -> SVGPathCommandFactory { if identifier == "" { return defaultFactory } if let factory = factories[identifier] { return factory } factories[identifier] = SVGPathCommandFactory() return factories[identifier]! } init() { commands["m"] = SVGMoveCommand() commands["l"] = SVGLineToCommand() commands["h"] = SVGHorizontalLineToCommand() commands["v"] = SVGVerticalLineToCommand() commands["c"] = SVGCurveToCommand() commands["s"] = SVGSmoothCurveToCommand() commands["q"] = SVGQuadraticCurveToCommand() commands["t"] = SVGSmoothQuadraticCurveToCommand() commands["z"] = SVGClosePathCommand() } func commandForCommandLetter(commandLetter: String) -> SVGPathCommand? { return commands[commandLetter.lowercaseString] } }
mit
293864b59cf209579f4e829add4586f4
42.829457
296
0.720729
4.073487
false
false
false
false
mac-cain13/DocumentStore
DocumentStore/Transaction/CoreDataTransaction.swift
1
8071
// // CoreDataTransaction.swift // DocumentStore // // Created by Mathijs Kadijk on 12-11-16. // Copyright © 2016 Mathijs Kadijk. All rights reserved. // import Foundation import CoreData class CoreDataTransaction: ReadWritableTransaction { private let context: NSManagedObjectContext private let validatedDocumentDescriptors: ValidatedDocumentDescriptors private let logger: Logger init(context: NSManagedObjectContext, documentDescriptors: ValidatedDocumentDescriptors, logTo logger: Logger) { self.context = context self.validatedDocumentDescriptors = documentDescriptors self.logger = logger } private func validateUseOfDocumentType<DocumentType: Document>(_: DocumentType.Type) throws { guard validatedDocumentDescriptors.documentDescriptors.contains(DocumentType.documentDescriptor) else { let error = DocumentStoreError( kind: .documentDescriptionNotRegistered, message: "The document description with identifier '\(DocumentType.documentDescriptor.name)' is not registered with the DocumentStore this transaction is associated with, please pass all DocumentDescriptions that are used to the DocumentStore initializer.", underlyingError: nil ) throw TransactionError.documentStoreError(error) } } func count<DocumentType>(matching query: Query<DocumentType>) throws -> Int { try validateUseOfDocumentType(DocumentType.self) let request: NSFetchRequest<NSNumber> = query.fetchRequest() do { return try convertExceptionToError { try context.count(for: request) } } catch let underlyingError { let error = DocumentStoreError( kind: .operationFailed, message: "Failed to count '\(DocumentType.documentDescriptor.name)' documents. This is an error in the DocumentStore library, please report this issue.", underlyingError: underlyingError ) logger.log(level: .error, message: "Error while performing count.", error: error) throw TransactionError.documentStoreError(error) } } func fetch<DocumentType>(matching query: Query<DocumentType>) throws -> [DocumentType] { try validateUseOfDocumentType(DocumentType.self) // Set up the fetch request let request: NSFetchRequest<NSManagedObject> = query.fetchRequest() request.returnsObjectsAsFaults = false // Perform the fetch let fetchResult: [NSManagedObject] do { fetchResult = try convertExceptionToError { try context.fetch(request) } } catch let underlyingError { let error = DocumentStoreError( kind: .operationFailed, message: "Failed to fetch '\(DocumentType.documentDescriptor.name)' documents. This is an error in the DocumentStore library, please report this issue.", underlyingError: underlyingError ) logger.log(level: .error, message: "Error while performing fetch.", error: error) throw TransactionError.documentStoreError(error) } // Deserialize documents return try fetchResult .compactMap { do { guard let documentData = $0.value(forKey: DocumentDataAttributeName) as? Data else { let error = DocumentStoreError( kind: .documentDataCorruption, message: "Failed to retrieve '\(DocumentDataAttributeName)' attribute contents and cast it to `Data` for a '\(DocumentType.documentDescriptor.name)' document. This is an error in the DocumentStore library, please report this issue.", underlyingError: nil ) logger.log(level: .error, message: "Encountered corrupt '\(DocumentDataAttributeName)' attribute.", error: error) throw DocumentDeserializationError(resolution: .skipDocument, underlyingError: error) } return try DocumentType.decode(from: documentData) } catch let error as DocumentDeserializationError { logger.log(level: .warn, message: "Deserializing '\(DocumentType.documentDescriptor.name)' document failed, recovering with '\(error.resolution)' resolution.", error: error.underlyingError) switch error.resolution { case .deleteDocument: context.delete($0) return nil case .skipDocument: return nil case .abortOperation: throw TransactionError.serializationFailed(error.underlyingError) } } catch let error { throw TransactionError.serializationFailed(error) } } } func insert<DocumentType: Document>(document: DocumentType, mode: InsertMode) throws -> Bool { try validateUseOfDocumentType(DocumentType.self) let identifierValue = DocumentType.documentDescriptor.identifier.resolver(document) let currentManagedObject = try fetchManagedObject(for: document, with: identifierValue) let managedObject: NSManagedObject switch (mode, currentManagedObject) { case (.replaceOnly, .none), (.addOnly, .some): return false case (.replaceOnly, let .some(currentManagedObject)), (.addOrReplace, let .some(currentManagedObject)): managedObject = currentManagedObject case (.addOnly, .none), (.addOrReplace, .none): managedObject = NSEntityDescription.insertNewObject(forEntityName: DocumentType.documentDescriptor.name, into: context) } do { let documentData = try DocumentType.encode(document) try convertExceptionToError { managedObject.setValue(documentData, forKey: DocumentDataAttributeName) managedObject.setValue(identifierValue, forKey: DocumentType.documentDescriptor.identifier.storageInformation.propertyName.keyPath) DocumentType.documentDescriptor.indices.forEach { managedObject.setValue($0.resolver(document), forKey: $0.storageInformation.propertyName.keyPath) } } return true } catch let error { throw TransactionError.serializationFailed(error) } } @discardableResult func delete<DocumentType>(matching query: Query<DocumentType>) throws -> Int { try validateUseOfDocumentType(DocumentType.self) let request: NSFetchRequest<NSManagedObject> = query.fetchRequest() request.includesPropertyValues = false do { let fetchResult = try convertExceptionToError { try context.fetch(request) } fetchResult.forEach(context.delete) return fetchResult.count } catch let underlyingError { let error = DocumentStoreError( kind: .operationFailed, message: "Failed to fetch '\(DocumentType.documentDescriptor.name)' documents. This is an error in the DocumentStore library, please report this issue.", underlyingError: underlyingError ) logger.log(level: .error, message: "Error while performing fetch.", error: error) throw TransactionError.documentStoreError(error) } } @discardableResult func delete<DocumentType: Document>(document: DocumentType) throws -> Bool { try validateUseOfDocumentType(DocumentType.self) guard let managedObject = try fetchManagedObject(for: document) else { return false } context.delete(managedObject) return true } func persistChanges() throws { if context.hasChanges { try context.save() } } private func fetchManagedObject<DocumentType: Document>(for document: DocumentType, with identifierValue: Any? = nil) throws -> NSManagedObject? { let identifierValue = identifierValue ?? DocumentType.documentDescriptor.identifier.resolver(document) let request = NSFetchRequest<NSManagedObject>(entityName: DocumentType.documentDescriptor.name) request.predicate = NSComparisonPredicate( leftExpression: NSExpression(forKeyPath: DocumentType.documentDescriptor.identifier.storageInformation.propertyName.keyPath), rightExpression: NSExpression(forConstantValue: identifierValue), modifier: .direct, type: .equalTo ) request.resultType = .managedObjectResultType return try convertExceptionToError { try context.fetch(request).first } } }
mit
1bd12e50431d161f121b391cd25704ed
39.552764
265
0.721066
5.408847
false
false
false
false
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/apiinteraction/discovery/ServerLocator.swift
1
5900
// // ServerLocator.swift // Emby.ApiClient // // Created by Vedran Ozir on 03/11/15. // Copyright © 2015 Vedran Ozir. All rights reserved. // import Foundation import CocoaAsyncSocket public class ServerLocator: NSObject, ServerDiscoveryProtocol, GCDAsyncUdpSocketDelegate { private let logger: ILogger private let jsonSerializer: IJsonSerializer private var onSuccess: (([ServerDiscoveryInfo]) -> Void)? var serverDiscoveryInfo: Set<ServerDiscoveryInfo> = [] public init( logger: ILogger, jsonSerializer: IJsonSerializer) { self.logger = logger; self.jsonSerializer = jsonSerializer; } // MARK: - utility methods public func findServers(timeoutMs: Int, onSuccess: @escaping ([ServerDiscoveryInfo]) -> Void, onError: @escaping (Error) -> Void) { let udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main) /*do { try udpSocket.bind(toPort: 7359) } catch let error { print("Error binding: \(error)") } do { try udpSocket.beginReceiving() } catch let error{ print("Error receiving: \(error)") }*/ // Find the server using UDP broadcast do { self.onSuccess = onSuccess try udpSocket.enableBroadcast(true) let sendData = "who is EmbyServer?".data(using: String.Encoding.utf8); let host = "255.255.255.255" let port: UInt16 = 7359; udpSocket.send(sendData!, toHost: host, port: port, withTimeout: TimeInterval(Double(timeoutMs)/1000.0), tag: 1) print("ServerLocator >>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch { print("Error sending DatagramPacket \(error)") onError(error) } } @objc func finished() { print("Found \(serverDiscoveryInfo.count) servers"); self.onSuccess?(Array(serverDiscoveryInfo)) } private func Receive(c: GCDAsyncUdpSocket, timeoutMs: UInt, onResponse: @escaping ([ServerDiscoveryInfo]) -> Void) throws { serverDiscoveryInfo = [] let timeout = TimeInterval(Double(timeoutMs) / 1000.0) Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(ServerLocator.finished), userInfo: nil, repeats: false) do { try c.beginReceiving() } catch { print (error) } } // MARK: - GCDAsyncUdpSocketDelegate /** * By design, UDP is a connectionless protocol, and connecting is not needed. * However, you may optionally choose to connect to a particular host for reasons * outlined in the documentation for the various connect methods listed above. * * This method is called if one of the connect methods are invoked, and the connection is successful. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didConnectToAddress address: Data) { print("didConnectToAddress") } /** * By design, UDP is a connectionless protocol, and connecting is not needed. * However, you may optionally choose to connect to a particular host for reasons * outlined in the documentation for the various connect methods listed above. * * This method is called if one of the connect methods are invoked, and the connection fails. * This may happen, for example, if a domain name is given for the host and the domain name is unable to be resolved. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error?) { print("didNotConnect") } /** * Called when the datagram with the given tag has been sent. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didSendDataWithTag tag: Int) { print("didSendDataWithTag") do { try self.Receive(c: sock, timeoutMs: UInt(1000), onResponse: { (serverDiscoveryInfo: [ServerDiscoveryInfo]) -> Void in print("serverDiscoveryInfo \(serverDiscoveryInfo)") }) } catch { print("\(error)") } } /** * Called if an error occurs while trying to send a datagram. * This could be due to a timeout, or something more serious such as the data being too large to fit in a sigle packet. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didNotSendDataWithTag tag: Int, dueToError error: Error?) { print("didNotSendDataWithTag") } /** * Called when the socket has received the requested datagram. **/ @objc public func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) { let json = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) as String? // We have a response print("ServerLocator >>> Broadcast response from server: \(String(describing: sock.localAddress())): \(String(describing: json))") do { if let serverInfo: ServerDiscoveryInfo = try! JSONDecoder().decode(ServerDiscoveryInfo.self, from: data) { self.serverDiscoveryInfo.insert(serverInfo) } } catch { print("\(error)") } } /** * Called when the socket is closed. **/ @objc public func udpSocketDidClose(_ sock: GCDAsyncUdpSocket, withError error: Error?) { print("udpSocketDidClose") } }
mit
1ffa74aec6e9cc00d4bd4d2f42c80d01
31.772222
149
0.597898
5.16098
false
false
false
false
thomasmeagher/TimeMachine
TimeMachine/Controllers/DataController.swift
2
1991
// // DataController.swift // HuntTimehop // // Created by thomas on 12/23/14. // Copyright (c) 2014 thomas. All rights reserved. // import Foundation import UIKit class DataController { class func jsonTokenParser(json: NSDictionary) -> Token? { var token: Token? if let json = json["access_token"] { let key: String = json as! String let expiryDate: NSDate = NSDate().plusDays(60) token = Token(key: key, expiryDate: expiryDate) } return token } class func jsonPostsParser(json: NSDictionary) -> [Product] { var products: [Product] = [] if let json = json["posts"] { let posts: [AnyObject] = json as! [AnyObject] for post in posts { let id: Int = post["id"]! as! Int let name: String = post["name"]! as! String let tagline: String = post["tagline"]! as! String let comments: Int = post["comments_count"]! as! Int let votes: Int = post["votes_count"]! as! Int let phURL: String = post["discussion_url"]! as! String let screenshotDictionary = post["screenshot_url"] as! NSDictionary let screenshotUrl: String = screenshotDictionary["850px"]! as! String let makerInside: Bool = post["maker_inside"]! as! Bool var exclusive: Bool? if let exclusiveDictionary = post["exclusive"] as? NSDictionary { let exclusiveNumber = exclusiveDictionary["exclusive"]! as! Int exclusive = Bool.init(exclusiveNumber) } else { exclusive = false } let userDictionary = post["user"] as! NSDictionary let hunter: String = userDictionary["name"]! as! String let product = Product(id: id, name: name, tagline: tagline, comments: comments, votes: votes, phURL: phURL, screenshotUrl: screenshotUrl, makerInside: makerInside, exclusive: exclusive!, hunter: hunter) products += [product] } } return products } }
mit
6bc25cbe32524fe35c3d137e13af213d
32.183333
210
0.614264
4.272532
false
false
false
false
HackMobile/music-interval-app
GymJamsV2/GymJamsV2/PlayerViewController.swift
1
3986
// // PlayerViewController.swift // GymJamsV2 // // Created by Kyle on 7/8/17. // Copyright © 2017 Kevin Nguyen. All rights reserved. // import UIKit class PlayerViewController: UIViewController, SPTAudioStreamingPlaybackDelegate, SPTAudioStreamingDelegate{ @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var sliderValueLabel: UILabel! @IBOutlet weak var updateAlbum: UILabel! @IBAction func sliderValueChanged(_ sender: UISlider) { var currentValue = Int(sender.value) sliderValueLabel.text = "\(currentValue)" sliderVal = currentValue } @IBOutlet weak var updateName: UILabel! func audioStreaming(_ audioStreaming: SPTAudioStreamingController!, didChange metadata: SPTPlaybackMetadata!) { player?.seek(to: 30, callback: {(error) in if error != nil { print("Error: couldn't skip"); } else { print ("Skipping Previous") } }); updateName.text = metadata.currentTrack?.name; updateAlbum.text = metadata.currentTrack?.artistName; var cover = metadata.currentTrack?.albumCoverArtURL; if (cover != nil) { imageView.setImageFromURl(stringImageUrl: cover!) } imageView.reloadInputViews() } var timer_ = Timer() @IBAction func playButtonPressed(_ sender: Any) { if (player?.playbackState.isPlaying)! { player?.setIsPlaying(false, callback: {(error) in if error != nil { print("Error: couldn't pause"); } else { print ("Pausing") } }); timer.invalidate() } else { player?.setIsPlaying(true, callback: {(error) in if error != nil { print("Error: couldn't start"); } else { print ("Starting") } }); setTimer() } } @IBAction func prevButtonPressed(_ sender: Any) { player?.skipPrevious({(error) in if error != nil { print("Error: couldn't skip"); } else { print ("Skipping Previous") } }); counter = sliderVal } @IBAction func skipButtonPressed(_ sender: Any) { player?.skipNext({(error) in if error != nil { print("Error: couldn't skip"); } else { print ("Skipping next") } }); counter = sliderVal } @IBOutlet weak var timerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() timerLabel.text = String(counter) player?.setShuffle(true, callback: {(error) in if error != nil { print("Error: couldn't shuffle") } else { print ("Shuffling") } }); player!.playbackDelegate = self player!.delegate = self as SPTAudioStreamingDelegate // Do any additional setup after loading the view. timer_ = Timer.scheduledTimer(timeInterval: 0.5, target:self, selector: #selector(PlayerViewController.updateCounter), userInfo: nil, repeats: true) } func updateCounter() { timerLabel.text = String(counter) } 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. } */ }
mit
111baa408958cfcf040458ed8fd48256
29.653846
156
0.553576
5.243421
false
false
false
false
VernierSoftwareTechnology/UIAlertWrapper
UIAlertWrapper.swift
1
11791
// // UIAlertWrapper.swift // UIAlertWrapper // // Created by Ruben Niculcea on 8/20/14. // Copyright (c) 2014 Vernier Software & Technology. All rights reserved. // import Foundation import UIKit private enum PresententionStyle { case Rect (CGRect) case BarButton (UIBarButtonItem) } private let alertDelegate = AlertDelegate() private var clickedButtonAtIndexBlock:(Int -> Void)? class AlertDelegate : NSObject, UIAlertViewDelegate, UIActionSheetDelegate { func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { clickedButtonAtIndexBlock!(buttonIndex) } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { if UIDevice.currentDevice().userInterfaceIdiom == .Pad { clickedButtonAtIndexBlock!(buttonIndex + 1) } else { clickedButtonAtIndexBlock!(buttonIndex) } } } /** UIAlertWrapper is a wrapper around UIAlertView/UIActionSheet and UIAlertController in order to simplify supporting both iOS 7 and iOS 8. It is not meant to be an exhaustive wrapper, it merely covers the common use cases around Alert Views and Action Sheets. */ class UIAlertWrapper : NSObject { private class func topViewController () -> UIViewController { let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController assert(rootViewController != nil, "App has no keyWindow, cannot present Alert/Action Sheet.") return UIAlertWrapper.topVisibleViewController(rootViewController!) } private class func topVisibleViewController(viewController: UIViewController) -> UIViewController { if viewController is UITabBarController { return UIAlertWrapper.topVisibleViewController((viewController as! UITabBarController).selectedViewController!) } else if viewController is UINavigationController { return UIAlertWrapper.topVisibleViewController((viewController as! UINavigationController).visibleViewController!) } else if viewController.presentedViewController != nil { return UIAlertWrapper.topVisibleViewController(viewController.presentedViewController!) } else if viewController.childViewControllers.count > 0 { return UIAlertWrapper.topVisibleViewController(viewController.childViewControllers.last!) } return viewController } /** Initializes and presents a new Action Sheet from a Bar Button Item on iPad or modally on iPhone - parameter title: The title of the Action Sheet - parameter cancelButtonTitle: The cancel button title - parameter destructiveButtonTitle: The destructive button title - parameter otherButtonTitles: An array of other button titles - parameter barButtonItem: The Bar Button Item to present from - parameter clickedButtonAtIndex: A closure that returns the buttonIndex of the button that was pressed. An index of 0 is always the cancel button or tapping outside of the popover on iPad. */ class func presentActionSheet(title title: String?, cancelButtonTitle: String, destructiveButtonTitle: String?, otherButtonTitles: [String], barButtonItem:UIBarButtonItem, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { self.presentActionSheet(title, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle, otherButtonTitles: otherButtonTitles, presententionStyle: .BarButton(barButtonItem), clickedButtonAtIndex: clickedButtonAtIndex) } /** Initializes and presents a new Action Sheet from a Frame on iPad or modally on iPhone - parameter title: The title of the Action Sheet - parameter cancelButtonTitle: The cancel button title - parameter destructiveButtonTitle: The destructive button title - parameter otherButtonTitles: An array of other button titles - parameter frame: The Frame to present from - parameter clickedButtonAtIndex: A closure that returns the buttonIndex of the button that was pressed. An index of 0 is always the cancel button or tapping outside of the popover on iPad. */ class func presentActionSheet(title title: String?, cancelButtonTitle: String, destructiveButtonTitle:String?, otherButtonTitles: [String], frame:CGRect, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { self.presentActionSheet(title, cancelButtonTitle: cancelButtonTitle, destructiveButtonTitle: destructiveButtonTitle, otherButtonTitles: otherButtonTitles, presententionStyle: .Rect(frame), clickedButtonAtIndex: clickedButtonAtIndex) } private class func presentActionSheet(title: String?, cancelButtonTitle: String, destructiveButtonTitle:String?, otherButtonTitles: [String], presententionStyle:PresententionStyle, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { let currentViewController = UIAlertWrapper.topViewController() if #available(iOS 8.0, *) { var buttonOffset = 1 let alert = UIAlertController(title: title, message: nil, preferredStyle: .ActionSheet) alert.addAction(UIAlertAction(title: cancelButtonTitle, style: .Cancel, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: 0) } })) if let _destructiveButtonTitle = destructiveButtonTitle { alert.addAction(UIAlertAction(title: _destructiveButtonTitle, style: .Destructive, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: 1) } })) buttonOffset += 1 } for (index, string) in otherButtonTitles.enumerate() { alert.addAction(UIAlertAction(title: string, style: .Default, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: index + buttonOffset) } })) } if UIDevice.currentDevice().userInterfaceIdiom == .Pad { switch presententionStyle { case let .Rect(rect): alert.popoverPresentationController?.sourceView = currentViewController.view alert.popoverPresentationController?.sourceRect = rect case let .BarButton(barButton): alert.popoverPresentationController?.barButtonItem = barButton } } currentViewController.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIActionSheet() if let _title = title { alert.title = _title } if UIDevice.currentDevice().userInterfaceIdiom == .Phone { alert.cancelButtonIndex = 0 alert.addButtonWithTitle(cancelButtonTitle) } if let _destructiveButtonTitle = destructiveButtonTitle { alert.destructiveButtonIndex = UIDevice.currentDevice().userInterfaceIdiom == .Phone ? 1 : 0 alert.addButtonWithTitle(_destructiveButtonTitle) } for string in otherButtonTitles { alert.addButtonWithTitle(string) } if let _clickedButtonAtIndex = clickedButtonAtIndex { clickedButtonAtIndexBlock = _clickedButtonAtIndex alert.delegate = alertDelegate } if UIDevice.currentDevice().userInterfaceIdiom == .Phone { alert.showInView(currentViewController.view) } else { switch presententionStyle { case let .Rect(rect): alert.showFromRect(rect, inView: currentViewController.view, animated: true) case let .BarButton(barButton): alert.showFromBarButtonItem(barButton, animated: true) } } } } /** Initializes and presents a new Alert - parameter title: The title of the Alert - parameter message: The message of the Alert - parameter cancelButtonTitle: The cancel button title - parameter otherButtonTitles: An array of other button titles - parameter clickedButtonAtIndex: A closure that returns the buttonIndex of the button that was pressed. An index of 0 is always the cancel button. */ class func presentAlert(title title: String, message: String, cancelButtonTitle: String, otherButtonTitles: [String]? = nil, clickedButtonAtIndex:((buttonIndex:Int) -> ())? = nil) { if #available(iOS 8.0, *) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: cancelButtonTitle, style: .Cancel, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: 0) } })) if let _otherButtonTitles = otherButtonTitles { for (index, string) in _otherButtonTitles.enumerate() { alert.addAction(UIAlertAction(title: string, style: .Default, handler: {(alert: UIAlertAction) in if let _clickedButtonAtIndex = clickedButtonAtIndex { _clickedButtonAtIndex(buttonIndex: index + 1) } })) } } let currentViewController = UIAlertWrapper.topViewController() currentViewController.presentViewController(alert, animated: true, completion: nil) } else { let alert = UIAlertView() alert.addButtonWithTitle(cancelButtonTitle); alert.cancelButtonIndex = 0 alert.title = title alert.message = message if let _otherButtonTitles = otherButtonTitles { for string in _otherButtonTitles { alert.addButtonWithTitle(string) } } if let _clickedButtonAtIndex = clickedButtonAtIndex { clickedButtonAtIndexBlock = _clickedButtonAtIndex alert.delegate = alertDelegate } alert.show() } } }
mit
f71869852a91c036c172cbd364930e85
44.879377
257
0.593079
6.931805
false
false
false
false
kevin00223/iOS-demo
rac_demo/Pods/ReactiveSwift/Sources/ValidatingProperty.swift
2
9976
import Result /// A mutable property that validates mutations before committing them. /// /// If the property wraps an arbitrary mutable property, changes originated from /// the inner property are monitored, and would be automatically validated. /// Note that these would still appear as committed values even if they fail the /// validation. /// /// ``` /// let root = MutableProperty("Valid") /// let outer = ValidatingProperty(root) { /// $0 == "Valid" ? .valid : .invalid(.outerInvalid) /// } /// /// outer.result.value // `.valid("Valid") /// /// root.value = "🎃" /// outer.result.value // `.invalid("🎃", .outerInvalid)` /// ``` public final class ValidatingProperty<Value, ValidationError: Swift.Error>: MutablePropertyProtocol { private let getter: () -> Value private let setter: (Value) -> Void /// The result of the last attempted edit of the root property. public let result: Property<Result> /// The current value of the property. /// /// The value could have failed the validation. Refer to `result` for the /// latest validation result. public var value: Value { get { return getter() } set { setter(newValue) } } /// A producer for Signals that will send the property's current value, /// followed by all changes over time, then complete when the property has /// deinitialized. public let producer: SignalProducer<Value, NoError> /// A signal that will send the property's changes over time, /// then complete when the property has deinitialized. public let signal: Signal<Value, NoError> /// The lifetime of the property. public let lifetime: Lifetime /// Create a `ValidatingProperty` that presents a mutable validating /// view for an inner mutable property. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - note: `inner` is retained by the created property. /// /// - parameters: /// - inner: The inner property which validated values are committed to. /// - validator: The closure to invoke for any proposed value to `self`. public init<Inner: ComposableMutablePropertyProtocol>( _ inner: Inner, _ validator: @escaping (Value) -> Decision ) where Inner.Value == Value { getter = { inner.value } producer = inner.producer signal = inner.signal lifetime = inner.lifetime // This flag temporarily suspends the monitoring on the inner property for // writebacks that are triggered by successful validations. var isSettingInnerValue = false (result, setter) = inner.withValue { initial in let mutableResult = MutableProperty(Result(initial, validator(initial))) mutableResult <~ inner.signal .filter { _ in !isSettingInnerValue } .map { Result($0, validator($0)) } return (Property(capturing: mutableResult), { input in // Acquire the lock of `inner` to ensure no modification happens until // the validation logic here completes. inner.withValue { _ in let writebackValue: Value? = mutableResult.modify { result in result = Result(input, validator(input)) return result.value } if let value = writebackValue { isSettingInnerValue = true inner.value = value isSettingInnerValue = false } } }) } } /// Create a `ValidatingProperty` that validates mutations before /// committing them. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - parameters: /// - initial: The initial value of the property. It is not required to /// pass the validation as specified by `validator`. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init( _ initial: Value, _ validator: @escaping (Value) -> Decision ) { self.init(MutableProperty(initial), validator) } /// Create a `ValidatingProperty` that presents a mutable validating /// view for an inner mutable property. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - note: `inner` is retained by the created property. /// /// - parameters: /// - inner: The inner property which validated values are committed to. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<Other: PropertyProtocol>( _ inner: MutableProperty<Value>, with other: Other, _ validator: @escaping (Value, Other.Value) -> Decision ) { // Capture a copy that reflects `other` without influencing the lifetime of // `other`. let other = Property(other) self.init(inner) { input in return validator(input, other.value) } // When `other` pushes out a new value, the resulting property would react // by revalidating itself with its last attempted value, regardless of // success or failure. other.signal .take(during: lifetime) .observeValues { [weak self] _ in guard let s = self else { return } switch s.result.value { case let .invalid(value, _): s.value = value case let .coerced(_, value, _): s.value = value case let .valid(value): s.value = value } } } /// Create a `ValidatingProperty` that validates mutations before /// committing them. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - parameters: /// - initial: The initial value of the property. It is not required to /// pass the validation as specified by `validator`. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<Other: PropertyProtocol>( _ initial: Value, with other: Other, _ validator: @escaping (Value, Other.Value) -> Decision ) { self.init(MutableProperty(initial), with: other, validator) } /// Create a `ValidatingProperty` which validates mutations before /// committing them. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - note: `inner` is retained by the created property. /// /// - parameters: /// - initial: The initial value of the property. It is not required to /// pass the validation as specified by `validator`. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<U, E>( _ initial: Value, with other: ValidatingProperty<U, E>, _ validator: @escaping (Value, U) -> Decision ) { self.init(MutableProperty(initial), with: other, validator) } /// Create a `ValidatingProperty` that presents a mutable validating /// view for an inner mutable property. /// /// The proposed value is only committed when `valid` is returned by the /// `validator` closure. /// /// - parameters: /// - inner: The inner property which validated values are committed to. /// - other: The property that `validator` depends on. /// - validator: The closure to invoke for any proposed value to `self`. public convenience init<U, E>( _ inner: MutableProperty<Value>, with other: ValidatingProperty<U, E>, _ validator: @escaping (Value, U) -> Decision ) { // Capture only `other.result` but not `other`. let otherValidations = other.result self.init(inner) { input in let otherValue: U switch otherValidations.value { case let .valid(value): otherValue = value case let .coerced(_, value, _): otherValue = value case let .invalid(value, _): otherValue = value } return validator(input, otherValue) } // When `other` pushes out a new validation result, the resulting property // would react by revalidating itself with its last attempted value, // regardless of success or failure. otherValidations.signal .take(during: lifetime) .observeValues { [weak self] _ in guard let s = self else { return } switch s.result.value { case let .invalid(value, _): s.value = value case let .coerced(_, value, _): s.value = value case let .valid(value): s.value = value } } } /// Represents a decision of a validator of a validating property made on a /// proposed value. public enum Decision { /// The proposed value is valid. case valid /// The proposed value is invalid, but the validator coerces it into a /// replacement which it deems valid. case coerced(Value, ValidationError?) /// The proposed value is invalid. case invalid(ValidationError) } /// Represents the result of the validation performed by a validating property. public enum Result { /// The proposed value is valid. case valid(Value) /// The proposed value is invalid, but the validator was able to coerce it /// into a replacement which it deemed valid. case coerced(replacement: Value, proposed: Value, error: ValidationError?) /// The proposed value is invalid. case invalid(Value, ValidationError) /// Whether the value is invalid. public var isInvalid: Bool { if case .invalid = self { return true } else { return false } } /// Extract the valid value, or `nil` if the value is invalid. public var value: Value? { switch self { case let .valid(value): return value case let .coerced(value, _, _): return value case .invalid: return nil } } /// Extract the error if the value is invalid. public var error: ValidationError? { if case let .invalid(_, error) = self { return error } else { return nil } } fileprivate init(_ value: Value, _ decision: Decision) { switch decision { case .valid: self = .valid(value) case let .coerced(replacement, error): self = .coerced(replacement: replacement, proposed: value, error: error) case let .invalid(error): self = .invalid(value, error) } } } }
mit
3befd45458d221a86b5b3d6f12789b70
29.489297
101
0.675326
3.81846
false
false
false
false
SeptAi/Cooperate
Cooperate/Cooperate/Class/View/Message/MessageCell.swift
1
1475
// // MessageCell.swift // Cooperate // // Created by J on 2017/1/17. // Copyright © 2017年 J. All rights reserved. // import UIKit class MessageCell: UITableViewCell { // 视图模型 var viewModel:MessageViewModel?{ didSet{ // 设置图像 // 设置内容 title.text = viewModel?.title author.text = viewModel?.author content.attributedText = viewModel?.normalAttrText } } @IBOutlet weak var msgImageView: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var author: UILabel! @IBOutlet weak var content: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code // Initialization code // 离屏渲染 - 消耗CPU换取速度 self.layer.drawsAsynchronously = true // 栅格化 - 异步绘制之后,会生成一张独立图像,在cell滚动时,实质滚动的是这张图片 // cell优化-减少图层的数量 // 停止滚动后,接收监听 self.layer.shouldRasterize = true // 栅格化 -- 必须制定分辨率,否则会模糊 self.layer.rasterizationScale = UIScreen.main.scale } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
2b6f6363840c99870fa5f359b2c7a82f
23.769231
65
0.595497
4.27907
false
false
false
false
openhab/openhab.ios
openHABWatch Extension/ComplicationController.swift
1
6480
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import ClockKit import DeviceKit import WatchKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Complication Configuration func getComplicationDescriptors(handler: @escaping ([CLKComplicationDescriptor]) -> Void) { // watchOS7: replacing depreciated CLKComplicationSupportedFamilies let descriptors = [ CLKComplicationDescriptor(identifier: "complication", displayName: Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String, supportedFamilies: CLKComplicationFamily.allCases) // Multiple complication support can be added here with more descriptors ] handler(descriptors) } func handleSharedComplicationDescriptors(_ complicationDescriptors: [CLKComplicationDescriptor]) { // Do any necessary work to support these newly shared complication descriptors } // MARK: - Timeline Configuration func getSupportedTimeTravelDirections(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimeTravelDirections) -> Void) { handler([]) } func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(nil) } func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { handler(nil) } func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) { handler(.showOnLockScreen) } // MARK: - Timeline Population func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { // Call the handler with the current timeline entry let template = getTemplate(complication: complication) if template != nil { handler(CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template!)) } } func getTimelineEntries(for complication: CLKComplication, before date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Placeholder Templates func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { // This method will be called once per supported complication, and the results will be cached handler(getTemplate(complication: complication)) } func getPlaceholderTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { handler(getTemplate(complication: complication)) } private func getTemplate(complication: CLKComplication) -> CLKComplicationTemplate? { // default ist circularSmall var template: CLKComplicationTemplate? switch complication.family { case .modularSmall: template = CLKComplicationTemplateModularSmallRingImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage()), fillFraction: 1, ringStyle: CLKComplicationRingStyle.closed) case .utilitarianSmall: template = CLKComplicationTemplateUtilitarianSmallRingImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage()), fillFraction: 1, ringStyle: CLKComplicationRingStyle.closed) case .circularSmall: template = CLKComplicationTemplateCircularSmallRingImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage()), fillFraction: 1, ringStyle: CLKComplicationRingStyle.closed) case .extraLarge: template = CLKComplicationTemplateExtraLargeSimpleImage(imageProvider: CLKImageProvider(onePieceImage: UIImage(named: "OHTemplateIcon") ?? UIImage())) case .graphicCorner: template = CLKComplicationTemplateGraphicCornerTextImage(textProvider: CLKSimpleTextProvider(text: "openHAB"), imageProvider: CLKFullColorImageProvider(fullColorImage: getGraphicCornerImage())) case .graphicBezel: let modTemplate = CLKComplicationTemplateGraphicCircularImage(imageProvider: CLKFullColorImageProvider(fullColorImage: getGraphicCornerImage())) template = CLKComplicationTemplateGraphicBezelCircularText(circularTemplate: modTemplate, textProvider: CLKSimpleTextProvider(text: "openHAB")) case .graphicCircular: template = CLKComplicationTemplateGraphicCircularImage(imageProvider: CLKFullColorImageProvider(fullColorImage: getGraphicCircularImage())) default: break } return template } private func getGraphicCornerImage() -> UIImage { let dimension: CGFloat = Device.current.diagonal < 2.0 ? 20 : 22 return getGraphicImage(withSize: CGSize(width: dimension, height: dimension)) } private func getGraphicCircularImage() -> UIImage { let dimension: CGFloat = Device.current.diagonal < 2.0 ? 42 : 47 return getGraphicImage(withSize: CGSize(width: dimension, height: dimension)) } private func getGraphicImage(withSize size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, WKInterfaceDevice.current().screenScale) if let image = UIImage(named: "OHIcon") { image.draw(in: rect.insetBy(dx: -(rect.width / 10), dy: -(rect.height / 10))) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image ?? UIImage() } }
epl-1.0
9f45180695a6eb4447ce178f93134a03
48.465649
227
0.72963
5.586207
false
false
false
false
jefflinwood/volunteer-recognition-ios
APASlapApp/APASlapApp/Login/LoginViewController.swift
1
1960
// // LoginViewController.swift // APASlapApp // // Created by Jeffrey Linwood on 6/3/17. // Copyright © 2017 Jeff Linwood. All rights reserved. // import UIKit import Firebase class LoginViewController: BaseViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! func showNewsFeed() { let storyboard = UIStoryboard.init(name: "NewsFeed", bundle: nil) if let vc = storyboard.instantiateInitialViewController() { present(vc, animated: false, completion: nil) } } override func viewWillAppear(_ animated: Bool) { if let auth = FIRAuth.auth() { if auth.currentUser != nil { showNewsFeed() } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(_ sender: Any) { if (emailTextField.text == "") { showErrorMessage(errorMessage:"Email can not be blank.") return } if (passwordTextField.text == "") { showErrorMessage(errorMessage:"Password can not be blank.") return } let email = emailTextField.text! let password = passwordTextField.text! if let auth = FIRAuth.auth() { auth.signIn(withEmail: email, password: password, completion: { (user, error) in if let error = error { self.showErrorMessage(errorMessage:error.localizedDescription) return } else { self.showNewsFeed() } }) } } }
mit
33b886652236b383ce30d7122859d287
25.12
92
0.554875
5.381868
false
false
false
false
grzegorzleszek/algorithms-swift
Sources/Sort.swift
1
3448
// // GraphTests.swift // // Copyright © 2018 Grzegorz.Leszek. 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. func mergeSort(elements: [Int]) -> [Int] { if (elements.count <= 1) { return elements } var left = [Int]() var right = [Int]() for (i, x) in elements.enumerated() { if i < elements.count / 2 { left.append(x) } else { right.append(x) } } left = mergeSort(elements: left) right = mergeSort(elements: right) return merge(left, right) } private func merge(_ left: [Int], _ right: [Int]) -> [Int] { var result = [Int]() var l = left var r = right while !l.isEmpty && !r.isEmpty { if l.first! <= r.first! { result.append(l.first!) l = [Int](l.dropFirst(1)) } else { result.append(r.first!) r = [Int](r.dropFirst(1)) } } while !l.isEmpty { result.append(l.first!) l = [Int](l.dropFirst(1)) } while !r.isEmpty { result.append(r.first!) r = [Int](r.dropFirst(1)) } return result } func quickSort(_ A: inout [Int], _ lo: Int, _ hi: Int) { if lo < hi { let p = partition(&A, lo, hi) quickSort(&A, lo, p - 1 ) quickSort(&A, p + 1, hi) } } private func partition(_ A: inout [Int], _ lo: Int, _ hi: Int) -> Int { let pivot = A[hi] var i = lo - 1 (lo...(hi - 1)).forEach { let j = $0 if A[j] < pivot { i = i + 1 A.swapAt(i, j) } } if A[hi] < A[i + 1] { A.swapAt(i + 1, hi) } return i + 1 } func bucketSort(_ arr: inout [Int], _ n: Int) { var b = [[Int]](repeatElement([Int](), count: n)) (0..<n).forEach { i in let bi = msbits(arr[i], n) b[bi].append(arr[i]) } (0..<n).forEach { i in insertionSort(&b[i]) } var index = 0 (0..<n).forEach { let i = $0 (0..<b[i].count).forEach { j in arr[index] = b[i][j]; index += 1 } } } private func msbits(_ x: Int, _ k: Int) -> Int { return min(abs(x), k - 1) } func insertionSort(_ A: inout [Int]) { var i = 1 while i < A.count { var j = i while j > 0 && A[j-1] > A[j] { A.swapAt(j, j-1) j = j - 1 } i = i + 1 } }
mit
308b6639eb50c5c70c041a349e6e1819
25.515385
80
0.547723
3.492401
false
false
false
false
DavidSkrundz/Lua
Sources/Lua/Value/Number.swift
1
3913
// // Number.swift // Lua // /// Represents a Lua numeric value since Lua does not make a distinction between /// `Int` and `Double` public final class Number { public let intValue: Int public let uintValue: UInt32 public let doubleValue: Double public let isInt: Bool public var hashValue: Int { if self.isInt { return self.intValue.hashValue } return self.doubleValue.hashValue } /// Create a new `Number` by popping the top value from the stack internal init(lua: Lua) { self.intValue = lua.raw.getInt(atIndex: TopIndex)! self.uintValue = lua.raw.getUInt(atIndex: TopIndex)! self.doubleValue = lua.raw.getDouble(atIndex: TopIndex)! lua.raw.pop(1) self.isInt = Double(self.intValue) == self.doubleValue } } extension Number: Equatable, Comparable {} public func ==(lhs: Number, rhs: Number) -> Bool { return lhs.doubleValue == rhs.doubleValue } public func <(lhs: Number, rhs: Number) -> Bool { return lhs.doubleValue < rhs.doubleValue } // Int public func ==(lhs: Number, rhs: Int) -> Bool { return lhs.intValue == rhs } public func !=(lhs: Number, rhs: Int) -> Bool { return lhs.intValue != rhs } public func < (lhs: Number, rhs: Int) -> Bool { return lhs.intValue < rhs } public func > (lhs: Number, rhs: Int) -> Bool { return lhs.intValue > rhs } public func <=(lhs: Number, rhs: Int) -> Bool { return lhs.intValue <= rhs } public func >=(lhs: Number, rhs: Int) -> Bool { return lhs.intValue >= rhs } public func ==(lhs: Int, rhs: Number) -> Bool { return lhs == rhs.intValue } public func !=(lhs: Int, rhs: Number) -> Bool { return lhs != rhs.intValue } public func < (lhs: Int, rhs: Number) -> Bool { return lhs < rhs.intValue } public func > (lhs: Int, rhs: Number) -> Bool { return lhs > rhs.intValue } public func <=(lhs: Int, rhs: Number) -> Bool { return lhs <= rhs.intValue } public func >=(lhs: Int, rhs: Number) -> Bool { return lhs >= rhs.intValue } // UInt32 public func ==(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue == rhs } public func !=(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue != rhs } public func < (lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue < rhs } public func > (lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue > rhs } public func <=(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue <= rhs } public func >=(lhs: Number, rhs: UInt32) -> Bool { return lhs.uintValue >= rhs } public func ==(lhs: UInt32, rhs: Number) -> Bool { return lhs == rhs.uintValue } public func !=(lhs: UInt32, rhs: Number) -> Bool { return lhs != rhs.uintValue } public func < (lhs: UInt32, rhs: Number) -> Bool { return lhs < rhs.uintValue } public func > (lhs: UInt32, rhs: Number) -> Bool { return lhs > rhs.uintValue } public func <=(lhs: UInt32, rhs: Number) -> Bool { return lhs <= rhs.uintValue } public func >=(lhs: UInt32, rhs: Number) -> Bool { return lhs >= rhs.uintValue } // Double public func ==(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue == rhs } public func !=(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue != rhs } public func < (lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue < rhs } public func > (lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue > rhs } public func <=(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue <= rhs } public func >=(lhs: Number, rhs: Double) -> Bool { return lhs.doubleValue >= rhs } public func ==(lhs: Double, rhs: Number) -> Bool { return lhs == rhs.doubleValue } public func !=(lhs: Double, rhs: Number) -> Bool { return lhs != rhs.doubleValue } public func < (lhs: Double, rhs: Number) -> Bool { return lhs < rhs.doubleValue } public func > (lhs: Double, rhs: Number) -> Bool { return lhs > rhs.doubleValue } public func <=(lhs: Double, rhs: Number) -> Bool { return lhs <= rhs.doubleValue } public func >=(lhs: Double, rhs: Number) -> Bool { return lhs >= rhs.doubleValue }
lgpl-3.0
7dc39f2bf5a32083aa41fdcc722221d1
42.966292
82
0.663685
3.456714
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Models/ManagedPerson.swift
1
4437
import Foundation import CoreData import WordPressKit public typealias Person = RemotePerson // MARK: - Reflects a Person, stored in Core Data // class ManagedPerson: NSManagedObject { func updateWith<T: Person>(_ person: T) { let canonicalAvatarURL = person.avatarURL.flatMap { Gravatar($0)?.canonicalURL } avatarURL = canonicalAvatarURL?.absoluteString displayName = person.displayName firstName = person.firstName lastName = person.lastName role = person.role siteID = Int64(person.siteID) userID = Int64(person.ID) linkedUserID = Int64(person.linkedUserID) username = person.username isSuperAdmin = person.isSuperAdmin kind = Int16(type(of: person).kind.rawValue) } func toUnmanaged() -> Person { switch Int(kind) { case PersonKind.user.rawValue: return User(managedPerson: self) case PersonKind.viewer.rawValue: return Viewer(managedPerson: self) case PersonKind.emailFollower.rawValue: return EmailFollower(managedPerson: self) default: return Follower(managedPerson: self) } } } // MARK: - Extensions // extension Person { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: managedPerson.role, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension User { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: managedPerson.role, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension Follower { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: RemoteRole.follower.slug, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension Viewer { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: RemoteRole.viewer.slug, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } } extension EmailFollower { init(managedPerson: ManagedPerson) { self.init(ID: Int(managedPerson.userID), username: managedPerson.username, firstName: managedPerson.firstName, lastName: managedPerson.lastName, displayName: managedPerson.displayName, role: RemoteRole.follower.slug, siteID: Int(managedPerson.siteID), linkedUserID: Int(managedPerson.linkedUserID), avatarURL: managedPerson.avatarURL.flatMap { URL(string: $0) }, isSuperAdmin: managedPerson.isSuperAdmin) } }
gpl-2.0
97cb49edd24ffad5d0b5e205faff4439
37.25
88
0.607167
5.539326
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Reader/Tab Navigation/ReaderTabView.swift
1
13906
import UIKit class ReaderTabView: UIView { private let mainStackView: UIStackView private let buttonsStackView: UIStackView private let tabBar: FilterTabBar private let filterButton: PostMetaButton private let resetFilterButton: UIButton private let horizontalDivider: UIView private let containerView: UIView private var loadingView: UIView? private let viewModel: ReaderTabViewModel private var filteredTabs: [(index: Int, topic: ReaderAbstractTopic)] = [] private var previouslySelectedIndex: Int = 0 private var discoverIndex: Int? { return tabBar.items.firstIndex(where: { ($0 as? ReaderTabItem)?.content.topicType == .discover }) } private var p2Index: Int? { return tabBar.items.firstIndex(where: { (($0 as? ReaderTabItem)?.content.topic as? ReaderTeamTopic)?.organizationID == SiteOrganizationType.p2.rawValue }) } init(viewModel: ReaderTabViewModel) { mainStackView = UIStackView() buttonsStackView = UIStackView() tabBar = FilterTabBar() filterButton = PostMetaButton(type: .custom) resetFilterButton = UIButton(type: .custom) horizontalDivider = UIView() containerView = UIView() self.viewModel = viewModel super.init(frame: .zero) viewModel.didSelectIndex = { [weak self] index in self?.tabBar.setSelectedIndex(index) self?.toggleButtonsView() } viewModel.onTabBarItemsDidChange { [weak self] tabItems, index in self?.tabBar.items = tabItems self?.tabBar.setSelectedIndex(index) self?.configureTabBarElements() self?.hideGhost() self?.addContentToContainerView() } setupViewElements() NotificationCenter.default.addObserver(self, selector: #selector(topicUnfollowed(_:)), name: .ReaderTopicUnfollowed, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(siteFollowed(_:)), name: .ReaderSiteFollowed, object: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UI setup extension ReaderTabView { /// Call this method to set the title of the filter button private func setFilterButtonTitle(_ title: String) { WPStyleGuide.applyReaderFilterButtonTitle(filterButton, title: title) } private func setupViewElements() { backgroundColor = .filterBarBackground setupMainStackView() setupTabBar() setupButtonsView() setupFilterButton() setupResetFilterButton() setupHorizontalDivider(horizontalDivider) activateConstraints() } private func setupMainStackView() { mainStackView.translatesAutoresizingMaskIntoConstraints = false mainStackView.axis = .vertical addSubview(mainStackView) mainStackView.addArrangedSubview(tabBar) mainStackView.addArrangedSubview(buttonsStackView) mainStackView.addArrangedSubview(horizontalDivider) mainStackView.addArrangedSubview(containerView) } private func setupTabBar() { tabBar.tabBarHeight = Appearance.barHeight WPStyleGuide.configureFilterTabBar(tabBar) tabBar.addTarget(self, action: #selector(selectedTabDidChange(_:)), for: .valueChanged) viewModel.fetchReaderMenu() } private func configureTabBarElements() { guard let tabItem = tabBar.currentlySelectedItem as? ReaderTabItem else { return } previouslySelectedIndex = tabBar.selectedIndex buttonsStackView.isHidden = tabItem.shouldHideButtonsView horizontalDivider.isHidden = tabItem.shouldHideButtonsView } private func setupButtonsView() { buttonsStackView.translatesAutoresizingMaskIntoConstraints = false buttonsStackView.isLayoutMarginsRelativeArrangement = true buttonsStackView.axis = .horizontal buttonsStackView.alignment = .fill buttonsStackView.addArrangedSubview(filterButton) buttonsStackView.addArrangedSubview(resetFilterButton) buttonsStackView.isHidden = true } private func setupFilterButton() { filterButton.translatesAutoresizingMaskIntoConstraints = false filterButton.contentEdgeInsets = Appearance.filterButtonInsets filterButton.imageEdgeInsets = Appearance.filterButtonimageInsets filterButton.titleEdgeInsets = Appearance.filterButtonTitleInsets filterButton.contentHorizontalAlignment = .leading filterButton.titleLabel?.font = Appearance.filterButtonFont WPStyleGuide.applyReaderFilterButtonStyle(filterButton) setFilterButtonTitle(Appearance.defaultFilterButtonTitle) filterButton.addTarget(self, action: #selector(didTapFilterButton), for: .touchUpInside) filterButton.accessibilityIdentifier = Accessibility.filterButtonIdentifier } private func setupResetFilterButton() { resetFilterButton.translatesAutoresizingMaskIntoConstraints = false resetFilterButton.contentEdgeInsets = Appearance.resetButtonInsets WPStyleGuide.applyReaderResetFilterButtonStyle(resetFilterButton) resetFilterButton.addTarget(self, action: #selector(didTapResetFilterButton), for: .touchUpInside) resetFilterButton.isHidden = true resetFilterButton.accessibilityIdentifier = Accessibility.resetButtonIdentifier resetFilterButton.accessibilityLabel = Accessibility.resetFilterButtonLabel } private func setupHorizontalDivider(_ divider: UIView) { divider.translatesAutoresizingMaskIntoConstraints = false divider.backgroundColor = Appearance.dividerColor } private func addContentToContainerView() { guard let controller = self.next as? UIViewController, let childController = viewModel.makeChildContentViewController(at: tabBar.selectedIndex) else { return } containerView.translatesAutoresizingMaskIntoConstraints = false childController.view.translatesAutoresizingMaskIntoConstraints = false controller.children.forEach { $0.remove() } controller.add(childController) containerView.pinSubviewToAllEdges(childController.view) if viewModel.shouldShowCommentSpotlight { let title = NSLocalizedString("Comment to start making connections.", comment: "Hint for users to grow their audience by commenting on other blogs.") childController.displayNotice(title: title) } } private func activateConstraints() { pinSubviewToAllEdges(mainStackView) NSLayoutConstraint.activate([ buttonsStackView.heightAnchor.constraint(equalToConstant: Appearance.barHeight), resetFilterButton.widthAnchor.constraint(equalToConstant: Appearance.resetButtonWidth), horizontalDivider.heightAnchor.constraint(equalToConstant: Appearance.dividerWidth), horizontalDivider.widthAnchor.constraint(equalTo: mainStackView.widthAnchor) ]) } func applyFilter(for selectedTopic: ReaderAbstractTopic?) { guard let selectedTopic = selectedTopic else { return } let selectedIndex = self.tabBar.selectedIndex // Remove any filters for selected index, then add new filter to array. self.filteredTabs.removeAll(where: { $0.index == selectedIndex }) self.filteredTabs.append((index: selectedIndex, topic: selectedTopic)) self.resetFilterButton.isHidden = false self.setFilterButtonTitle(selectedTopic.title) } } // MARK: - Actions private extension ReaderTabView { /// Tab bar @objc func selectedTabDidChange(_ tabBar: FilterTabBar) { // If the tab was previously filtered, refilter it. // Otherwise reset the filter. if let existingFilter = filteredTabs.first(where: { $0.index == tabBar.selectedIndex }) { if previouslySelectedIndex == discoverIndex { // Reset the container view to show a feed's content. addContentToContainerView() } viewModel.setFilterContent(topic: existingFilter.topic) resetFilterButton.isHidden = false setFilterButtonTitle(existingFilter.topic.title) } else { addContentToContainerView() } previouslySelectedIndex = tabBar.selectedIndex viewModel.showTab(at: tabBar.selectedIndex) toggleButtonsView() } func toggleButtonsView() { guard let tabItems = tabBar.items as? [ReaderTabItem] else { return } // hide/show buttons depending on the selected tab. Do not execute the animation if not necessary. guard buttonsStackView.isHidden != tabItems[tabBar.selectedIndex].shouldHideButtonsView else { return } let shouldHideButtons = tabItems[self.tabBar.selectedIndex].shouldHideButtonsView self.buttonsStackView.isHidden = shouldHideButtons self.horizontalDivider.isHidden = shouldHideButtons } /// Filter button @objc func didTapFilterButton() { /// Present from the image view to align to the left hand side viewModel.presentFilter(from: filterButton.imageView ?? filterButton) { [weak self] selectedTopic in guard let self = self else { return } self.applyFilter(for: selectedTopic) } } /// Reset filter button @objc func didTapResetFilterButton() { filteredTabs.removeAll(where: { $0.index == tabBar.selectedIndex }) setFilterButtonTitle(Appearance.defaultFilterButtonTitle) resetFilterButton.isHidden = true guard let tabItem = tabBar.currentlySelectedItem as? ReaderTabItem else { return } viewModel.resetFilter(selectedItem: tabItem) } @objc func topicUnfollowed(_ notification: Foundation.Notification) { guard let userInfo = notification.userInfo, let topic = userInfo[ReaderNotificationKeys.topic] as? ReaderAbstractTopic, let existingFilter = filteredTabs.first(where: { $0.topic == topic }) else { return } filteredTabs.removeAll(where: { $0 == existingFilter }) if existingFilter.index == tabBar.selectedIndex { didTapResetFilterButton() } } @objc func siteFollowed(_ notification: Foundation.Notification) { guard let userInfo = notification.userInfo, let site = userInfo[ReaderNotificationKeys.topic] as? ReaderSiteTopic, site.organizationType == .p2, p2Index == nil else { return } // If a P2 is followed but the P2 tab is not in the Reader tab bar, // refresh the Reader menu to display it. viewModel.fetchReaderMenu() } } // MARK: - Ghost private extension ReaderTabView { /// Build the ghost tab bar func makeGhostTabBar() -> FilterTabBar { let ghostTabBar = FilterTabBar() ghostTabBar.items = Appearance.ghostTabItems ghostTabBar.isUserInteractionEnabled = false ghostTabBar.tabBarHeight = Appearance.barHeight ghostTabBar.dividerColor = .clear return ghostTabBar } /// Show the ghost tab bar func showGhost() { let ghostTabBar = makeGhostTabBar() tabBar.addSubview(ghostTabBar) tabBar.pinSubviewToAllEdges(ghostTabBar) loadingView = ghostTabBar ghostTabBar.startGhostAnimation(style: GhostStyle(beatDuration: GhostStyle.Defaults.beatDuration, beatStartColor: .placeholderElement, beatEndColor: .placeholderElementFaded)) } /// Hide the ghost tab bar func hideGhost() { loadingView?.stopGhostAnimation() loadingView?.removeFromSuperview() loadingView = nil } struct GhostTabItem: FilterTabBarItem { var title: String let accessibilityIdentifier = "" } } // MARK: - Appearance private extension ReaderTabView { enum Appearance { static let barHeight: CGFloat = 48 static let tabBarAnimationsDuration = 0.2 static let defaultFilterButtonTitle = NSLocalizedString("Filter", comment: "Title of the filter button in the Reader") static let filterButtonMaxFontSize: CGFloat = 28.0 static let filterButtonFont = WPStyleGuide.fontForTextStyle(.headline, fontWeight: .regular) static let filterButtonInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) static let filterButtonimageInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0) static let filterButtonTitleInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0) static let resetButtonWidth: CGFloat = 32 static let resetButtonInsets = UIEdgeInsets(top: 1, left: -4, bottom: -1, right: 4) static let dividerWidth: CGFloat = .hairlineBorderWidth static let dividerColor: UIColor = .divider // "ghost" titles are set to the default english titles, as they won't be visible anyway static let ghostTabItems = [GhostTabItem(title: "Following"), GhostTabItem(title: "Discover"), GhostTabItem(title: "Likes"), GhostTabItem(title: "Saved")] } } // MARK: - Accessibility extension ReaderTabView { private enum Accessibility { static let filterButtonIdentifier = "ReaderFilterButton" static let resetButtonIdentifier = "ReaderResetButton" static let resetFilterButtonLabel = NSLocalizedString("Reset filter", comment: "Accessibility label for the reset filter button in the reader.") } }
gpl-2.0
93b7f916d92b132ad25e3a3783e36fd0
36.281501
162
0.685388
5.675918
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Index/Index+Settings.swift
1
3685
// // Index+Settings.swift // // // Created by Vladislav Fitc on 03/03/2020. // import Foundation public extension Index { // MARK: - Get Settings /** Get the Settings of an index. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Async operation */ @discardableResult func getSettings(requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<Settings>) -> Operation & TransportTask { let command = Command.Settings.GetSettings(indexName: name, requestOptions: requestOptions) return execute(command, completion: completion) } /** Get the Settings of an index. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Settings object */ func getSettings(requestOptions: RequestOptions? = nil) throws -> Settings { let command = Command.Settings.GetSettings(indexName: name, requestOptions: requestOptions) return try execute(command) } // Set settings /** Create or change an index’s Settings. Only non-null settings are overridden; null settings are left unchanged Performance wise, it’s better to setSettings before pushing the data. - Parameter settings: The Settings to be set. - Parameter resetToDefault: Reset a settings to its default value. - Parameter forwardToReplicas: Whether to forward the same settings to the replica indices. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Async operation */ @discardableResult func setSettings(_ settings: Settings, resetToDefault: [Settings.Key] = [], forwardToReplicas: Bool? = nil, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask { let command = Command.Settings.SetSettings(indexName: name, settings: settings, resetToDefault: resetToDefault, forwardToReplicas: forwardToReplicas, requestOptions: requestOptions) return execute(command, completion: completion) } /** Create or change an index’s Settings. Only non-null settings are overridden; null settings are left unchanged Performance wise, it’s better to setSettings before pushing the data. - Parameter settings: The Settings to be set. - Parameter resetToDefault: Reset a settings to its default value. - Parameter forwardToReplicas: Whether to forward the same settings to the replica indices. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: RevisionIndex object */ @discardableResult func setSettings(_ settings: Settings, resetToDefault: [Settings.Key] = [], forwardToReplicas: Bool? = nil, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> { let command = Command.Settings.SetSettings(indexName: name, settings: settings, resetToDefault: resetToDefault, forwardToReplicas: forwardToReplicas, requestOptions: requestOptions) return try execute(command) } }
mit
73bde5acc74c08c7e00fa379d19036fd
42.77381
125
0.615447
6.138564
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/About/Settings/SettingsViewController.swift
1
5881
// // SettingsViewController.swift // EclipseSoundscapes // // Created by Arlindo Goncalves on 7/18/17. // // Copyright © 2017 Arlindo Goncalves. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see [http://www.gnu.org/licenses/]. // // For Contact email: arlindo@eclipsesoundscapes.org import Eureka import RxSwift import RxCocoa class SettingsViewController: BaseViewController, TypedRowControllerType, UITableViewDelegate, UITableViewDataSource { var row: RowOf<String>! var onDismissCallback: ((UIViewController) -> Void)? lazy var headerView : ShrinkableHeaderView = { let view = ShrinkableHeaderView(title: localizedString(key: "SettingsHeaderTitle"), titleColor: .black) view.backgroundColor = SoundscapesColor.NavBarColor view.maxHeaderHeight = 60 view.isShrinkable = false return view }() lazy var backBtn : UIButton = { var btn = UIButton(type: .system) btn.addSqueeze() btn.setImage(#imageLiteral(resourceName: "left-small").withRenderingMode(.alwaysTemplate), for: .normal) btn.tintColor = .black btn.addTarget(self, action: #selector(close), for: .touchUpInside) btn.accessibilityLabel = localizedString(key: "Back") return btn }() private let tableView = UITableView(frame: .zero, style: .grouped) private let disposeBag = DisposeBag() private let viewModel = SettingsViewModel() override func viewDidLoad() { super.viewDidLoad() setup() } private func setup() { setupViews() setupTableView() setupViewModel() } private func setupViews() { view.backgroundColor = headerView.backgroundColor view.addSubviews(headerView, tableView) headerView.headerHeightConstraint = headerView.anchor(view.safeAreaLayoutGuide.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: headerView.maxHeaderHeight).last headerView.addSubviews(backBtn) backBtn.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true backBtn.leftAnchor.constraint(equalTo: headerView.leftAnchor, constant: 10).isActive = true tableView.anchorWithConstantsToTop(headerView.bottomAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0) } private func setupTableView() { tableView.delegate = self tableView.dataSource = self tableView.register(ToggleCell.self, forCellReuseIdentifier: ToggleCell.identifier) tableView.register(LanguageCell.self, forCellReuseIdentifier: LanguageCell.identifier) tableView.register(TextHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: TextHeaderFooterView.identifier) tableView.tableFooterView = UIView() tableView.estimatedSectionHeaderHeight = 60 } private func setupViewModel() { viewModel.showAlertSignal .emit(to: rx.presentAlert(preferredStyle: .alert)) .disposed(by: disposeBag) } func numberOfSections(in tableView: UITableView) -> Int { return viewModel.sectionCount } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.getSettingsSection(for: section)?.itemCount ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let item = viewModel.getSettingsSection(for: indexPath.section)?.getItem(at: indexPath.row) else { fatalError("No Setting at at indexPath: \(indexPath)") } let cell = tableView.dequeueReusableCell(withIdentifier: item.cellIdentifier, for: indexPath) if let cell = cell as? SettingCell { cell.configure(with: item) } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let section = viewModel.getSettingsSection(for: section) as? SettingsHeaderSection else { return nil } let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: section.headerIdentifier) if let textHeaderSection = section as? SettingTextHeaderSection { guard let textHeader = view as? TextHeaderFooterView else { return nil } textHeader.configure(with: textHeaderSection.headerText) } return view } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let section = viewModel.getSettingsSection(for: section) as? SettingsFooterSection else { return nil } let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: section.footerIdentifier) if let textFooterSection = section as? SettingTextFooterSection { guard let textHeader = view as? TextHeaderFooterView else { return nil } textHeader.configure(with: textFooterSection.footerText) } return view } @objc private func close() { self.dismiss(animated: true, completion: nil) } }
gpl-3.0
9c5e7e416611fdfc7c7fb6b822c248a5
39.833333
295
0.702891
5.113043
false
false
false
false
GermanCentralLibraryForTheBlind/LargePrintMusicNotes
LargePrintMusicNotesViewer/AppDelegate.swift
1
7478
// Created by Lars Voigt. // //The MIT License (MIT) //Copyright (c) 2016 German Central Library for the Blind (DZB) //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL //THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white] UIBarButtonItem.appearance().tintColor = UIColor.white UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().tintColor = UIColor.white return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "de.lv.LargePrintMusicNotesViewer" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "LargePrintMusicNotesViewer", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
07c17e3953c3f7b533e171614827fbcc
56.083969
291
0.728136
5.708397
false
false
false
false
finder39/Swimgur
SWNetworking/Comment.swift
1
1981
// // Comment.swift // Swimgur // // Created by Joseph Neuman on 11/2/14. // Copyright (c) 2014 Joseph Neuman. All rights reserved. // import Foundation public class Comment { public var id: Int! public var imageID: String? public var comment: String? public var author: String? public var authorID: String? public var onAlbum: Bool? public var albumCover: String? public var ups: Int? public var downs: Int? public var points: Int? public var datetime: Int = 0 public var parentID: String? public var deleted: Bool? public var vote: String? public var children: [Comment] = [] // expansion management in table public var expanded = false public var depth = 0 public init(dictionary:Dictionary<String, AnyObject>, depth theDepth:Int) { id = dictionary["id"] as AnyObject! as Int! imageID = dictionary["image_id"] as AnyObject? as? String comment = dictionary["comment"] as AnyObject? as? String author = dictionary["author"] as AnyObject? as? String authorID = dictionary["author_id"] as AnyObject? as? String onAlbum = dictionary["on_album"] as AnyObject? as? Bool albumCover = dictionary["album_cover"] as AnyObject? as? String ups = dictionary["ups"] as AnyObject? as? Int downs = dictionary["downs"] as AnyObject? as? Int points = dictionary["points"] as AnyObject? as? Int datetime = dictionary["datetime"] as AnyObject! as Int! parentID = dictionary["parent_id"] as AnyObject? as? String deleted = dictionary["deleted"] as AnyObject? as? Bool vote = dictionary["vote"] as AnyObject? as? String depth = theDepth if let children = (dictionary["children"] as AnyObject?) as? [Dictionary<String, AnyObject>] { for child in children { self.children.append(Comment(dictionary: child, depth:depth+1)) } } } public convenience init(dictionary:Dictionary<String, AnyObject>) { self.init(dictionary: dictionary, depth:0) } }
mit
efa9fb59ed2a84fdfc0f69a216b63706
32.033333
98
0.684503
4.042857
false
false
false
false
Kiandr/CrackingCodingInterview
Swift/Ch 15. Threads and Locks/Ch 15. Threads and Locks.playground/Pages/15.3 Dining Philoslophers.xcplaygroundpage/Contents.swift
1
4725
import Foundation /*: 15.3 Dining Philosophers: In the famouse dining philosophers problem, a bunch of philosophers are sitting around a circular table with one chopstick between them. A philosopher needs both chopsticks to eat and always picks up the left chopstick before the right one. A deadlock could potentially occur if all of the philosophers reached for the left chopstick at the same time. Using threads and locks, implement a simulation of the dining philosophers problem that prevents deadlock. */ struct Fork { let number: Int fileprivate var _state = State.Initial let serialQueue = DispatchQueue(label: "Fork") enum State { case Initial case InUse case Free } init(number: Int) { self.number = number } } extension Fork: CustomStringConvertible { var state: State { get { var state = State.Initial serialQueue.sync { state = self._state } return state } set(newState) { serialQueue.sync { self._state = newState } } } var description: String { return "fork \(number) state \(state)" } } final class PhilosopherOp: Operation { let philosopher: String fileprivate(set) var _state = State.Initial fileprivate(set) var left: Fork fileprivate(set) var right: Fork fileprivate let serialQueue = DispatchQueue(label: "Operation") enum State { case Initial case Thinking case Eating } init(name: String, left: Fork, right: Fork) { self.philosopher = name self.left = left self.right = right } } extension PhilosopherOp { func usLeft() { left.state = .InUse updateState() } func useRight() { right.state = .InUse updateState() } func useBoth() { left.state = .InUse right.state = .InUse updateState() } func wait() { right.state = .Free left.state = .Free updateState() } private func updateState() { guard case left.state = Fork.State.InUse, case right.state = Fork.State.InUse else { return state = .Thinking } state = .Eating } override var isExecuting: Bool { return _state == .Eating } override var isFinished: Bool { return false } fileprivate var state: State { get { var state = State.Initial serialQueue.sync { state = self._state } return state } set(newState) { serialQueue.sync { self._state = newState } } } override var description: String { return "\(philosopher): state = \(state) left = \(left), right = \(right)" } } func runPhilosophers(philosophers: [PhilosopherOp], forks: [Fork]) { precondition(forks.count == philosophers.count, "number of forks must equal number of philosophers") let operationQueue = OperationQueue() operationQueue.maxConcurrentOperationCount = forks.count / 2 operationQueue.addOperations(philosophers, waitUntilFinished: false) var philosophers = philosophers var eatingPhilosphers = [PhilosopherOp]() let useRight: (PhilosopherOp) -> () = { p in p.useRight() } let useLeft: (PhilosopherOp) -> () = { p in p.usLeft() } let useBoth: (PhilosopherOp) -> () = { p in p.useBoth() } let wait: (PhilosopherOp) -> () = { p in p.wait() } let funcs = [useRight, useLeft, wait, useBoth, wait] for _ in 0..<forks.count { eatingPhilosphers.forEach { p in p.wait() } eatingPhilosphers.removeAll() funcs.enumerated().forEach { i, f in f(philosophers[i]) } philosophers.forEach { p in if p.state == .Eating { eatingPhilosphers.append(p) } } philosophers.forEach { p in print("\(p)") } let p = philosophers.remove(at: 0) philosophers.append(p) } } let forkCount = 5 var forks = (0..<forkCount).map { Fork(number: $0) } var philosopherNames = ["b", "c", "d", "e"] let firstPhilosopher = PhilosopherOp(name: "a", left: forks[0], right: forks.last!) var philosophers = [firstPhilosopher] for (i, _) in philosopherNames.enumerated() { let philosopher = PhilosopherOp(name: philosopherNames[i], left: forks[i + 1], right: forks[i]) philosophers.append(philosopher) } runPhilosophers(philosophers: philosophers, forks: forks)
mit
559279566cc01df00f28d4bab6e187aa
26.155172
486
0.584762
4.470199
false
false
false
false
milseman/swift
stdlib/public/core/Zip.swift
8
5446
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// Creates a sequence of pairs built out of two underlying sequences. /// /// In the `Zip2Sequence` instance returned by this function, the elements of /// the *i*th pair are the *i*th elements of each underlying sequence. The /// following example uses the `zip(_:_:)` function to iterate over an array /// of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" /// /// If the two sequences passed to `zip(_:_:)` are different lengths, the /// resulting sequence is the same length as the shorter sequence. In this /// example, the resulting array is the same length as `words`: /// /// let naturalNumbers = 1...Int.max /// let zipped = Array(zip(words, naturalNumbers)) /// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)] /// /// - Parameters: /// - sequence1: The first sequence or collection to zip. /// - sequence2: The second sequence or collection to zip. /// - Returns: A sequence of tuple pairs, where the elements of each pair are /// corresponding elements of `sequence1` and `sequence2`. public func zip<Sequence1, Sequence2>( _ sequence1: Sequence1, _ sequence2: Sequence2 ) -> Zip2Sequence<Sequence1, Sequence2> { return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2) } /// An iterator for `Zip2Sequence`. public struct Zip2Iterator< Iterator1 : IteratorProtocol, Iterator2 : IteratorProtocol > : IteratorProtocol { /// The type of element returned by `next()`. public typealias Element = (Iterator1.Element, Iterator2.Element) /// Creates an instance around a pair of underlying iterators. internal init(_ iterator1: Iterator1, _ iterator2: Iterator2) { (_baseStream1, _baseStream2) = (iterator1, iterator2) } /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. public mutating func next() -> Element? { // The next() function needs to track if it has reached the end. If we // didn't, and the first sequence is longer than the second, then when we // have already exhausted the second sequence, on every subsequent call to // next() we would consume and discard one additional element from the // first sequence, even though next() had already returned nil. if _reachedEnd { return nil } guard let element1 = _baseStream1.next(), let element2 = _baseStream2.next() else { _reachedEnd = true return nil } return (element1, element2) } internal var _baseStream1: Iterator1 internal var _baseStream2: Iterator2 internal var _reachedEnd: Bool = false } /// A sequence of pairs built out of two underlying sequences. /// /// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th /// elements of each underlying sequence. To create a `Zip2Sequence` instance, /// use the `zip(_:_:)` function. /// /// The following example uses the `zip(_:_:)` function to iterate over an /// array of strings and a countable range at the same time: /// /// let words = ["one", "two", "three", "four"] /// let numbers = 1...4 /// /// for (word, number) in zip(words, numbers) { /// print("\(word): \(number)") /// } /// // Prints "one: 1" /// // Prints "two: 2 /// // Prints "three: 3" /// // Prints "four: 4" public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> : Sequence { @available(*, deprecated, renamed: "Sequence1.Iterator") public typealias Stream1 = Sequence1.Iterator @available(*, deprecated, renamed: "Sequence2.Iterator") public typealias Stream2 = Sequence2.Iterator /// A type whose instances can produce the elements of this /// sequence, in order. public typealias Iterator = Zip2Iterator<Sequence1.Iterator, Sequence2.Iterator> @available(*, unavailable, renamed: "Iterator") public typealias Generator = Iterator /// Creates an instance that makes pairs of elements from `sequence1` and /// `sequence2`. public // @testable init(_sequence1 sequence1: Sequence1, _sequence2 sequence2: Sequence2) { (_sequence1, _sequence2) = (sequence1, sequence2) } /// Returns an iterator over the elements of this sequence. public func makeIterator() -> Iterator { return Iterator( _sequence1.makeIterator(), _sequence2.makeIterator()) } internal let _sequence1: Sequence1 internal let _sequence2: Sequence2 } extension Zip2Sequence { @available(*, unavailable, message: "use zip(_:_:) free function instead") public init(_ sequence1: Sequence1, _ sequence2: Sequence2) { Builtin.unreachable() } }
apache-2.0
ef7bb373cfad3ae99b887ca134ef7f4e
35.550336
82
0.648366
4.073298
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ElegantPresentationController.swift
2
6274
// // ElegantPresentation.swift // TwitterPresentationController // // Created by Kyle Bashour on 2/21/16. // Copyright © 2016 Kyle Bashour. All rights reserved. // import UIKit typealias CoordinatedAnimation = UIViewControllerTransitionCoordinatorContext? -> Void class ElegantPresentationController: UIPresentationController { // MARK: - Properties /// Dims the presenting view controller, if option is set private lazy var dimmingView: UIView = { let view = UIView() view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5) view.alpha = 0 view.userInteractionEnabled = false return view }() /// For dismissing on tap if option is set private lazy var recognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("dismiss:")) /// An options struct containing the customization options set private let options: PresentationOptions // MARK: - Lifecycle /** Initializes and returns a presentation controller for transitioning between the specified view controllers - parameter presentedViewController: The view controller being presented modally. - parameter presentingViewController: The view controller whose content represents the starting point of the transition. - parameter options: An options struct for customizing the appearance and behavior of the presentation. - returns: An initialized presentation controller object. */ init(presentedViewController: UIViewController, presentingViewController: UIViewController, options: PresentationOptions) { self.options = options super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController) } // MARK: - Presenting and dismissing override func presentationTransitionWillBegin() { // If the option is set, then add the gesture recognizer for dismissal to the container if options.dimmingViewTapDismisses { containerView!.addGestureRecognizer(recognizer) } // Prepare and position the dimming view dimmingView.alpha = 0 dimmingView.frame = containerView!.bounds containerView?.insertSubview(dimmingView, atIndex: 0) // Animate these properties with the transtion coordinator if possible let animations: CoordinatedAnimation = { [unowned self] _ in self.dimmingView.alpha = self.options.dimmingViewAlpha self.presentingViewController.view.transform = self.options.presentingTransform } transtionWithCoordinator(animations) } override func dismissalTransitionWillBegin() { // Animate these properties with the transtion coordinator if possible let animations: CoordinatedAnimation = { [unowned self] _ in self.dimmingView.alpha = 0 self.presentingViewController.view.transform = CGAffineTransformIdentity } transtionWithCoordinator(animations) } // MARK: - Adaptation override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { /* There's a bug when rotating that makes the presented view controller permanently larger or smaller if this isn't here. I'm probably doing something wrong :P It jumps because it's not in the animation block, but isn't noticiable unless in slow-mo. Placing it in the animation block does not fix the issue, so here it is. */ presentingViewController.view.transform = CGAffineTransformIdentity // Animate these with the coordinator let animations: CoordinatedAnimation = { [unowned self] _ in self.dimmingView.frame = self.containerView!.bounds self.presentingViewController.view.transform = self.options.presentingTransform self.presentedView()?.frame = self.frameOfPresentedViewInContainerView() } coordinator.animateAlongsideTransition(animations, completion: nil) } override func sizeForChildContentContainer(container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { // Percent height doesn't make sense as a negative value or greater than zero, so we'll enforce it let percentHeight = min(abs(options.presentedPercentHeight), 1) // Return the appropiate height based on which option is set if options.usePercentHeight { return CGSize(width: parentSize.width, height: parentSize.height * CGFloat(percentHeight)) } else if options.presentedHeight > 0 { return CGSize(width: parentSize.width, height: options.presentedHeight) } return parentSize } override func frameOfPresentedViewInContainerView() -> CGRect { // Grab the parent and child sizes let parentSize = containerView!.bounds.size let childSize = sizeForChildContentContainer(presentedViewController, withParentContainerSize: parentSize) // Create and return an appropiate frame return CGRect(x: 0, y: parentSize.height - childSize.height, width: childSize.width, height: childSize.height) } // MARK: - Helper functions // For the tap-to-dismiss func dismiss(sender: UITapGestureRecognizer) { presentedViewController.dismissViewControllerAnimated(true, completion: nil) } /* I noticed myself doing this a lot (more so in earlier versions) so I made a quick function. Simply takes a closure with animations in them and attempts to animate with the coordinator. */ private func transtionWithCoordinator(animations: CoordinatedAnimation) { if let coordinator = presentingViewController.transitionCoordinator() { coordinator.animateAlongsideTransition(animations, completion: nil) } else { animations(nil) } } }
agpl-3.0
54f8bb8ae27afdbf2e293419dfe633e9
38.708861
136
0.682927
6.037536
false
false
false
false
milseman/swift
test/TypeCoercion/overload_noncall.swift
9
1937
// RUN: %target-typecheck-verify-swift struct X { } struct Y { } struct Z { } func f0(_ x1: X, x2: X) -> X {} // expected-note{{found this candidate}} func f0(_ y1: Y, y2: Y) -> Y {} // expected-note{{found this candidate}} var f0 : X // expected-note {{found this candidate}} expected-note {{'f0' previously declared here}} func f0_init(_ x: X, y: Y) -> X {} var f0 : (_ x : X, _ y : Y) -> X = f0_init // expected-error{{invalid redeclaration}} func f1(_ x: X) -> X {} func f2(_ g: (_ x: X) -> X) -> ((_ y: Y) -> Y) { } func test_conv() { var _ : (_ x1 : X, _ x2 : X) -> X = f0 var _ : (X, X) -> X = f0 var _ : (Y, X) -> X = f0 // expected-error{{ambiguous reference to member 'f0(_:x2:)'}} var _ : (X) -> X = f1 var a7 : (X) -> (X) = f1 var a8 : (_ x2 : X) -> (X) = f1 var a9 : (_ x2 : X) -> ((X)) = f1 a7 = a8 a8 = a9 a9 = a7 var _ : ((X) -> X) -> ((Y) -> Y) = f2 var _ : ((_ x2 : X) -> (X)) -> (((_ y2 : Y) -> (Y))) = f2 typealias fp = ((X) -> X) -> ((Y) -> Y) var _ = f2 } var xy : X // expected-note {{previously declared here}} var xy : Y // expected-error {{invalid redeclaration of 'xy'}} func accept_X(_ x: inout X) { } func accept_XY(_ x: inout X) -> X { } func accept_XY(_ y: inout Y) -> Y { } func accept_Z(_ z: inout Z) -> Z { } func test_inout() { var x : X accept_X(&x); accept_X(xy); // expected-error{{passing value of type 'X' to an inout parameter requires explicit '&'}} {{12-12=&}} accept_X(&xy); _ = accept_XY(&x); x = accept_XY(&xy); x = xy x = &xy; // expected-error{{cannot assign value of type 'inout X' to type 'X'}} accept_Z(&xy); // expected-error{{cannot convert value of type 'X' to expected argument type 'Z'}} } func lvalue_or_rvalue(_ x: inout X) -> X { } func lvalue_or_rvalue(_ x: X) -> Y { } func test_lvalue_or_rvalue() { var x : X var y : Y let x1 = lvalue_or_rvalue(&x) x = x1 let y1 = lvalue_or_rvalue(x) y = y1 _ = y }
apache-2.0
45e7053d57d4043dc547a62154f2e4da
26.671429
118
0.52349
2.596515
false
false
false
false
jboullianne/EndlessTunes
EndlessSoundFeed/ETEvent.swift
1
2133
// // ETEvent.swift // EndlessSoundFeed // // Created by Jean-Marc Boullianne on 6/18/17. // Copyright © 2017 Jean-Marc Boullianne. All rights reserved. // import Foundation class ETEvent { var type:ETEventType var author:String var authorUID:String var track:Track? var playlist:Playlist? var follower:String? var followerUID:String? var date:Date init(type: ETEventType, author:String, authorUID:String, date:Date) { self.type = type self.author = author self.authorUID = authorUID self.date = date } } extension ETEvent { var dateString:String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz" return dateFormatter.string(from: self.date) } static func getDateFromString(dateString: String) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzz" return dateFormatter.date(from: dateString)! } func timeStringFromNow() -> String { let dateInterval = DateInterval(start: self.date, end: Date()) let difference = dateInterval.duration let minutes = Int(difference.divided(by: 60)) let hours = Int(difference.divided(by: 3600)) let days = Int(difference.divided(by: 86400)) if(days > 1){ return "\(days) days ago" }else if (days == 1){ return "Yesterday" }else if(hours == 1){ return "1 hour ago" }else if(hours > 1){ return "\(hours) hours ago" }else if(minutes > 1){ return "\(minutes) minutes ago" } return "Just Now" } } enum ETEventType { case SharedPlaylist case CreatedPlaylist case Activity func toString() -> String{ switch self { case .Activity: return "Activity" case .CreatedPlaylist: return "Created Playlist" case .SharedPlaylist: return "Shared Playlist" } } }
gpl-3.0
29ded3bc4628a2fe9ada11c092357e79
23.790698
73
0.582083
4.333333
false
false
false
false
P0ed/Fx
Sources/Fx/Reactive/Disposable.swift
1
3989
/// Represents something that can be “disposed,” usually associated with freeing /// resources or canceling work. public protocol Disposable: AnyObject { func dispose() } /// A disposable that will not dispose on deinit public final class ManualDisposable: Disposable { private let action: Atomic<(() -> Void)?> /// Initializes the disposable to run the given action upon disposal. public init(action: @escaping () -> Void) { self.action = Atomic(action) } public func dispose() { let oldAction = action.swap(nil) oldAction?() } } /// A disposable that will run an action upon disposal. Disposes on deinit. public final class ActionDisposable: Disposable { private let manualDisposable: ManualDisposable /// Initializes the disposable to run the given action upon disposal. public init(action: @escaping () -> Void) { manualDisposable = ManualDisposable(action: action) } deinit { dispose() } public func dispose() { manualDisposable.dispose() } } /// A disposable that will dispose of any number of other disposables. Disposes on deinit. public final class CompositeDisposable: Disposable { private let disposables: Atomic<Bag<Disposable>> /// Initializes a CompositeDisposable containing the given sequence of /// disposables. public init<S: Sequence>(_ disposables: S) where S.Iterator.Element == Disposable { var bag: Bag<Disposable> = Bag() for disposable in disposables { _ = bag.insert(disposable) } self.disposables = Atomic(bag) } /// Initializes an empty CompositeDisposable. public convenience init() { self.init([]) } deinit { dispose() } public func dispose() { let ds = disposables.swap(Bag()) for d in ds.reversed() { d.dispose() } } /// Adds the given disposable to the list, then returns a handle which can /// be used to opaquely remove the disposable later (if desired). public func addDisposable(_ disposable: Disposable) -> ManualDisposable { var token: RemovalToken! disposables.modify { token = $0.insert(disposable) } return ManualDisposable { [weak self] in self?.disposables.modify { $0.removeValueForToken(token) } } } /// Adds the right-hand-side disposable to the left-hand-side /// `CompositeDisposable`. /// /// disposable += producer /// .filter { ... } /// .map { ... } /// .start(observer) /// @discardableResult public static func +=(lhs: CompositeDisposable, rhs: Disposable) -> ManualDisposable { lhs.addDisposable(rhs) } @discardableResult public static func += (disposable: CompositeDisposable, action: @escaping () -> Void) -> ManualDisposable { disposable += ActionDisposable(action: action) } @discardableResult public func capture(_ object: Any) -> ManualDisposable { self += { Fx.capture(object) } } } /// A disposable that will optionally dispose of another disposable. Disposes on deinit. public final class SerialDisposable: Disposable { private let atomicDisposable = Atomic(Disposable?.none) /// The inner disposable to dispose of. /// /// Whenever this property is set (even to the same value!), the previous /// disposable is automatically disposed. public var innerDisposable: Disposable? { get { atomicDisposable.value } set { let oldDisposable = atomicDisposable.swap(newValue) oldDisposable?.dispose() } } /// Initializes the receiver to dispose of the argument when the /// SerialDisposable is disposed. public init(_ disposable: Disposable? = nil) { innerDisposable = disposable } deinit { dispose() } public func dispose() { innerDisposable = nil } } public extension ManualDisposable { static func • (lhs: ManualDisposable, rhs: ManualDisposable) -> ManualDisposable { ManualDisposable(action: lhs.dispose • rhs.dispose) } } public extension ActionDisposable { static func • (lhs: ActionDisposable, rhs: ActionDisposable) -> ActionDisposable { ActionDisposable(action: lhs.dispose • rhs.dispose) } }
mit
1d5cf99bbc39c9823b68b3a41745fbd8
24.49359
108
0.708323
3.965105
false
false
false
false
TheAppCookbook/MiseEnPlace
Source/KeyboardLayoutConstraint.swift
1
2497
// // KeyboardLayoutConstraint.swift // MiseEnPlace // // Inspired by James Tang's work with Spring. // // Created by PATRICK PERINI on 9/12/15. // Copyright © 2015 pcperini. All rights reserved. // import UIKit public class KeyboardLayoutConstraint: NSLayoutConstraint { // MARK: Properties private var offset: CGFloat = 0.0 private var keyboardHeight: CGFloat = 0.0 { didSet { self.constant = self.offset + self.keyboardHeight } } // MARK: Mutators private func updateKeyboardHeight(userInfo: NSDictionary) { if let frameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue { let frame = frameValue.CGRectValue() self.keyboardHeight = frame.height } else { self.keyboardHeight = 0.0 } if let durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber, let curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber { let options = UIViewAnimationOptions(rawValue: curveValue.unsignedLongValue) let duration = NSTimeInterval(durationValue.doubleValue) UIView.animateWithDuration(duration, delay: 0, options: options, animations: { () -> Void in UIApplication.sharedApplication().keyWindow?.layoutIfNeeded() }, completion: nil) } } // MARK: Lifecycle public override func awakeFromNib() { super.awakeFromNib() self.offset = self.constant NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Responders func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo else { return } self.updateKeyboardHeight(userInfo) } func keyboardWillHide(notification: NSNotification) { guard var userInfo = notification.userInfo else { return } userInfo.removeValueForKey(UIKeyboardFrameEndUserInfoKey) self.updateKeyboardHeight(userInfo) } }
mit
816457207692d958968b2c4352b79f02
33.191781
108
0.643029
5.685649
false
false
false
false
jam891/BFKit-Swift
Source/BFKit/BFLog.swift
3
3269
// // BFLog.swift // BFKit // // The MIT License (MIT) // // Copyright (c) 2015 Fabrizio Brancati. 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 UIKit // MARK: - Global variables - /// Use this variable to activate or deactivate the BFLog function public var BFLogActive: Bool = true // MARK: - Global functions - /** Exented NSLog :param: message Console message :param: filename File :param: function Function name :param: line Line number */ public func BFLog(var message: String, filename: String = __FILE__, function: String = __FUNCTION__, line: Int = __LINE__) { if BFLogActive { if message.hasSuffix("\n") == false { message += "\n" } BFLogClass.logString += message let filenameNoExt = NSString(UTF8String: filename)!.lastPathComponent.stringByDeletingPathExtension let log = "(\(function)) (\(filenameNoExt):\(line) \(message)" let timestamp = NSDate.dateInformationDescriptionWithInformation(NSDate().dateInformation(), dateSeparator: "-", usFormat: true, nanosecond: true) print("\(timestamp) \(filenameNoExt):\(line) \(function): \(message)") BFLogClass.detailedLogString += log } } /// Get the log string public var BFLogString: String { if BFLogActive { return BFLogClass.logString } else { return "" } } /// Get the detailed log string public var BFDetailedLogString: String { if BFLogActive { return BFLogClass.detailedLogString } else { return "" } } /** Clear the log string */ public func BFLogClear() { if BFLogActive { BFLogClass.clearLog() } } /// The private BFLogClass created to manage the log strings private class BFLogClass { // MARK: - Variables - /// The log string private static var logString: String = "" /// The detailed log string private static var detailedLogString: String = "" // MARK: - Class functions - /** Private, clear the log string */ private static func clearLog() { logString = "" detailedLogString = "" } }
mit
a8d00f77c56e71a0bf00b2df74874d30
25.795082
154
0.664117
4.411606
false
false
false
false
michalkonturek/MKUnits
MKUnits/Classes/Unit.swift
1
6595
// // Unit.swift // MKUnits // // Copyright (c) 2016 Michal Konturek <michal.konturek@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /** Represents an `unit of measurement`. - author: Michal Konturek */ open class Unit { open let name: String open let symbol: String open let ratio: NSDecimalNumber /** Instantiates an `Unit` object. - parameter name: `unit name`. - parameter symbol: `unit symbol`. - parameter ratio: conversion ratio to a `base unit`. - author: Michal Konturek */ public init(name: String, symbol: String, ratio: NSNumber) { self.name = name self.symbol = symbol self.ratio = NSDecimalNumber(decimal: ratio.decimalValue) } /** Converts given `amount` from `base unit` to `this unit`. - parameter amount: `amount` in `base unit`. - returns: `amount` converted to `this unit`. - author: Michal Konturek */ open func convertFromBaseUnit(_ amount: NSNumber) -> NSNumber { let converted = NSDecimalNumber(decimal: amount.decimalValue) return converted.dividing(by: self.ratio) } /** Converts given `amount` from `this unit` to `base unit`. - parameter amount: `amount` in `this unit`. - returns: `amount` converted to `base unit`. - author: Michal Konturek */ open func convertToBaseUnit(_ amount: NSNumber) -> NSNumber { let converted = NSDecimalNumber(decimal: amount.decimalValue) return converted.multiplying(by: self.ratio) } } // MARK: - CustomStringConvertible extension Unit: CustomStringConvertible { public var description: String { return self.symbol } } // MARK: - UnitConvertible /** A type with ability to convert between units. - author: Michal Konturek */ public protocol UnitConvertible { /** Converts `amount` from `this unit` to `destination unit`. - parameter amount: `amount` in `this unit`. - parameter to: `destination unit`. - returns: `amount` converted to `destination unit`. - author: Michal Konturek */ func convert(_ amount: NSNumber, to: Unit) -> NSNumber /** Converts `amount` from `source unit` to `this unit`. - parameter amount: `amount` in `source unit`. - parameter from: `source unit`. - returns: `amount` converted from `source unit` to `this unit`. - author: Michal Konturek */ func convert(_ amount: NSNumber, from: Unit) -> NSNumber /** Converts `amount` from `source unit` to `destination unit`. - parameter amount: `amount` in `source unit`. - parameter from: `source unit`. - parameter to: `destination unit`. - returns: `amount` converted from `source unit` to `destination unit`. - author: Michal Konturek */ func convert(_ amount: NSNumber, from: Unit, to: Unit) -> NSNumber /** Returns `true` if `this unit` is convertible with `other unit`. - parameter with: `other unit` to compare with. - author: Michal Konturek */ func isConvertible(_ with: Unit) -> Bool } extension Unit: UnitConvertible { /** Converts `amount` from `this unit` to `destination unit`. - parameter amount: `amount` in `this unit`. - parameter to: `destination unit`. - returns: `amount` converted to `destination unit`. - author: Michal Konturek */ public func convert(_ amount: NSNumber, to: Unit) -> NSNumber { return self.convert(amount, from: self, to: to) } /** Converts `amount` from `source unit` to `this unit`. - parameter amount: `amount` in `source unit`. - parameter from: `source unit`. - returns: `amount` converted from `source unit` to `this unit`. - author: Michal Konturek */ public func convert(_ amount: NSNumber, from: Unit) -> NSNumber { return self.convert(amount, from: from, to: self) } /** Converts `amount` from `source unit` to `destination unit`. - parameter amount: `amount` in `source unit`. - parameter from: `source unit`. - parameter to: `destination unit`. - returns: `amount` converted from `source unit` to `destination unit`. - author: Michal Konturek */ public func convert(_ amount: NSNumber, from: Unit, to: Unit) -> NSNumber { let baseAmount = from.convertToBaseUnit(amount) let converted = to.convertFromBaseUnit(baseAmount) return converted } /** Returns `true` if `this unit` is convertible with `other unit`. - parameter with: `other unit` to compare with. - author: Michal Konturek */ public func isConvertible(_ with: Unit) -> Bool { return type(of: with) == type(of: self) } } // MARK: - Equatable extension Unit: Equatable { /** Returns `true` if `this unit` is the same as `other unit`. - important: Comparison is done on `type` and `unit symbol`. - parameter other: `other unit` to compare with. - author: Michal Konturek */ public func equals(_ other: Unit) -> Bool { if type(of: other) !== type(of: self) { return false } return self.symbol == other.symbol } } public func == <T>(lhs: T, rhs: T) -> Bool where T: Unit { return lhs.equals(rhs) }
mit
5387c60b65233c815d678f7702d277b9
28.052863
81
0.626535
4.361772
false
false
false
false
nathawes/swift
test/SILGen/generic_closures.swift
8
15391
// RUN: %target-swift-emit-silgen -module-name generic_closures -parse-stdlib %s | %FileCheck %s import Swift var zero: Int // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A21_nondependent_context{{[_0-9a-zA-Z]*}}F func generic_nondependent_context<T>(_ x: T, y: Int) -> Int { func foo() -> Int { return y } func bar() -> Int { return y } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]](%1) // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[BAR:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[BAR_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[BAR]](%1) // CHECK: destroy_value [[BAR_CLOSURE]] let _ = bar // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]] _ = foo() // CHECK: [[BAR:%.*]] = function_ref @$s16generic_closures0A21_nondependent_context{{.*}} : $@convention(thin) (Int) -> Int // CHECK: [[BAR_CLOSURE:%.*]] = apply [[BAR]] // CHECK: [[BAR_CLOSURE]] return bar() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A8_capture{{[_0-9a-zA-Z]*}}F func generic_capture<T>(_ x: T) -> Any.Type { func foo() -> Any.Type { return T.self } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>() // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A8_capture{{.*}} : $@convention(thin) <τ_0_0> () -> @thick Any.Type // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>() // CHECK: return [[FOO_CLOSURE]] return foo() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A13_capture_cast{{[_0-9a-zA-Z]*}}F func generic_capture_cast<T>(_ x: T, y: Any) -> Bool { func foo(_ a: Any) -> Bool { return a is T } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>() // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A13_capture_cast{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed Any) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T>([[ARG:%.*]]) // CHECK: return [[FOO_CLOSURE]] return foo(y) } protocol Concept { var sensical: Bool { get } } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A22_nocapture_existential{{[_0-9a-zA-Z]*}}F func generic_nocapture_existential<T>(_ x: T, y: Concept) -> Bool { func foo(_ a: Concept) -> Bool { return a.sensical } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = thin_to_thick_function [[FOO]] // CHECK: destroy_value [[FOO_CLOSURE]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A22_nocapture_existential{{.*}} : $@convention(thin) (@in_guaranteed Concept) -> Bool // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]([[ARG:%.*]]) // CHECK: return [[FOO_CLOSURE]] return foo(y) } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures0A18_dependent_context{{[_0-9a-zA-Z]*}}F func generic_dependent_context<T>(_ x: T, y: Int) -> T { func foo() -> T { return x } // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FOO]]<T>([[BOX:%.*]]) // CHECK: [[FOO_CLOSURE_CONV:%.*]] = convert_function [[FOO_CLOSURE]] // CHECK: destroy_value [[FOO_CLOSURE_CONV]] let _ = foo // CHECK: [[FOO:%.*]] = function_ref @$s16generic_closures0A18_dependent_context{{.*}} : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[FOO_CLOSURE:%.*]] = apply [[FOO]]<T> // CHECK: return return foo() } enum Optionable<Wrapped> { case none case some(Wrapped) } class NestedGeneric<U> { class func generic_nondependent_context<T>(_ x: T, y: Int, z: U) -> Int { func foo() -> Int { return y } let _ = foo return foo() } class func generic_dependent_inner_context<T>(_ x: T, y: Int, z: U) -> T { func foo() -> T { return x } let _ = foo return foo() } class func generic_dependent_outer_context<T>(_ x: T, y: Int, z: U) -> U { func foo() -> U { return z } let _ = foo return foo() } class func generic_dependent_both_contexts<T>(_ x: T, y: Int, z: U) -> (T, U) { func foo() -> (T, U) { return (x, z) } let _ = foo return foo() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures13NestedGenericC20nested_reabstraction{{[_0-9a-zA-Z]*}}F // CHECK: [[REABSTRACT:%.*]] = function_ref @$sIeg_ytIegr_TR // CHECK: partial_apply [callee_guaranteed] [[REABSTRACT]] func nested_reabstraction<T>(_ x: T) -> Optionable<() -> ()> { return .some({}) } } // <rdar://problem/15417773> // Ensure that nested closures capture the generic parameters of their nested // context. // CHECK: sil hidden [ossa] @$s16generic_closures018nested_closure_in_A0yxxlF : $@convention(thin) <T> (@in_guaranteed T) -> @out T // CHECK: function_ref [[OUTER_CLOSURE:@\$s16generic_closures018nested_closure_in_A0yxxlFxyXEfU_]] // CHECK: sil private [ossa] [[OUTER_CLOSURE]] : $@convention(thin) <T> (@in_guaranteed T) -> @out T // CHECK: function_ref [[INNER_CLOSURE:@\$s16generic_closures018nested_closure_in_A0yxxlFxyXEfU_xyXEfU_]] // CHECK: sil private [ossa] [[INNER_CLOSURE]] : $@convention(thin) <T> (@in_guaranteed T) -> @out T { func nested_closure_in_generic<T>(_ x:T) -> T { return { { x }() }() } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures16local_properties{{[_0-9a-zA-Z]*}}F func local_properties<T>(_ t: inout T) { var prop: T { get { return t } set { t = newValue } } // CHECK: [[GETTER_REF:%[0-9]+]] = function_ref [[GETTER_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER_REF]] t = prop // CHECK: [[SETTER_REF:%[0-9]+]] = function_ref [[SETTER_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0, @inout_aliasable τ_0_0) -> () // CHECK: apply [[SETTER_REF]] prop = t var prop2: T { get { return t } set { // doesn't capture anything } } // CHECK: [[GETTER2_REF:%[0-9]+]] = function_ref [[GETTER2_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@inout_aliasable τ_0_0) -> @out τ_0_0 // CHECK: apply [[GETTER2_REF]] t = prop2 // CHECK: [[SETTER2_REF:%[0-9]+]] = function_ref [[SETTER2_CLOSURE:@\$s16generic_closures16local_properties[_0-9a-zA-Z]*]] : $@convention(thin) <τ_0_0> (@in τ_0_0) -> () // CHECK: apply [[SETTER2_REF]] prop2 = t } protocol Fooable { static func foo() -> Bool } // <rdar://problem/16399018> func shmassert(_ f: @autoclosure () -> Bool) {} // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures08capture_A6_param{{[_0-9a-zA-Z]*}}F func capture_generic_param<A: Fooable>(_ x: A) { shmassert(A.foo()) } // Make sure we use the correct convention when capturing class-constrained // member types: <rdar://problem/24470533> class Class {} protocol HasClassAssoc { associatedtype Assoc : Class } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlF // CHECK: bb0([[ARG1:%.*]] : $*T, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed @substituted <τ_0_0, τ_0_1 where τ_0_0 : _RefCountedObject, τ_0_1 : _RefCountedObject> (@guaranteed τ_0_0) -> @owned τ_0_1 for <T.Assoc, T.Assoc>): // CHECK: [[GENERIC_FN:%.*]] = function_ref @$s16generic_closures027captures_class_constrained_A0_1fyx_5AssocQzAEctAA08HasClassF0RzlFA2EcycfU_ // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] // CHECK: [[CONCRETE_FN:%.*]] = partial_apply [callee_guaranteed] [[GENERIC_FN]]<T>([[ARG2_COPY]]) func captures_class_constrained_generic<T : HasClassAssoc>(_ x: T, f: @escaping (T.Assoc) -> T.Assoc) { let _: () -> (T.Assoc) -> T.Assoc = { f } } // Make sure local generic functions can have captures // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures06outer_A01t1iyx_SitlF : $@convention(thin) <T> (@in_guaranteed T, Int) -> () func outer_generic<T>(t: T, i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic1<U>(u: U) -> Int { return i } func inner_generic2<U>(u: U) -> T { return t } let _: (()) -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>() : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[THUNK:%.*]] = function_ref @$sytytIegnr_Ieg_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF06inner_A10_nocaptureL_1uqd__qd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0) -> @out τ_1_0 _ = inner_generic_nocapture(u: t) // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>(%1) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$sytSiIegnd_SiIegd_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> Int = inner_generic1 // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic1L_1uSiqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, Int) -> Int _ = inner_generic1(u: t) // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<T, ()>([[ARG:%.*]]) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @$sytxIegnr_xIegr_lTR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]<T>([[CLOSURE]]) // CHECK: [[THUNK_CLOSURE_CONV:%.*]] = convert_function [[THUNK_CLOSURE]] // CHECK: destroy_value [[THUNK_CLOSURE_CONV]] let _: (()) -> T = inner_generic2 // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures06outer_A01t1iyx_SitlF14inner_generic2L_1uxqd___tr__lF : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<T, T>({{.*}}) : $@convention(thin) <τ_0_0><τ_1_0> (@in_guaranteed τ_1_0, @in_guaranteed τ_0_0) -> @out τ_0_0 _ = inner_generic2(u: t) } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures14outer_concrete1iySi_tF : $@convention(thin) (Int) -> () func outer_concrete(i: Int) { func inner_generic_nocapture<U>(u: U) -> U { return u } func inner_generic<U>(u: U) -> Int { return i } // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>() : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[THUNK:%.*]] = function_ref @$sytytIegnr_Ieg_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> () = inner_generic_nocapture // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A10_nocaptureL_1uxx_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> @out τ_0_0 _ = inner_generic_nocapture(u: i) // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[FN]]<()>(%0) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[THUNK:%.*]] = function_ref @$sytSiIegnd_SiIegd_TR // CHECK: [[THUNK_CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[THUNK]]([[CLOSURE]]) // CHECK: destroy_value [[THUNK_CLOSURE]] let _: (()) -> Int = inner_generic // CHECK: [[FN:%.*]] = function_ref @$s16generic_closures14outer_concrete1iySi_tF06inner_A0L_1uSix_tlF : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int // CHECK: [[RESULT:%.*]] = apply [[FN]]<Int>({{.*}}) : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, Int) -> Int _ = inner_generic(u: i) } // CHECK-LABEL: sil hidden [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF : $@convention(thin) <T> (@in_guaranteed T) -> () func mixed_generic_nongeneric_nesting<T>(t: T) { func outer() { func middle<U>(u: U) { func inner() -> U { return u } inner() } middle(u: 11) } outer() } // CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF : $@convention(thin) <T> () -> () // CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> () // CHECK-LABEL: sil private [ossa] @$s16generic_closures06mixed_A19_nongeneric_nesting1tyx_tlF5outerL_yylF6middleL_1uyqd___tr__lF5innerL_qd__yr__lF : $@convention(thin) <T><U> (@in_guaranteed U) -> @out U protocol Doge { associatedtype Nose : NoseProtocol } protocol NoseProtocol { associatedtype Squeegee } protocol Doggo {} struct DogSnacks<A : Doggo> {} func capture_same_type_representative<Daisy: Doge, Roo: Doggo>(slobber: Roo, daisy: Daisy) where Roo == Daisy.Nose.Squeegee { var s = DogSnacks<Daisy.Nose.Squeegee>() _ = { _ = s } }
apache-2.0
127a848483a2feac05ba77a1683fe4ef
44.254438
228
0.615455
2.948911
false
false
false
false
bizz84/SwiftyStoreKit
Sources/SwiftyStoreKit/SwiftyStoreKit.swift
1
18464
// // SwiftyStoreKit.swift // SwiftyStoreKit // // Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import StoreKit public class SwiftyStoreKit { private let productsInfoController: ProductsInfoController fileprivate let paymentQueueController: PaymentQueueController fileprivate let receiptVerificator: InAppReceiptVerificator init(productsInfoController: ProductsInfoController = ProductsInfoController(), paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default()), receiptVerificator: InAppReceiptVerificator = InAppReceiptVerificator()) { self.productsInfoController = productsInfoController self.paymentQueueController = paymentQueueController self.receiptVerificator = receiptVerificator } // MARK: private methods fileprivate func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppProductRequest { return productsInfoController.retrieveProductsInfo(productIds, completion: completion) } fileprivate func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) -> InAppProductRequest { return retrieveProductsInfo(Set([productId])) { result -> Void in if let product = result.retrievedProducts.first { self.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion) } else if let error = result.error { completion(.error(error: SKError(_nsError: error as NSError))) } else if let invalidProductId = result.invalidProductIDs.first { let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ] let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo) completion(.error(error: SKError(_nsError: error))) } else { let error = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: nil) completion(.error(error: SKError(_nsError: error))) } } } fileprivate func purchase(product: SKProduct, quantity: Int, atomically: Bool, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping (PurchaseResult) -> Void) { paymentQueueController.startPayment(Payment(product: product, paymentDiscount: paymentDiscount, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox) { result in completion(self.processPurchaseResult(result)) }) } fileprivate func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) { paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in let results = self.processRestoreResults(results) completion(results) }) } fileprivate func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) { paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion)) } fileprivate func onEntitlementRevocation(completion: @escaping ([String]) -> Void) { paymentQueueController.onEntitlementRevocation(EntitlementRevocation(callback: completion)) } fileprivate func finishTransaction(_ transaction: PaymentTransaction) { paymentQueueController.finishTransaction(transaction) } private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult { switch result { case .purchased(let purchase): return .success(purchase: purchase) case .deferred(let purchase): return .deferred(purchase: purchase) case .failed(let error): return .error(error: error) case .restored(let purchase): return .error(error: storeInternalError(description: "Cannot restore product \(purchase.productId) from purchase path")) } } private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults { var restoredPurchases: [Purchase] = [] var restoreFailedPurchases: [(SKError, String?)] = [] for result in results { switch result { case .purchased(let purchase): let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path") restoreFailedPurchases.append((error, purchase.productId)) case .deferred(let purchase): let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path") restoreFailedPurchases.append((error, purchase.productId)) case .failed(let error): restoreFailedPurchases.append((error, nil)) case .restored(let purchase): restoredPurchases.append(purchase) } } return RestoreResults(restoredPurchases: restoredPurchases, restoreFailedPurchases: restoreFailedPurchases) } private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError { let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ]) return SKError(_nsError: error) } } extension SwiftyStoreKit { // MARK: Singleton fileprivate static let sharedInstance = SwiftyStoreKit() // MARK: Public methods - Purchases /// Check if the current device can make payments. /// - returns: `false` if this device is not able or allowed to make payments public class var canMakePayments: Bool { return SKPaymentQueue.canMakePayments() } /// Retrieve products information /// - Parameter productIds: The set of product identifiers to retrieve corresponding products for /// - Parameter completion: handler for result /// - returns: A cancellable `InAppRequest` object @discardableResult public class func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) -> InAppRequest { return sharedInstance.retrieveProductsInfo(productIds, completion: completion) } /// Purchase a product /// - Parameter productId: productId as specified in App Store Connect /// - Parameter quantity: quantity of the product to be purchased /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately) /// - Parameter applicationUsername: an opaque identifier for the user’s account on your system /// - Parameter completion: handler for result /// - returns: A cancellable `InAppRequest` object @discardableResult public class func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) -> InAppRequest { return sharedInstance.purchaseProduct(productId, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion) } /// Purchase a product /// - Parameter product: product to be purchased /// - Parameter quantity: quantity of the product to be purchased /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately) /// - Parameter applicationUsername: an opaque identifier for the user’s account on your system /// - Parameter product: optional discount to be applied. Must be of `SKProductPayment` type /// - Parameter completion: handler for result public class func purchaseProduct(_ product: SKProduct, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, paymentDiscount: PaymentDiscount? = nil, completion: @escaping ( PurchaseResult) -> Void) { sharedInstance.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, paymentDiscount: paymentDiscount, completion: completion) } /// Restore purchases /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately) /// - Parameter applicationUsername: an opaque identifier for the user’s account on your system /// - Parameter completion: handler for result public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) { sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion) } /// Complete transactions /// - Parameter atomically: whether the product is purchased atomically (e.g. `finishTransaction` is called immediately) /// - Parameter completion: handler for result public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) { sharedInstance.completeTransactions(atomically: atomically, completion: completion) } /// Entitlement revocation notification /// - Parameter completion: handler for result (list of product identifiers revoked) @available(iOS 14, tvOS 14, OSX 11, watchOS 7, macCatalyst 14, *) public class func onEntitlementRevocation(completion: @escaping ([String]) -> Void) { sharedInstance.onEntitlementRevocation(completion: completion) } /// Finish a transaction /// /// Once the content has been delivered, call this method to finish a transaction that was performed non-atomically /// - Parameter transaction: transaction to finish public class func finishTransaction(_ transaction: PaymentTransaction) { sharedInstance.finishTransaction(transaction) } /// Register a handler for `SKPaymentQueue.shouldAddStorePayment` delegate method. /// - requires: iOS 11.0+ public static var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler? { didSet { sharedInstance.paymentQueueController.shouldAddStorePaymentHandler = shouldAddStorePaymentHandler } } /// Register a handler for `paymentQueue(_:updatedDownloads:)` /// - seealso: `paymentQueue(_:updatedDownloads:)` public static var updatedDownloadsHandler: UpdatedDownloadsHandler? { didSet { sharedInstance.paymentQueueController.updatedDownloadsHandler = updatedDownloadsHandler } } public class func start(_ downloads: [SKDownload]) { sharedInstance.paymentQueueController.start(downloads) } public class func pause(_ downloads: [SKDownload]) { sharedInstance.paymentQueueController.pause(downloads) } public class func resume(_ downloads: [SKDownload]) { sharedInstance.paymentQueueController.resume(downloads) } public class func cancel(_ downloads: [SKDownload]) { sharedInstance.paymentQueueController.cancel(downloads) } } extension SwiftyStoreKit { // MARK: Public methods - Receipt verification /// Return receipt data from the application bundle. This is read from `Bundle.main.appStoreReceiptURL`. public static var localReceiptData: Data? { return sharedInstance.receiptVerificator.appStoreReceiptData } /// Verify application receipt /// - Parameter validator: receipt validator to use /// - Parameter forceRefresh: If `true`, refreshes the receipt even if one already exists. /// - Parameter completion: handler for result /// - returns: A cancellable `InAppRequest` object @discardableResult public class func verifyReceipt(using validator: ReceiptValidator, forceRefresh: Bool = false, completion: @escaping (VerifyReceiptResult) -> Void) -> InAppRequest? { return sharedInstance.receiptVerificator.verifyReceipt(using: validator, forceRefresh: forceRefresh, completion: completion) } /// Fetch application receipt /// - Parameter forceRefresh: If true, refreshes the receipt even if one already exists. /// - Parameter completion: handler for result /// - returns: A cancellable `InAppRequest` object @discardableResult public class func fetchReceipt(forceRefresh: Bool, completion: @escaping (FetchReceiptResult) -> Void) -> InAppRequest? { return sharedInstance.receiptVerificator.fetchReceipt(forceRefresh: forceRefresh, completion: completion) } /// Verify the purchase of a Consumable or NonConsumable product in a receipt /// - Parameter productId: the product id of the purchase to verify /// - Parameter inReceipt: the receipt to use for looking up the purchase /// - returns: A `VerifyPurchaseResult`, which may be either `notPurchased` or `purchased`. public class func verifyPurchase(productId: String, inReceipt receipt: ReceiptInfo) -> VerifyPurchaseResult { return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt) } /** * Verify the validity of a subscription (auto-renewable, free or non-renewing) in a receipt. * * This method extracts all transactions matching the given productId and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date to determine its validity. * - Parameter type: `.autoRenewable` or `.nonRenewing`. * - Parameter productId: The product id of the subscription to verify. * - Parameter receipt: The receipt to use for looking up the subscription. * - Parameter validUntil: Date to check against the expiry date of the subscription. This is only used if a date is not found in the receipt. * - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt. */ public class func verifySubscription(ofType type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult { return InAppReceipt.verifySubscriptions(ofType: type, productIds: [productId], inReceipt: receipt, validUntil: date) } /** * Verify the validity of a set of subscriptions in a receipt. * * This method extracts all transactions matching the given productIds and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date, to determine its validity. * - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group. * - Remark: The type parameter determines how the expiration dates are calculated for all subscriptions. Make sure all productIds match the specified subscription type to avoid incorrect results. * - Parameter type: `.autoRenewable` or `.nonRenewing`. * - Parameter productIds: The product IDs of the subscriptions to verify. * - Parameter receipt: The receipt to use for looking up the subscriptions * - Parameter validUntil: Date to check against the expiry date of the subscriptions. This is only used if a date is not found in the receipt. * - returns: Either `.notPurchased` or `.purchased` / `.expired` with the expiry date found in the receipt. */ public class func verifySubscriptions(ofType type: SubscriptionType = .autoRenewable, productIds: Set<String>, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult { return InAppReceipt.verifySubscriptions(ofType: type, productIds: productIds, inReceipt: receipt, validUntil: date) } /// Get the distinct product identifiers from receipt. /// /// This Method extracts all product identifiers. (Including cancelled ones). /// - Note: You can use this method to get all unique product identifiers from receipt. /// - Parameter type: `.autoRenewable` or `.nonRenewing`. /// - Parameter receipt: The receipt to use for looking up product identifiers. /// - returns: Either `Set<String>` or `nil`. public class func getDistinctPurchaseIds(ofType type: SubscriptionType = .autoRenewable, inReceipt receipt: ReceiptInfo) -> Set<String>? { return InAppReceipt.getDistinctPurchaseIds(ofType: type, inReceipt: receipt) } }
mit
46d380d3c2d8a703c0618cea4a1f289a
54.933333
271
0.713512
5.537954
false
false
false
false
sschiau/swift
test/SourceKit/Sema/injected_vfs_after_edit.swift
3
617
func foo(_ structDefinedInSameTarget: StructDefinedInSameTarget) { let _: Double = structDefinedInSameTarget.methodDefinedInSameTarget() // CHECK: cannot convert value of type '()' to specified type 'Double' // CHECK: cannot convert value of type '()' to specified type 'Int' } // RUN: %sourcekitd-test -req=open -vfs-files=/target_file2.swift=%S/../Inputs/vfs/other_file_in_target.swift %s -pass-as-sourcetext -- %s /target_file2.swift -target %target-triple == \ // RUN: -req=print-diags %s == \ // RUN: -req=edit %s -pos=2:12 -length=6 -replace='Int' == \ // RUN: -req=print-diags %s | %FileCheck %s
apache-2.0
7756cabbf9f838300e369b61ac8a6d88
60.7
186
0.685575
3.40884
false
true
false
false
AblePear/Peary
PearyTests/sockaddr_inTests.swift
1
4721
import XCTest @testable import Peary class sockaddr_inTests: XCTestCase { func testInit() { let address = sockaddr_in() XCTAssertEqual(address.sin_len, UInt8(0)) XCTAssertEqual(address.sin_family, sa_family_t(AF_UNSPEC)) XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0).networkByteOrder) XCTAssertEqual(address.sin_port, in_port_t(0).networkByteOrder) XCTAssertEqual(address.address, in_addr("0.0.0.0")) XCTAssertEqual(address.port, in_port_t(0).hostByteOrder) XCTAssertEqual("\(address)", "0.0.0.0:0") XCTAssert(!address.isValid) } func testInitWithAddressAndPort() { let address = sockaddr_in(address: 0x01020304, port: 42) XCTAssertEqual(address.sin_len, UInt8(MemoryLayout<sockaddr_in>.size)) XCTAssertEqual(address.sin_family, sa_family_t(AF_INET)) XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x01020304).networkByteOrder) XCTAssertEqual(address.sin_port, in_port_t(42).networkByteOrder) XCTAssertEqual(address.address, in_addr("1.2.3.4")) XCTAssertEqual(address.port, in_port_t(42).hostByteOrder) XCTAssertEqual("\(address)", "1.2.3.4:42") XCTAssert(address.isValid) } func testInitWithAddressTextAndPort() { let address = sockaddr_in("1.2.3.4", port: 42)! XCTAssertEqual(address.sin_len, UInt8(MemoryLayout<sockaddr_in>.size)) XCTAssertEqual(address.sin_family, sa_family_t(AF_INET)) XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x01020304).networkByteOrder) XCTAssertEqual(address.sin_port, in_port_t(42).networkByteOrder) XCTAssertEqual(address.address, in_addr("1.2.3.4")) XCTAssertEqual(address.port, in_port_t(42).hostByteOrder) XCTAssertEqual("\(address)", "1.2.3.4:42") XCTAssert(address.isValid) } func testInitWithEmptyAddressText() { let address = sockaddr_in("", port: 42) XCTAssertNil(address) } func testInitWithInvalidAddressText() { let address = sockaddr_in("invalid", port: 42) XCTAssertNil(address) } func testInitWithSockAddrStorage() { var storage = sockaddr_storage() withUnsafeMutablePointer(to: &storage) { return $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_len = UInt8(MemoryLayout<sockaddr_storage>.size) $0.pointee.sin_family = sa_family_t(AF_INET) $0.pointee.sin_addr = in_addr("1.2.3.4")! $0.pointee.sin_port = in_port_t(port: 42) } } let address = sockaddr_in(storage) XCTAssertTrue(address.isValid) XCTAssertEqual(address.address, in_addr("1.2.3.4")) XCTAssertEqual(address.port, in_port_t(42).hostByteOrder) } func testSetAddress() { var address = sockaddr_in("1.2.3.4", port: 80)! XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x01020304).networkByteOrder) XCTAssertEqual(address.address, in_addr("1.2.3.4")) address.address = in_addr("4.5.6.7")! XCTAssertEqual(address.sin_addr.s_addr, in_addr_t(0x04050607).networkByteOrder) XCTAssertEqual(address.address, in_addr("4.5.6.7")) } func testSetPort() { var address = sockaddr_in("1.2.3.4", port: 80)! XCTAssertEqual(address.sin_port, in_port_t(80).networkByteOrder) XCTAssertEqual(address.port, in_port_t(80)) address.port = in_port_t(8080) XCTAssertEqual(address.sin_port, in_port_t(8080).networkByteOrder) XCTAssertEqual(address.port, in_port_t(8080)) } func testAsSockaddrPointer() { let address = sockaddr_in("1.2.3.4", port: 42)! let result = address.asSockaddrPointer { sockaddr -> Bool in XCTAssertEqual(sa_family_t(AF_INET), sockaddr.pointee.sa_family) XCTAssertEqual(address.length, socklen_t(sockaddr.pointee.sa_len)) return true } XCTAssertTrue(result) } func testEquatable() { let address1 = sockaddr_in("1.2.3.4", port: 80)! let address2 = sockaddr_in("1.2.3.4", port: 80)! let address3 = sockaddr_in("2.2.3.4", port: 80)! let address4 = sockaddr_in("2.2.3.4", port: 81)! XCTAssertEqual(address1, address2) XCTAssertEqual(address2, address1) XCTAssertNotEqual(address1, address3) XCTAssertNotEqual(address3, address1) XCTAssertNotEqual(address3, address4) XCTAssertNotEqual(address4, address3) } }
bsd-2-clause
73b804d1e5ae2afadbf2fa379e9f5da4
38.341667
87
0.622114
3.80419
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/Cells/Badge/BadgeAsset/DefaultBadgeAssetPresenter.swift
1
786
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxRelay import RxSwift public final class DefaultBadgeAssetPresenter: BadgeAssetPresenting { public typealias PresentationState = BadgeAsset.State.BadgeItem.Presentation public var state: Observable<PresentationState> { stateRelay.asObservable() } public let interactor: BadgeAssetInteracting private let stateRelay = BehaviorRelay<PresentationState>(value: .loading) private let disposeBag = DisposeBag() public init(interactor: BadgeAssetInteracting = DefaultBadgeAssetInteractor()) { self.interactor = interactor interactor.state .map { .init(with: $0) } .bindAndCatch(to: stateRelay) .disposed(by: disposeBag) } }
lgpl-3.0
cb84827a47661b9a31a3f17c8c65d276
31.708333
84
0.715924
5.233333
false
false
false
false
huonw/swift
test/SILGen/metatypes.swift
1
4296
// RUN: %target-swift-emit-silgen -parse-stdlib -enable-sil-ownership %s | %FileCheck %s import Swift protocol SomeProtocol { func method() func static_method() } protocol A {} struct SomeStruct : A {} class SomeClass : SomeProtocol { func method() {} func static_method() {} } class SomeSubclass : SomeClass {} // CHECK-LABEL: sil hidden @$S9metatypes07static_A0{{[_0-9a-zA-Z]*}}F func static_metatypes() -> (SomeStruct.Type, SomeClass.Type, SomeClass.Type) { // CHECK: [[STRUCT:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[CLASS:%[0-9]+]] = metatype $@thick SomeClass.Type // CHECK: [[SUBCLASS:%[0-9]+]] = metatype $@thick SomeSubclass.Type // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[STRUCT]] : {{.*}}, [[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (SomeStruct.self, SomeClass.self, SomeSubclass.self) } // CHECK-LABEL: sil hidden @$S9metatypes07struct_A0{{[_0-9a-zA-Z]*}}F func struct_metatypes(s: SomeStruct) -> (SomeStruct.Type, SomeStruct.Type) { // CHECK: [[STRUCT1:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: [[STRUCT2:%[0-9]+]] = metatype $@thin SomeStruct.Type // CHECK: tuple ([[STRUCT1]] : {{.*}}, [[STRUCT2]] : {{.*}}) return (type(of: s), SomeStruct.self) } // CHECK-LABEL: sil hidden @$S9metatypes06class_A0{{[_0-9a-zA-Z]*}}F func class_metatypes(c: SomeClass, s: SomeSubclass) -> (SomeClass.Type, SomeClass.Type) { // CHECK: [[CLASS:%[0-9]+]] = value_metatype $@thick SomeClass.Type, // CHECK: [[SUBCLASS:%[0-9]+]] = value_metatype $@thick SomeSubclass.Type, // CHECK: [[SUBCLASS_UPCAST:%[0-9]+]] = upcast [[SUBCLASS]] : ${{.*}} to $@thick SomeClass.Type // CHECK: tuple ([[CLASS]] : {{.*}}, [[SUBCLASS_UPCAST]] : {{.*}}) return (type(of: c), type(of: s)) } // CHECK-LABEL: sil hidden @$S9metatypes010archetype_A0{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : @trivial $*T): func archetype_metatypes<T>(t: T) -> (T.Type, T.Type) { // CHECK: [[STATIC_T:%[0-9]+]] = metatype $@thick T.Type // CHECK: [[DYN_T:%[0-9]+]] = value_metatype $@thick T.Type, %0 // CHECK: tuple ([[STATIC_T]] : {{.*}}, [[DYN_T]] : {{.*}}) return (T.self, type(of: t)) } // CHECK-LABEL: sil hidden @$S9metatypes012existential_A0{{[_0-9a-zA-Z]*}}F func existential_metatypes(p: SomeProtocol) -> SomeProtocol.Type { // CHECK: existential_metatype $@thick SomeProtocol.Type return type(of: p) } struct SomeGenericStruct<T> {} func generic_metatypes<T>(x: T) -> (SomeGenericStruct<T>.Type, SomeGenericStruct<SomeStruct>.Type) { // CHECK: metatype $@thin SomeGenericStruct<T> // CHECK: metatype $@thin SomeGenericStruct<SomeStruct> return (SomeGenericStruct<T>.self, SomeGenericStruct<SomeStruct>.self) } // rdar://16610078 // CHECK-LABEL: sil hidden @$S9metatypes30existential_metatype_from_thinypXpyF : $@convention(thin) () -> @thick Any.Type // CHECK: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin() -> Any.Type { return SomeStruct.self } // CHECK-LABEL: sil hidden @$S9metatypes36existential_metatype_from_thin_valueypXpyF : $@convention(thin) () -> @thick Any.Type // CHECK: [[T1:%.*]] = metatype $@thin SomeStruct.Type // CHECK: [[T0:%.*]] = function_ref @$S9metatypes10SomeStructV{{[_0-9a-zA-Z]*}}fC // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: debug_value [[T2]] : $SomeStruct, let, name "s" // CHECK-NEXT: [[T0:%.*]] = metatype $@thin SomeStruct.Type // CHECK-NEXT: [[T1:%.*]] = metatype $@thick SomeStruct.Type // CHECK-NEXT: [[T2:%.*]] = init_existential_metatype [[T1]] : $@thick SomeStruct.Type, $@thick Any.Type // CHECK-NEXT: return [[T2]] : $@thick Any.Type func existential_metatype_from_thin_value() -> Any.Type { let s = SomeStruct() return type(of: s) } // CHECK-LABEL: sil hidden @$S9metatypes20specialized_metatypes10DictionaryVySSSiGyF // CHECK: metatype $@thin Dictionary<String, Int>.Type func specialized_metatype() -> Dictionary<String, Int> { let dict = Swift.Dictionary<Swift.String, Int>() return dict }
apache-2.0
c2c0b5d02a04b2479902f908087478cf
38.054545
127
0.641294
3.332816
false
false
false
false
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Views/MXCalendarView/Cells/MXAccessoryView.swift
1
1962
// // Created by Maxim Pervushin on 19/01/16. // Copyright (c) 2016 Maxim Pervushin. All rights reserved. // import UIKit @IBDesignable class MXAccessoryView: UIView { @IBInspectable var value: Int = 0 { didSet { setNeedsDisplay() } } @IBInspectable var maxValue: Int = 0 { didSet { setNeedsDisplay() } } private var _activeSegmentColor = UIColor.clearColor() private var _inactiveSegmentColor = UIColor.clearColor() override func drawRect(rect: CGRect) { if maxValue == 0 { return } let ctx = UIGraphicsGetCurrentContext() let borderRectSide = min(bounds.size.width, bounds.size.height) - 4 let radius = (borderRectSide - borderRectSide / 6) / 2 let center = CGPointMake(bounds.size.width / 2, bounds.size.height / 2) let segmentSize = CGFloat(2.0 * M_PI) / CGFloat(maxValue) let rotation = CGFloat(-0.5 * M_PI) for currentSegment in 0 ... maxValue - 1 { let startAngle = segmentSize * CGFloat(currentSegment) + rotation let endAngle = segmentSize * CGFloat(currentSegment + 1) + rotation CGContextAddArc(ctx, center.x, center.y, radius, startAngle, endAngle, 0) CGContextSetStrokeColorWithColor(ctx, (currentSegment < value ? _activeSegmentColor : _inactiveSegmentColor).CGColor) CGContextStrokePath(ctx) } } } extension MXAccessoryView { // MARK: - UIAppearance dynamic var activeSegmentColor: UIColor { // UI_APPEARANCE_SELECTOR get { return _activeSegmentColor } set { _activeSegmentColor = newValue } } dynamic var inactiveSegmentColor: UIColor { // UI_APPEARANCE_SELECTOR get { return _inactiveSegmentColor } set { _inactiveSegmentColor = newValue } } }
mit
55f90b927dcb0c47cc55e853dbfef412
26.263889
129
0.601427
4.785366
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/lottie-ios/lottie-swift/src/Public/AnimationCache/LRUAnimationCache.swift
1
1238
// // LRUAnimationCache.swift // lottie-swift // // Created by Brandon Withrow on 2/5/19. // import Foundation /** An Animation Cache that will store animations up to `cacheSize`. Once `cacheSize` is reached, the least recently used animation will be ejected. The default size of the cache is 100. */ public class LRUAnimationCache: AnimationCacheProvider { public init() { } /// Clears the Cache. public func clearCache() { cacheMap.removeAll() lruList.removeAll() } /// The global shared Cache. public static let sharedCache = LRUAnimationCache() /// The size of the cache. public var cacheSize: Int = 100 public func animation(forKey: String) -> Animation? { guard let animation = cacheMap[forKey] else { return nil } if let index = lruList.firstIndex(of: forKey) { lruList.remove(at: index) lruList.append(forKey) } return animation } public func setAnimation(_ animation: Animation, forKey: String) { cacheMap[forKey] = animation lruList.append(forKey) if lruList.count > cacheSize { lruList.remove(at: 0) } } fileprivate var cacheMap: [String : Animation] = [:] fileprivate var lruList: [String] = [] }
mit
c65306d6ce9f468eca3a08ccf376f967
21.925926
80
0.66559
4.099338
false
false
false
false
networkextension/SFSocket
SFSocket/udp/NWUDPSocket.swift
1
2997
import Foundation import NetworkExtension import AxLogger /// The delegate protocol of `NWUDPSocket`. public protocol NWUDPSocketDelegate: class { /** Socket did receive data from remote. - parameter data: The data. - parameter from: The socket the data is read from. */ func didReceiveData(_ data: Data, from: NWUDPSocket) } /// The wrapper for NWUDPSession. /// /// - note: This class is thread-safe. open class NWUDPSocket { fileprivate let session: NWUDPSession fileprivate var pendingWriteData: [Data] = [] fileprivate var writing = false fileprivate let queue: DispatchQueue = DispatchQueue(label: "NWUDPSocket.queue", attributes: []) /// The delegate instance. open weak var delegate: NWUDPSocketDelegate? /// The time when the last activity happens. /// /// Since UDP do not have a "close" semantic, this can be an indicator of timeout. open var lastActive: Date = Date() /** Create a new UDP socket connecting to remote. - parameter host: The host. - parameter port: The port. */ init?(host: String, port: Int) { guard let udpsession = RawSocketFactory.TunnelProvider?.createUDPSession(to: NWHostEndpoint(hostname: host, port: "\(port)"), from: nil) else { return nil } session = udpsession session.setReadHandler({ [ weak self ] dataArray, error in guard let sSelf = self else { return } sSelf.updateActivityTimer() guard error == nil else { AxLogger.log("Error when reading from remote server. \(String(describing: error))",level: .Error) return } for data in dataArray! { sSelf.delegate?.didReceiveData(data, from: sSelf) } }, maxDatagrams: 32) } /** Send data to remote. - parameter data: The data to send. */ func writeData(_ data: Data) { queue.async { self.pendingWriteData.append(data) self.checkWrite() } } func disconnect() { queue.async { self.session.cancel() } } fileprivate func checkWrite() { queue.async { self.updateActivityTimer() guard !self.writing else { return } guard self.pendingWriteData.count > 0 else { return } self.writing = true self.session.writeMultipleDatagrams(self.pendingWriteData) {_ in self.writing = false self.checkWrite() } self.pendingWriteData.removeAll(keepingCapacity: true) } } fileprivate func updateActivityTimer() { lastActive = Date() } }
bsd-3-clause
9f57e391034d19b6661559c18d49448d
26.495413
151
0.548882
5.0625
false
false
false
false
3DprintFIT/octoprint-ios-client
OctoPhone/View Related/Print Profile/PrintProfileViewController.swift
1
5556
// // PrintProfileViewController.swift // OctoPhone // // Created by Josef Dolezal on 03/04/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit import ReactiveSwift import ReactiveCocoa import Result /// Print profile detail flow controller protocol PrintProfileViewControllerDelegate: class { /// Called when user tapped done button func doneButtonTapped() /// Called when user tapped close button func closeButtonTapped() /// Called when user tapped on delete button func deleteButtonTapped() } /// Print profile detail controller class PrintProfileViewController: BaseViewController { // MARK: - Properties /// Controller logic fileprivate var viewModel: PrintProfileViewModelType! /// Button for done action private lazy var doneButton: UIBarButtonItem = { let button = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneButtonTapped)) return button }() /// Button for close action private lazy var closeButton: UIBarButtonItem = { let button = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(closeButtonTapped)) return button }() /// Button for delete profile action private lazy var deleteButton: UIBarButtonItem = { let button = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deleteButtonTapped)) return button }() /// Input for profile name private weak var nameField: FormTextInputView! /// Input for profile identifier private weak var identifierField: FormTextInputView! /// Input for printer model private weak var modelField: FormTextInputView! // MARK: - Initializers convenience init(viewModel: PrintProfileViewModelType) { self.init() self.viewModel = viewModel } // MARK: - Controller lifecycle override func loadView() { super.loadView() let nameField = FormTextInputView() let identifierField = FormTextInputView() let modelField = FormTextInputView() let formInputs = [nameField, identifierField, modelField] let scrollView = UIScrollView() let stackView = UIStackView(arrangedSubviews: formInputs, axis: .vertical) view.addSubview(scrollView) scrollView.addSubview(stackView) scrollView.contentOffset.y = navigationController?.navigationBar.frame.height ?? 0.0 scrollView.alwaysBounceVertical = true scrollView.isScrollEnabled = true scrollView.snp.makeConstraints { make in make.edges.equalToSuperview() } stackView.snp.makeConstraints { make in make.edges.width.equalToSuperview() } self.nameField = nameField self.identifierField = identifierField self.modelField = modelField navigationItem.leftBarButtonItem = closeButton navigationItem.rightBarButtonItem = doneButton } override func viewDidLoad() { super.viewDidLoad() bindViewModel() } // MARK: - Internal logic /// Binds outputs of View Model to UI and converts /// user interaction to View Model inputs private func bindViewModel() { nameField.textField.reactive.continuousTextValues.signal.observeValues { [weak self] text in self?.viewModel.inputs.profileNameChanged(text) } identifierField.textField.reactive.continuousTextValues.signal.observeValues { [weak self] text in self?.viewModel.inputs.profileIdentifierChanged(text) } modelField.textField.reactive.continuousTextValues.signal.observeValues { [weak self] text in self?.viewModel.inputs.profileModelChanged(text) } nameField.descriptionLabel.reactive.text <~ viewModel.outputs.profileNameDescription nameField.textField.reactive.text <~ viewModel.outputs.profileNameValue identifierField.descriptionLabel.reactive.text <~ viewModel.outputs.profileIdentifierDescription identifierField.textField.reactive.text <~ viewModel.outputs.profileIdentifierValue modelField.descriptionLabel.reactive.text <~ viewModel.outputs.profileModelDescription modelField.textField.reactive.text <~ viewModel.outputs.profileModelValue identifierField.textField.reactive.isEnabled <~ viewModel.outputs.profileIdentifierIsEditable doneButton.reactive.isEnabled <~ viewModel.outputs.doneButtonIsEnabled if viewModel.outputs.closeButtonIsHidden.value { navigationItem.leftBarButtonItem = deleteButton } viewModel.outputs.displayError.startWithValues { [weak self] error in self?.presentError(title: error.title, message: error.message) } } /// Done button action callback func doneButtonTapped() { viewModel.inputs.doneButtonTapped() } /// Close button action callback func closeButtonTapped() { viewModel.inputs.closeButtonTapped() } /// Delete button action callback func deleteButtonTapped() { let controller = DeletionDialogFactory .createDialog(title: nil, message: tr(.doYouReallyWantToDeletePrintProfile)) { [weak self] in self?.viewModel.inputs.deleteButtonTapped() } present(controller, animated: true, completion: nil) } }
mit
772f082c408542ccb9b2bf62134b1947
31.48538
106
0.683888
5.709147
false
false
false
false
jovito-royeca/Decktracker
ios/old/Decktracker/View/Decks/StartingHandViewController.swift
1
20716
// // StartingHandViewController.swift // Decktracker // // Created by Jovit Royeca on 12/30/14. // Copyright (c) 2014 Jovito Royeca. All rights reserved. // import UIKit enum StartingHandShowMode: CustomStringConvertible { case ByHand case ByGraveyard case ByLibrary var description : String { switch self { case ByHand: return "Hand" case ByGraveyard: return "Graveyard" case ByLibrary: return "Library" } } } class StartingHandViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate { var initialHand = 7 var viewButton:UIBarButtonItem? var showButton:UIBarButtonItem? var newButton:UIBarButtonItem? var mulliganButton:UIBarButtonItem? var drawButton:UIBarButtonItem? var tblHand:UITableView? var colHand:UICollectionView? var bottomToolbar:UIToolbar? var viewMode:String? var showMode:StartingHandShowMode? var deck:Deck? var arrayDeck:[String]? var arrayHand:[String]? var arrayGraveyard:[String]? var arrayLibrary:[String]? var viewLoadedOnce = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. hidesBottomBarWhenPushed = true let dX:CGFloat = 0 var dY:CGFloat = 0 let dWidth = self.view.frame.size.width var dHeight = self.view.frame.size.height-44 var frame:CGRect? viewButton = UIBarButtonItem(image: UIImage(named: "list.png"), style: UIBarButtonItemStyle.Plain, target: self, action: "viewButtonTapped") showButton = UIBarButtonItem(image: UIImage(named: "view_file.png"), style: UIBarButtonItemStyle.Plain, target: self, action: "showButtonTapped") newButton = UIBarButtonItem(title: "New Hand", style: UIBarButtonItemStyle.Plain, target: self, action: "newButtonTapped") mulliganButton = UIBarButtonItem(title: "Mulligan", style: UIBarButtonItemStyle.Plain, target: self, action: "mulliganButtonTapped") drawButton = UIBarButtonItem(title: "Draw", style: UIBarButtonItemStyle.Plain, target: self, action: "drawButtonTapped") dY = dHeight dHeight = 44 frame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight) bottomToolbar = UIToolbar(frame: frame!) bottomToolbar!.items = [newButton!, UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil), mulliganButton!, UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil), drawButton!] self.navigationItem.title = "Starting Hand" self.navigationItem.rightBarButtonItems = [showButton!, viewButton!] if let value = NSUserDefaults.standardUserDefaults().stringForKey(kCardViewMode) { if value == kCardViewModeList { self.viewMode = kCardViewModeList self.showTableView() } else if value == kCardViewModeGrid2x2 { self.viewMode = kCardViewModeGrid2x2 viewButton!.image = UIImage(named: "2x2.png") self.showGridView() } else if value == kCardViewModeGrid3x3 { self.viewMode = kCardViewModeGrid3x3 viewButton!.image = UIImage(named: "3x3.png") self.showGridView() } else { self.viewMode = kCardViewModeList self.showTableView() } } else { self.viewMode = kCardViewModeList self.showTableView() } view.addSubview(bottomToolbar!) self.viewLoadedOnce = false self.newButtonTapped() #if !DEBUG // send the screen to Google Analytics if let tracker = GAI.sharedInstance().defaultTracker { tracker.set(kGAIScreenName, value: "Starting Hand") tracker.send(GAIDictionaryBuilder.createScreenView().build() as [NSObject : AnyObject]) } #endif } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func viewButtonTapped() { var initialSelection = 0 if self.viewMode == kCardViewModeList { initialSelection = 0 } else if self.viewMode == kCardViewModeGrid2x2 { initialSelection = 1 } else if self.viewMode == kCardViewModeGrid3x3 { initialSelection = 2 } let doneBlock = { (picker: ActionSheetStringPicker?, selectedIndex: NSInteger, selectedValue: AnyObject?) -> Void in switch selectedIndex { case 0: self.viewMode = kCardViewModeList self.viewButton!.image = UIImage(named: "list.png") self.showTableView() case 1: self.viewMode = kCardViewModeGrid2x2 self.viewButton!.image = UIImage(named: "2x2.png") self.showGridView() case 2: self.viewMode = kCardViewModeGrid3x3 self.viewButton!.image = UIImage(named: "3x3.png") self.showGridView() default: break } NSUserDefaults.standardUserDefaults().setObject(self.viewMode, forKey: kCardViewMode) NSUserDefaults.standardUserDefaults().synchronize() } ActionSheetStringPicker.showPickerWithTitle("View As", rows: [kCardViewModeList, kCardViewModeGrid2x2, kCardViewModeGrid3x3], initialSelection: initialSelection, doneBlock: doneBlock, cancelBlock: nil, origin: view) } func showButtonTapped() { var initialSelection = 0 switch self.showMode! { case .ByHand: initialSelection = 0 case .ByGraveyard: initialSelection = 1 case .ByLibrary: initialSelection = 2 } let doneBlock = { (picker: ActionSheetStringPicker?, selectedIndex: NSInteger, selectedValue: AnyObject?) -> Void in switch selectedIndex { case 0: self.showMode = .ByHand case 1: self.showMode = .ByGraveyard case 2: self.showMode = .ByLibrary default: break } if self.viewMode == kCardViewModeList { self.tblHand!.reloadData() } else if self.viewMode == kCardViewModeGrid2x2 || self.viewMode == kCardViewModeGrid3x3 { self.colHand!.reloadData() } else if self.viewMode == kCardViewModeGrid3x3 { initialSelection = 2 } } ActionSheetStringPicker.showPickerWithTitle("Show Cards In", rows: [StartingHandShowMode.ByHand.description, StartingHandShowMode.ByGraveyard.description, StartingHandShowMode.ByLibrary.description], initialSelection: initialSelection, doneBlock: doneBlock, cancelBlock: nil, origin: view) } func newButtonTapped() { initialHand = 7 self.mulliganButton!.enabled = true self.drawButton!.enabled = true arrayHand = Array() arrayGraveyard = Array() arrayLibrary = Array() self.initDeck() self.shuffleLibrary() self.drawCards(initialHand) self.showMode = StartingHandShowMode.ByHand if self.viewMode == kCardViewModeList { tblHand!.reloadData() } else if self.viewMode == kCardViewModeGrid2x2 || self.viewMode == kCardViewModeGrid3x3 { colHand!.reloadData() } } func mulliganButtonTapped() { initialHand -= 1 if initialHand <= 1 { self.mulliganButton!.enabled = false } // put cards from hand to library while arrayHand!.count > 0 { let cardId = arrayHand!.removeLast() arrayLibrary!.append(cardId) } // put cards from graveyard to library while arrayGraveyard!.count > 0 { let cardId = arrayGraveyard!.removeLast() arrayLibrary!.append(cardId) } self.shuffleLibrary() self.drawCards(initialHand) self.showMode = StartingHandShowMode.ByHand if self.viewMode == kCardViewModeList { tblHand!.reloadData() } else if self.viewMode == kCardViewModeGrid2x2 || self.viewMode == kCardViewModeGrid3x3 { colHand!.reloadData() } } func drawButtonTapped() { if arrayLibrary!.count <= 0 { self.drawButton!.enabled = false } self.drawCards(1) self.showMode = StartingHandShowMode.ByHand if self.viewMode == kCardViewModeList { tblHand!.reloadData() } else if self.viewMode == kCardViewModeGrid2x2 || self.viewMode == kCardViewModeGrid3x3{ colHand!.reloadData() } } func showTableView() { let dX:CGFloat = 0 let dY = viewLoadedOnce ? 0 : UIApplication.sharedApplication().statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height let dWidth = self.view.frame.size.width let dHeight = self.view.frame.size.height-dY-44 let frame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight) tblHand = UITableView(frame: frame, style: UITableViewStyle.Plain) tblHand!.delegate = self tblHand!.dataSource = self if colHand != nil { colHand!.removeFromSuperview() } view.addSubview(tblHand!) } func showGridView() { let dX:CGFloat = 0 let dY = viewLoadedOnce ? 0 : UIApplication.sharedApplication().statusBarFrame.size.height + self.navigationController!.navigationBar.frame.size.height let dWidth = self.view.frame.size.width let dHeight = self.view.frame.size.height-dY-44 let frame = CGRect(x:dX, y:dY, width:dWidth, height:dHeight) let divisor:CGFloat = viewMode == kCardViewModeGrid2x2 ? 2 : 3 let layout = CSStickyHeaderFlowLayout() layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.headerReferenceSize = CGSize(width:view.frame.width, height: 22) layout.itemSize = CGSize(width: frame.width/divisor, height: frame.height/divisor) colHand = UICollectionView(frame: frame, collectionViewLayout: layout) colHand!.dataSource = self colHand!.delegate = self colHand!.registerClass(CardImageCollectionViewCell.self, forCellWithReuseIdentifier: "Card") colHand!.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier:"Header") colHand!.backgroundColor = UIColor(patternImage: UIImage(contentsOfFile: "\(NSBundle.mainBundle().bundlePath)/images/Gray_Patterned_BG.jpg")!) if tblHand != nil { tblHand!.removeFromSuperview() } view.addSubview(colHand!) } func initDeck() { arrayDeck = Array() for dict in self.deck!.arrLands { let d = dict as! Dictionary<String, AnyObject> let cardId = d["cardId"] as! String // let card = DTCard(forPrimaryKey: cardId) let qty = d["qty"] as! NSNumber for var i=0; i<qty.integerValue; i++ { arrayDeck!.append(cardId) } } for dict in self.deck!.arrCreatures { let d = dict as! Dictionary<String, AnyObject> let cardId = d["cardId"] as! String // let card = DTCard(forPrimaryKey: cardId) let qty = d["qty"] as! NSNumber for var i=0; i<qty.integerValue; i++ { arrayDeck!.append(cardId) } } for dict in self.deck!.arrOtherSpells { let d = dict as! Dictionary<String, AnyObject> let cardId = d["cardId"] as! String // let card = DTCard(forPrimaryKey: cardId) let qty = d["qty"] as! NSNumber for var i=0; i<qty.integerValue; i++ { arrayDeck!.append(cardId) } } } func shuffleLibrary() { var arrayTemp = [String]() // put cards from deck to library while arrayDeck!.count > 0 { let cardId = arrayDeck!.removeLast() arrayLibrary!.append(cardId) } // put cards from library to temp while arrayLibrary!.count > 0 { let count = UInt32(arrayLibrary!.count) let random = Int(arc4random_uniform(count)) let cardId = arrayLibrary!.removeAtIndex(random) arrayTemp.append(cardId) } // put cards from temp to library while arrayTemp.count > 0 { let cardId = arrayTemp.removeLast() arrayLibrary!.append(cardId) } } func drawCards(howMany: Int) { for var i=0; i<howMany; i++ { if arrayLibrary!.count <= 0 { return } let cardId = arrayLibrary!.removeLast() arrayHand!.append(cardId) } } func discardCard(index: Int) { let cardId = arrayHand!.removeAtIndex(index) arrayGraveyard!.append(cardId) if self.viewMode == kCardViewModeList { tblHand!.reloadData() } else if self.viewMode == kCardViewModeGrid2x2 || self.view == kCardViewModeGrid3x3{ colHand!.reloadData() } } // MARK: UITableViewDataSource func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var count = 0 switch self.showMode! { case .ByHand: count = self.arrayHand!.count case .ByGraveyard: count = self.arrayGraveyard!.count case .ByLibrary: count = self.arrayLibrary!.count } return "Cards In \(self.showMode!.description): \(count)" } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return CGFloat(CARD_SUMMARY_VIEW_CELL_HEIGHT) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.showMode! { case .ByHand: return self.arrayHand!.count case .ByGraveyard: return self.arrayGraveyard!.count case .ByLibrary: return self.arrayLibrary!.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? var cardSummaryView:CardSummaryView? var cardId:String? switch self.showMode! { case .ByHand: if (self.arrayHand!.count > 0) { cardId = self.arrayHand![indexPath.row] } case .ByGraveyard: if (self.arrayGraveyard!.count > 0) { cardId = self.arrayGraveyard![indexPath.row] } case .ByLibrary: if (self.arrayLibrary!.count > 0) { cardId = self.arrayLibrary![indexPath.row] } } if let x = tableView.dequeueReusableCellWithIdentifier(kCardInfoViewIdentifier) as UITableViewCell! { cell = x for subView in cell!.contentView.subviews { if subView is CardSummaryView { cardSummaryView = subView as? CardSummaryView break } } } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: kCardInfoViewIdentifier) cardSummaryView = NSBundle.mainBundle().loadNibNamed("CardSummaryView", owner: self, options: nil).first as? CardSummaryView cardSummaryView!.frame = CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: CGFloat(CARD_SUMMARY_VIEW_CELL_HEIGHT)) cell!.contentView.addSubview(cardSummaryView!) } cell!.accessoryType = UITableViewCellAccessoryType.None cell!.selectionStyle = UITableViewCellSelectionStyle.None cardSummaryView!.displayCard(cardId) return cell! } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool{ return self.showMode == .ByHand } func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return "Discard" } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { self.discardCard(indexPath.row) } // MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch self.showMode! { case .ByHand: return self.arrayHand!.count case .ByGraveyard: return self.arrayGraveyard!.count case .ByLibrary: return self.arrayLibrary!.count } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cardId:String? switch self.showMode! { case .ByHand: if (self.arrayHand!.count > 0) { cardId = self.arrayHand![indexPath.row] } case .ByGraveyard: if (self.arrayGraveyard!.count > 0) { cardId = self.arrayGraveyard![indexPath.row] } case .ByLibrary: if (self.arrayLibrary!.count > 0) { cardId = self.arrayLibrary![indexPath.row] } } let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Card", forIndexPath: indexPath) as! CardImageCollectionViewCell cell.displayCard(cardId!, cropped: false, showName: false, showSetIcon: false) return cell } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var view:UICollectionReusableView? if kind == UICollectionElementKindSectionHeader { var count = 0 switch self.showMode! { case .ByHand: count = self.arrayHand!.count case .ByGraveyard: count = self.arrayGraveyard!.count case .ByLibrary: count = self.arrayLibrary!.count } let text = " Cards In \(self.showMode!.description): \(count)" let label = UILabel(frame: CGRect(x:0, y:0, width:self.view.frame.size.width, height:22)) label.text = text label.backgroundColor = UIColor.whiteColor() label.font = UIFont.boldSystemFontOfSize(18) view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier:"Header", forIndexPath:indexPath) as UICollectionReusableView! if view == nil { view = UICollectionReusableView(frame: CGRect(x:0, y:0, width:self.view.frame.size.width, height:22)) } view!.addSubview(label) } return view! } }
apache-2.0
45761ea087617ac553abf69911ed7f0c
35.471831
193
0.582883
5.509574
false
false
false
false
JohnSundell/SwiftKit
Source/Shared/Require.swift
1
1053
import Foundation /// Require that an optional is not nil, or throw an NSError (with an optional explicit message) public func Require<T>(optional: Optional<T>, errorMessage: String? = nil) throws -> T { guard let value = optional else { throw NSError(name: errorMessage ?? "Required value was nil") } return value } /// Require that a value is not nil, and that it may be cast to another type, or throw an NSError (with an optional explicit message) public func RequireAndCast<A, B>(value: A?, errorMessage: String? = nil) throws -> B { guard let value = try Require(value, errorMessage: errorMessage) as? B else { throw NSError(name: errorMessage ?? "Could not perform cast") } return value } /// Require that an expression avaluates to true, or throw an NSError (with an optional explicit message) public func Require(@autoclosure expression: () -> Bool, errorMessage: String? = nil) throws { if !expression() { throw NSError(name: errorMessage ?? "Requirement not fulfilled") } }
mit
8ac6b2271dc4f4b78b22d9275ebf89a0
39.5
133
0.692308
4.315574
false
false
false
false
readium/r2-streamer-swift
r2-streamer-swift/Parser/Readium/ReadiumWebPubParser.swift
1
5149
// // ReadiumWebPubParser.swift // r2-streamer-swift // // Created by Mickaël Menu on 25.06.19. // // Copyright 2019 Readium Foundation. All rights reserved. // Use of this source code is governed by a BSD-style license which is detailed // in the LICENSE file present in the project repository where this source code is maintained. // import Foundation import R2Shared public enum ReadiumWebPubParserError: Error { case parseFailure(url: URL, Error?) case missingFile(path: String) } /// Parser for a Readium Web Publication (packaged, or as a manifest). public class ReadiumWebPubParser: PublicationParser, Loggable { public enum Error: Swift.Error { case manifestNotFound case invalidManifest } private let pdfFactory: PDFDocumentFactory private let httpClient: HTTPClient public init(pdfFactory: PDFDocumentFactory, httpClient: HTTPClient) { self.pdfFactory = pdfFactory self.httpClient = httpClient } public func parse(asset: PublicationAsset, fetcher: Fetcher, warnings: WarningLogger?) throws -> Publication.Builder? { guard let mediaType = asset.mediaType(), mediaType.isReadiumWebPubProfile else { return nil } let isPackage = !mediaType.isRWPM // Reads the manifest data from the fetcher. guard let manifestData: Data = ( isPackage ? try? fetcher.readData(at: "/manifest.json") // For a single manifest file, reads the first (and only) file in the fetcher. : try? fetcher.readData(at: fetcher.links.first) ) else { throw Error.manifestNotFound } let manifest = try Manifest(json: JSONSerialization.jsonObject(with: manifestData), isPackaged: isPackage) var fetcher = fetcher // For a manifest, we discard the `fetcher` provided by the Streamer, because it was only // used to read the manifest file. We use an `HTTPFetcher` instead to serve the remote // resources. if !isPackage { let baseURL = manifest.link(withRel: .`self`)?.url(relativeTo: nil)?.deletingLastPathComponent() fetcher = HTTPFetcher(client: httpClient, baseURL: baseURL) } let userProperties = UserProperties() if mediaType.matches(.readiumWebPub) { fetcher = TransformingFetcher(fetcher: fetcher, transformers: [ EPUBHTMLInjector(metadata: manifest.metadata, userProperties: userProperties).inject(resource:) ]) } if mediaType.matches(.lcpProtectedPDF) { // Checks the requirements from the spec, see. https://readium.org/lcp-specs/drafts/lcpdf guard !manifest.readingOrder.isEmpty, manifest.readingOrder.all(matchMediaType: .pdf) else { throw Error.invalidManifest } } return Publication.Builder( mediaType: mediaType, format: (mediaType.matches(.lcpProtectedPDF) ? .pdf : .webpub), manifest: manifest, fetcher: fetcher, servicesBuilder: PublicationServicesBuilder(setup: { switch mediaType { case .lcpProtectedPDF: $0.setPositionsServiceFactory(LCPDFPositionsService.makeFactory(pdfFactory: self.pdfFactory)) case .divina, .divinaManifest: $0.setPositionsServiceFactory(PerResourcePositionsService.makeFactory(fallbackMediaType: "image/*")) case .readiumAudiobook, .readiumAudiobookManifest, .lcpProtectedAudiobook: $0.setLocatorServiceFactory(AudioLocatorService.makeFactory()) case .readiumWebPub: $0.setSearchServiceFactory(_StringSearchService.makeFactory()) default: break } }), setupPublication: { publication in if mediaType.matches(.readiumWebPub) { publication.userProperties = userProperties publication.userSettingsUIPreset = EPUBParser.userSettingsPreset(for: publication.metadata) } } ) } @available(*, unavailable, message: "Use an instance of `Streamer` to open a `Publication`") public static func parse(at url: URL) throws -> (PubBox, PubParsingCallback) { fatalError("Not available") } } private extension MediaType { /// Returns whether this media type is of a Readium Web Publication profile. var isReadiumWebPubProfile: Bool { matchesAny( .readiumWebPub, .readiumWebPubManifest, .readiumAudiobook, .readiumAudiobookManifest, .lcpProtectedAudiobook, .divina, .divinaManifest, .lcpProtectedPDF ) } } @available(*, unavailable, renamed: "ReadiumWebPubParserError") public typealias WEBPUBParserError = ReadiumWebPubParserError @available(*, unavailable, renamed: "ReadiumWebPubParser") public typealias WEBPUBParser = ReadiumWebPubParser
bsd-3-clause
a02087cb23347fcda3908c5f154fe7ab
38
123
0.640249
5.076923
false
false
false
false
fxm90/GradientProgressBar
Example/Pods/SnapshotTesting/Sources/SnapshotTesting/Snapshotting/UIView.swift
1
2380
#if os(iOS) || os(tvOS) import UIKit extension Snapshotting where Value == UIView, Format == UIImage { /// A snapshot strategy for comparing views based on pixel equality. public static var image: Snapshotting { return .image() } /// A snapshot strategy for comparing views based on pixel equality. /// /// - Parameters: /// - drawHierarchyInKeyWindow: Utilize the simulator's key window in order to render `UIAppearance` and `UIVisualEffect`s. This option requires a host application for your tests and will _not_ work for framework test targets. /// - precision: The percentage of pixels that must match. /// - size: A view size override. /// - traits: A trait collection override. public static func image( drawHierarchyInKeyWindow: Bool = false, precision: Float = 1, size: CGSize? = nil, traits: UITraitCollection = .init() ) -> Snapshotting { return SimplySnapshotting.image(precision: precision, scale: traits.displayScale).asyncPullback { view in snapshotView( config: .init(safeArea: .zero, size: size ?? view.frame.size, traits: .init()), drawHierarchyInKeyWindow: drawHierarchyInKeyWindow, traits: traits, view: view, viewController: .init() ) } } } extension Snapshotting where Value == UIView, Format == String { /// A snapshot strategy for comparing views based on a recursive description of their properties and hierarchies. public static var recursiveDescription: Snapshotting { return Snapshotting.recursiveDescription() } /// A snapshot strategy for comparing views based on a recursive description of their properties and hierarchies. public static func recursiveDescription( size: CGSize? = nil, traits: UITraitCollection = .init() ) -> Snapshotting<UIView, String> { return SimplySnapshotting.lines.pullback { view in let dispose = prepareView( config: .init(safeArea: .zero, size: size ?? view.frame.size, traits: traits), drawHierarchyInKeyWindow: false, traits: .init(), view: view, viewController: .init() ) defer { dispose() } return purgePointers( view.perform(Selector(("recursiveDescription"))).retain().takeUnretainedValue() as! String ) } } } #endif
mit
2058b59a8b0d4eb2c111a1283a6f8c6a
35.615385
230
0.665126
4.779116
false
false
false
false
ello/ello-ios
Specs/Controllers/WebBrowser/ElloWebBrowserViewControllerSpec.swift
1
1863
//// /// ElloWebBrowserViewControllerSpec.swift // @testable import Ello import Quick import Nimble class ElloWebBrowserViewControllerSpec: QuickSpec { override func spec() { describe("ElloWebBrowserViewController") { it("is easy to create a navigation controller w/ browser") { let nav = ElloWebBrowserViewController.navigationControllerWithWebBrowser() expect(nav.rootWebBrowser()).to(beAKindOf(ElloWebBrowserViewController.self)) } it("is easy to create a navigation controller w/ custom browser") { let browser = ElloWebBrowserViewController() let nav = ElloWebBrowserViewController.navigationControllerWithBrowser(browser) expect(nav.rootWebBrowser()).to(equal(browser)) } it("has a fancy done button") { let nav = ElloWebBrowserViewController.navigationControllerWithWebBrowser() let browser: ElloWebBrowserViewController = nav.rootWebBrowser() as! ElloWebBrowserViewController let xButton = browser.navigationItem.leftBarButtonItem! expect(xButton.action).to( equal(#selector(ElloWebBrowserViewController.doneButtonPressed(_:))) ) } it("has a fancy share button") { let nav = ElloWebBrowserViewController.navigationControllerWithWebBrowser() let browser: ElloWebBrowserViewController = nav.rootWebBrowser() as! ElloWebBrowserViewController let shareButton = browser.navigationItem.rightBarButtonItem! expect(shareButton.action).to( equal(#selector(ElloWebBrowserViewController.shareButtonPressed(_:))) ) } } } }
mit
858d74942a5ed34243e6954fe9985572
43.357143
95
0.625872
6.606383
false
false
false
false
leo150/Pelican
Sources/Pelican/API/Types/Markup/InlineKey.swift
1
4536
// // InlineKey.swift // Pelican // // Created by Takanu Kyriako on 31/08/2017. // import Foundation import Vapor import FluentProvider /** Defines a single keyboard key on a `MarkupInline` keyboard. Each key supports one of 4 different modes: _ _ _ _ _ **Callback Data** This sends a small String back to the bot as a `CallbackQuery`, which is automatically filtered back to the session and to a `callbackState` if one exists. Alternatively if the keyboard the button belongs to is part of a `Prompt`, it will automatically be received by it in the respective ChatSession, and the prompt will respond based on how you have set it up. **URL** The button when pressed will re-direct users to a webpage. **Inine Query Switch** This can only be used when the bot supports Inline Queries. This prompts the user to select one of their chats to open it, and when open the client will insert the bot‘s username and a specified query in the input field. **Inline Query Current Chat** This can only be used when the bot supports Inline Queries. Pressing the button will insert the bot‘s username and an optional specific inline query in the current chat's input field. */ final public class MarkupInlineKey: Model, Equatable { public var storage = Storage() public var text: String // Label text public var data: String public var type: InlineKeyType /** Creates a `MarkupInlineKey` as a URL key. This key type causes the specified URL to be opened by the client when button is pressed. If it links to a public Telegram chat or bot, it will be immediately opened. */ public init(fromURL url: String, text: String) { self.text = text self.data = url self.type = .url } /** Creates a `MarkupInlineKey` as a Callback Data key. This key sends the defined callback data back to the bot to be handled. - parameter callback: The data to be sent back to the bot once pressed. Accepts 1-64 bytes of data. - parameter text: The text label to be shown on the button. Set to nil if you wish it to be the same as the callback. */ public init?(fromCallbackData callback: String, text: String?) { // Check to see if the callback meets the byte requirement. if callback.lengthOfBytes(using: String.Encoding.utf8) > 64 { PLog.error("The MarkupKey with the text label, \"\(String(describing:text))\" has a callback of \(callback) that exceeded 64 bytes.") return nil } // Check to see if we have a label if text != nil { self.text = text! } else { self.text = callback } self.data = callback self.type = .callbackData } /** Creates a `MarkupInlineKey` as a Current Chat Inline Query key. This key prompts the user to select one of their chats, open it and insert the bot‘s username and the specified query in the input field. */ public init(fromInlineQueryCurrent data: String, text: String) { self.text = text self.data = data self.type = .switchInlineQuery_currentChat } /** Creates a `MarkupInlineKey` as a New Chat Inline Query key. This key inserts the bot‘s username and the specified inline query in the current chat's input field. Can be empty. */ public init(fromInlineQueryNewChat data: String, text: String) { self.text = text self.data = data self.type = .switchInlineQuery } static public func ==(lhs: MarkupInlineKey, rhs: MarkupInlineKey) -> Bool { if lhs.text != rhs.text { return false } if lhs.type != rhs.type { return false } if lhs.data != rhs.data { return false } return true } // Ignore context, just try and build an object from a node. public required init(row: Row) throws { text = try row.get("text") if row["url"] != nil { data = try row.get("url") type = .url } else if row["callback_data"] != nil { data = try row.get("callback_data") type = .url } else if row["switch_inline_query"] != nil { data = try row.get("switch_inline_query") type = .url } else if row["switch_inline_query_current_chat"] != nil { data = try row.get("switch_inline_query_current_chat") type = .url } else { data = "" type = .url } } public func makeRow() throws -> Row { var row = Row() try row.set("text", text) switch type { case .url: try row.set("url", data) case .callbackData: try row.set("callback_data", data) case .switchInlineQuery: try row.set("switch_inline_query", data) case .switchInlineQuery_currentChat: try row.set("switch_inline_query_current_chat", data) } return row } }
mit
d07d976547af5b16b1816b57bad5d4fe
27.124224
138
0.696334
3.551373
false
false
false
false
ello/ello-ios
Sources/Controllers/LoggedOut/LoggedOutViewController.swift
1
2964
//// /// LoggedOutViewController.swift // import SnapKit protocol BottomBarController: class { var navigationBarsVisible: Bool? { get } var bottomBarVisible: Bool { get } var bottomBarHeight: CGFloat { get } var bottomBarView: UIView { get } func setNavigationBarsVisible(_ visible: Bool, animated: Bool) } class LoggedOutViewController: BaseElloViewController, BottomBarController { private var _navigationBarsVisible: Bool = true override var navigationBarsVisible: Bool? { return _navigationBarsVisible } let bottomBarVisible: Bool = true var bottomBarHeight: CGFloat { return screen.bottomBarHeight } var bottomBarView: UIView { return screen.bottomBarView } var childView: UIView? private var _mockScreen: LoggedOutScreenProtocol? var screen: LoggedOutScreenProtocol { set(screen) { _mockScreen = screen } get { return fetchScreen(_mockScreen) } } private var userActionAttemptedObserver: NotificationObserver? func setNavigationBarsVisible(_ visible: Bool, animated: Bool) { _navigationBarsVisible = visible } override func addChild(_ childController: UIViewController) { super.addChild(childController) childView = childController.view if isViewLoaded { screen.setControllerView(childController.view) } } override func loadView() { let screen = LoggedOutScreen() screen.delegate = self view = screen } override func viewDidLoad() { super.viewDidLoad() if let childView = childView { screen.setControllerView(childView) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNotificationObservers() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) removeNotificationObservers() } } extension LoggedOutViewController { func setupNotificationObservers() { userActionAttemptedObserver = NotificationObserver( notification: LoggedOutNotifications.userActionAttempted ) { [weak self] action in switch action { case .relationshipChange: Tracker.shared.loggedOutRelationshipAction() case .postTool: Tracker.shared.loggedOutPostTool() case .artistInviteSubmit: Tracker.shared.loggedOutArtistInviteSubmit() } self?.screen.showJoinText() } } func removeNotificationObservers() { userActionAttemptedObserver?.removeObserver() } } extension LoggedOutViewController: LoggedOutProtocol { func showLoginScreen() { Tracker.shared.loginButtonTapped() appViewController?.showLoginScreen() } func showJoinScreen() { Tracker.shared.joinButtonTapped() appViewController?.showJoinScreen() } }
mit
f04ed19d120eb4787b24b8c2e4a9e001
27.776699
79
0.671053
5.458564
false
false
false
false
mshafer/stock-portfolio-ios
Portfolio/HoldingTableViewCell.swift
1
3162
// // HoldingTableViewCell.swift // Portfolio // // Created by Michael Shafer on 22/09/15. // Copyright © 2015 mshafer. All rights reserved. // import Foundation import UIKit class HoldingTableViewCell: UITableViewCell { @IBOutlet var symbol: UILabel! @IBOutlet var name: UILabel! @IBOutlet var currentValue: UILabel! @IBOutlet var quantityAndPrice: UILabel! @IBOutlet var changeTodayInDollars: UILabel! @IBOutlet var changeTodayAsPercentage: UILabel! @IBOutlet var constraintNameAndQuantityPriceHorizontalSpace: NSLayoutConstraint! @IBOutlet var constraintSymbolAndCurrentValueHorizontalSpace: NSLayoutConstraint! override func setEditing(editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) self.setVisibilityOfValues(!editing) } func setVisibilityOfValues(isVisible: Bool) { self.currentValue.hidden = !isVisible; self.quantityAndPrice.hidden = !isVisible; self.changeTodayInDollars.hidden = !isVisible; self.changeTodayAsPercentage.hidden = !isVisible; if isVisible { self.addConstraint(self.constraintNameAndQuantityPriceHorizontalSpace) self.addConstraint(self.constraintSymbolAndCurrentValueHorizontalSpace) } else { self.removeConstraint(self.constraintNameAndQuantityPriceHorizontalSpace) self.removeConstraint(self.constraintSymbolAndCurrentValueHorizontalSpace) } } func configureForHolding(holding: Holding) { self.setHoldingValues(holding) self.setColours(holding) } func setHoldingValues(holding: Holding) { self.symbol.text = holding.symbol self.name.text = holding.name self.currentValue.text = holding.currentValue == nil ? "-" : Util.currencyToString(holding.currentValue!, currencyCode: holding.currencyCode) self.quantityAndPrice.text = holdingQuantityAndPrice(holding) self.quantityAndPrice.sizeToFit() self.changeTodayInDollars.text = holding.changeTodayAsDollars == nil ? "-" : Util.currencyToString(holding.changeTodayAsDollars!, currencyCode: holding.currencyCode) self.changeTodayAsPercentage.text = holding.changeTodayAsFraction == nil ? "-" : Util.fractionToPercentage(holding.changeTodayAsFraction!) } func setColours(holding: Holding) { let colour: UIColor if (holding.changeTodayAsDollars == nil || holding.changeTodayAsDollars >= 0) { colour = UIColor(hex: "#45BF55") } else { colour = UIColor.dangerColor() } self.changeTodayInDollars.textColor = colour self.changeTodayAsPercentage.textColor = colour } // MARK: - Computed strings for display in the UI func holdingQuantityAndPrice(holding: Holding) -> String { let price = holding.currentPrice == nil ? "-" : Util.currencyToString(holding.currentPrice!, currencyCode: holding.currencyCode) return [ String(holding.numberOfShares), "@", price ].joinWithSeparator("") } }
gpl-3.0
6e8dddb08f99b162d524c181ce78aa4b
38.5125
173
0.689655
5.065705
false
false
false
false
ayong6/iOSNote
swift语言/swift语言/2. 字符串.playground/Contents.swift
1
1369
//: Playground - noun: a place where people can play import UIKit // 字符串的介绍 // 字符串在任何的开发中使用都是非常频繁的 // OC和Swift中字符串的区别 // 在OC中字符串类型时NSString,在Swift中字符串类型是String // OC中字符串@"",Swift中字符串"" // 使用 String 的原因 // String 是一个结构体,性能更高 // NSString 是一个 OC 对象,性能略差 // String 支持直接遍历 // Swift 提供了 String 和 NSString 之间的无缝转换 // 字符串遍历 var str = "Hello, Swift" for c in str.characters { print(c) } // 两个字符串的拼接 let str1 = "Hello" let str2 = "World" let str3 = str1 + str2 // 字符串和其他数据类型的拼接 let name = "why" let age = 18 let info = "my name is \(name), age is \(age)" // 字符串的格式化 // 比如时间:03:04 let min = 3 let second = 4 let time = String(format: "%02d:%02d", arguments: [min, second]) // 字符串的截取 // Swift中提供了特殊的截取方式 // 该方式非常麻烦 // Index非常难创建 // 简单的方式是将String转成NSString来使用 // 在标识符后加:as NSString即可 let myStr = "www.520it.com" var subStr = (myStr as NSString).substringFromIndex(4) subStr = (myStr as NSString).substringToIndex(3) subStr = (myStr as NSString).substringWithRange(NSRange(location: 4, length: 5))
apache-2.0
774ccee44a43800d1a1a9879650227dc
19.346939
80
0.702106
2.739011
false
false
false
false
ayong6/iOSNote
swift语言/swift语言/3. 数组和字典.playground/Contents.swift
1
3584
//: Playground - noun: a place where people can play import UIKit /********************* 数组 ********************/ // 数组 // 数组使用有序列表存储同一个类型的多个值。 // 1. 数组中的元素可以相同 // 2. 数组中的元素类型必须一致 var array = [1, 2, 3, 1, 2, 3] // 数组的定义 // swift数组应遵循 Array<Element>这样的形式,可以简写[Element] // swift开发中,可以使用AnyObject代替NSObject var array1: [Int] var array2: Array<Int> // 创建一个空数组 array1 = [Int]() array2 = Array<Int>() var array3: Array<Int> = [] // 数组的操作 // 1> 添加元素 array.append(4) array1.append(123) // 2> 删除元素 // 删除指定位置的元素 array.removeAtIndex(0) //删除第一个位置的元素 array.removeFirst() // 删除末尾的元素 array.removeLast() // 删除全部元素 array.removeAll() array = [] // 3> 修改元素 // 通过下标索引修改元素的值 array1[0] = 999 // 在指定位置插入元素 array1.insert(000, atIndex: 1) // 通过区间索引赋值,区间不能超过数组的索引范围 array1[0...1] = [111, 999] // 4> 访问元素 // 通过下标索引访问数组中的元素 array1[0] // 判断数组是否为空 array.isEmpty // 对数组的遍历 // 1> 通过下标值遍历 for i in 0..<array1.count { print(i) } // 2> 通过for-in遍历 for i in array1 { print(i) } // 数组的合并 // 1> 类型相同的数组的合并 var array4 = array1 + array2 // 2> 类型不同的数组的合并 let arr1 = [1, 2, 3] let arr2 = ["one", "two", "three"] var arr = [AnyObject]() for item in arr1 { arr.append(item) } for item in arr2 { arr.append(item) } print(arr) // 创建一个带有默认值的数组 let array5 = [Double](count: 3, repeatedValue: 0.0) /********************* 字典 ********************/ // 字典 // 字典的定义 // Swift的字典使用Dictionary<Key, Value>定义,其中Key是字典中键的数据类型,Value是字典中对应于键所存储值的数据类型。我们也可以用[Key: Value]这样快捷的形式去创建一个字典类型。 var dic: [String: AnyObject] var dic1: Dictionary<String, AnyObject> // 字典初始化 /* 1. 通常字典中,key是字符串,value是任意的类型 2. AnyObject 类似 OC中的 id;但是在swift中真的是万物皆对象 */ dic = [String: AnyObject]() dic1 = Dictionary<String, AnyObject>() var dic2: Dictionary<String, AnyObject> = [:] // 字典的操作 // 1> 添加元素 dic["name"] = "zhangsan" dic["age"] = 18 // 2> 删除元素 // 删除key对应的值 dic.removeValueForKey("id") // 删除全部元素 dic.removeAll() // 3> 修改元素 ,如果有对应的键值,则修改元素;如果没有对应的键值,则添加元素 dic["name"] = "xiaohei" // 更新字典中的值,如果不存在,就新建 dic.updateValue(123, forKey: "id") // 4> 访问元素 // 获取到的值因为是AnyObject对象,需要进行转换! let name: String = dic["name"] as! String // 判断字典是否为空 dic.isEmpty // 对字典的比遍历 // 1> 遍历字典中所有的键 for key in dic.keys { print(key) } // 2> 遍历字典中所有的值 for value in dic.values { print(value) } // 3> 遍历字典中所以的键值对 for (key, value) in dic { print("key:\(key), value:\(value)") } // 字典的合并 // 注意:字典的类型无论是否一致,都不可以通过相加+来合并 dic1["age"] = 22 for (key, value) in dic1 { dic.updateValue(value, forKey: key) } print(dic)
apache-2.0
cbea138ac6f981e05107dc4d266af542
12.210526
112
0.628685
2.537917
false
false
false
false
jsslai/Action
Carthage/Checkouts/RxSwift/RxCocoa/OSX/NSImageView+Rx.swift
3
2394
// // NSImageView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 5/17/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif import Cocoa extension Reactive where Base: NSImageView { /** Bindable sink for `image` property. */ public var image: AnyObserver<NSImage?> { return image(transitionType: nil) } /** Bindable sink for `image` property. - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) */ @available(*, deprecated, renamed: "image(transitionType:)") public func imageAnimated(_ transitionType: String?) -> AnyObserver<NSImage?> { return UIBindingObserver(UIElement: self.base) { control, value in if let transitionType = transitionType { if value != nil { let transition = CATransition() transition.duration = 0.25 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = transitionType control.layer?.add(transition, forKey: kCATransition) } } else { control.layer?.removeAllAnimations() } control.image = value }.asObserver() } /** Bindable sink for `image` property. - parameter transitionType: Optional transition type while setting the image (kCATransitionFade, kCATransitionMoveIn, ...) */ public func image(transitionType: String? = nil) -> AnyObserver<NSImage?> { return UIBindingObserver(UIElement: self.base) { control, value in if let transitionType = transitionType { if value != nil { let transition = CATransition() transition.duration = 0.25 transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = transitionType control.layer?.add(transition, forKey: kCATransition) } } else { control.layer?.removeAllAnimations() } control.image = value }.asObserver() } }
mit
2e2f4c3652230c8a04c3c1c0190293fe
33.185714
127
0.594651
5.591121
false
false
false
false
material-components/material-components-ios
components/AppBar/examples/AppBarTypicalUseExample.swift
2
4067
// Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import MaterialComponents.MaterialAppBar import MaterialComponents.MaterialAppBar_Theming import MaterialComponents.MaterialContainerScheme class AppBarTypicalUseSwiftExample: UITableViewController { // Step 1: Create and initialize an App Bar. let appBarViewController = MDCAppBarViewController() @objc var containerScheme: MDCContainerScheming = MDCContainerScheme() deinit { // Required for pre-iOS 11 devices because we've enabled observesTrackingScrollViewScrollEvents. appBarViewController.headerView.trackingScrollView = nil } init() { super.init(nibName: nil, bundle: nil) self.title = "App Bar (Swift)" // Behavioral flags. appBarViewController.inferTopSafeAreaInsetFromViewController = true appBarViewController.headerView.minMaxHeightIncludesSafeArea = false // Step 2: Add the headerViewController as a child. self.addChild(appBarViewController) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() appBarViewController.applyPrimaryTheme(withScheme: containerScheme) // Allows us to avoid forwarding events, but means we can't enable shift behaviors. appBarViewController.headerView.observesTrackingScrollViewScrollEvents = true // Recommended step: Set the tracking scroll view. appBarViewController.headerView.trackingScrollView = self.tableView // Step 2: Register the App Bar views. view.addSubview(appBarViewController.view) appBarViewController.didMove(toParent: self) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Right", style: .done, target: nil, action: nil) } // Optional step: If you allow the header view to hide the status bar you must implement this // method and return the headerViewController. override var childForStatusBarHidden: UIViewController? { return appBarViewController } // Optional step: The Header View Controller does basic inspection of the header view's background // color to identify whether the status bar should be light or dark-themed. override var childForStatusBarStyle: UIViewController? { return appBarViewController } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } } // MARK: Catalog by convention extension AppBarTypicalUseSwiftExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["App Bar", "App Bar (Swift)"], "primaryDemo": false, "presentable": false, ] } @objc func catalogShouldHideNavigation() -> Bool { return true } } // MARK: - Typical application code (not Material-specific) // MARK: UITableViewDataSource extension AppBarTypicalUseSwiftExample { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 50 } override func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath ) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell") cell.layoutMargins = .zero cell.textLabel?.text = "\(indexPath.row)" cell.selectionStyle = .none return cell } }
apache-2.0
c8c9c1939884b3f9a8318ab197e423df
31.536
100
0.741824
4.984069
false
false
false
false
brentdax/swift
test/IRGen/struct_resilience.swift
2
13112
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-resilience %s | %FileCheck %s // RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-resilience -O %s import resilient_struct import resilient_enum // CHECK: %TSi = type <{ [[INT:i32|i64]] }> // CHECK-LABEL: @"$s17struct_resilience26StructWithResilientStorageVMf" = internal global // Resilient structs from outside our resilience domain are manipulated via // value witnesses // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience30functionWithResilientTypesSize_1f010resilient_A00G0VAFn_A2FnXEtF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.opaque*) public func functionWithResilientTypesSize(_ s: __owned Size, f: (__owned Size) -> Size) -> Size { // CHECK: entry: // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8*** // CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1 // CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]] // CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 8 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]] // CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]] // CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16 // CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque* // CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]] // CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]] // CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* noalias [[STRUCT_ADDR]], %swift.opaque* noalias %1, %swift.type* [[METADATA]]) // CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)* // CHECK: [[SELF:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted* // CHECK: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* swiftself [[SELF]]) // CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1 // CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]] // CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)* // CHECK: call void [[destroy]](%swift.opaque* noalias %1, %swift.type* [[METADATA]]) // CHECK-NEXT: bitcast // CHECK-NEXT: call // CHECK-NEXT: ret void return f(s) } // CHECK-LABEL: declare{{( dllimport)?}} swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa" // CHECK-SAME: ([[INT]]) // Rectangle has fixed layout inside its resilience domain, and dynamic // layout on the outside. // // Make sure we use a type metadata accessor function, and load indirect // field offsets from it. // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience35functionWithResilientTypesRectangleyy010resilient_A00G0VF"(%T16resilient_struct9RectangleV* noalias nocapture) public func functionWithResilientTypesRectangle(_ r: Rectangle) { // CHECK: entry: // CHECK-NEXT: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 0) // CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32* // CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4]] // CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[FIELD_OFFSET_VECTOR]], i32 2 // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]] // CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T16resilient_struct9RectangleV* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi* // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] _ = r.color // CHECK-NEXT: ret void } // Resilient structs from inside our resilience domain are manipulated // directly. public struct MySize { public let w: Int public let h: Int } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience32functionWithMyResilientTypesSize_1fAA0eH0VAEn_A2EnXEtF"(%T17struct_resilience6MySizeV* noalias nocapture sret, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|(16)}}), i8*, %swift.opaque*) public func functionWithMyResilientTypesSize(_ s: __owned MySize, f: (__owned MySize) -> MySize) -> MySize { // CHECK: alloca // CHECK: [[TEMP:%.*]] = alloca %T17struct_resilience6MySizeV // CHECK: bitcast // CHECK: llvm.lifetime.start // CHECK: bitcast // CHECK: [[COPY:%.*]] = bitcast %T17struct_resilience6MySizeV* %5 to i8* // CHECK: [[ARG:%.*]] = bitcast %T17struct_resilience6MySizeV* %1 to i8* // CHECK: call void @llvm.memcpy{{.*}}(i8* align {{4|8}} [[COPY]], i8* align {{4|8}} [[ARG]], {{i32 8|i64 16}}, i1 false) // CHECK: [[FN:%.*]] = bitcast i8* %2 // CHECK: call swiftcc void [[FN]](%T17struct_resilience6MySizeV* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void return f(s) } // Structs with resilient storage from a different resilience domain require // runtime metadata instantiation, just like generics. public struct StructWithResilientStorage { public let s: Size public let ss: (Size, Size) public let n: Int public let i: ResilientInt } // Make sure we call a function to access metadata of structs with // resilient layout, and go through the field offset vector in the // metadata when accessing stored properties. // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience26StructWithResilientStorageV1nSivg"(%T17struct_resilience26StructWithResilientStorageV* {{.*}}) // CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMa"([[INT]] 0) // CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0 // CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32* // CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4]] // CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[FIELD_OFFSET_VECTOR]], i32 2 // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]] // CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T17struct_resilience26StructWithResilientStorageV* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi* // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] // CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]] // Indirect enums with resilient payloads are still fixed-size. public struct StructWithIndirectResilientEnum { public let s: FunnyShape public let n: Int } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience31StructWithIndirectResilientEnumV1nSivg"(%T17struct_resilience31StructWithIndirectResilientEnumV* {{.*}}) // CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T17struct_resilience31StructWithIndirectResilientEnumV, %T17struct_resilience31StructWithIndirectResilientEnumV* %0, i32 0, i32 1 // CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]] // CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]] // Partial application of methods on resilient value types public struct ResilientStructWithMethod { public func method() {} } // Corner case -- type is address-only in SIL, but empty in IRGen // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1ryAA0f10StructWithG0V_tF"(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture) public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) { _ = r.method } // Type is address-only in SIL, and resilient in IRGen // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1sy010resilient_A04SizeV_tF"(%swift.opaque* noalias nocapture) public func partialApplyOfResilientMethod(s: Size) { _ = s.method } public func wantsAny(_ any: Any) {} public func resilientAny(s : ResilientWeakRef) { wantsAny(s) } // CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience12resilientAny1sy0c1_A016ResilientWeakRefV_tF"(%swift.opaque* noalias nocapture) // CHECK: entry: // CHECK: [[ANY:%.*]] = alloca %Any // CHECK: [[META:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct16ResilientWeakRefVMa"([[INT]] 0) // CHECK: [[META2:%.*]] = extractvalue %swift.metadata_response %3, 0 // CHECK: [[TYADDR:%.*]] = getelementptr inbounds %Any, %Any* %1, i32 0, i32 1 // CHECK: store %swift.type* [[META2]], %swift.type** [[TYADDR]] // CHECK: call %swift.opaque* @__swift_allocate_boxed_opaque_existential_0(%Any* [[ANY]]) // CHECK: call swiftcc void @"$s17struct_resilience8wantsAnyyyypF"(%Any* noalias nocapture dereferenceable({{(32|16)}}) [[ANY]]) // CHECK: call void @__swift_destroy_boxed_opaque_existential_0(%Any* [[ANY]]) // CHECK: ret void // Public metadata accessor for our resilient struct // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s17struct_resilience6MySizeVMa" // CHECK-SAME: ([[INT]]) // CHECK: ret %swift.metadata_response { %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @"$s17struct_resilience6MySizeVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 } // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMr"(%swift.type*, i8*, i8**) // CHECK: [[FIELDS:%.*]] = alloca [4 x i8**] // CHECK: [[TUPLE_LAYOUT:%.*]] = alloca %swift.full_type_layout, // CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0 // public let s: Size // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319) // CHECK: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[T0:%.*]] = bitcast %swift.type* [[SIZE_METADATA]] to i8*** // CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], [[INT]] -1 // CHECK: [[SIZE_VWT:%.*]] = load i8**, i8*** [[T1]], // CHECK: [[SIZE_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0 // CHECK: store i8** [[SIZE_LAYOUT_1:%.*]], i8*** [[FIELD_1]] // public let ss: (Size, Size) // CHECK: [[SIZE_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: [[SIZE_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8 // CHECK: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT]], i8** [[SIZE_LAYOUT_2]], i8** [[SIZE_LAYOUT_3]]) // CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT]] to i8** // CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1 // CHECK: store i8** [[T0]], i8*** [[FIELD_2]] // Fixed-layout aggregate -- we can reference a static value witness table // public let n: Int // CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2 // CHECK: store i8** getelementptr inbounds (i8*, i8** @"$sBi{{32|64}}_WV", i32 {{.*}}), i8*** [[FIELD_3]] // Resilient aggregate with one field -- make sure we don't look inside it // public let i: ResilientInt // CHECK: call swiftcc %swift.metadata_response @"$s16resilient_struct12ResilientIntVMa"([[INT]] 319) // CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3 // CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]] // CHECK: call void @swift_initStructMetadata(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 4, i8*** [[FIELDS_ADDR]], i32* {{.*}})
apache-2.0
b408649b16924fa0714c600ec79fbe57
54.324895
304
0.671751
3.543784
false
false
false
false
kousun12/RxSwift
RxCocoa/iOS/UIGestureRecognizer+Rx.swift
4
2054
// // UIGestureRecognizer+Rx.swift // Touches // // Created by Carlos García on 10/6/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif // This should be only used from `MainScheduler` class GestureTarget: RxTarget { typealias Callback = (UIGestureRecognizer) -> Void let selector = Selector("eventHandler:") weak var gestureRecognizer: UIGestureRecognizer? var callback: Callback? init(_ gestureRecognizer: UIGestureRecognizer, callback: Callback) { self.gestureRecognizer = gestureRecognizer self.callback = callback super.init() gestureRecognizer.addTarget(self, action: selector) let method = self.methodForSelector(selector) if method == nil { fatalError("Can't find method") } } func eventHandler(sender: UIGestureRecognizer!) { if let callback = self.callback, gestureRecognizer = self.gestureRecognizer { callback(gestureRecognizer) } } override func dispose() { super.dispose() self.gestureRecognizer?.removeTarget(self, action: self.selector) self.callback = nil } } extension UIGestureRecognizer { /** Reactive wrapper for gesture recognizer events. */ public var rx_event: ControlEvent<UIGestureRecognizer> { let source: Observable<UIGestureRecognizer> = create { [weak self] observer in MainScheduler.ensureExecutingOnScheduler() guard let control = self else { observer.on(.Completed) return NopDisposable.instance } let observer = GestureTarget(control) { control in observer.on(.Next(control)) } return observer }.takeUntil(rx_deallocated) return ControlEvent(source: source) } } #endif
mit
2ba85974fa11425542e5b5ddc58b034f
24.345679
86
0.605943
5.250639
false
false
false
false
Mazy-ma/DemoBySwift
LoopProgressDemo/LoopProgressDemo/ViewController.swift
1
1132
// // ViewController.swift // LoopProgressDemo // // Created by Mazy on 2017/5/22. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class ViewController: UIViewController { var loopView: LoopView? override func viewDidLoad() { super.viewDidLoad() // 设置环形视图并添加到主视图 let loopView = LoopView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) loopView.center = view.center loopView.backgroundColor = UIColor.blue.withAlphaComponent(0.5) view.addSubview(loopView) self.loopView = loopView // 设置滑块 let slider = UISlider(frame: CGRect(x: 20, y: loopView.frame.origin.y + 300 + 50, width: view.bounds.width-40, height: 30)) slider.addTarget(self, action: #selector(changeMaskValue), for: .valueChanged) slider.value = 0.5 view.addSubview(slider) } /// 通过滑块控制环形视图的角度 func changeMaskValue(slider: UISlider) { self.loopView?.animationWithStrokeEnd(strokeEnd: CGFloat(slider.value)) } }
apache-2.0
a959d19b6e9c9d8fbc5cb67c09378f23
25.725
131
0.630496
3.944649
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/find-k-th-smallest-pair-distance.swift
2
2660
/** * https://leetcode.com/problems/find-k-th-smallest-pair-distance/ * * */ // Date: Fri May 1 10:21:02 PDT 2020 class Solution { /// - Complexity: /// - Time: O(nlogn + n + w + nlogw) func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int { // O(nlogn) let nums = nums.sorted() let n = nums.count var occurrence = Array(repeating: 0, count: n) // O(n) for index in 1 ..< n { if nums[index] == nums[index - 1] { occurrence[index] = 1 + occurrence[index - 1] } } var numberOfPointsBeforeX: [Int] = Array(repeating: 0, count: nums.last! * 2) var countIndex = 0 // O(w) for point in 0 ..< numberOfPointsBeforeX.count { while countIndex < nums.count, point == nums[countIndex] { countIndex += 1 } numberOfPointsBeforeX[point] = countIndex } var left = 0 var right = nums.last! - nums.first! + 1 // O(nlogw) while left < right { // Here mid is the distance. let mid = left + (right - left) / 2 // Calculate the number of pairs starting from each nums[index], end with nums[index] + mid var count = 0 for index in 0 ..< n { // Here is why we need an array with size nums.last! * 2. count += numberOfPointsBeforeX[nums[index] + mid] - numberOfPointsBeforeX[nums[index]] + occurrence[index] } if count >= k { right = mid } else { left = mid + 1 } } return left == (nums.last! - nums.first! + 1) ? -1 : left } } /** * https://leetcode.com/problems/find-k-th-smallest-pair-distance/ * * */ // Date: Fri May 1 11:05:06 PDT 2020 class Solution { func smallestDistancePair(_ nums: [Int], _ k: Int) -> Int { // O(nlogn) let nums = nums.sorted() var left = 0 var right = nums.last! - nums.first! + 1 // O(nlogw) while left < right { let mid = left + (right - left) / 2 var count = 0 var start = 0 for end in 0 ..< nums.count { while nums[end] - nums[start] > mid { start += 1 } count += end - start } if count >= k { right = mid } else { left = mid + 1 } } return left == (nums.last! - nums.first! + 1) ? -1 : left } }
mit
426c75cd9b0e4b8fa54936f2df215253
28.555556
122
0.458271
4
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/YellowPage/SearchView.swift
1
2706
// // SearchView.swift // YellowPage // // Created by Halcao on 2017/2/23. // Copyright © 2017年 Halcao. All rights reserved. // import UIKit import SnapKit class SearchView: UIView { let backBtn = UIButton(type: .custom) let textField = UITextField() /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ let bgdView = UIView() override func draw(_ rect: CGRect) { super.draw(rect) bgdView.frame = rect self.addSubview(bgdView) self.backgroundColor = UIColor(red: 0.1059, green: 0.6352, blue: 0.9019, alpha: 0.5) bgdView.backgroundColor = UIColor(red: 0.1059, green: 0.6352, blue: 0.9019, alpha: 1) backBtn.setImage(UIImage(named: "back"), for: .normal) backBtn.adjustsImageWhenHighlighted = false bgdView.addSubview(backBtn) backBtn.snp.makeConstraints { make in make.width.equalTo(20) make.height.equalTo(20) make.centerY.equalTo(self).offset(7) make.left.equalTo(self).offset(20) } let separator = UIView() separator.backgroundColor = UIColor(red: 0.074, green: 0.466, blue: 0.662, alpha: 1) bgdView.addSubview(separator) separator.snp.makeConstraints { make in make.width.equalTo(1) make.height.equalTo(20) make.centerY.equalTo(self).offset(7) make.left.equalTo(backBtn.snp.right).offset(10) } let iconView = UIImageView() iconView.image = UIImage(named: "search") bgdView.addSubview(iconView) iconView.snp.makeConstraints { make in make.width.equalTo(20) make.height.equalTo(20) make.centerY.equalTo(self).offset(7) make.left.equalTo(separator.snp.right).offset(10) } let baseLine = UIView() baseLine.backgroundColor = UIColor.white bgdView.addSubview(baseLine) baseLine.snp.makeConstraints { make in make.height.equalTo(1) make.top.equalTo(iconView.snp.bottom).offset(4) make.left.equalTo(iconView.snp.left) make.right.equalTo(bgdView).offset(-15) } self.addSubview(textField) textField.snp.makeConstraints { make in make.left.equalTo(iconView.snp.right).offset(2) make.right.equalTo(baseLine.snp.right) make.bottom.equalTo(baseLine.snp.top).offset(-3) make.height.equalTo(20) } } }
mit
fbec79b39f1d79b60af5dc610ae6c27d
31.178571
93
0.603034
4.126718
false
false
false
false
mateuszmackowiak/MMLogger
MMLogger/Classes/Logstash/MMAsyncSocketManager.swift
1
3372
// // Created by Mateusz Mackowiak on 04/03/2017. // Copyright (c) 2016 Mateusz Mackowiak. All rights reserved. // import Foundation import CocoaAsyncSocket protocol MMAsyncSocketManagerDelegate: class { func socketDidConnect(_ socket: MMAsyncSocketManager) func socket(_ socket: MMAsyncSocketManager, didWriteDataWithTag tag: Int) } class MMAsyncSocketManager: NSObject { enum AsyncSocketError: Error { case failedConnection(Error) } weak var delegate: MMAsyncSocketManagerDelegate? private(set) var socket: GCDAsyncSocket! var debug: Bool = false let host: String let port: UInt16 let timeout: TimeInterval open var useTLS: Bool = false let localSocketQueue = DispatchQueue(label: "\(NSUUID().uuidString).com.GCDAsyncSocketDelegateQueue") init(host: String, port: UInt16, timeout: TimeInterval) { self.host = host self.port = port self.timeout = timeout super.init() self.socket = GCDAsyncSocket(delegate: self, delegateQueue: localSocketQueue) } func send() { if !self.socket.isConnected { do { _ = try self.connect() } catch { print("Failed to start socket: \(error)") return } } if (self.useTLS) { self.socket.startTLS([String(kCFStreamSSLPeerName): NSString(string: host)]) } else { self.socketDidSecure(self.socket) } } func write(_ data: Data, withTimeout timeout: TimeInterval, tag: Int) { self.socket.write(data, withTimeout: timeout, tag: tag) } } extension MMAsyncSocketManager { func connect() throws -> Bool { guard !self.socket.isConnected else { return true } do { try self.socket.connect(toHost: host, onPort: port, withTimeout: timeout) } catch { print("Failed to connect socket: \(error)") throw AsyncSocketError.failedConnection(error) } return true } func disconnect() { self.socket.disconnect() } func disconnectSafely() { self.socket.disconnectAfterWriting() } } extension MMAsyncSocketManager { func isSecure() -> Bool { return self.socket.isSecure } func isConnected() -> Bool { return self.socket.isConnected } } extension MMAsyncSocketManager: GCDAsyncSocketDelegate { func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) { if debug { print("Socket connected!") } } func socketDidSecure(_ sock: GCDAsyncSocket) { self.delegate?.socketDidConnect(self) } func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) { if debug { print("Socket did write") } self.delegate?.socket(self, didWriteDataWithTag: tag) } func socketDidCloseReadStream(_ sock: GCDAsyncSocket) { if !debug { return } print("Socket did close read stream") } func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) { if !debug { return } if let err = err { print("Socket disconnected with error: \(err)") } else { print("Socket disconnected!") } } }
mit
ada827eac2842bc7499307b5b0b64739
24.353383
105
0.608244
4.789773
false
false
false
false
temoki/TortoiseGraphics
PlaygroundBook/Sources/Playground/PlaygroundCanvasLiveView.swift
1
1307
#if os (iOS) import UIKit public class PlaygroundCanvasLiveView: UIViewController { public init() { super.init(nibName: nil, bundle: nil) } public init(size: CGSize) { super.init(nibName: nil, bundle: nil) self.preferredContentSize = size } required init?(coder: NSCoder) { super.init(coder: coder) } public var canvas: Canvas { return playgroundCanvas } public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white _ = playgroundCanvas } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() playgroundCanvas.canvasDidLayout() } lazy var playgroundCanvas: PlaygroundCanvas = { let canvas = PlaygroundCanvas(size: Vec2D(size: view.bounds.size)) canvas.translatesAutoresizingMaskIntoConstraints = false view.addSubview(canvas) NSLayoutConstraint.activate([ view.topAnchor.constraint(equalTo: canvas.topAnchor), view.bottomAnchor.constraint(equalTo: canvas.bottomAnchor), view.leftAnchor.constraint(equalTo: canvas.leftAnchor), view.rightAnchor.constraint(equalTo: canvas.rightAnchor) ]) return canvas }() } #endif
mit
6767f373e0a5bbcaa09202322e7b9ab2
26.229167
74
0.648814
4.932075
false
false
false
false
atl009/WordPress-iOS
WordPress/Classes/ViewRelated/Aztec/ViewControllers/AztecPostViewController.swift
1
143201
import Foundation import UIKit import Aztec import CocoaLumberjack import Gridicons import WordPressShared import AFNetworking import WPMediaPicker import SVProgressHUD import AVKit // MARK: - Aztec's Native Editor! // class AztecPostViewController: UIViewController, PostEditor { /// Closure to be executed when the editor gets closed /// var onClose: ((_ changesSaved: Bool) -> ())? /// Indicates if Aztec was launched for Photo Posting /// var isOpenedDirectlyForPhotoPost = false /// Format Bar /// fileprivate(set) lazy var formatBar: Aztec.FormatBar = { return self.createToolbar() }() /// Aztec's Awesomeness /// fileprivate(set) lazy var richTextView: Aztec.TextView = { let paragraphStyle = ParagraphStyle.default // Paragraph style customizations will go here. paragraphStyle.lineSpacing = 4 let textView = Aztec.TextView(defaultFont: Fonts.regular, defaultParagraphStyle: paragraphStyle, defaultMissingImage: Assets.defaultMissingImage) textView.inputProcessor = PipelineProcessor([VideoShortcodeProcessor.videoPressPreProcessor, VideoShortcodeProcessor.wordPressVideoPreProcessor, CalypsoProcessorIn()]) textView.outputProcessor = PipelineProcessor([VideoShortcodeProcessor.videoPressPostProcessor, VideoShortcodeProcessor.wordPressVideoPostProcessor, CalypsoProcessorOut()]) let accessibilityLabel = NSLocalizedString("Rich Content", comment: "Post Rich content") self.configureDefaultProperties(for: textView, accessibilityLabel: accessibilityLabel) textView.delegate = self textView.formattingDelegate = self textView.textAttachmentDelegate = self textView.backgroundColor = Colors.aztecBackground textView.linkTextAttributes = [NSUnderlineStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), NSForegroundColorAttributeName: Colors.aztecLinkColor] textView.textAlignment = .natural if #available(iOS 11, *) { textView.smartDashesType = .no textView.smartQuotesType = .no } return textView }() /// Aztec's Text Placeholder /// fileprivate(set) lazy var placeholderLabel: UILabel = { let label = UILabel() label.text = NSLocalizedString("Share your story here...", comment: "Aztec's Text Placeholder") label.textColor = Colors.placeholder label.font = Fonts.regular label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.textAlignment = .natural return label }() /// Raw HTML Editor /// fileprivate(set) lazy var htmlTextView: UITextView = { let storage = HTMLStorage(defaultFont: Fonts.regular) let layoutManager = NSLayoutManager() let container = NSTextContainer() storage.addLayoutManager(layoutManager) layoutManager.addTextContainer(container) let textView = UITextView(frame: .zero, textContainer: container) let accessibilityLabel = NSLocalizedString("HTML Content", comment: "Post HTML content") self.configureDefaultProperties(for: textView, accessibilityLabel: accessibilityLabel) textView.isHidden = true textView.delegate = self textView.accessibilityIdentifier = "HTMLContentView" textView.autocorrectionType = .no textView.autocapitalizationType = .none if #available(iOS 11, *) { textView.smartDashesType = .no textView.smartQuotesType = .no } return textView }() /// Title's UITextView /// fileprivate(set) lazy var titleTextField: UITextView = { let textView = UITextView() textView.accessibilityLabel = NSLocalizedString("Title", comment: "Post title") textView.delegate = self textView.font = Fonts.title textView.returnKeyType = .next textView.textColor = UIColor.darkText let titleParagraphStyle = NSMutableParagraphStyle() titleParagraphStyle.alignment = .natural textView.typingAttributes = [NSForegroundColorAttributeName: UIColor.darkText, NSFontAttributeName: Fonts.title, NSParagraphStyleAttributeName: titleParagraphStyle] textView.translatesAutoresizingMaskIntoConstraints = false textView.textAlignment = .natural textView.isScrollEnabled = false textView.backgroundColor = .clear textView.spellCheckingType = .default return textView }() /// Placeholder Label /// fileprivate(set) lazy var titlePlaceholderLabel: UILabel = { let placeholderText = NSLocalizedString("Title", comment: "Placeholder for the post title.") let titlePlaceholderLabel = UILabel() let attributes = [NSForegroundColorAttributeName: Colors.title, NSFontAttributeName: Fonts.title] titlePlaceholderLabel.attributedText = NSAttributedString(string: placeholderText, attributes: attributes) titlePlaceholderLabel.sizeToFit() titlePlaceholderLabel.translatesAutoresizingMaskIntoConstraints = false titlePlaceholderLabel.textAlignment = .natural return titlePlaceholderLabel }() /// Title's Height Constraint /// fileprivate var titleHeightConstraint: NSLayoutConstraint! /// Title's Top Constraint /// fileprivate var titleTopConstraint: NSLayoutConstraint! /// Placeholder's Top Constraint /// fileprivate var textPlaceholderTopConstraint: NSLayoutConstraint! /// Separator View /// fileprivate(set) lazy var separatorView: UIView = { let v = UIView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 1)) v.backgroundColor = Colors.separator v.translatesAutoresizingMaskIntoConstraints = false return v }() /// Negative Offset BarButtonItem: Used to fine tune navigationBar Items /// fileprivate lazy var separatorButtonItem: UIBarButtonItem = { let separator = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) return separator }() /// NavigationBar's Close Button /// fileprivate lazy var closeBarButtonItem: UIBarButtonItem = { let cancelItem = UIBarButtonItem(customView: self.closeButton) cancelItem.accessibilityLabel = NSLocalizedString("Close", comment: "Action button to close edior and cancel changes or insertion of post") cancelItem.accessibilityIdentifier = "Close" return cancelItem }() /// NavigationBar's Blog Picker Button /// fileprivate lazy var blogPickerBarButtonItem: UIBarButtonItem = { let pickerItem = UIBarButtonItem(customView: self.blogPickerButton) pickerItem.accessibilityLabel = NSLocalizedString("Switch Blog", comment: "Action button to switch the blog to which you'll be posting") return pickerItem }() /// Media Uploading Status Button /// fileprivate lazy var mediaUploadingBarButtonItem: UIBarButtonItem = { let barButton = UIBarButtonItem(customView: self.mediaUploadingButton) barButton.accessibilityLabel = NSLocalizedString("Media Uploading", comment: "Message to indicate progress of uploading media to server") return barButton }() /// Publish Button fileprivate(set) lazy var publishButton: UIButton = { let button = UIButton(type: .system) button.addTarget(self, action: #selector(publishButtonTapped(sender:)), for: .touchUpInside) button.setTitle(self.postEditorStateContext.publishButtonText, for: .normal) button.sizeToFit() button.isEnabled = self.postEditorStateContext.isPublishButtonEnabled button.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) return button }() /// Publish Button fileprivate(set) lazy var publishBarButtonItem: UIBarButtonItem = { let button = UIBarButtonItem(customView: self.publishButton) return button }() fileprivate lazy var moreButton: UIButton = { let image = Gridicon.iconOfType(.ellipsis) let button = UIButton(type: .system) button.setImage(image, for: .normal) button.frame = CGRect(origin: .zero, size: image.size) button.accessibilityLabel = NSLocalizedString("More", comment: "Action button to display more available options") button.addTarget(self, action: #selector(moreWasPressed), for: .touchUpInside) button.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) return button }() /// NavigationBar's More Button /// fileprivate lazy var moreBarButtonItem: UIBarButtonItem = { let moreItem = UIBarButtonItem(customView: self.moreButton) return moreItem }() /// Dismiss Button /// fileprivate lazy var closeButton: WPButtonForNavigationBar = { let cancelButton = WPStyleGuide.buttonForBar(with: Assets.closeButtonModalImage, target: self, selector: #selector(closeWasPressed)) cancelButton.leftSpacing = Constants.cancelButtonPadding.left cancelButton.rightSpacing = Constants.cancelButtonPadding.right cancelButton.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) return cancelButton }() /// Blog Picker's Button /// fileprivate lazy var blogPickerButton: WPBlogSelectorButton = { let button = WPBlogSelectorButton(frame: .zero, buttonStyle: .typeSingleLine) button.addTarget(self, action: #selector(blogPickerWasPressed), for: .touchUpInside) if #available(iOS 11, *) { button.translatesAutoresizingMaskIntoConstraints = false } button.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal) return button }() /// Media Uploading Button /// fileprivate lazy var mediaUploadingButton: WPUploadStatusButton = { let button = WPUploadStatusButton(frame: CGRect(origin: .zero, size: Constants.uploadingButtonSize)) button.setTitle(NSLocalizedString("Media Uploading", comment: "Message to indicate progress of uploading media to server"), for: .normal) button.addTarget(self, action: #selector(displayCancelMediaUploads), for: .touchUpInside) if #available(iOS 11, *) { button.translatesAutoresizingMaskIntoConstraints = false } button.setContentHuggingPriority(UILayoutPriorityDefaultLow, for: .horizontal) return button }() /// Beta Tag Button /// fileprivate lazy var betaButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false WPStyleGuide.configureBetaButton(button) button.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) button.isEnabled = true button.addTarget(self, action: #selector(betaButtonTapped), for: .touchUpInside) return button }() /// Active Editor's Mode /// fileprivate(set) var mode = EditMode.richText { willSet { switch mode { case .html: setHTML(getHTML(), for: .richText) case .richText: setHTML(getHTML(), for: .html) } } didSet { switch mode { case .html: htmlTextView.becomeFirstResponder() case .richText: richTextView.becomeFirstResponder() } refreshEditorVisibility() refreshPlaceholderVisibility() refreshTitlePosition() } } /// Post being currently edited /// fileprivate(set) var post: AbstractPost { didSet { removeObservers(fromPost: oldValue) addObservers(toPost: post) postEditorStateContext = createEditorStateContext(for: post) refreshInterface() } } /// Active Downloads /// fileprivate var activeMediaRequests = [AFImageDownloadReceipt]() /// Boolean indicating whether the post should be removed whenever the changes are discarded, or not. /// fileprivate var shouldRemovePostOnDismiss = false /// Media Library Data Source /// fileprivate lazy var mediaLibraryDataSource: MediaLibraryPickerDataSource = { return MediaLibraryPickerDataSource(post: self.post) }() /// Device Photo Library Data Source /// fileprivate lazy var devicePhotoLibraryDataSource = WPPHAssetDataSource() /// Media Progress Coordinator /// fileprivate lazy var mediaProgressCoordinator: MediaProgressCoordinator = { let coordinator = MediaProgressCoordinator() coordinator.delegate = self return coordinator }() /// Media Progress View /// fileprivate lazy var mediaProgressView: UIProgressView = { let progressView = UIProgressView(progressViewStyle: .bar) progressView.backgroundColor = Colors.progressBackground progressView.progressTintColor = Colors.progressTint progressView.trackTintColor = Colors.progressTrack progressView.translatesAutoresizingMaskIntoConstraints = false progressView.isHidden = true return progressView }() /// Selected Text Attachment /// fileprivate var currentSelectedAttachment: MediaAttachment? /// Last Interface Element that was a First Responder /// fileprivate var lastFirstResponder: UIView? /// Maintainer of state for editor - like for post button /// fileprivate lazy var postEditorStateContext: PostEditorStateContext = { return self.createEditorStateContext(for: self.post) }() /// Current keyboard rect used to help size the inline media picker /// fileprivate var currentKeyboardFrame: CGRect = .zero /// Origin of selected media, used for analytics /// fileprivate var selectedMediaOrigin: WPAppAnalytics.SelectedMediaOrigin = .none /// Options /// fileprivate var optionsViewController: OptionsTableViewController! /// Media Picker /// fileprivate lazy var insertToolbarItem: UIButton = { let insertItem = UIButton(type: .custom) insertItem.titleLabel?.font = Fonts.mediaPickerInsert insertItem.tintColor = WPStyleGuide.wordPressBlue() insertItem.setTitleColor(WPStyleGuide.wordPressBlue(), for: .normal) return insertItem }() fileprivate var mediaPickerInputViewController: WPInputMediaPickerViewController? fileprivate var originalLeadingBarButtonGroup = [UIBarButtonItemGroup]() fileprivate var originalTrailingBarButtonGroup = [UIBarButtonItemGroup]() /// Verification Prompt Helper /// /// - Returns: `nil` when there's no need for showing the verification prompt. fileprivate lazy var verificationPromptHelper: AztecVerificationPromptHelper? = { return AztecVerificationPromptHelper(account: self.post.blog.account) }() // MARK: - Initializers required init(post: AbstractPost) { self.post = post super.init(nibName: nil, bundle: nil) self.restorationIdentifier = Restoration.restorationIdentifier self.restorationClass = type(of: self) self.shouldRemovePostOnDismiss = post.shouldRemoveOnDismiss addObservers(toPost: post) } required init?(coder aDecoder: NSCoder) { preconditionFailure("Aztec Post View Controller must be initialized by code") } deinit { NotificationCenter.default.removeObserver(self) removeObservers(fromPost: post) cancelAllPendingMediaRequests() } // MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() // This needs to called first configureMediaAppearance() // TODO: Fix the warnings triggered by this one! WPFontManager.loadNotoFontFamily() registerAttachmentImageProviders() createRevisionOfPost() // Setup configureNavigationBar() configureView() configureSubviews() // Register HTML Processors for WordPress shortcodes // UI elements might get their properties reset when the view is effectively loaded. Refresh it all! refreshInterface() // Setup Autolayout view.setNeedsUpdateConstraints() if isOpenedDirectlyForPhotoPost { presentMediaPickerFullScreen(animated: false) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) resetNavigationColors() configureDismissButton() startListeningToNotifications() verificationPromptHelper?.updateVerificationStatus() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) restoreFirstResponder() // Handles refreshing controls with state context after options screen is dismissed editorContentWasUpdated() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopListeningToNotifications() rememberFirstResponder() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var safeInsets = self.view.layoutMargins safeInsets.top = richTextView.textContainerInset.top richTextView.textContainerInset = safeInsets htmlTextView.textContainerInset = safeInsets } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.resizeBlogPickerButton() self.updateTitleHeight() }) dismissOptionsViewControllerIfNecessary() } override func willMove(toParentViewController parent: UIViewController?) { super.willMove(toParentViewController: parent) guard let navigationController = parent as? UINavigationController else { return } configureMediaProgressView(in: navigationController.navigationBar) } // MARK: - Title and Title placeholder position methods func refreshTitlePosition() { let referenceView: UITextView = mode == .richText ? richTextView : htmlTextView titleTopConstraint.constant = -(referenceView.contentOffset.y+referenceView.contentInset.top) var contentInset = referenceView.contentInset contentInset.top = (titleHeightConstraint.constant + separatorView.frame.height) referenceView.contentInset = contentInset textPlaceholderTopConstraint.constant = referenceView.textContainerInset.top + referenceView.contentInset.top } func updateTitleHeight() { let referenceView: UITextView = mode == .richText ? richTextView : htmlTextView let layoutMargins = view.layoutMargins let insets = titleTextField.textContainerInset var titleWidth = titleTextField.bounds.width if titleWidth <= 0 { // Use the title text field's width if available, otherwise calculate it. // View's frame minus left and right margins as well as margin between title and beta button titleWidth = view.frame.width - (insets.left + insets.right + layoutMargins.left + layoutMargins.right) - betaButton.frame.width } let sizeThatShouldFitTheContent = titleTextField.sizeThatFits(CGSize(width: titleWidth, height: CGFloat.greatestFiniteMagnitude)) titleHeightConstraint.constant = max(sizeThatShouldFitTheContent.height, titleTextField.font!.lineHeight + insets.top + insets.bottom) textPlaceholderTopConstraint.constant = referenceView.textContainerInset.top + referenceView.contentInset.top var contentInset = referenceView.contentInset contentInset.top = (titleHeightConstraint.constant + separatorView.frame.height) referenceView.contentInset = contentInset referenceView.setContentOffset(CGPoint(x: 0, y: -contentInset.top), animated: false) } // MARK: - Construction Helpers /// Returns a new Editor Context for a given Post instance. /// private func createEditorStateContext(for post: AbstractPost) -> PostEditorStateContext { var originalPostStatus: BasePost.Status? = nil if let originalPost = post.original, let postStatus = originalPost.status, originalPost.hasRemote() { originalPostStatus = postStatus } // Self-hosted non-Jetpack blogs have no capabilities, so we'll default // to showing Publish Now instead of Submit for Review. // let userCanPublish = post.blog.capabilities != nil ? post.blog.isPublishingPostsAllowed() : true return PostEditorStateContext(originalPostStatus: originalPostStatus, userCanPublish: userCanPublish, publishDate: post.dateCreated, delegate: self) } // MARK: - Configuration Methods override func updateViewConstraints() { super.updateViewConstraints() titleHeightConstraint = titleTextField.heightAnchor.constraint(equalToConstant: titleTextField.font!.lineHeight) titleTopConstraint = titleTextField.topAnchor.constraint(equalTo: view.topAnchor, constant: -richTextView.contentOffset.y) textPlaceholderTopConstraint = placeholderLabel.topAnchor.constraint(equalTo: richTextView.topAnchor, constant: richTextView.textContainerInset.top + richTextView.contentInset.top) updateTitleHeight() let layoutGuide = view.layoutMarginsGuide NSLayoutConstraint.activate([ titleTextField.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor), titleTopConstraint, titleHeightConstraint ]) NSLayoutConstraint.activate([ betaButton.centerYAnchor.constraint(equalTo: titlePlaceholderLabel.centerYAnchor), betaButton.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor), titleTextField.trailingAnchor.constraint(equalTo: betaButton.leadingAnchor, constant: -titleTextField.textContainerInset.right) ]) let insets = titleTextField.textContainerInset NSLayoutConstraint.activate([ titlePlaceholderLabel.leftAnchor.constraint(equalTo: titleTextField.leftAnchor, constant: insets.left + titleTextField.textContainer.lineFragmentPadding), titlePlaceholderLabel.rightAnchor.constraint(equalTo: titleTextField.rightAnchor, constant: -insets.right - titleTextField.textContainer.lineFragmentPadding), titlePlaceholderLabel.topAnchor.constraint(equalTo: titleTextField.topAnchor, constant: insets.top), titlePlaceholderLabel.heightAnchor.constraint(equalToConstant: titleTextField.font!.lineHeight) ]) NSLayoutConstraint.activate([ separatorView.leftAnchor.constraint(equalTo: layoutGuide.leftAnchor), separatorView.rightAnchor.constraint(equalTo: layoutGuide.rightAnchor), separatorView.topAnchor.constraint(equalTo: titleTextField.bottomAnchor), separatorView.heightAnchor.constraint(equalToConstant: separatorView.frame.height) ]) NSLayoutConstraint.activate([ richTextView.leadingAnchor.constraint(equalTo: view.leadingAnchor), richTextView.trailingAnchor.constraint(equalTo: view.trailingAnchor), richTextView.topAnchor.constraint(equalTo: view.topAnchor), richTextView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) NSLayoutConstraint.activate([ htmlTextView.leftAnchor.constraint(equalTo: richTextView.leftAnchor), htmlTextView.rightAnchor.constraint(equalTo: richTextView.rightAnchor), htmlTextView.topAnchor.constraint(equalTo: richTextView.topAnchor), htmlTextView.bottomAnchor.constraint(equalTo: richTextView.bottomAnchor) ]) NSLayoutConstraint.activate([ placeholderLabel.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor, constant: Constants.placeholderPadding.left), placeholderLabel.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor, constant: -(Constants.placeholderPadding.right + richTextView.textContainer.lineFragmentPadding)), textPlaceholderTopConstraint, placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: richTextView.bottomAnchor, constant: Constants.placeholderPadding.bottom) ]) } private func configureDefaultProperties(for textView: UITextView, accessibilityLabel: String) { textView.accessibilityLabel = accessibilityLabel textView.font = Fonts.regular textView.keyboardDismissMode = .interactive textView.textColor = UIColor.darkText textView.translatesAutoresizingMaskIntoConstraints = false } func configureNavigationBar() { navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.accessibilityIdentifier = "Azctec Editor Navigation Bar" navigationItem.leftBarButtonItems = [separatorButtonItem, closeBarButtonItem, blogPickerBarButtonItem] navigationItem.rightBarButtonItems = [moreBarButtonItem, publishBarButtonItem, separatorButtonItem] } /// This is to restore the navigation bar colors after the UIDocumentPickerViewController has been dismissed, /// either by uploading media or cancelling. Doing this in the UIDocumentPickerDelegate methods either did /// nothing or the resetting wasn't permanent. /// fileprivate func resetNavigationColors() { WPStyleGuide.configureNavigationBarAppearance() } func configureDismissButton() { let image = isModal() ? Assets.closeButtonModalImage : Assets.closeButtonRegularImage closeButton.setImage(image, for: .normal) } func configureView() { edgesForExtendedLayout = UIRectEdge() view.backgroundColor = .white } func configureSubviews() { view.addSubview(richTextView) view.addSubview(htmlTextView) view.addSubview(titleTextField) view.addSubview(titlePlaceholderLabel) view.addSubview(separatorView) view.addSubview(placeholderLabel) view.addSubview(betaButton) } func configureMediaProgressView(in navigationBar: UINavigationBar) { guard mediaProgressView.superview == nil else { return } navigationBar.addSubview(mediaProgressView) NSLayoutConstraint.activate([ mediaProgressView.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor), mediaProgressView.widthAnchor.constraint(equalTo: navigationBar.widthAnchor), mediaProgressView.topAnchor.constraint(equalTo: navigationBar.bottomAnchor, constant: -mediaProgressView.frame.height) ]) } func registerAttachmentImageProviders() { let providers: [TextViewAttachmentImageProvider] = [ SpecialTagAttachmentRenderer(), CommentAttachmentRenderer(font: Fonts.regular), HTMLAttachmentRenderer(font: Fonts.regular) ] for provider in providers { richTextView.registerAttachmentImageProvider(provider) } } func startListeningToNotifications() { let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil) nc.addObserver(self, selector: #selector(keyboardDidHide), name: .UIKeyboardDidHide, object: nil) nc.addObserver(self, selector: #selector(applicationWillResignActive(_:)), name: .UIApplicationWillResignActive, object: nil) } func stopListeningToNotifications() { let nc = NotificationCenter.default nc.removeObserver(self, name: .UIKeyboardWillShow, object: nil) nc.removeObserver(self, name: .UIKeyboardDidHide, object: nil) nc.removeObserver(self, name: .UIApplicationWillResignActive, object: nil) } func rememberFirstResponder() { lastFirstResponder = view.findFirstResponder() lastFirstResponder?.resignFirstResponder() } func restoreFirstResponder() { let nextFirstResponder = lastFirstResponder ?? titleTextField nextFirstResponder.becomeFirstResponder() } func refreshInterface() { reloadBlogPickerButton() reloadEditorContents() resizeBlogPickerButton() reloadPublishButton() refreshNavigationBar() } func refreshNavigationBar() { if postEditorStateContext.isUploadingMedia { navigationItem.leftBarButtonItems = [separatorButtonItem, closeBarButtonItem, mediaUploadingBarButtonItem] } else { navigationItem.leftBarButtonItems = [separatorButtonItem, closeBarButtonItem, blogPickerBarButtonItem] } } func setHTML(_ html: String) { setHTML(html, for: mode) } private func setHTML(_ html: String, for mode: EditMode) { switch mode { case .html: htmlTextView.text = html case .richText: richTextView.setHTML(html) self.processVideoPressAttachments() } } func getHTML() -> String { let html: String switch mode { case .html: html = htmlTextView.text case .richText: html = richTextView.getHTML() } return html } func reloadEditorContents() { let content = post.content ?? String() titleTextField.text = post.postTitle setHTML(content) } func reloadBlogPickerButton() { var pickerTitle = post.blog.url ?? String() if let blogName = post.blog.settings?.name, blogName.isEmpty == false { pickerTitle = blogName } let titleText = NSAttributedString(string: pickerTitle, attributes: [NSFontAttributeName: Fonts.blogPicker]) let shouldEnable = !isSingleSiteMode blogPickerButton.setAttributedTitle(titleText, for: .normal) blogPickerButton.buttonMode = shouldEnable ? .multipleSite : .singleSite blogPickerButton.isEnabled = shouldEnable } func reloadPublishButton() { publishButton.setTitle(postEditorStateContext.publishButtonText, for: .normal) publishButton.isEnabled = postEditorStateContext.isPublishButtonEnabled } func resizeBlogPickerButton() { // On iOS 11 no resize is needed because the StackView on the navigation bar will do the work if #available(iOS 11, *) { return } // On iOS 10 and before we still need to manually resize the button. // Ensure the BlogPicker gets it's maximum possible size blogPickerButton.sizeToFit() // Cap the size, according to the current traits var blogPickerSize = hasHorizontallyCompactView() ? Constants.blogPickerCompactSize : Constants.blogPickerRegularSize blogPickerSize.width = min(blogPickerSize.width, blogPickerButton.frame.width) blogPickerButton.frame.size = blogPickerSize } // MARK: - Keyboard Handling override var keyCommands: [UIKeyCommand] { if richTextView.isFirstResponder { return [ UIKeyCommand(input: "B", modifierFlags: .command, action: #selector(toggleBold), discoverabilityTitle: NSLocalizedString("Bold", comment: "Discoverability title for bold formatting keyboard shortcut.")), UIKeyCommand(input: "I", modifierFlags: .command, action: #selector(toggleItalic), discoverabilityTitle: NSLocalizedString("Italic", comment: "Discoverability title for italic formatting keyboard shortcut.")), UIKeyCommand(input: "S", modifierFlags: [.command], action: #selector(toggleStrikethrough), discoverabilityTitle: NSLocalizedString("Strikethrough", comment: "Discoverability title for strikethrough formatting keyboard shortcut.")), UIKeyCommand(input: "U", modifierFlags: .command, action: #selector(toggleUnderline(_:)), discoverabilityTitle: NSLocalizedString("Underline", comment: "Discoverability title for underline formatting keyboard shortcut.")), UIKeyCommand(input: "Q", modifierFlags: [.command, .alternate], action: #selector(toggleBlockquote), discoverabilityTitle: NSLocalizedString("Block Quote", comment: "Discoverability title for block quote keyboard shortcut.")), UIKeyCommand(input: "K", modifierFlags: .command, action: #selector(toggleLink), discoverabilityTitle: NSLocalizedString("Insert Link", comment: "Discoverability title for insert link keyboard shortcut.")), UIKeyCommand(input: "M", modifierFlags: [.command, .alternate], action: #selector(presentMediaPicker), discoverabilityTitle: NSLocalizedString("Insert Media", comment: "Discoverability title for insert media keyboard shortcut.")), UIKeyCommand(input: "U", modifierFlags: [.command, .alternate], action: #selector(toggleUnorderedList), discoverabilityTitle: NSLocalizedString("Bullet List", comment: "Discoverability title for bullet list keyboard shortcut.")), UIKeyCommand(input: "O", modifierFlags: [.command, .alternate], action: #selector(toggleOrderedList), discoverabilityTitle: NSLocalizedString("Numbered List", comment: "Discoverability title for numbered list keyboard shortcut.")), UIKeyCommand(input: "H", modifierFlags: [.command, .shift], action: #selector(toggleEditingMode), discoverabilityTitle: NSLocalizedString("Toggle HTML Source ", comment: "Discoverability title for HTML keyboard shortcut.")) ] } else if htmlTextView.isFirstResponder { return [UIKeyCommand(input: "H", modifierFlags: [.command, .shift], action: #selector(toggleEditingMode), discoverabilityTitle: NSLocalizedString("Toggle HTML Source ", comment: "Discoverability title for HTML keyboard shortcut.")) ] } return [] } func keyboardWillShow(_ notification: Foundation.Notification) { guard let userInfo = notification.userInfo as? [String: AnyObject], let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } // Convert the keyboard frame from window base coordinate currentKeyboardFrame = view.convert(keyboardFrame, from: nil) refreshInsets(forKeyboardFrame: keyboardFrame) } func keyboardDidHide(_ notification: Foundation.Notification) { guard let userInfo = notification.userInfo as? [String: AnyObject], let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } currentKeyboardFrame = .zero refreshInsets(forKeyboardFrame: keyboardFrame) } fileprivate func refreshInsets(forKeyboardFrame keyboardFrame: CGRect) { let referenceView: UIScrollView = mode == .richText ? richTextView : htmlTextView let scrollInsets = UIEdgeInsets(top: referenceView.scrollIndicatorInsets.top, left: 0, bottom: view.frame.maxY - (keyboardFrame.minY + self.view.layoutMargins.bottom), right: 0) let contentInsets = UIEdgeInsets(top: referenceView.contentInset.top, left: 0, bottom: view.frame.maxY - (keyboardFrame.minY + self.view.layoutMargins.bottom), right: 0) htmlTextView.scrollIndicatorInsets = scrollInsets htmlTextView.contentInset = contentInsets richTextView.scrollIndicatorInsets = scrollInsets richTextView.contentInset = contentInsets } func updateFormatBar() { guard let toolbar = richTextView.inputAccessoryView as? Aztec.FormatBar else { return } var identifiers = [FormattingIdentifier]() if richTextView.selectedRange.length > 0 { identifiers = richTextView.formatIdentifiersSpanningRange(richTextView.selectedRange) } else { identifiers = richTextView.formatIdentifiersForTypingAttributes() } toolbar.selectItemsMatchingIdentifiers(identifiers.map({ $0.rawValue })) } } // MARK: - SDK Workarounds! // extension AztecPostViewController { /// Note: /// When presenting an UIAlertController using a navigationBarButton as a source, the entire navigationBar /// gets set as a passthru view, allowing invalid scenarios, such as: pressing the Dismiss Button, while there's /// an ActionSheet onscreen. /// override func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) { super.present(viewControllerToPresent, animated: flag) { if let alert = viewControllerToPresent as? UIAlertController, alert.preferredStyle == .actionSheet { alert.popoverPresentationController?.passthroughViews = nil } completion?() } } } // MARK: - Actions // extension AztecPostViewController { @IBAction func publishButtonTapped(sender: UIBarButtonItem) { trackPostSave(stat: postEditorStateContext.publishActionAnalyticsStat) publishTapped(dismissWhenDone: postEditorStateContext.publishActionDismissesEditor) } @IBAction func secondaryPublishButtonTapped(dismissWhenDone: Bool = true) { let publishPostClosure = { if self.postEditorStateContext.secondaryPublishButtonAction == .save { self.post.status = .draft } else if self.postEditorStateContext.secondaryPublishButtonAction == .publish { self.post.date_created_gmt = Date() self.post.status = .publish } if let stat = self.postEditorStateContext.secondaryPublishActionAnalyticsStat { self.trackPostSave(stat: stat) } self.publishTapped(dismissWhenDone: dismissWhenDone) } if presentedViewController != nil { dismiss(animated: true, completion: publishPostClosure) } else { publishPostClosure() } } func showPostHasChangesAlert() { let title = NSLocalizedString("You have unsaved changes.", comment: "Title of message with options that shown when there are unsaved changes and the author is trying to move away from the post.") let cancelTitle = NSLocalizedString("Keep Editing", comment: "Button shown if there are unsaved changes and the author is trying to move away from the post.") let saveTitle = NSLocalizedString("Save Draft", comment: "Button shown if there are unsaved changes and the author is trying to move away from the post.") let updateTitle = NSLocalizedString("Update Draft", comment: "Button shown if there are unsaved changes and the author is trying to move away from an already published/saved post.") let discardTitle = NSLocalizedString("Discard", comment: "Button shown if there are unsaved changes and the author is trying to move away from the post.") let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) // Button: Keep editing alertController.addCancelActionWithTitle(cancelTitle) // Button: Save Draft/Update Draft if post.hasLocalChanges() { if !post.hasRemote() { // The post is a local draft or an autosaved draft: Discard or Save alertController.addDefaultActionWithTitle(saveTitle) { _ in self.post.status = .draft self.trackPostSave(stat: self.postEditorStateContext.publishActionAnalyticsStat) self.publishTapped(dismissWhenDone: true) } } else if post.status == .draft { // The post was already a draft alertController.addDefaultActionWithTitle(updateTitle) { _ in self.trackPostSave(stat: self.postEditorStateContext.publishActionAnalyticsStat) self.publishTapped(dismissWhenDone: true) } } } // Button: Discard alertController.addDestructiveActionWithTitle(discardTitle) { _ in self.discardChangesAndUpdateGUI() } alertController.popoverPresentationController?.barButtonItem = closeBarButtonItem present(alertController, animated: true, completion: nil) } private func publishTapped(dismissWhenDone: Bool) { // Cancel publishing if media is currently being uploaded if mediaProgressCoordinator.isRunning { displayMediaIsUploadingAlert() return } // If there is any failed media allow it to be removed or cancel publishing if mediaProgressCoordinator.hasFailedMedia { displayHasFailedMediaAlert(then: { // Failed media is removed, try again. // Note: Intentionally not tracking another analytics stat here (no appropriate one exists yet) self.publishTapped(dismissWhenDone: dismissWhenDone) }) return } // If the user is trying to publish to WP.com and they haven't verified their account, prompt them to do so. if let verificationHelper = verificationPromptHelper, verificationHelper.neeedsVerification(before: postEditorStateContext.action) { verificationHelper.displayVerificationPrompt(from: self) { [weak self] verifiedInBackground in // User could've been plausibly silently verified in the background. // If so, proceed to publishing the post as normal, otherwise save it as a draft. if !verifiedInBackground { self?.post.status = .draft } self?.publishTapped(dismissWhenDone: dismissWhenDone) } return } SVProgressHUD.setDefaultMaskType(.clear) SVProgressHUD.show(withStatus: postEditorStateContext.publishVerbText) postEditorStateContext.updated(isBeingPublished: true) // Finally, publish the post. publishPost() { uploadedPost, error in self.postEditorStateContext.updated(isBeingPublished: false) SVProgressHUD.dismiss() let generator = UINotificationFeedbackGenerator() generator.prepare() if let error = error { DDLogError("Error publishing post: \(error.localizedDescription)") SVProgressHUD.showDismissibleError(withStatus: self.postEditorStateContext.publishErrorText) generator.notificationOccurred(.error) } else if let uploadedPost = uploadedPost { self.post = uploadedPost generator.notificationOccurred(.success) } if dismissWhenDone { self.dismissOrPopView(didSave: true) } else { self.createRevisionOfPost() } } } @IBAction func closeWasPressed() { cancelEditing() } @IBAction func blogPickerWasPressed() { assert(isSingleSiteMode == false) guard post.hasSiteSpecificChanges() else { displayBlogSelector() return } displaySwitchSiteAlert() } @IBAction func moreWasPressed() { displayMoreSheet() } @IBAction func betaButtonTapped() { WPAppAnalytics.track(.editorAztecBetaLink) FancyAlertViewController.presentWhatsNewWebView(from: self) } private func trackPostSave(stat: WPAnalyticsStat) { guard stat != .editorSavedDraft && stat != .editorQuickSavedDraft else { WPAppAnalytics.track(stat, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post.blog) return } let originalWordCount = post.original?.content?.wordCount() ?? 0 let wordCount = post.content?.wordCount() ?? 0 var properties: [String: Any] = ["word_count": wordCount, WPAppAnalyticsKeyEditorSource: Analytics.editorSource] if post.hasRemote() { properties["word_diff_count"] = originalWordCount } if stat == .editorPublishedPost { properties[WPAnalyticsStatEditorPublishedPostPropertyCategory] = post.hasCategories() properties[WPAnalyticsStatEditorPublishedPostPropertyPhoto] = post.hasPhoto() properties[WPAnalyticsStatEditorPublishedPostPropertyTag] = post.hasTags() properties[WPAnalyticsStatEditorPublishedPostPropertyVideo] = post.hasVideo() } WPAppAnalytics.track(stat, withProperties: properties, with: post) } } // MARK: - Private Helpers // private extension AztecPostViewController { func displayBlogSelector() { guard let sourceView = blogPickerButton.imageView else { fatalError() } // Setup Handlers let successHandler: BlogSelectorSuccessHandler = { selectedObjectID in self.dismiss(animated: true, completion: nil) guard let blog = self.mainContext.object(with: selectedObjectID) as? Blog else { return } self.recreatePostRevision(in: blog) self.mediaLibraryDataSource = MediaLibraryPickerDataSource(post: self.post) } let dismissHandler: BlogSelectorDismissHandler = { self.dismiss(animated: true, completion: nil) } // Setup Picker let selectorViewController = BlogSelectorViewController(selectedBlogObjectID: post.blog.objectID, successHandler: successHandler, dismissHandler: dismissHandler) selectorViewController.title = NSLocalizedString("Select Site", comment: "Blog Picker's Title") selectorViewController.displaysPrimaryBlogOnTop = true // Note: // On iPad Devices, we'll disable the Picker's SearchController's "Autohide Navbar Feature", since // upon dismissal, it may force the NavigationBar to show up, even when it was initially hidden. selectorViewController.displaysNavigationBarWhenSearching = WPDeviceIdentification.isiPad() // Setup Navigation let navigationController = AdaptiveNavigationController(rootViewController: selectorViewController) navigationController.configurePopoverPresentationStyle(from: sourceView) // Done! present(navigationController, animated: true, completion: nil) } func displayMoreSheet() { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if postEditorStateContext.isSecondaryPublishButtonShown, let buttonTitle = postEditorStateContext.secondaryPublishButtonText { let dismissWhenDone = postEditorStateContext.secondaryPublishButtonAction == .publish alert.addActionWithTitle(buttonTitle, style: dismissWhenDone ? .destructive : .default ) { _ in self.secondaryPublishButtonTapped(dismissWhenDone: dismissWhenDone) } } alert.addDefaultActionWithTitle(MoreSheetAlert.previewTitle) { _ in self.displayPreview() } alert.addDefaultActionWithTitle(MoreSheetAlert.optionsTitle) { _ in self.displayPostOptions() } alert.addCancelActionWithTitle(MoreSheetAlert.cancelTitle) alert.popoverPresentationController?.barButtonItem = moreBarButtonItem present(alert, animated: true, completion: nil) } func displaySwitchSiteAlert() { let alert = UIAlertController(title: SwitchSiteAlert.title, message: SwitchSiteAlert.message, preferredStyle: .alert) alert.addDefaultActionWithTitle(SwitchSiteAlert.acceptTitle) { _ in self.displayBlogSelector() } alert.addCancelActionWithTitle(SwitchSiteAlert.cancelTitle) present(alert, animated: true, completion: nil) } func displayPostOptions() { let settingsViewController: PostSettingsViewController if post is Page { settingsViewController = PageSettingsViewController(post: post) } else { settingsViewController = PostSettingsViewController(post: post) } settingsViewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(settingsViewController, animated: true) } func displayPreview() { let previewController = PostPreviewViewController(post: post) previewController.hidesBottomBarWhenPushed = true navigationController?.pushViewController(previewController, animated: true) } func displayMediaIsUploadingAlert() { let alertController = UIAlertController(title: MediaUploadingAlert.title, message: MediaUploadingAlert.message, preferredStyle: .alert) alertController.addDefaultActionWithTitle(MediaUploadingAlert.acceptTitle) present(alertController, animated: true, completion: nil) } func displayHasFailedMediaAlert(then: @escaping () -> ()) { let alertController = UIAlertController(title: FailedMediaRemovalAlert.title, message: FailedMediaRemovalAlert.message, preferredStyle: .alert) alertController.addDefaultActionWithTitle(MediaUploadingAlert.acceptTitle) { alertAction in self.removeFailedMedia() then() } alertController.addCancelActionWithTitle(FailedMediaRemovalAlert.cancelTitle) present(alertController, animated: true, completion: nil) } @IBAction func displayCancelMediaUploads() { let alertController = UIAlertController(title: MediaUploadingCancelAlert.title, message: MediaUploadingCancelAlert.message, preferredStyle: .alert) alertController.addDefaultActionWithTitle(MediaUploadingCancelAlert.acceptTitle) { alertAction in self.mediaProgressCoordinator.cancelAllPendingUploads() } alertController.addCancelActionWithTitle(MediaUploadingCancelAlert.cancelTitle) present(alertController, animated: true, completion: nil) return } } // MARK: - PostEditorStateContextDelegate & support methods // extension AztecPostViewController: PostEditorStateContextDelegate { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case BasePost.statusKeyPath: if let status = post.status { postEditorStateContext.updated(postStatus: status) editorContentWasUpdated() } case #keyPath(AbstractPost.dateCreated): let dateCreated = post.dateCreated ?? Date() postEditorStateContext.updated(publishDate: dateCreated) editorContentWasUpdated() case #keyPath(AbstractPost.content): editorContentWasUpdated() default: super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } private var editorHasContent: Bool { let titleIsEmpty = post.postTitle?.isEmpty ?? true let contentIsEmpty = post.content?.isEmpty ?? true return !titleIsEmpty || !contentIsEmpty } private var editorHasChanges: Bool { return post.hasUnsavedChanges() } internal func editorContentWasUpdated() { postEditorStateContext.updated(hasContent: editorHasContent) postEditorStateContext.updated(hasChanges: editorHasChanges) } internal func context(_ context: PostEditorStateContext, didChangeAction: PostEditorAction) { reloadPublishButton() } internal func context(_ context: PostEditorStateContext, didChangeActionAllowed: Bool) { reloadPublishButton() } internal func addObservers(toPost: AbstractPost) { toPost.addObserver(self, forKeyPath: AbstractPost.statusKeyPath, options: [], context: nil) toPost.addObserver(self, forKeyPath: #keyPath(AbstractPost.dateCreated), options: [], context: nil) toPost.addObserver(self, forKeyPath: #keyPath(AbstractPost.content), options: [], context: nil) } internal func removeObservers(fromPost: AbstractPost) { fromPost.removeObserver(self, forKeyPath: AbstractPost.statusKeyPath) fromPost.removeObserver(self, forKeyPath: #keyPath(AbstractPost.dateCreated)) fromPost.removeObserver(self, forKeyPath: #keyPath(AbstractPost.content)) } } // MARK: - UITextViewDelegate methods // extension AztecPostViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { switch textView { case titleTextField: return shouldChangeTitleText(in: range, replacementText: text) default: return true } } func textViewDidChangeSelection(_ textView: UITextView) { updateFormatBar() } func textViewDidChange(_ textView: UITextView) { mapUIContentToPostAndSave() refreshPlaceholderVisibility() switch textView { case titleTextField: updateTitleHeight() case richTextView: updateFormatBar() default: break } } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { textView.textAlignment = .natural switch textView { case titleTextField: formatBar.enabled = false case richTextView: formatBar.enabled = true case htmlTextView: formatBar.enabled = false // Disable the bar, except for the source code button let htmlButton = formatBar.items.first(where: { $0.identifier == FormattingIdentifier.sourcecode.rawValue }) htmlButton?.isEnabled = true default: break } if mediaPickerInputViewController == nil { textView.inputAccessoryView = formatBar } return true } func scrollViewDidScroll(_ scrollView: UIScrollView) { refreshTitlePosition() } // MARK: - Title Input Sanitization /// Sanitizes an input for insertion in the title text view. /// /// - Parameters: /// - input: the input for the title text view. /// /// - Returns: the sanitized string /// private func sanitizeInputForTitle(_ input: String) -> String { var sanitizedText = input while let range = sanitizedText.rangeOfCharacter(from: CharacterSet.newlines, options: [], range: nil) { sanitizedText = sanitizedText.replacingCharacters(in: range, with: " ") } return sanitizedText } /// This method performs all necessary checks to verify if the title text can be changed, /// or if some other action should be performed instead. /// /// - Important: this method sanitizes newlines, since they're not allowed in the title. /// /// - Parameters: /// - range: the range that would be modified. /// - text: the new text for the specified range. /// /// - Returns: `true` if the modification can take place, `false` otherwise. /// private func shouldChangeTitleText(in range: NSRange, replacementText text: String) -> Bool { guard text.count > 1 else { guard text.rangeOfCharacter(from: CharacterSet.newlines, options: [], range: nil) == nil else { richTextView.becomeFirstResponder() richTextView.selectedRange = NSRange(location: 0, length: 0) return false } return true } let sanitizedInput = sanitizeInputForTitle(text) let newlinesWereRemoved = sanitizedInput != text guard !newlinesWereRemoved else { titleTextField.insertText(sanitizedInput) return false } return true } } // MARK: - UITextFieldDelegate methods // extension AztecPostViewController { func titleTextFieldDidChange(_ textField: UITextField) { mapUIContentToPostAndSave() editorContentWasUpdated() } } // MARK: - TextViewFormattingDelegate methods // extension AztecPostViewController: Aztec.TextViewFormattingDelegate { func textViewCommandToggledAStyle() { updateFormatBar() } } // MARK: - HTML Mode Switch methods // extension AztecPostViewController { enum EditMode { case richText case html mutating func toggle() { switch self { case .richText: self = .html case .html: self = .richText } } } func refreshEditorVisibility() { let isRichEnabled = mode == .richText htmlTextView.isHidden = isRichEnabled richTextView.isHidden = !isRichEnabled } func refreshPlaceholderVisibility() { placeholderLabel.isHidden = richTextView.isHidden || !richTextView.text.isEmpty titlePlaceholderLabel.isHidden = !titleTextField.text.isEmpty } } // MARK: - FormatBarDelegate Conformance // extension AztecPostViewController: Aztec.FormatBarDelegate { func formatBarTouchesBegan(_ formatBar: FormatBar) { dismissOptionsViewControllerIfNecessary() } /// Called when the overflow items in the format bar are either shown or hidden /// as a result of the user tapping the toggle button. /// func formatBar(_ formatBar: FormatBar, didChangeOverflowState overflowState: FormatBarOverflowState) { let action = overflowState == .visible ? "made_visible" : "made_hidden" trackFormatBarAnalytics(stat: .editorTappedMoreItems, action: action) } } // MARK: FormatBar Actions // extension AztecPostViewController { func handleAction(for barItem: FormatBarItem) { guard let identifier = barItem.identifier else { return } if let formattingIdentifier = FormattingIdentifier(rawValue: identifier) { switch formattingIdentifier { case .bold: toggleBold() case .italic: toggleItalic() case .underline: toggleUnderline() case .strikethrough: toggleStrikethrough() case .blockquote: toggleBlockquote() case .unorderedlist, .orderedlist: toggleList(fromItem: barItem) case .link: toggleLink() case .media: break case .sourcecode: toggleEditingMode() case .p, .header1, .header2, .header3, .header4, .header5, .header6: toggleHeader(fromItem: barItem) case .horizontalruler: insertHorizontalRuler() case .more: insertMore() } updateFormatBar() } else if let mediaIdentifier = FormatBarMediaIdentifier(rawValue: identifier) { switch mediaIdentifier { case .deviceLibrary: trackFormatBarAnalytics(stat: .editorMediaPickerTappedDevicePhotos) presentMediaPickerFullScreen(animated: true, dataSourceType: .device) case .camera: trackFormatBarAnalytics(stat: .editorMediaPickerTappedCamera) mediaPickerInputViewController?.showCapture() case .mediaLibrary: trackFormatBarAnalytics(stat: .editorMediaPickerTappedMediaLibrary) presentMediaPickerFullScreen(animated: true, dataSourceType: .mediaLibrary) case .otherApplications: trackFormatBarAnalytics(stat: .editorMediaPickerTappedOtherApps) showDocumentPicker() } } } func handleFormatBarLeadingItem(_ item: UIButton) { toggleMediaPicker(fromButton: item) } func handleFormatBarTrailingItem(_ item: UIButton) { guard let mediaPicker = mediaPickerInputViewController else { return } mediaPickerController(mediaPicker.mediaPicker, didFinishPicking: mediaPicker.mediaPicker.selectedAssets) } func toggleBold() { trackFormatBarAnalytics(stat: .editorTappedBold) richTextView.toggleBold(range: richTextView.selectedRange) } func toggleItalic() { trackFormatBarAnalytics(stat: .editorTappedItalic) richTextView.toggleItalic(range: richTextView.selectedRange) } func toggleUnderline() { trackFormatBarAnalytics(stat: .editorTappedUnderline) richTextView.toggleUnderline(range: richTextView.selectedRange) } func toggleStrikethrough() { trackFormatBarAnalytics(stat: .editorTappedStrikethrough) richTextView.toggleStrikethrough(range: richTextView.selectedRange) } func toggleOrderedList() { trackFormatBarAnalytics(stat: .editorTappedOrderedList) richTextView.toggleOrderedList(range: richTextView.selectedRange) } func toggleUnorderedList() { trackFormatBarAnalytics(stat: .editorTappedUnorderedList) richTextView.toggleUnorderedList(range: richTextView.selectedRange) } func toggleList(fromItem item: FormatBarItem) { let listOptions = Constants.lists.map { listType -> OptionsTableViewOption in let title = NSAttributedString(string: listType.description, attributes: [:]) return OptionsTableViewOption(image: listType.iconImage, title: title, accessibilityLabel: listType.accessibilityLabel) } var index: Int? = nil if let listType = listTypeForSelectedText() { index = Constants.lists.index(of: listType) } showOptionsTableViewControllerWithOptions(listOptions, fromBarItem: item, selectedRowIndex: index, onSelect: { [weak self] selected in let listType = Constants.lists[selected] switch listType { case .unordered: self?.toggleUnorderedList() case .ordered: self?.toggleOrderedList() } }) } func toggleBlockquote() { trackFormatBarAnalytics(stat: .editorTappedBlockquote) richTextView.toggleBlockquote(range: richTextView.selectedRange) } func listTypeForSelectedText() -> TextList.Style? { var identifiers = [FormattingIdentifier]() if richTextView.selectedRange.length > 0 { identifiers = richTextView.formatIdentifiersSpanningRange(richTextView.selectedRange) } else { identifiers = richTextView.formatIdentifiersForTypingAttributes() } let mapping: [FormattingIdentifier: TextList.Style] = [ .orderedlist: .ordered, .unorderedlist: .unordered ] for (key, value) in mapping { if identifiers.contains(key) { return value } } return nil } func toggleLink() { trackFormatBarAnalytics(stat: .editorTappedLink) var linkTitle = "" var linkURL: URL? = nil var linkRange = richTextView.selectedRange // Let's check if the current range already has a link assigned to it. if let expandedRange = richTextView.linkFullRange(forRange: richTextView.selectedRange) { linkRange = expandedRange linkURL = richTextView.linkURL(forRange: expandedRange) } linkTitle = richTextView.attributedText.attributedSubstring(from: linkRange).string showLinkDialog(forURL: linkURL, title: linkTitle, range: linkRange) } func showLinkDialog(forURL url: URL?, title: String?, range: NSRange) { let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button") let removeTitle = NSLocalizedString("Remove Link", comment: "Label action for removing a link from the editor") let insertTitle = NSLocalizedString("Insert Link", comment: "Label action for inserting a link on the editor") let updateTitle = NSLocalizedString("Update Link", comment: "Label action for updating a link on the editor") let isInsertingNewLink = (url == nil) var urlToUse = url if isInsertingNewLink { if let pastedURL = UIPasteboard.general.value(forPasteboardType: String(kUTTypeURL)) as? URL { urlToUse = pastedURL } } let insertButtonTitle = isInsertingNewLink ? insertTitle : updateTitle let alertController = UIAlertController(title: insertButtonTitle, message: nil, preferredStyle: .alert) // TextField: URL alertController.addTextField(configurationHandler: { [weak self] textField in textField.clearButtonMode = .always textField.placeholder = NSLocalizedString("URL", comment: "URL text field placeholder") textField.text = urlToUse?.absoluteString textField.addTarget(self, action: #selector(AztecPostViewController.alertTextFieldDidChange), for: UIControlEvents.editingChanged) }) // TextField: Link Name alertController.addTextField(configurationHandler: { textField in textField.clearButtonMode = .always textField.placeholder = NSLocalizedString("Link Name", comment: "Link name field placeholder") textField.isSecureTextEntry = false textField.autocapitalizationType = .sentences textField.autocorrectionType = .default textField.spellCheckingType = .default textField.text = title }) // Action: Insert let insertAction = alertController.addDefaultActionWithTitle(insertButtonTitle) { [weak self] action in self?.richTextView.becomeFirstResponder() let linkURLString = alertController.textFields?.first?.text var linkTitle = alertController.textFields?.last?.text if linkTitle == nil || linkTitle!.isEmpty { linkTitle = linkURLString } guard let urlString = linkURLString, let url = URL(string: urlString), let title = linkTitle else { return } self?.richTextView.setLink(url, title: title, inRange: range) } // Disabled until url is entered into field insertAction.isEnabled = urlToUse?.absoluteString.isEmpty == false // Action: Remove if !isInsertingNewLink { alertController.addDestructiveActionWithTitle(removeTitle) { [weak self] action in self?.trackFormatBarAnalytics(stat: .editorTappedUnlink) self?.richTextView.becomeFirstResponder() self?.richTextView.removeLink(inRange: range) } } // Action: Cancel alertController.addCancelActionWithTitle(cancelTitle) { [weak self] _ in self?.richTextView.becomeFirstResponder() } present(alertController, animated: true, completion: nil) } func alertTextFieldDidChange(_ textField: UITextField) { guard let alertController = presentedViewController as? UIAlertController, let urlFieldText = alertController.textFields?.first?.text, let insertAction = alertController.actions.first else { return } insertAction.isEnabled = !urlFieldText.isEmpty } private var mediaInputToolbar: UIToolbar { let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: Constants.toolbarHeight)) toolbar.barTintColor = WPStyleGuide.aztecFormatBarBackgroundColor toolbar.tintColor = WPStyleGuide.aztecFormatBarActiveColor let gridButton = UIBarButtonItem(image: Gridicon.iconOfType(.grid), style: .plain, target: self, action: #selector(mediaAddShowFullScreen)) gridButton.accessibilityLabel = NSLocalizedString("Open full media picker", comment: "Editor button to swich the media picker from quick mode to full picker") toolbar.items = [ UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(mediaAddInputCancelled)), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), gridButton, UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(mediaAddInputDone)) ] for item in toolbar.items! { item.tintColor = WPStyleGuide.aztecFormatBarActiveColor item.setTitleTextAttributes([NSForegroundColorAttributeName: WPStyleGuide.aztecFormatBarActiveColor], for: .normal) } return toolbar } // MARK: - Media Input toolbar button actions /// Method to be called when the grid icon is pressed on the media input toolbar. /// /// - Parameter sender: the button that was pressed. func mediaAddShowFullScreen(_ sender: UIBarButtonItem) { presentMediaPickerFullScreen(animated: true) restoreInputAssistantItems() } /// Method to be called when canceled is pressed. /// /// - Parameter sender: the button that was pressed. func mediaAddInputCancelled(_ sender: UIBarButtonItem) { guard let mediaPicker = mediaPickerInputViewController?.mediaPicker else { return } mediaPickerControllerDidCancel(mediaPicker) restoreInputAssistantItems() } /// Method to be called when done is pressed on the media input toolbar. /// /// - Parameter sender: the button that was pressed. func mediaAddInputDone(_ sender: UIBarButtonItem) { guard let mediaPicker = mediaPickerInputViewController?.mediaPicker else { return } let selectedAssets = mediaPicker.selectedAssets mediaPickerController(mediaPicker, didFinishPicking: selectedAssets) restoreInputAssistantItems() } func restoreInputAssistantItems() { richTextView.inputAssistantItem.leadingBarButtonGroups = originalLeadingBarButtonGroup richTextView.inputAssistantItem.trailingBarButtonGroups = originalTrailingBarButtonGroup richTextView.autocorrectionType = .yes richTextView.reloadInputViews() } @IBAction func presentMediaPicker() { if let item = formatBar.leadingItem { presentMediaPicker(fromButton: item, animated: true) } } fileprivate func presentMediaPickerFullScreen(animated: Bool, dataSourceType: MediaPickerDataSourceType = .device) { let options = WPMediaPickerOptions() options.showMostRecentFirst = true options.filter = [.all] options.allowCaptureOfMedia = false let picker = WPNavigationMediaPickerViewController() switch dataSourceType { case .device: picker.dataSource = devicePhotoLibraryDataSource case .mediaLibrary: picker.startOnGroupSelector = false picker.showGroupSelector = false picker.dataSource = mediaLibraryDataSource } picker.selectionActionTitle = Constants.mediaPickerInsertText picker.mediaPicker.options = options picker.delegate = self picker.modalPresentationStyle = .currentContext if let previousPicker = mediaPickerInputViewController?.mediaPicker { picker.mediaPicker.selectedAssets = previousPicker.selectedAssets } present(picker, animated: true) } private func toggleMediaPicker(fromButton button: UIButton) { if mediaPickerInputViewController != nil { closeMediaPickerInputViewController() trackFormatBarAnalytics(stat: .editorMediaPickerTappedDismiss) } else { presentMediaPicker(fromButton: button, animated: true) } } private func presentMediaPicker(fromButton button: UIButton, animated: Bool = true) { trackFormatBarAnalytics(stat: .editorTappedImage) let options = WPMediaPickerOptions() options.showMostRecentFirst = true options.filter = [WPMediaType.image, WPMediaType.video] options.allowMultipleSelection = true options.allowCaptureOfMedia = false options.scrollVertically = true let picker = WPInputMediaPickerViewController(options: options) mediaPickerInputViewController = picker updateToolbar(formatBar, forMode: .media) originalLeadingBarButtonGroup = richTextView.inputAssistantItem.leadingBarButtonGroups originalTrailingBarButtonGroup = richTextView.inputAssistantItem.trailingBarButtonGroups richTextView.inputAssistantItem.leadingBarButtonGroups = [] richTextView.inputAssistantItem.trailingBarButtonGroups = [] richTextView.autocorrectionType = .no picker.mediaPicker.viewControllerToUseToPresent = self picker.dataSource = WPPHAssetDataSource.sharedInstance() picker.mediaPicker.mediaPickerDelegate = self if currentKeyboardFrame != .zero { // iOS is not adjusting the media picker's height to match the default keyboard's height when autoresizingMask // is set to UIViewAutoresizingFlexibleHeight (even though the docs claim it should). Need to manually // set the picker's frame to the current keyboard's frame. picker.view.autoresizingMask = [] picker.view.frame = CGRect(x: 0, y: 0, width: currentKeyboardFrame.width, height: mediaKeyboardHeight) } presentToolbarViewControllerAsInputView(picker) } func toggleEditingMode() { if mediaProgressCoordinator.isRunning { displayMediaIsUploadingAlert() return } if mediaProgressCoordinator.hasFailedMedia { displayHasFailedMediaAlert(then: { self.toggleEditingMode() }) return } trackFormatBarAnalytics(stat: .editorTappedHTML) formatBar.overflowToolbar(expand: true) mode.toggle() } func toggleHeader(fromItem item: FormatBarItem) { trackFormatBarAnalytics(stat: .editorTappedHeader) let headerOptions = Constants.headers.map { headerType -> OptionsTableViewOption in let attributes = [ NSFontAttributeName: UIFont.systemFont(ofSize: CGFloat(headerType.fontSize)), NSForegroundColorAttributeName: WPStyleGuide.darkGrey() ] let title = NSAttributedString(string: headerType.description, attributes: attributes) return OptionsTableViewOption(image: headerType.iconImage, title: title, accessibilityLabel: headerType.accessibilityLabel) } let selectedIndex = Constants.headers.index(of: self.headerLevelForSelectedText()) showOptionsTableViewControllerWithOptions(headerOptions, fromBarItem: item, selectedRowIndex: selectedIndex, onSelect: { [weak self] selected in guard let range = self?.richTextView.selectedRange else { return } let selectedStyle = Analytics.headerStyleValues[selected] self?.trackFormatBarAnalytics(stat: .editorTappedHeaderSelection, headingStyle: selectedStyle) self?.richTextView.toggleHeader(Constants.headers[selected], range: range) self?.optionsViewController = nil self?.changeRichTextInputView(to: nil) }) } func insertHorizontalRuler() { trackFormatBarAnalytics(stat: .editorTappedHorizontalRule) richTextView.replaceWithHorizontalRuler(at: richTextView.selectedRange) } func insertMore() { trackFormatBarAnalytics(stat: .editorTappedMore) richTextView.replace(richTextView.selectedRange, withComment: Constants.moreAttachmentText) } func headerLevelForSelectedText() -> Header.HeaderType { var identifiers = [FormattingIdentifier]() if richTextView.selectedRange.length > 0 { identifiers = richTextView.formatIdentifiersSpanningRange(richTextView.selectedRange) } else { identifiers = richTextView.formatIdentifiersForTypingAttributes() } let mapping: [FormattingIdentifier: Header.HeaderType] = [ .header1: .h1, .header2: .h2, .header3: .h3, .header4: .h4, .header5: .h5, .header6: .h6, ] for (key, value) in mapping { if identifiers.contains(key) { return value } } return .none } private func showDocumentPicker() { let docTypes = [String(kUTTypeImage), String(kUTTypeMovie)] let docPicker = UIDocumentPickerViewController(documentTypes: docTypes, in: .import) docPicker.delegate = self WPStyleGuide.configureDocumentPickerNavBarAppearance() present(docPicker, animated: true, completion: nil) } // MARK: - Present Toolbar related VC fileprivate func dismissOptionsViewControllerIfNecessary() { guard optionsViewController != nil else { return } dismissOptionsViewController() } func showOptionsTableViewControllerWithOptions(_ options: [OptionsTableViewOption], fromBarItem barItem: FormatBarItem, selectedRowIndex index: Int?, onSelect: OptionsTableViewController.OnSelectHandler?) { // Hide the input view if we're already showing these options if let optionsViewController = optionsViewController ?? (presentedViewController as? OptionsTableViewController), optionsViewController.options == options { self.optionsViewController = nil changeRichTextInputView(to: nil) return } optionsViewController = OptionsTableViewController(options: options) optionsViewController.cellDeselectedTintColor = WPStyleGuide.aztecFormatBarInactiveColor optionsViewController.cellBackgroundColor = WPStyleGuide.aztecFormatPickerBackgroundColor optionsViewController.cellSelectedBackgroundColor = WPStyleGuide.aztecFormatPickerSelectedCellBackgroundColor optionsViewController.view.tintColor = WPStyleGuide.aztecFormatBarActiveColor optionsViewController.onSelect = { [weak self] selected in onSelect?(selected) self?.dismissOptionsViewController() } let selectRow = { guard let index = index else { return } self.optionsViewController?.selectRow(at: index) } if UIDevice.current.userInterfaceIdiom == .pad { presentToolbarViewController(optionsViewController, asPopoverFromBarItem: barItem, completion: selectRow) } else { presentToolbarViewControllerAsInputView(optionsViewController) selectRow() } } private func presentToolbarViewController(_ viewController: UIViewController, asPopoverFromBarItem barItem: FormatBarItem, completion: (() -> Void)? = nil) { viewController.modalPresentationStyle = .popover viewController.popoverPresentationController?.permittedArrowDirections = [.down] viewController.popoverPresentationController?.sourceView = view let frame = barItem.superview?.convert(barItem.frame, to: UIScreen.main.coordinateSpace) optionsViewController.popoverPresentationController?.sourceRect = view.convert(frame!, from: UIScreen.main.coordinateSpace) optionsViewController.popoverPresentationController?.backgroundColor = WPStyleGuide.aztecFormatPickerBackgroundColor optionsViewController.popoverPresentationController?.delegate = self present(viewController, animated: true, completion: completion) } private func presentToolbarViewControllerAsInputView(_ viewController: UIViewController) { self.addChildViewController(viewController) changeRichTextInputView(to: viewController.view) viewController.didMove(toParentViewController: self) } private func dismissOptionsViewController() { switch UIDevice.current.userInterfaceIdiom { case .pad: dismiss(animated: true, completion: nil) default: optionsViewController?.removeFromParentViewController() changeRichTextInputView(to: nil) } optionsViewController = nil } func changeRichTextInputView(to: UIView?) { guard richTextView.inputView != to else { return } richTextView.inputView = to richTextView.reloadInputViews() } fileprivate func trackFormatBarAnalytics(stat: WPAnalyticsStat, action: String? = nil, headingStyle: String? = nil) { var properties = [WPAppAnalyticsKeyEditorSource: Analytics.editorSource] if let action = action { properties["action"] = action } if let headingStyle = headingStyle { properties["heading_style"] = headingStyle } WPAppAnalytics.track(stat, withProperties: properties, with: post) } // MARK: - Toolbar creation // Used to determine which icons to show on the format bar fileprivate enum FormatBarMode { case text case media } fileprivate func updateToolbar(_ toolbar: Aztec.FormatBar, forMode mode: FormatBarMode) { if let leadingItem = toolbar.leadingItem { rotateMediaToolbarItem(leadingItem, forMode: mode) } toolbar.trailingItem = nil switch mode { case .text: toolbar.setDefaultItems(scrollableItemsForToolbar, overflowItems: overflowItemsForToolbar) case .media: toolbar.setDefaultItems(mediaItemsForToolbar, overflowItems: []) } } private func rotateMediaToolbarItem(_ item: UIButton, forMode mode: FormatBarMode) { let transform: CGAffineTransform let accessibilityIdentifier: String let accessibilityLabel: String switch mode { case .text: accessibilityIdentifier = FormattingIdentifier.media.accessibilityIdentifier accessibilityLabel = FormattingIdentifier.media.accessibilityLabel transform = .identity case .media: accessibilityIdentifier = "format_toolbar_close_media" accessibilityLabel = NSLocalizedString("Close Media Picker", comment: "Accessibility label for button that closes the media picker on formatting toolbar") transform = CGAffineTransform(rotationAngle: Constants.Animations.formatBarMediaButtonRotationAngle) } let animator = UIViewPropertyAnimator(duration: Constants.Animations.formatBarMediaButtonRotationDuration, curve: .easeInOut) { item.transform = transform } animator.addCompletion({ position in if position == .end { item.accessibilityIdentifier = accessibilityIdentifier item.accessibilityLabel = accessibilityLabel } }) animator.startAnimation() } func makeToolbarButton(identifier: FormattingIdentifier) -> FormatBarItem { return makeToolbarButton(identifier: identifier.rawValue, provider: identifier) } func makeToolbarButton(identifier: FormatBarMediaIdentifier) -> FormatBarItem { return makeToolbarButton(identifier: identifier.rawValue, provider: identifier) } func makeToolbarButton(identifier: String, provider: FormatBarItemProvider) -> FormatBarItem { let button = FormatBarItem(image: provider.iconImage, identifier: identifier) button.accessibilityLabel = provider.accessibilityLabel button.accessibilityIdentifier = provider.accessibilityIdentifier return button } func createToolbar() -> Aztec.FormatBar { let toolbar = Aztec.FormatBar() toolbar.tintColor = WPStyleGuide.aztecFormatBarInactiveColor toolbar.highlightedTintColor = WPStyleGuide.aztecFormatBarActiveColor toolbar.selectedTintColor = WPStyleGuide.aztecFormatBarActiveColor toolbar.disabledTintColor = WPStyleGuide.aztecFormatBarDisabledColor toolbar.dividerTintColor = WPStyleGuide.aztecFormatBarDividerColor toolbar.overflowToggleIcon = Gridicon.iconOfType(.ellipsis) toolbar.leadingItem = makeToolbarButton(identifier: .media) updateToolbar(toolbar, forMode: .text) toolbar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: Constants.toolbarHeight) toolbar.formatter = self toolbar.barItemHandler = { [weak self] item in self?.handleAction(for: item) } toolbar.leadingItemHandler = { [weak self] item in self?.handleFormatBarLeadingItem(item) } toolbar.trailingItemHandler = { [weak self] item in self?.handleFormatBarTrailingItem(item) } return toolbar } var mediaItemsForToolbar: [FormatBarItem] { var toolbarButtons = [makeToolbarButton(identifier: .deviceLibrary)] if UIImagePickerController.isSourceTypeAvailable(.camera) { toolbarButtons.append(makeToolbarButton(identifier: .camera)) } toolbarButtons.append(makeToolbarButton(identifier: .mediaLibrary)) if #available(iOS 11, *), FeatureFlag.iCloudFilesSupport.enabled { toolbarButtons.append(makeToolbarButton(identifier: .otherApplications)) } return toolbarButtons } var scrollableItemsForToolbar: [FormatBarItem] { let headerButton = makeToolbarButton(identifier: .p) var alternativeIcons = [String: UIImage]() let headings = Constants.headers.suffix(from: 1) // Remove paragraph style for heading in headings { alternativeIcons[heading.formattingIdentifier.rawValue] = heading.iconImage } headerButton.alternativeIcons = alternativeIcons let listButton = makeToolbarButton(identifier: .unorderedlist) var listIcons = [String: UIImage]() for list in Constants.lists { listIcons[list.formattingIdentifier.rawValue] = list.iconImage } listButton.alternativeIcons = listIcons return [ headerButton, listButton, makeToolbarButton(identifier: .blockquote), makeToolbarButton(identifier: .bold), makeToolbarButton(identifier: .italic), makeToolbarButton(identifier: .link) ] } var overflowItemsForToolbar: [FormatBarItem] { return [ makeToolbarButton(identifier: .underline), makeToolbarButton(identifier: .strikethrough), makeToolbarButton(identifier: .horizontalruler), makeToolbarButton(identifier: .more), makeToolbarButton(identifier: .sourcecode) ] } } // MARK: - UINavigationControllerDelegate Conformance // extension AztecPostViewController: UINavigationControllerDelegate { } // MARK: - UIPopoverPresentationControllerDelegate // extension AztecPostViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { if optionsViewController != nil { optionsViewController = nil } } } // MARK: - Unknown HTML // private extension AztecPostViewController { func displayUnknownHtmlEditor(for attachment: HTMLAttachment) { let targetVC = UnknownEditorViewController(attachment: attachment) targetVC.onDidSave = { [weak self] html in self?.richTextView.edit(attachment) { htmlAttachment in htmlAttachment.rawHTML = html } self?.dismiss(animated: true, completion: nil) } targetVC.onDidCancel = { [weak self] in self?.dismiss(animated: true, completion: nil) } let navigationController = UINavigationController(rootViewController: targetVC) displayAsPopover(viewController: navigationController) } func displayAsPopover(viewController: UIViewController) { viewController.modalPresentationStyle = .popover viewController.preferredContentSize = view.frame.size let presentationController = viewController.popoverPresentationController presentationController?.sourceView = view presentationController?.delegate = self present(viewController, animated: true, completion: nil) } } // MARK: - Cancel/Dismiss/Persistence Logic // private extension AztecPostViewController { // TODO: Rip this out and put it into the PostService func createRevisionOfPost() { guard let context = post.managedObjectContext else { return } // Using performBlock: with the AbstractPost on the main context: // Prevents a hang on opening this view on slow and fast devices // by deferring the cloning and UI update. // Slower devices have the effect of the content appearing after // a short delay context.performAndWait { self.post = self.post.createRevision() ContextManager.sharedInstance().save(context) } } // TODO: Rip this and put it into PostService, as well func recreatePostRevision(in blog: Blog) { let shouldCreatePage = post is Page let postService = PostService(managedObjectContext: mainContext) let newPost = shouldCreatePage ? postService.createDraftPage(for: blog) : postService.createDraftPost(for: blog) newPost.content = contentByStrippingMediaAttachments() newPost.postTitle = post.postTitle newPost.password = post.password newPost.status = post.status newPost.dateCreated = post.dateCreated newPost.dateModified = post.dateModified if let source = post as? Post, let target = newPost as? Post { target.tags = source.tags } discardChanges() post = newPost createRevisionOfPost() RecentSitesService().touch(blog: blog) // TODO: Add this snippet, if needed, once we've relocated this helper to PostService //[self syncOptionsIfNecessaryForBlog:blog afterBlogChanged:YES]; } func cancelEditing() { stopEditing() if post.canSave() && post.hasUnsavedChanges() { showPostHasChangesAlert() } else { discardChangesAndUpdateGUI() } } func stopEditing() { view.endEditing(true) } func discardChanges() { guard let context = post.managedObjectContext, let originalPost = post.original else { return } WPAppAnalytics.track(.editorDiscardedChanges, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post) post = originalPost post.deleteRevision() if shouldRemovePostOnDismiss { post.remove() } mediaProgressCoordinator.cancelAllPendingUploads() ContextManager.sharedInstance().save(context) } func discardChangesAndUpdateGUI() { discardChanges() dismissOrPopView(didSave: false) } func dismissOrPopView(didSave: Bool) { stopEditing() WPAppAnalytics.track(.editorClosed, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post) if let onClose = onClose { onClose(didSave) } else if isModal() { presentingViewController?.dismiss(animated: true, completion: nil) } else { _ = navigationController?.popViewController(animated: true) } } func contentByStrippingMediaAttachments() -> String { if mode == .html { setHTML(htmlTextView.text) } richTextView.removeMediaAttachments() let strippedHTML = getHTML() if mode == .html { setHTML(strippedHTML) } return strippedHTML } func mapUIContentToPostAndSave() { post.postTitle = titleTextField.text post.content = getHTML() ContextManager.sharedInstance().save(post.managedObjectContext!) } func publishPost(completion: ((_ post: AbstractPost?, _ error: Error?) -> Void)? = nil) { mapUIContentToPostAndSave() let managedObjectContext = ContextManager.sharedInstance().mainContext let postService = PostService(managedObjectContext: managedObjectContext) postService.uploadPost(post, success: { uploadedPost in completion?(uploadedPost, nil) }) { error in completion?(nil, error) } } } // MARK: - Computed Properties // private extension AztecPostViewController { var mainContext: NSManagedObjectContext { return ContextManager.sharedInstance().mainContext } var currentBlogCount: Int { let service = BlogService(managedObjectContext: mainContext) return service.blogCountForAllAccounts() } var isSingleSiteMode: Bool { return currentBlogCount <= 1 || post.hasRemote() } /// Height to use for the inline media picker based on iOS version and screen orientation. /// var mediaKeyboardHeight: CGFloat { var keyboardHeight: CGFloat // Let's assume a sensible default for the keyboard height based on orientation let keyboardFrameRatioDefault = UIInterfaceOrientationIsPortrait(UIApplication.shared.statusBarOrientation) ? Constants.mediaPickerKeyboardHeightRatioPortrait : Constants.mediaPickerKeyboardHeightRatioLandscape let keyboardHeightDefault = (keyboardFrameRatioDefault * UIScreen.main.bounds.height) if #available(iOS 11, *) { // On iOS 11, we need to make an assumption the hardware keyboard is attached based on // the height of the current keyboard frame being less than our sensible default. If it is // "attached", let's just use our default. if currentKeyboardFrame.height < keyboardHeightDefault { keyboardHeight = keyboardHeightDefault } else { keyboardHeight = (currentKeyboardFrame.height - Constants.toolbarHeight) } } else { // On iOS 10, when the soft keyboard is visible, the keyboard's frame is within the dimensions of the screen. // However, when an external keyboard is present, the keyboard's frame is located offscreen. Test to see if // that is true and adjust the keyboard height as necessary. if (currentKeyboardFrame.origin.y + currentKeyboardFrame.height) > view.frame.height { keyboardHeight = (currentKeyboardFrame.maxY - view.frame.height) } else { keyboardHeight = (currentKeyboardFrame.height - Constants.toolbarHeight) } } // Sanity check keyboardHeight = max(keyboardHeight, keyboardHeightDefault) return keyboardHeight } } // MARK: - MediaProgressCoordinatorDelegate // extension AztecPostViewController: MediaProgressCoordinatorDelegate { func configureMediaAppearance() { MediaAttachment.defaultAppearance.progressBackgroundColor = Colors.mediaProgressBarBackground MediaAttachment.defaultAppearance.progressColor = Colors.mediaProgressBarTrack MediaAttachment.defaultAppearance.overlayColor = Colors.mediaProgressOverlay MediaAttachment.defaultAppearance.overlayBorderWidth = Constants.mediaOverlayBorderWidth MediaAttachment.defaultAppearance.overlayBorderColor = Colors.mediaOverlayBorderColor } func mediaProgressCoordinator(_ mediaProgressCoordinator: MediaProgressCoordinator, progressDidChange progress: Float) { mediaProgressView.isHidden = !mediaProgressCoordinator.isRunning mediaProgressView.progress = progress for (attachmentID, progress) in self.mediaProgressCoordinator.mediaUploading { guard let attachment = richTextView.attachment(withId: attachmentID) else { continue } if progress.fractionCompleted >= 1 { attachment.progress = nil } else { attachment.progress = progress.fractionCompleted } richTextView.refresh(attachment) } } func mediaProgressCoordinatorDidStartUploading(_ mediaProgressCoordinator: MediaProgressCoordinator) { postEditorStateContext.update(isUploadingMedia: true) refreshNavigationBar() } func mediaProgressCoordinatorDidFinishUpload(_ mediaProgressCoordinator: MediaProgressCoordinator) { postEditorStateContext.update(isUploadingMedia: false) refreshNavigationBar() } } // MARK: - Media Support // extension AztecPostViewController { fileprivate func insertExternalMediaWithURL(_ url: URL) { do { var newAttachment: MediaAttachment? var newStatType: WPAnalyticsStat? let expected = try MediaURLExporter.expectedExport(with: url) switch expected { case .image: newAttachment = imageAttachmentWithPlaceholder() newStatType = .editorAddedPhotoViaOtherApps case .video: newAttachment = videoAttachmentWithPlaceholder() newStatType = .editorAddedVideoViaOtherApps default: break } guard let attachment = newAttachment, let statType = newStatType else { return } let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) mediaService.createMedia(url: url, forPost: post.objectID, thumbnailCallback: { [weak self](thumbnailURL) in self?.handleThumbnailURL(thumbnailURL, attachment: attachment) }, completion: { [weak self](media, error) in self?.handleNewMedia(media, error: error, attachment: attachment, statType: statType) }) } catch { print(MediaURLExporter().exporterErrorWith(error: error)) return } } fileprivate func insertDeviceMedia(phAsset: PHAsset) { switch phAsset.mediaType { case .image: insertDeviceImage(phAsset: phAsset) case .video: insertDeviceVideo(phAsset: phAsset) default: return } } fileprivate func insertDeviceImage(phAsset: PHAsset) { let attachment = imageAttachmentWithPlaceholder() let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) mediaService.createMedia(with: phAsset, forPost: post.objectID, thumbnailCallback: { [weak self](thumbnailURL) in self?.handleThumbnailURL(thumbnailURL, attachment: attachment) }, completion: { [weak self](media, error) in self?.handleNewMedia(media, error: error, attachment: attachment, statType: .editorAddedPhotoViaLocalLibrary) }) } fileprivate func insertDeviceVideo(phAsset: PHAsset) { let attachment = videoAttachmentWithPlaceholder() let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) mediaService.createMedia(with: phAsset, forPost: post.objectID, thumbnailCallback: { [weak self](thumbnailURL) in self?.handleThumbnailURL(thumbnailURL, attachment: attachment) }, completion: { [weak self](media, error) in self?.handleNewMedia(media, error: error, attachment: attachment, statType: .editorAddedVideoViaLocalLibrary) }) } fileprivate func insertSiteMediaLibrary(media: Media) { if media.hasRemote { insertRemoteSiteMediaLibrary(media: media) } else { insertLocalSiteMediaLibrary(media: media) } } private func imageAttachmentWithPlaceholder() -> ImageAttachment { return richTextView.replaceWithImage(at: self.richTextView.selectedRange, sourceURL: URL(string: "placeholder://")!, placeHolderImage: Assets.defaultMissingImage) } private func videoAttachmentWithPlaceholder() -> VideoAttachment { return richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: URL(string: "placeholder://")!, posterURL: URL(string: "placeholder://")!, placeHolderImage: Assets.defaultMissingImage) } private func handleThumbnailURL(_ thumbnailURL: URL, attachment: Any) { DispatchQueue.main.async { if let attachment = attachment as? ImageAttachment { attachment.updateURL(thumbnailURL) self.richTextView.refresh(attachment) } else if let attachment = attachment as? VideoAttachment { attachment.posterURL = thumbnailURL self.richTextView.refresh(attachment) } } } private func handleNewMedia(_ media: Media?, error: Error?, attachment: MediaAttachment, statType: WPAnalyticsStat) { guard let media = media, error == nil else { DispatchQueue.main.async { self.handleError(error as NSError?, onAttachment: attachment) } return } WPAppAnalytics.track(statType, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post.blog) upload(media: media, mediaID: attachment.identifier) } fileprivate func insertRemoteSiteMediaLibrary(media: Media) { guard let remoteURLStr = media.remoteURL, let remoteURL = URL(string: remoteURLStr) else { return } switch media.mediaType { case .image: let attachment = richTextView.replaceWithImage(at: richTextView.selectedRange, sourceURL: remoteURL, placeHolderImage: Assets.defaultMissingImage) attachment.alt = media.alt WPAppAnalytics.track(.editorAddedPhotoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post) case .video: var posterURL: URL? if let posterURLString = media.remoteThumbnailURL { posterURL = URL(string: posterURLString) } let attachment = richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: remoteURL, posterURL: posterURL, placeHolderImage: Assets.defaultMissingImage) if let videoPressGUID = media.videopressGUID, !videoPressGUID.isEmpty { attachment.videoPressID = videoPressGUID richTextView.refresh(attachment) } WPAppAnalytics.track(.editorAddedVideoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post) default: // If we drop in here, let's just insert a link the the remote media let linkTitle = media.title?.nonEmptyString() ?? remoteURLStr richTextView.setLink(remoteURL, title: linkTitle, inRange: richTextView.selectedRange) WPAppAnalytics.track(.editorAddedOtherMediaViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post) } self.mediaProgressCoordinator.finishOneItem() } fileprivate func insertLocalSiteMediaLibrary(media: Media) { var tempMediaURL = URL(string: "placeholder://")! if let absoluteURL = media.absoluteLocalURL { tempMediaURL = absoluteURL } var attachment: MediaAttachment? if media.mediaType == .image { attachment = self.richTextView.replaceWithImage(at: richTextView.selectedRange, sourceURL: tempMediaURL, placeHolderImage: Assets.defaultMissingImage) WPAppAnalytics.track(.editorAddedPhotoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post) } else if media.mediaType == .video, let remoteURLStr = media.remoteURL, let remoteURL = URL(string: remoteURLStr) { attachment = richTextView.replaceWithVideo(at: richTextView.selectedRange, sourceURL: remoteURL, posterURL: media.absoluteThumbnailLocalURL, placeHolderImage: Assets.defaultMissingImage) WPAppAnalytics.track(.editorAddedVideoViaWPMediaLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: selectedMediaOrigin), with: post) } if let attachment = attachment { upload(media: media, mediaID: attachment.identifier) } } fileprivate func saveToMedia(attachment: MediaAttachment) { guard let image = attachment.image else { return } mediaProgressCoordinator.track(numberOfItems: 1) let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) mediaService.createMedia(with: image, withMediaID: "CopyPasteImage", forPost: post.objectID, thumbnailCallback: { (thumbnailURL) in DispatchQueue.main.async { if let imageAttachment = attachment as? ImageAttachment { imageAttachment.updateURL(thumbnailURL) self.richTextView.refresh(imageAttachment) } } }, completion: { [weak self](media, error) in guard let strongSelf = self else { return } guard let media = media, error == nil else { DispatchQueue.main.async { strongSelf.handleError(error as NSError?, onAttachment: attachment) } return } if media.mediaType == .image { WPAppAnalytics.track(.editorAddedPhotoViaLocalLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: strongSelf.selectedMediaOrigin), with: strongSelf.post.blog) } else if media.mediaType == .video { WPAppAnalytics.track(.editorAddedVideoViaLocalLibrary, withProperties: WPAppAnalytics.properties(for: media, mediaOrigin: strongSelf.selectedMediaOrigin), with: strongSelf.post.blog) } strongSelf.upload(media: media, mediaID: attachment.identifier) }) } private func upload(media: Media, mediaID: String) { guard let attachment = richTextView.attachment(withId: mediaID) else { return } let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) var uploadProgress: Progress? mediaService.uploadMedia(media, progress: &uploadProgress, success: { _ in guard let remoteURLStr = media.remoteURL, let remoteURL = URL(string: remoteURLStr) else { return } DispatchQueue.main.async { if let imageAttachment = attachment as? ImageAttachment { if let width = media.width?.intValue { imageAttachment.width = width } if let height = media.height?.intValue { imageAttachment.height = height } if let mediaID = media.mediaID?.intValue { imageAttachment.imageID = mediaID } imageAttachment.updateURL(remoteURL, refreshAsset: false) } else if let videoAttachment = attachment as? VideoAttachment, let videoURLString = media.remoteURL { videoAttachment.srcURL = URL(string: videoURLString) if let videoPosterURLString = media.remoteThumbnailURL { videoAttachment.posterURL = URL(string: videoPosterURLString) } if let videoPressGUID = media.videopressGUID, !videoPressGUID.isEmpty { videoAttachment.videoPressID = videoPressGUID } } } }, failure: { [weak self] error in guard let strongSelf = self else { return } WPAppAnalytics.track(.editorUploadMediaFailed, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: strongSelf.post.blog) DispatchQueue.main.async { strongSelf.handleError(error as NSError?, onAttachment: attachment) } }) if let progress = uploadProgress { mediaProgressCoordinator.track(progress: progress, ofObject: media, withMediaID: mediaID) } } private func handleError(_ error: NSError?, onAttachment attachment: Aztec.MediaAttachment) { let message = NSLocalizedString("Failed to insert media.\n Please tap for options.", comment: "Error message to show to use when media insertion on a post fails") if let error = error { if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { self.richTextView.remove(attachmentID: attachment.identifier) return } mediaProgressCoordinator.attach(error: error, toMediaID: attachment.identifier) } let attributeMessage = NSAttributedString(string: message, attributes: mediaMessageAttributes) attachment.message = attributeMessage attachment.overlayImage = Gridicon.iconOfType(.refresh, withSize: Constants.mediaOverlayIconSize) attachment.shouldHideBorder = true richTextView.refresh(attachment) } fileprivate func removeFailedMedia() { let failedMediaIDs = mediaProgressCoordinator.failedMediaIDs for mediaID in failedMediaIDs { richTextView.remove(attachmentID: mediaID) mediaProgressCoordinator.cancelAndStopTrack(of: mediaID) } } fileprivate func processVideoPressAttachments() { richTextView.textStorage.enumerateAttachments { (attachment, range) in if let videoAttachment = attachment as? VideoAttachment, let videoSrcURL = videoAttachment.srcURL, videoSrcURL.scheme == VideoShortcodeProcessor.videoPressScheme, let videoPressID = videoSrcURL.host { // It's videoPress video so let's fetch the information for the video let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) mediaService.getMediaURL(fromVideoPressID: videoPressID, in: self.post.blog, success: { (videoURLString, posterURLString) in videoAttachment.srcURL = URL(string: videoURLString) if let validPosterURLString = posterURLString, let posterURL = URL(string: validPosterURLString) { videoAttachment.posterURL = posterURL } self.richTextView.refresh(videoAttachment) }, failure: { (error) in DDLogError("Unable to find information for VideoPress video with ID = \(videoPressID). Details: \(error.localizedDescription)") }) } else if let videoAttachment = attachment as? VideoAttachment, let videoSrcURL = videoAttachment.srcURL, videoAttachment.posterURL == nil { let asset = AVURLAsset(url: videoSrcURL as URL, options: nil) let imgGenerator = AVAssetImageGenerator(asset: asset) imgGenerator.maximumSize = .zero imgGenerator.appliesPreferredTrackTransform = true let timeToCapture = NSValue(time: CMTimeMake(0, 1)) imgGenerator.generateCGImagesAsynchronously(forTimes: [timeToCapture], completionHandler: { (time, cgImage, actualTime, result, error) in guard let cgImage = cgImage else { return } let uiImage = UIImage(cgImage: cgImage) let url = self.URLForTemporaryFileWithFileExtension(".jpg") do { try uiImage.writeJPEGToURL(url) DispatchQueue.main.async { videoAttachment.posterURL = url self.richTextView.refresh(videoAttachment) } } catch { DDLogError("Unable to grab frame from video = \(videoSrcURL). Details: \(error.localizedDescription)") } }) } } } private func URLForTemporaryFileWithFileExtension(_ fileExtension: String) -> URL { assert(!fileExtension.isEmpty, "file Extension cannot be empty") let fileName = "\(ProcessInfo.processInfo.globallyUniqueString)_file.\(fileExtension)" let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName) return fileURL } // TODO: Extract these strings into structs like other items fileprivate func displayActions(forAttachment attachment: MediaAttachment, position: CGPoint) { let mediaID = attachment.identifier let title: String = NSLocalizedString("Media Options", comment: "Title for action sheet with media options.") var message: String? let alertController = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) alertController.addActionWithTitle(NSLocalizedString("Dismiss", comment: "User action to dismiss media options."), style: .cancel, handler: { (action) in if attachment == self.currentSelectedAttachment { self.currentSelectedAttachment = nil self.resetMediaAttachmentOverlay(attachment) self.richTextView.refresh(attachment) } }) if let imageAttachment = attachment as? ImageAttachment { alertController.preferredAction = alertController.addActionWithTitle(NSLocalizedString("Edit", comment: "User action to edit media details."), style: .default, handler: { (action) in self.displayDetails(forAttachment: imageAttachment) }) } else if let videoAttachment = attachment as? VideoAttachment, mediaProgressCoordinator.error(forMediaID: mediaID) == nil, !mediaProgressCoordinator.isMediaUploading(mediaID: mediaID) { alertController.preferredAction = alertController.addActionWithTitle(NSLocalizedString("Play Video", comment: "User action to play a video on the editor."), style: .default, handler: { (action) in self.displayPlayerFor(videoAttachment: videoAttachment, atPosition: position) }) } // Is upload still going? if let mediaProgress = mediaProgressCoordinator.progress(forMediaID: mediaID), mediaProgress.completedUnitCount < mediaProgress.totalUnitCount { alertController.addActionWithTitle(NSLocalizedString("Stop Upload", comment: "User action to stop upload."), style: .destructive, handler: { (action) in mediaProgress.cancel() self.richTextView.remove(attachmentID: mediaID) }) } else { if let error = mediaProgressCoordinator.error(forMediaID: mediaID) { message = error.localizedDescription alertController.addActionWithTitle(NSLocalizedString("Retry Upload", comment: "User action to retry media upload."), style: .default, handler: { (action) in //retry upload if let media = self.mediaProgressCoordinator.object(forMediaID: mediaID) as? Media, let attachment = self.richTextView.attachment(withId: mediaID) { self.resetMediaAttachmentOverlay(attachment) attachment.progress = 0 self.richTextView.refresh(attachment) self.mediaProgressCoordinator.track(numberOfItems: 1) WPAppAnalytics.track(.editorUploadMediaRetried, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: self.post.blog) self.upload(media: media, mediaID: mediaID) } }) } alertController.addActionWithTitle(NSLocalizedString("Remove", comment: "User action to remove media."), style: .destructive, handler: { (action) in self.richTextView.remove(attachmentID: mediaID) }) } alertController.title = title alertController.message = message alertController.popoverPresentationController?.sourceView = richTextView alertController.popoverPresentationController?.sourceRect = CGRect(origin: position, size: CGSize(width: 1, height: 1)) alertController.popoverPresentationController?.permittedArrowDirections = .any present(alertController, animated: true, completion: { () in UIMenuController.shared.setMenuVisible(false, animated: false) }) } func displayDetails(forAttachment attachment: ImageAttachment) { let controller = AztecAttachmentViewController() controller.attachment = attachment controller.onUpdate = { [weak self] (alignment, size, alt) in self?.richTextView.edit(attachment) { updated in updated.alignment = alignment updated.size = size updated.alt = alt } } controller.onCancel = { [weak self] in if attachment == self?.currentSelectedAttachment { self?.currentSelectedAttachment = nil self?.resetMediaAttachmentOverlay(attachment) self?.richTextView.refresh(attachment) } } let navController = UINavigationController(rootViewController: controller) navController.modalPresentationStyle = .formSheet present(navController, animated: true, completion: nil) WPAppAnalytics.track(.editorEditedImage, withProperties: [WPAppAnalyticsKeyEditorSource: Analytics.editorSource], with: post) } var mediaMessageAttributes: [String: Any] { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center let attributes: [String: Any] = [NSFontAttributeName: Fonts.mediaOverlay, NSParagraphStyleAttributeName: paragraphStyle, NSForegroundColorAttributeName: UIColor.white] return attributes } func placeholderImage(for attachment: NSTextAttachment) -> UIImage { let imageSize = CGSize(width: 128, height: 128) let icon: UIImage switch attachment { case _ as ImageAttachment: icon = Gridicon.iconOfType(.image, withSize: imageSize) case _ as VideoAttachment: icon = Gridicon.iconOfType(.video, withSize: imageSize) default: icon = Gridicon.iconOfType(.attachment, withSize: imageSize) } icon.addAccessibilityForAttachment(attachment) return icon } // [2017-08-30] We need to auto-close the input media picker when multitasking panes are resized - iOS // is dropping the input picker's view from the view hierarchy. Not an ideal solution, but prevents // the user from seeing an empty grey rect as a keyboard. Issue affects the 7.9", 9.7", and 10.5" // iPads only...not the 12.9" // See http://www.openradar.me/radar?id=4972612522344448 for more details. func applicationWillResignActive(_ notification: Foundation.Notification) { if UIDevice.isPad() { closeMediaPickerInputViewController() } } func closeMediaPickerInputViewController() { guard mediaPickerInputViewController != nil else { return } mediaPickerInputViewController = nil changeRichTextInputView(to: nil) updateToolbar(formatBar, forMode: .text) restoreInputAssistantItems() } fileprivate func resetMediaAttachmentOverlay(_ mediaAttachment: MediaAttachment) { if mediaAttachment is ImageAttachment { mediaAttachment.overlayImage = nil } mediaAttachment.message = nil mediaAttachment.shouldHideBorder = false } } // MARK: - TextViewAttachmentDelegate Conformance // extension AztecPostViewController: TextViewAttachmentDelegate { public func textView(_ textView: TextView, selected attachment: NSTextAttachment, atPosition position: CGPoint) { if !richTextView.isFirstResponder { richTextView.becomeFirstResponder() } switch attachment { case let attachment as HTMLAttachment: displayUnknownHtmlEditor(for: attachment) case let attachment as MediaAttachment: selected(textAttachment: attachment, atPosition: position) default: break } } func selected(textAttachment attachment: MediaAttachment, atPosition position: CGPoint) { // Check to see if this is an error if mediaProgressCoordinator.error(forMediaID: attachment.identifier) == nil { // If it's a new attachment tapped let's unmark the previous one... if let selectedAttachment = currentSelectedAttachment { self.resetMediaAttachmentOverlay(selectedAttachment) richTextView.refresh(selectedAttachment) } // ...and mark the newly tapped attachment let message = "" attachment.message = NSAttributedString(string: message, attributes: mediaMessageAttributes) richTextView.refresh(attachment) currentSelectedAttachment = attachment } // Display the action sheet right away displayActions(forAttachment: attachment, position: position) } func displayPlayerFor(videoAttachment: VideoAttachment, atPosition position: CGPoint) { guard let videoURL = videoAttachment.srcURL else { return } if let videoPressID = videoAttachment.videoPressID { // It's videoPress video so let's fetch the information for the video let mediaService = MediaService(managedObjectContext: ContextManager.sharedInstance().mainContext) mediaService.getMediaURL(fromVideoPressID: videoPressID, in: self.post.blog, success: { (videoURLString, posterURLString) in guard let videoURL = URL(string: videoURLString) else { return } videoAttachment.srcURL = videoURL if let validPosterURLString = posterURLString, let posterURL = URL(string: validPosterURLString) { videoAttachment.posterURL = posterURL } self.richTextView.refresh(videoAttachment) self.displayVideoPlayer(for: videoURL) }, failure: { (error) in DDLogError("Unable to find information for VideoPress video with ID = \(videoPressID). Details: \(error.localizedDescription)") }) } else { displayVideoPlayer(for: videoURL) } } func displayVideoPlayer(for videoURL: URL) { let asset = AVURLAsset(url: videoURL) let controller = AVPlayerViewController() let playerItem = AVPlayerItem(asset: asset) let player = AVPlayer(playerItem: playerItem) controller.showsPlaybackControls = true controller.player = player player.play() present(controller, animated: true, completion: nil) } public func textView(_ textView: TextView, deselected attachment: NSTextAttachment, atPosition position: CGPoint) { deselected(textAttachment: attachment, atPosition: position) } func deselected(textAttachment attachment: NSTextAttachment, atPosition position: CGPoint) { currentSelectedAttachment = nil if let mediaAttachment = attachment as? MediaAttachment { self.resetMediaAttachmentOverlay(mediaAttachment) richTextView.refresh(mediaAttachment) } } func textView(_ textView: TextView, attachment: NSTextAttachment, imageAt url: URL, onSuccess success: @escaping (UIImage) -> Void, onFailure failure: @escaping () -> Void) { var requestURL = url let imageMaxDimension = max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height) //use height zero to maintain the aspect ratio when fetching var size = CGSize(width: imageMaxDimension, height: 0) let request: URLRequest if url.isFileURL { request = URLRequest(url: url) } else if self.post.blog.isPrivate() { // private wpcom image needs special handling. // the size that WPImageHelper expects is pixel size size.width = size.width * UIScreen.main.scale requestURL = WPImageURLHelper.imageURLWithSize(size, forImageURL: requestURL) request = PrivateSiteURLProtocol.requestForPrivateSite(from: requestURL) } else if !self.post.blog.isHostedAtWPcom && self.post.blog.isBasicAuthCredentialStored() { size.width = size.width * UIScreen.main.scale requestURL = WPImageURLHelper.imageURLWithSize(size, forImageURL: requestURL) request = URLRequest(url: requestURL) } else { // the size that PhotonImageURLHelper expects is points size requestURL = PhotonImageURLHelper.photonURL(with: size, forImageURL: requestURL) request = URLRequest(url: requestURL) } let imageDownloader = AFImageDownloader.defaultInstance() let receipt = imageDownloader.downloadImage(for: request, success: { [weak self](request, response, image) in guard self != nil else { return } DispatchQueue.main.async(execute: { success(image) }) }) { [weak self](request, response, error) in guard self != nil else { return } DispatchQueue.main.async(execute: { failure() }) } if let receipt = receipt { activeMediaRequests.append(receipt) } } func textView(_ textView: TextView, urlFor imageAttachment: ImageAttachment) -> URL? { saveToMedia(attachment: imageAttachment) return nil } func cancelAllPendingMediaRequests() { let imageDownloader = AFImageDownloader.defaultInstance() for receipt in activeMediaRequests { imageDownloader.cancelTask(for: receipt) } activeMediaRequests.removeAll() } func textView(_ textView: TextView, deletedAttachmentWith attachmentID: String) { mediaProgressCoordinator.cancelAndStopTrack(of: attachmentID) } func textView(_ textView: TextView, placeholderFor attachment: NSTextAttachment) -> UIImage { return placeholderImage(for: attachment) } } // MARK: - MediaPickerViewController Delegate Conformance // extension AztecPostViewController: WPMediaPickerViewControllerDelegate { func mediaPickerControllerDidCancel(_ picker: WPMediaPickerViewController) { if picker != mediaPickerInputViewController?.mediaPicker { dismiss(animated: true, completion: nil) } } func mediaPickerController(_ picker: WPMediaPickerViewController, didFinishPicking assets: [WPMediaAsset]) { if picker != mediaPickerInputViewController?.mediaPicker { dismiss(animated: true, completion: nil) selectedMediaOrigin = .fullScreenPicker } else { selectedMediaOrigin = .inlinePicker } closeMediaPickerInputViewController() if assets.isEmpty { return } mediaProgressCoordinator.track(numberOfItems: assets.count) for asset in assets { switch asset { case let phAsset as PHAsset: insertDeviceMedia(phAsset: phAsset) case let media as Media: insertSiteMediaLibrary(media: media) default: continue } } } func mediaPickerController(_ picker: WPMediaPickerViewController, selectionChanged assets: [WPMediaAsset]) { updateFormatBarInsertAssetCount() } func mediaPickerController(_ picker: WPMediaPickerViewController, didSelect asset: WPMediaAsset) { updateFormatBarInsertAssetCount() } func mediaPickerController(_ picker: WPMediaPickerViewController, didDeselect asset: WPMediaAsset) { updateFormatBarInsertAssetCount() } private func updateFormatBarInsertAssetCount() { guard let assetCount = mediaPickerInputViewController?.mediaPicker.selectedAssets.count else { return } if assetCount == 0 { formatBar.trailingItem = nil } else { insertToolbarItem.setTitle(String(format: Constants.mediaPickerInsertText, NSNumber(value: assetCount)), for: .normal) if formatBar.trailingItem != insertToolbarItem { formatBar.trailingItem = insertToolbarItem } } } } // MARK: - Accessibility Helpers // extension UIImage { func addAccessibilityForAttachment(_ attachment: NSTextAttachment) { if let attachment = attachment as? ImageAttachment, let accessibilityLabel = attachment.alt { self.accessibilityLabel = accessibilityLabel } } } // MARK: - State Restoration // extension AztecPostViewController: UIViewControllerRestoration { class func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { return restoreAztec(withCoder: coder) } override func encodeRestorableState(with coder: NSCoder) { super.encodeRestorableState(with: coder) coder.encode(post.objectID.uriRepresentation(), forKey: Restoration.postIdentifierKey) coder.encode(shouldRemovePostOnDismiss, forKey: Restoration.shouldRemovePostKey) } class func restoreAztec(withCoder coder: NSCoder) -> AztecPostViewController? { let context = ContextManager.sharedInstance().mainContext guard let postURI = coder.decodeObject(forKey: Restoration.postIdentifierKey) as? URL, let objectID = context.persistentStoreCoordinator?.managedObjectID(forURIRepresentation: postURI) else { return nil } let post = try? context.existingObject(with: objectID) guard let restoredPost = post as? AbstractPost else { return nil } let aztecViewController = AztecPostViewController(post: restoredPost) aztecViewController.shouldRemovePostOnDismiss = coder.decodeBool(forKey: Restoration.shouldRemovePostKey) return aztecViewController } } // MARK: - UIDocumentPickerDelegate extension AztecPostViewController: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { selectedMediaOrigin = .documentPicker mediaProgressCoordinator.track(numberOfItems: urls.count) for documentURL in urls { insertExternalMediaWithURL(documentURL) } } } // MARK: - Constants // extension AztecPostViewController { struct Analytics { static let editorSource = "aztec" static let headerStyleValues = ["none", "h1", "h2", "h3", "h4", "h5", "h6"] } struct Assets { static let closeButtonModalImage = Gridicon.iconOfType(.cross) static let closeButtonRegularImage = UIImage(named: "icon-posts-editor-chevron") static let defaultMissingImage = Gridicon.iconOfType(.image) } struct Constants { static let defaultMargin = CGFloat(20) static let cancelButtonPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 5) static let blogPickerCompactSize = CGSize(width: 125, height: 30) static let blogPickerRegularSize = CGSize(width: 300, height: 30) static let uploadingButtonSize = CGSize(width: 150, height: 30) static let moreAttachmentText = "more" static let placeholderPadding = UIEdgeInsets(top: 8, left: 5, bottom: 0, right: 0) static let headers = [Header.HeaderType.none, .h1, .h2, .h3, .h4, .h5, .h6] static let lists = [TextList.Style.unordered, .ordered] static let toolbarHeight = CGFloat(44.0) static let mediaPickerInsertText = NSLocalizedString("Insert %@", comment: "Button title used in media picker to insert media (photos / videos) into a post. Placeholder will be the number of items that will be inserted.") static let mediaPickerKeyboardHeightRatioPortrait = CGFloat(0.20) static let mediaPickerKeyboardHeightRatioLandscape = CGFloat(0.30) static let mediaOverlayBorderWidth = CGFloat(3.0) static let mediaOverlayIconSize = CGSize(width: 32, height: 32) struct Animations { static let formatBarMediaButtonRotationDuration: TimeInterval = 0.3 static let formatBarMediaButtonRotationAngle: CGFloat = .pi / 4.0 } } struct MoreSheetAlert { static let htmlTitle = NSLocalizedString("Switch to HTML", comment: "Switches the Editor to HTML Mode") static let richTitle = NSLocalizedString("Switch to Rich Text", comment: "Switches the Editor to Rich Text Mode") static let previewTitle = NSLocalizedString("Preview", comment: "Displays the Post Preview Interface") static let optionsTitle = NSLocalizedString("Options", comment: "Displays the Post's Options") static let cancelTitle = NSLocalizedString("Cancel", comment: "Dismisses the Alert from Screen") } struct Colors { static let aztecBackground = UIColor.clear static let title = WPStyleGuide.grey() static let separator = WPStyleGuide.greyLighten30() static let placeholder = WPStyleGuide.grey() static let progressBackground = WPStyleGuide.wordPressBlue() static let progressTint = UIColor.white static let progressTrack = WPStyleGuide.wordPressBlue() static let mediaProgressOverlay = WPStyleGuide.darkGrey().withAlphaComponent(CGFloat(0.6)) static let mediaProgressBarBackground = WPStyleGuide.lightGrey() static let mediaProgressBarTrack = WPStyleGuide.wordPressBlue() static let aztecLinkColor = WPStyleGuide.mediumBlue() static let mediaOverlayBorderColor = WPStyleGuide.wordPressBlue() } struct Fonts { static let regular = WPFontManager.notoRegularFont(ofSize: 16) static let semiBold = WPFontManager.systemSemiBoldFont(ofSize: 16) static let title = WPFontManager.notoBoldFont(ofSize: 24.0) static let blogPicker = Fonts.semiBold static let mediaPickerInsert = WPFontManager.systemMediumFont(ofSize: 15.0) static let mediaOverlay = WPFontManager.systemSemiBoldFont(ofSize: 15.0) } struct Restoration { static let restorationIdentifier = "AztecPostViewController" static let postIdentifierKey = AbstractPost.classNameWithoutNamespaces() static let shouldRemovePostKey = "shouldRemovePostOnDismiss" } struct SwitchSiteAlert { static let title = NSLocalizedString("Change Site", comment: "Title of an alert prompting the user that they are about to change the blog they are posting to.") static let message = NSLocalizedString("Choosing a different site will lose edits to site specific content like media and categories. Are you sure?", comment: "And alert message warning the user they will loose blog specific edits like categories, and media if they change the blog being posted to.") static let acceptTitle = NSLocalizedString("OK", comment: "Accept Action") static let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel Action") } struct MediaUploadingAlert { static let title = NSLocalizedString("Uploading media", comment: "Title for alert when trying to save/exit a post before media upload process is complete.") static let message = NSLocalizedString("You are currently uploading media. Please wait until this completes.", comment: "This is a notification the user receives if they are trying to save a post (or exit) before the media upload process is complete.") static let acceptTitle = NSLocalizedString("OK", comment: "Accept Action") } struct FailedMediaRemovalAlert { static let title = NSLocalizedString("Uploads failed", comment: "Title for alert when trying to save post with failed media items") static let message = NSLocalizedString("Some media uploads failed. This action will remove all failed media from the post.\nSave anyway?", comment: "Confirms with the user if they save the post all media that failed to upload will be removed from it.") static let acceptTitle = NSLocalizedString("Yes", comment: "Accept Action") static let cancelTitle = NSLocalizedString("Not Now", comment: "Nicer dialog answer for \"No\".") } struct MediaUploadingCancelAlert { static let title = NSLocalizedString("Cancel media uploads", comment: "Dialog box title for when the user is cancelling an upload.") static let message = NSLocalizedString("You are currently uploading media. This action will cancel uploads in progress.\n\nAre you sure?", comment: "This prompt is displayed when the user attempts to stop media uploads in the post editor.") static let acceptTitle = NSLocalizedString("Yes", comment: "Yes") static let cancelTitle = NSLocalizedString("Not Now", comment: "Nicer dialog answer for \"No\".") } }
gpl-2.0
cf91982ec6819502f7d03b94077b801a
40.591926
325
0.656846
5.988416
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Idiomatic/ToggleBoolRule.swift
1
3635
import SwiftSyntax import SwiftSyntaxBuilder struct ToggleBoolRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule, OptInRule { var configuration = SeverityConfiguration(.warning) init() {} static var description = RuleDescription( identifier: "toggle_bool", name: "Toggle Bool", description: "Prefer `someBool.toggle()` over `someBool = !someBool`.", kind: .idiomatic, nonTriggeringExamples: [ Example("isHidden.toggle()\n"), Example("view.clipsToBounds.toggle()\n"), Example("func foo() { abc.toggle() }"), Example("view.clipsToBounds = !clipsToBounds\n"), Example("disconnected = !connected\n"), Example("result = !result.toggle()") ], triggeringExamples: [ Example("↓isHidden = !isHidden\n"), Example("↓view.clipsToBounds = !view.clipsToBounds\n"), Example("func foo() { ↓abc = !abc }") ], corrections: [ Example("↓isHidden = !isHidden\n"): Example("isHidden.toggle()\n"), Example("↓view.clipsToBounds = !view.clipsToBounds\n"): Example("view.clipsToBounds.toggle()\n"), Example("func foo() { ↓abc = !abc }"): Example("func foo() { abc.toggle() }") ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? { Rewriter( locationConverter: file.locationConverter, disabledRegions: disabledRegions(file: file) ) } } private extension ToggleBoolRule { final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: ExprListSyntax) { if node.hasToggleBoolViolation { violations.append(node.positionAfterSkippingLeadingTrivia) } } } final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter { private(set) var correctionPositions: [AbsolutePosition] = [] let locationConverter: SourceLocationConverter let disabledRegions: [SourceRange] init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) { self.locationConverter = locationConverter self.disabledRegions = disabledRegions } override func visit(_ node: ExprListSyntax) -> ExprListSyntax { guard node.hasToggleBoolViolation, !node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else { return super.visit(node) } correctionPositions.append(node.positionAfterSkippingLeadingTrivia) let newNode = node .replacing(childAt: 0, with: "\(node.first!.withoutTrivia()).toggle()") .removingLast() .removingLast() .withLeadingTrivia(node.leadingTrivia ?? .zero) .withTrailingTrivia(node.trailingTrivia ?? .zero) return super.visit(newNode) } } } private extension ExprListSyntax { var hasToggleBoolViolation: Bool { guard count == 3, dropFirst().first?.is(AssignmentExprSyntax.self) == true, last?.is(PrefixOperatorExprSyntax.self) == true, let lhs = first?.withoutTrivia().description, let rhs = last?.withoutTrivia().description, rhs == "!\(lhs)" else { return false } return true } }
mit
581cfd2e4a123925f40b87b1c1b0bac9
34.519608
109
0.602263
5.391369
false
false
false
false
CodeDrunkard/ARViewer
ARViewer/Core/ARView.swift
1
5304
// // ARView.swift // ARViewer // // Created by JT Ma on 11/04/2017. // Copyright © 2017 JT Ma. All rights reserved. // import UIKit import SceneKit import CoreMotion import AVFoundation import SpriteKit public enum ARControlMode: Int { case motion case touch } public class ARView: SCNView { public var controlMode: ARControlMode! { didSet { switchControlMode(to: controlMode) resetCameraAngles() } } public var panoramaTexture: UIImage? { didSet { guard let texture = panoramaTexture else { return } let material = SCNMaterial() material.diffuse.contents = texture material.diffuse.mipFilter = .nearest material.diffuse.magnificationFilter = .nearest material.diffuse.contentsTransform = SCNMatrix4MakeScale(-1, 1, 1) material.diffuse.wrapS = .repeat material.cullMode = .front let sphere = SCNSphere() sphere.radius = 50 sphere.segmentCount = 300 sphere.firstMaterial = material panoramaNode.geometry = sphere } } public var panoramaVideoPlayer: AVPlayer? { didSet { guard let videoPlayer = panoramaVideoPlayer else { return } let videoSize = CGSize(width: 1920, height: 960) let videoNode = SKVideoNode(avPlayer: videoPlayer) videoNode.position = videoSize.midPoint videoNode.xScale = -1 videoNode.yScale = -1 videoNode.size = videoSize let videoScene = SKScene(size: videoSize) videoScene.scaleMode = .aspectFit videoScene.addChild(videoNode) let material = SCNMaterial() material.diffuse.contents = videoScene material.cullMode = .front let sphere = SCNSphere() sphere.radius = 100 sphere.segmentCount = 300 sphere.firstMaterial = material panoramaNode.geometry = sphere } } public var panSpeed: (x: Float, y: Float) = (x: 0.005, y: 0.005) public override init(frame: CGRect) { super.init(frame: frame) loadScene() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadScene() } deinit { if motionManager.isDeviceMotionActive { motionManager.stopDeviceMotionUpdates() } } public func loadScene() { let camera = SCNCamera() camera.zFar = 100 camera.xFov = 60 camera.yFov = 60 cameraNode.camera = camera panoramaNode.position = SCNVector3Make(0, 0, 0) cameraNode.position = panoramaNode.position let scene = SCNScene() scene.rootNode.addChildNode(cameraNode) scene.rootNode.addChildNode(panoramaNode) self.scene = scene backgroundColor = UIColor.black } fileprivate let panoramaNode = SCNNode() fileprivate let cameraNode = SCNNode() fileprivate var prevLocation = CGPoint.zero fileprivate var motionManager = CMMotionManager() } extension ARView { fileprivate func resetCameraAngles() { cameraNode.eulerAngles = SCNVector3Make(0, 0, 0) } public func switchControlMode(to mode: ARControlMode) { gestureRecognizers?.removeAll() switch mode { case .touch: let panGestureRec = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_ :))) addGestureRecognizer(panGestureRec) if motionManager.isDeviceMotionActive { motionManager.stopDeviceMotionUpdates() } case .motion: guard motionManager.isAccelerometerAvailable else { return } motionManager.deviceMotionUpdateInterval = 0.01 motionManager.startDeviceMotionUpdates(to: OperationQueue.main, withHandler: {[unowned self] (motionData, error) in guard let motionData = motionData else { print("\(String(describing: error?.localizedDescription))") self.motionManager.stopGyroUpdates() return } self.cameraNode.orientation = motionData.gaze() }) } } @objc private func handlePan(_ gesture: UIPanGestureRecognizer) { if (gesture.state == .began) { prevLocation = CGPoint.zero } else if (gesture.state == .changed) { let location = gesture.translation(in: self) let orientation = cameraNode.eulerAngles let newOrientation = SCNVector3Make(orientation.x + Float(location.y - prevLocation.y) * panSpeed.x, orientation.y + Float(location.x - prevLocation.x) * panSpeed.y, orientation.z) cameraNode.eulerAngles = newOrientation prevLocation = location } } }
mit
4b1874851440b968e7f20a9a0de064d0
30.565476
112
0.568735
5.450154
false
false
false
false
LYM-mg/MGOFO
MGOFO/MGOFO/Class/Extesion/UIViewController+Extension.swift
1
10619
// // UIViewController+Extension.swift // chart2 // // Created by i-Techsys.com on 16/11/30. // Copyright © 2016年 i-Techsys. All rights reserved. // import UIKit import MBProgressHUD import SnapKit private let mainScreenW = UIScreen.main.bounds.size.width private let mainScreenH = UIScreen.main.bounds.size.height // MARK: - HUD extension UIViewController { // MARK:- RuntimeKey 动态绑属性 // 改进写法【推荐】 struct RuntimeKey { static let mg_HUDKey = UnsafeRawPointer.init(bitPattern: "mg_HUDKey".hashValue) static let mg_GIFKey = UnsafeRawPointer(bitPattern: "mg_GIFKey".hashValue) static let mg_GIFWebView = UnsafeRawPointer(bitPattern: "mg_GIFWebView".hashValue) /// ...其他Key声明 } // MARK:- HUD /** ================================= HUD蒙版提示 ====================================== **/ // 蒙版提示HUD var MBHUD: MBProgressHUD? { set { objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_HUDKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_HUDKey) as? MBProgressHUD } } /** * 提示信息 * * @param view 显示在哪个view * @param hint 提示 */ func showHudInView(view: UIView, hint: String?, yOffset: CGFloat = 0.0) { let hud = MBProgressHUD(view: view) hud.label.text = hint! view.addSubview(hud) if yOffset != 0.0 { hud.margin = 10.0; hud.offset.y += yOffset; } hud.show(animated: true) self.MBHUD = hud } /// 如果设置了图片名,mode的其他其他设置将失效 func showHudInViewWithMode(view: UIView, hint: String?, mode: MBProgressHUDMode = .text, imageName: String?) { let hud = MBProgressHUD(view: view) hud.label.text = hint! view.addSubview(hud) hud.mode = mode if imageName != nil { hud.mode = .customView hud.customView = UIImageView(image: UIImage(named: imageName!)) } hud.show(animated: true) self.MBHUD = hud } /** * 隐藏HUD */ func hideHud(){ self.MBHUD?.hide(animated: true) } /** * 提示信息 mode: MBProgressHUDModeText * * @param hint 提示 */ func showHint(hint: String?, mode: MBProgressHUDMode = .text) { //显示提示信息 guard let view = UIApplication.shared.delegate?.window else { return } let hud = MBProgressHUD.showAdded(to: view!, animated: true) hud.isUserInteractionEnabled = false hud.mode = MBProgressHUDMode.text hud.label.text = hint!; hud.mode = mode hud.margin = 10.0; hud.removeFromSuperViewOnHide = true hud.hide(animated: true, afterDelay: 1.5) } func showHint(hint: String?,mode: MBProgressHUDMode? = .text,view: UIView? = (UIApplication.shared.delegate?.window!)!, yOffset: CGFloat = 0.0){ //显示提示信息 let hud = MBProgressHUD.showAdded(to: view!, animated: true) hud.isUserInteractionEnabled = false hud.mode = MBProgressHUDMode.text hud.label.text = hint! if mode == .customView { hud.mode = .customView hud.customView = UIImageView(image: UIImage(named: "happy_face_icon")) } if mode != nil { hud.mode = mode! } hud.margin = 15.0 if yOffset != 0.0 { hud.offset.y += yOffset; } hud.removeFromSuperViewOnHide = true hud.hide(animated: true, afterDelay: 1.5) } // 带图片的提示HUD,延时2秒消失 func showHint(hint: String?,imageName: String?) { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.isUserInteractionEnabled = false hud.mode = MBProgressHUDMode.text hud.label.text = hint! if imageName != nil { hud.mode = .customView hud.customView = UIImageView(image: UIImage(named: imageName!)) }else { hud.mode = .text } hud.removeFromSuperViewOnHide = true hud.hide(animated: true, afterDelay: 1.5) } // MARK: - 显示Gif图片 /** ============================ UIImageView显示GIF加载动画 =============================== **/ // MARK: - UIImageView显示Gif加载状态 /** 显示加载动画的UIImageView */ var mg_gifView: UIImageView? { set { objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFKey) as? UIImageView } } /** * 显示GIF加载动画 * * @param images gif图片数组, 不传的话默认是自带的 * @param view 显示在哪个view上, 如果不传默认就是self.view */ func mg_showGifLoding(_ images: [UIImage]?,size: CGSize? , inView view: UIView?) { var images = images if images == nil { images = [UIImage(named: "hold1_60x72")!,UIImage(named: "hold2_60x72")!,UIImage(named: "hold3_60x72")!] } var size = size if size == nil { size = CGSize(width: 60, height: 70) } let gifView = UIImageView() var view = view if view == nil { view = self.view } view?.addSubview(gifView) self.mg_gifView = gifView gifView.snp.makeConstraints { (make) in make.center.equalToSuperview() make.size.equalTo(size!) } gifView.playGifAnimation(images: images!) } /** * 取消GIF加载动画 */ func mg_hideGifLoding() { self.mg_gifView?.stopGifAnimation() self.mg_gifView = nil; } /** * 判断数组是否为空 * * @param array 数组 * * @return yes or no */ func isNotEmptyArray(array: [Any]) -> Bool { if array.count >= 0 && !array.isEmpty{ return true }else { return false } } /** ============================== UIWebView显示GIF加载动画 ================================= **/ // MARK: - UIWebView显示GIF加载动画 /** UIWebView显示Gif加载状态 */ weak var mg_GIFWebView: UIWebView? { set { objc_setAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFWebView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { return objc_getAssociatedObject(self, UIViewController.RuntimeKey.mg_GIFWebView) as? UIWebView } } /// 使用webView加载GIF图片 /** * 如果view传了参数,移除的时候也要传同一个参数 */ func mg_showWebGifLoading(frame:CGRect?, gifName: String?,view: UIView?, filter: Bool? = false) { var gifName = gifName if gifName == nil || gifName == "" { gifName = "gif2" } var frame = frame if frame == CGRect.zero || frame == nil { frame = CGRect(x: 0, y: (self.navigationController != nil) ? navHeight : CGFloat(0), width: mainScreenW, height: mainScreenH) } /// 得先提前创建webView,不能在子线程创建webView,不然程序会崩溃 let webView = UIWebView(frame: frame!) // 子线程加载耗时操作加载GIF图片 DispatchQueue.global().async { // 守卫校验 guard let filePath = Bundle.main.path(forResource: gifName, ofType: "gif") else { return } guard let gifData: Data = NSData(contentsOfFile: filePath) as? Data else { return } if (frame?.size.height)! < mainScreenH - navHeight { webView.center = CGPoint(x: (mainScreenW-webView.frame.size.width)/2, y: (mainScreenH-webView.frame.size.height)/2) }else { webView.center = self.view.center } webView.scalesPageToFit = true webView.load(gifData, mimeType: "image/gif", textEncodingName: "UTF-8", baseURL: URL(fileURLWithPath: filePath)) webView.autoresizingMask = [.flexibleWidth,.flexibleHeight] webView.backgroundColor = UIColor.black webView.isOpaque = false webView.isUserInteractionEnabled = false webView.tag = 10000 // 回到主线程将webView加到 UIApplication.shared.delegate?.window DispatchQueue.main.async { var view = view if view == nil { // 添加到窗口 view = (UIApplication.shared.delegate?.window)! }else { // 添加到控制器 self.mg_GIFWebView = webView } view?.addSubview(webView) view?.bringSubview(toFront: webView) //创建一个灰色的蒙版,提升效果( 可选 ) if filter! { // true let filter = UIView(frame: self.view.frame) filter.backgroundColor = UIColor(white: 0.9, alpha: 0.3) webView.insertSubview(filter, at: 0) } } } } /** * 取消GIF加载动画,隐藏webView */ func mg_hideWebGifLoding(view: UIView?) { if view == nil { // 从窗口中移除 guard let view = UIApplication.shared.delegate?.window else { return } guard let webView = view?.viewWithTag(10000) as? UIWebView else { return } webView.removeFromSuperview() webView.alpha = 0.0 }else { // 从控制器中移除 self.mg_GIFWebView?.removeFromSuperview() self.mg_GIFWebView?.alpha = 0.0 } } } // MARK: - 侧滑相关控制器 extension UIViewController { func getRevealViewController() -> SWRevealViewController { var parent: UIViewController? = self // let revealClass: AnyClass = SWRevealViewController.classForCoder() while (nil != (parent = parent?.parent) && !(parent is SWRevealViewController)) { } return (parent as! SWRevealViewController) } }
mit
01df634cb6a7fe61a51e71de4e1ad608
30.840764
149
0.55151
4.377408
false
false
false
false
CodeEagle/SSImageBrowser
Source/SSCaptionView.swift
1
4067
// // SSCaptionView.swift // Pods // // Created by LawLincoln on 15/7/10. // // import UIKit public final class SSCaptionView: UIView { var photo: SSPhoto? private var labelPadding: CGFloat { return 10 } private lazy var label: UILabel = { let label = UILabel(frame: CGRect(x: self.labelPadding, y: 0, width: self.bounds.size.width - self.labelPadding * 2, height: self.bounds.size.height)) label.autoresizingMask = [.flexibleWidth, .flexibleHeight] label.isOpaque = false label.backgroundColor = UIColor.clear label.textAlignment = .center label.lineBreakMode = NSLineBreakMode.byWordWrapping label.numberOfLines = 3 label.textColor = UIColor.white label.shadowColor = UIColor(white: 0, alpha: 0.5) label.shadowOffset = CGSize(width: 0, height: 1) label.font = UIFont.systemFont(ofSize: 17) label.text = "" return label }() convenience init(aPhoto: SSPhoto) { let screenBound = UIScreen.main.bounds var screenWidth = screenBound.size.width let orientation = UIDevice.current.orientation if orientation == .landscapeLeft || orientation == .landscapeRight { screenWidth = screenBound.size.height } self.init(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44)) photo = aPhoto isOpaque = false setBackground() setupCaption() } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func layoutSubviews() { super.layoutSubviews() if let view = viewWithTag(101) { let len = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) view.frame = CGRect(x: 0, y: -100, width: len, height: 130 + 100) } } /** To create your own custom caption view, subclass this view and override the following two methods (as well as any other UIView methods that you see fit): Override -setupCaption so setup your subviews and customise the appearance of your custom caption You can access the photo's data by accessing the _photo ivar If you need more data per photo then simply subclass IDMPhoto and return your subclass to the photo browsers -photoBrowser:photoAtIndex: delegate method */ private func setupCaption() { if let cap = photo?.caption() { label.text = cap } addSubview(label) } /** Override -sizeThatFits: and return a CGSize specifying the height of your custom caption view. With width property is ignored and the caption is displayed the full width of the screen :param: size CGSize :returns: CGSize */ open override func sizeThatFits(_ size: CGSize) -> CGSize { if label.text == nil || label.text?.isEmpty == true { return .zero } var maxHeight: CGFloat = 9999 if label.numberOfLines > 0 { maxHeight = label.font.lineHeight * CGFloat(label.numberOfLines) } let text = label.text! let width = size.width - labelPadding * 2 let font = label.font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize) let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName: font]) let size = CGSize(width: width, height: maxHeight) let rect = attributedText.boundingRect(with: size , options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil) let textSize = rect.size return CGSize(width: size.width, height: textSize.height + labelPadding * 2) } private func setBackground() { let len = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) let fadeView = UIView(frame: CGRect(x: 0, y: -100, width: len, height: 130 + 100)) // Static width, autoresizingMask is not working fadeView.tag = 101 let gradient = CAGradientLayer() gradient.frame = fadeView.bounds gradient.colors = [UIColor(white: 0, alpha: 0).cgColor, UIColor(white: 0, alpha: 0.8).cgColor] fadeView.layer.insertSublayer(gradient, at: 0) fadeView.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(fadeView) } }
mit
0d63c138cd196af2970ee7a4056d648d
32.61157
158
0.69732
3.999017
false
false
false
false
Sephiroth87/C-swifty4
C-swifty4 tvOS/ContextBackedView.swift
1
3274
// // ContextBackedView.swift // C-swifty4 iOS // // Created by Fabio Ritrovato on 10/01/2015. // Copyright (c) 2015 orange in a day. All rights reserved. // import UIKit private class ContextBackedLayer: CALayer { private var size: CGSize = .zero private var safeArea: UIEdgeInsets = .zero private var context: CGContext? override init() { super.init() actions = ["contents": NSNull()] backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0).cgColor updateContentsRect() } required init?(coder aDecoder: NSCoder) { fatalError() } func setTextureSize(_ size: CGSize, safeArea: UIEdgeInsets) { let colorSpace = CGColorSpaceCreateDeviceRGB() self.size = size self.safeArea = safeArea context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: Int(size.width) * 4, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! updateContentsRect() } override func display() { guard let context = context else { return } let cgImage = context.makeImage() contents = cgImage } fileprivate func setData(_ data: UnsafePointer<UInt32>) { guard let context = context else { return } let address = context.data memcpy(address, data, Int(size.width) * Int(size.height) * 4) let cgImage = context.makeImage() contents = cgImage } override var bounds: CGRect { didSet { if bounds.size != oldValue.size { updateContentsRect() } } } private func updateContentsRect() { let safeW = size.width - safeArea.left - safeArea.right let safeH = size.height - safeArea.top - safeArea.bottom var wScale = bounds.width / safeW var hScale = bounds.height / safeH if wScale > hScale { wScale /= hScale hScale = safeH / size.height } else { hScale /= wScale wScale = safeW / size.width } if wScale >= 1.0 { wScale *= safeW / size.width } if hScale >= 1.0 { hScale *= safeH / size.height } let x = -wScale * 0.5 + (0.5 + ((safeArea.left + safeArea.right) / size.width) / 2.0) let y = -hScale * 0.5 + (0.5 + ((safeArea.bottom + safeArea.top) / size.height) / 2.0) contentsRect = CGRect(x: x, y: y, width: wScale, height: hScale) } } class ContextBackedView: UIView { override class var layerClass : AnyClass { return ContextBackedLayer.self } func setTextureSize(_ size: CGSize, safeArea: (top: Int, left: Int, bottom: Int, right: Int)) { let layer = self.layer as! ContextBackedLayer layer.setTextureSize(size, safeArea: UIEdgeInsets(top: CGFloat(safeArea.top), left: CGFloat(safeArea.left), bottom: CGFloat(safeArea.bottom), right: CGFloat(safeArea.right))) } override func draw(_ rect: CGRect) { } internal func setData(_ data: UnsafePointer<UInt32>) { let layer = self.layer as! ContextBackedLayer layer.setData(data) } }
mit
263ad68097b77be8f8545ff0d0b499e4
31.098039
220
0.596823
4.251948
false
false
false
false
MichaelJordanYang/JDYangDouYuZB
JDYDouYuZb/JDYDouYuZb/Application/Classes/Home/Controller/HomeViewController.swift
1
4973
// // HomeViewController.swift // JDYDouYuZb // // Created by xiaoyang on 2016/12/24. // Copyright © 2016年 JDYang. All rights reserved. // import UIKit fileprivate let kTitleViewHeight : CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 fileprivate lazy var pageTitleView : PageTitleView = { //设置菜单标题尺寸 let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenWidth, height: kTitleViewHeight) let titles = ["推荐", "游戏", "娱乐", "趣玩"]//设置菜单标题显示内容文字 let titleView = PageTitleView(frame: titleFrame, titles: titles)//保存到pageTitleView中 //titleView.backgroundColor = UIColor.purple return titleView }() fileprivate lazy var pageContentView : PageContentView = { //1.确定内容的frame let contentHeight = kScreenHeight - kStatusBarH - kNavigationBarH - kTitleViewHeight let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewHeight, width: kScreenHeight, height: contentHeight) //2.确定所有的子控制器 var childs = [UIViewController]() //创建数组子控制器 //通过for循环创建 for _ in 0..<4 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childs, parentViewController: self) return contentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() //设置UI界面 setUpUI() } } // MARK: -设置UI页面 extension HomeViewController { fileprivate func setUpUI() { //0.不需要调整UIScrollview的内边距. 系统默认会帮我们调整所以设置不调整内边距 automaticallyAdjustsScrollViewInsets = false //1.设置导航栏 setUpNavigationBar() //2.添加TitleView view.addSubview(pageTitleView) //3添加ContenView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.orange } //设置导航栏 fileprivate func setUpNavigationBar() { //1.设置左侧的按钮 /* let btn = UIButton() let image = UIImage(named: "logo") btn.setImage(image, for: .normal) btn.sizeToFit()//让按钮自适应图片 */ navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") //UIBarButtonItem(customView: btn)//传一个自定义view //2.设置右侧的item let size = CGSize(width: 40, height: 40)//定义宽高尺寸 /* let hisoryBtn = UIButton() hisoryBtn.setImage(UIImage(named: "image_my_history"), for: .normal) hisoryBtn.setImage(UIImage(named: "Image_my_history_click"), for: .highlighted) //hisoryBtn.sizeToFit() hisoryBtn.frame = CGRect(origin: CGPoint.zero, size: size) */ let historyItem = UIBarButtonItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size) //UIBarButtonItem.createItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size) /* let searchBtn = UIButton() searchBtn.setImage(UIImage(named: "btn_search"), for: .normal) searchBtn.setImage(UIImage(named: "btn_search_clicked"), for: .highlighted) //searchBtn.sizeToFit() searchBtn.frame = CGRect(origin: CGPoint.zero, size: size) */ let searchItem = UIBarButtonItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size) //UIBarButtonItem.createItem.createItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size) /* let qrcodeBtn = UIButton() qrcodeBtn.setImage(UIImage(named: "Image_scan"), for: .normal) qrcodeBtn.setImage(UIImage(named: "Image_scan_click"), for: .highlighted) //qrcodeBtn.sizeToFit() qrcodeBtn.frame = CGRect(origin: CGPoint.zero, size: size) */ let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size) //UIBarButtonItem.createItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem] } }
mit
29f1efe3c8d63e53b4801cf1fe9eb819
38.176471
156
0.600815
4.811146
false
false
false
false
davefoxy/SwiftBomb
SwiftBomb/Classes/Requests/AuthenticationRequests.swift
1
1356
// // AuthenticationRequests.swift // SwiftBomb // // Created by David Fox on 17/04/2016. // Copyright © 2016 David Fox. All rights reserved. // import Foundation extension SwiftBomb { static func createAuthenticationSession() -> AuthenticationSession { let instance = SwiftBomb.framework let authenticationSession = AuthenticationSession(requestFactory: instance.requestFactory!, networkingManager: instance.networkingManager!, authenticationStore: (instance.requestFactory?.authenticationStore)!) return authenticationSession } } extension RequestFactory { func authenticationRegCodeRequest() -> SwiftBombRequest { var request = SwiftBombRequest(configuration: configuration, path: "apple-tv/get-code", method: .get) request.responseFormat = .xml request.addURLParameter("deviceID", value: "XXX") return request } func authenticationAPIKeyRequest(_ regCode: String) -> SwiftBombRequest { var request = SwiftBombRequest(configuration: configuration, path: "apple-tv/get-result", method: .get) request.addURLParameter("deviceID", value: "XXX") request.addURLParameter("partner", value: "apple-tv") request.addURLParameter("regCode", value: regCode) return request } }
mit
db0a7f4c1c95e6361e5e51098f37ed4f
32.04878
217
0.687085
5
false
true
false
false
simonnarang/Fandom-IOS
Fandomm/ChangePWTableViewController.swift
1
2844
// // ChangePWTableViewController.swift // Fandomm // // Created by Simon Narang on 3/30/16. // Copyright © 2016 Simon Narang. All rights reserved. // import UIKit class ChangePWTableViewController: UITableViewController { var usernameFourTextOne = String() override func viewDidLoad() { super.viewDidLoad() self.clearsSelectionOnViewWillAppear = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 3 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
unlicense
5164c3c80f28392fa0ae56179d05fc98
30.588889
157
0.683433
5.531128
false
false
false
false
cuappdev/podcast-ios
old/Podcast/OnboardingButton.swift
1
867
// // OnboardingButton.swift // Podcast // // Created by Natasha Armbrust on 3/2/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import UIKit /// semi-transparent buttons used in onboarding view class OnboardingButton: UIButton { convenience init(title: String) { self.init(frame: .zero, title: title) } init(frame: CGRect, title: String) { super.init(frame: frame) backgroundColor = UIColor.offWhite.withAlphaComponent(0.15) layer.cornerRadius = 2 layer.borderWidth = 1.5 layer.borderColor = UIColor.offWhite.cgColor setTitle(title, for: .normal) titleLabel?.font = ._14SemiboldFont() setTitleColor(.offWhite, for: .normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
207fad002a65ec54af979937df66498b
23.742857
67
0.65358
4.143541
false
false
false
false
odigeoteam/TableViewKit
Examples/Viper/TableViewKit+VIPER/AboutModule/MoreAboutItem.swift
1
1575
import Foundation import TableViewKit enum MoreAboutItemType { case faq, contact, terms, feedback, share, rate func title() -> String { switch self { case .faq: return "FAQ" case .contact: return "Contact Us" case .terms: return "Terms and Conditions" case .feedback: return "Send us your feedback" case .share: return "Share the app" case .rate: return "Rate the app" } } } class MoreAboutItem: TableItem, Selectable, Editable { public static var drawer = AnyCellDrawer(MoreAboutDrawer.self) var type: MoreAboutItemType var title: String? var onSelection: (Selectable) -> Void = { _ in } var actions: [UITableViewRowAction]? weak var manager: TableViewManager? let presenter: AboutPresenterProtocol? init(type: MoreAboutItemType, presenter: AboutPresenterProtocol?, manager: TableViewManager?) { self.presenter = presenter self.manager = manager self.type = type self.title = type.title() } func didSelect() { switch type { case .faq: presenter?.showFaq() case .contact: presenter?.showContactUs() case .terms: presenter?.showTermsAndConditions() case .feedback: presenter?.showFeedback() case .share: presenter?.showShareApp() case .rate: presenter?.showRateApp() } deselect(animated: true) } }
mit
bf26711fcc3db56c364e9bd447ff7fbd
24
99
0.581587
4.758308
false
false
false
false
Harley-xk/Chrysan
Chrysan/Sources/Responders/HUDBarProgressView.swift
1
2190
// // HUDBarProgressView.swift // Chrysan // // Created by Harley-xk on 2020/9/28. // Copyright © 2020 Harley. All rights reserved. // import Foundation import UIKit import SnapKit public class HUDBarProgressView: UIView, StatusIndicatorView { public struct Options { public init() {} public var barSize = CGSize(width: 200, height: 15) public var barColor = UIColor.systemBlue public var barBackgroundColor = UIColor.darkGray public var textColor = UIColor.white public var textFont = UIFont.systemFont(ofSize: 11) } public class func makeBar(with options: Options) -> HUDBarProgressView { let barView = HUDBarProgressView(options: options) return barView } public let progressView: ProgressIndicatorView = HorizontalProgressBar() public let textLabel = UILabel() init(options: Options) { super.init(frame: CGRect(origin: .zero, size: options.barSize)) self.options = options setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private var options: Options = Options() private func setup() { addSubview(progressView) progressView.snp.makeConstraints { // $0.center.equalToSuperview() $0.left.right.equalToSuperview() $0.top.bottom.equalToSuperview().inset(10) $0.size.equalTo(options.barSize) } addSubview(textLabel) textLabel.snp.makeConstraints { $0.center.equalToSuperview() } updateOptions() } func updateOptions() { progressView.tintColor = options.barColor progressView.backgroundColor = options.barBackgroundColor textLabel.font = options.textFont textLabel.textColor = options.textColor setNeedsDisplay() } public func updateStatus(from: Status, to new: Status) { let progress = CGFloat(new.progress ?? 0) progressView.progress = progress textLabel.text = new.progressText ?? String(format: "%.0f%%", progress * 100) } }
mit
dc0addad0407a4cf95d5a45916e6ae34
27.802632
85
0.627684
4.800439
false
false
false
false
wangrui460/WRNavigationBar_swift
WRNavigationBar_swift/Pods/Kingfisher/Sources/CacheSerializer.swift
5
3729
// // CacheSerializer.swift // Kingfisher // // Created by Wei Wang on 2016/09/02. // // Copyright (c) 2017 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// An `CacheSerializer` would be used to convert some data to an image object for /// retrieving from disk cache and vice versa for storing to disk cache. public protocol CacheSerializer { /// Get the serialized data from a provided image /// and optional original data for caching to disk. /// /// /// - parameter image: The image needed to be serialized. /// - parameter original: The original data which is just downloaded. /// If the image is retrieved from cache instead of /// downloaded, it will be `nil`. /// /// - returns: A data which will be stored to cache, or `nil` when no valid /// data could be serialized. func data(with image: Image, original: Data?) -> Data? /// Get an image deserialized from provided data. /// /// - parameter data: The data from which an image should be deserialized. /// - parameter options: Options for deserialization. /// /// - returns: An image deserialized or `nil` when no valid image /// could be deserialized. func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? } /// `DefaultCacheSerializer` is a basic `CacheSerializer` used in default cache of /// Kingfisher. It could serialize and deserialize PNG, JEPG and GIF images. For /// image other than these formats, a normalized `pngRepresentation` will be used. public struct DefaultCacheSerializer: CacheSerializer { public static let `default` = DefaultCacheSerializer() private init() {} public func data(with image: Image, original: Data?) -> Data? { let imageFormat = original?.kf.imageFormat ?? .unknown let data: Data? switch imageFormat { case .PNG: data = image.kf.pngRepresentation() case .JPEG: data = image.kf.jpegRepresentation(compressionQuality: 1.0) case .GIF: data = image.kf.gifRepresentation() case .unknown: data = original ?? image.kf.normalized.kf.pngRepresentation() } return data } public func image(with data: Data, options: KingfisherOptionsInfo?) -> Image? { let options = options ?? KingfisherEmptyOptionsInfo return Kingfisher<Image>.image( data: data, scale: options.scaleFactor, preloadAllAnimationData: options.preloadAllAnimationData, onlyFirstFrame: options.onlyLoadFirstFrame) } }
mit
9a1d9ce1ee205dd308115e605fbd600d
41.862069
84
0.680343
4.708333
false
false
false
false
practicalswift/swift
test/decl/ext/extensions.swift
11
3642
// RUN: %target-typecheck-verify-swift extension extension_for_invalid_type_1 { // expected-error {{use of undeclared type 'extension_for_invalid_type_1'}} func f() { } } extension extension_for_invalid_type_2 { // expected-error {{use of undeclared type 'extension_for_invalid_type_2'}} static func f() { } } extension extension_for_invalid_type_3 { // expected-error {{use of undeclared type 'extension_for_invalid_type_3'}} init() {} } extension extension_for_invalid_type_4 { // expected-error {{use of undeclared type 'extension_for_invalid_type_4'}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } extension extension_for_invalid_type_5 { // expected-error {{use of undeclared type 'extension_for_invalid_type_5'}} typealias X = Int } //===--- Test that we only allow extensions at file scope. struct Foo { } extension NestingTest1 { // expected-error {{use of undeclared type 'NestingTest1'}} extension Foo {} // expected-error {{declaration is only valid at file scope}} } struct NestingTest2 { extension Foo {} // expected-error {{declaration is only valid at file scope}} } class NestingTest3 { extension Foo {} // expected-error {{declaration is only valid at file scope}} } enum NestingTest4 { extension Foo {} // expected-error {{declaration is only valid at file scope}} } protocol NestingTest5 { extension Foo {} // expected-error {{declaration is only valid at file scope}} } func nestingTest6() { extension Foo {} // expected-error {{declaration is only valid at file scope}} } //===--- Test that we only allow extensions only for nominal types. struct S1 { struct NestedStruct {} } extension S1 {} // no-error extension S1.Type {} // expected-error {{cannot extend a metatype 'S1.Type'}} extension S1.NestedStruct {} // no-error struct S1_2 { // expected-error @+2 {{type member must not be named 'Type', since it would conflict with the 'foo.Type' expression}} // expected-note @+1 {{if this name is unavoidable, use backticks to escape it}} {{8-12=`Type`}} enum Type {} } struct S1_3 { enum `Type` {} // no-error } extension S1_2.Type {} // expected-error {{cannot extend a metatype 'S1_2.Type'}} extension S1_3.`Type` {} // no-error typealias TA_S1 = S1 extension TA_S1 {} // no-error typealias TA_S1_NestedStruct = S1.NestedStruct extension TA_S1_NestedStruct {} // no-error enum U1 { struct NestedStruct {} } extension U1 {} // no-error extension U1.NestedStruct {} // no-error class C1 { struct NestedStruct {} } extension C1 {} // no-error extension C1.NestedStruct {} // no-error protocol P1 {} protocol P2 {} extension () {} // expected-error {{non-nominal type '()' cannot be extended}} typealias TupleAlias = (x: Int, y: Int) extension TupleAlias {} // expected-error{{non-nominal type 'TupleAlias' (aka '(x: Int, y: Int)') cannot be extended}} // Test property accessors in extended types class C {} extension C { var p1: Int { get {return 1} set(v) {} } } var c = C() var x = c.p1 c.p1 = 1 protocol P3 { associatedtype Assoc func foo() -> Assoc } struct X3 : P3 { } extension X3.Assoc { // expected-error{{'Assoc' is not a member type of 'X3'}} } extension X3 { func foo() -> Int { return 0 } } // Make sure the test case from https://bugs.swift.org/browse/SR-3847 doesn't // cause problems when the later extension is incorrectly nested inside another // declaration. extension C1.NestedStruct { static let originalValue = 0 } struct WrapperContext { extension C1.NestedStruct { // expected-error {{declaration is only valid at file scope}} static let propUsingMember = originalValue } }
apache-2.0
15985eb07875ced0318b2ad1c46ed458
27.904762
120
0.694673
3.556641
false
true
false
false
kemalenver/SwiftHackerRank
Algorithms/Implementation.playground/Pages/Implementation - SockMerchant.xcplaygroundpage/Contents.swift
1
505
// number of elements var n = 9 // read array and map the elements to integer var readLine = "10 20 20 10 10 30 50 10 20" var arr = readLine.split(separator: " ").map { Int(String($0))! } var matches = [Int:Int]() for x in arr { if var count = matches[x] { count += 1 matches[x] = count } else { matches[x] = 1 } } var pairs = 0 for (_, value) in matches { let currentPair = Int(value / 2) pairs += currentPair } print(pairs)
mit
01970f0a36105c8e7879a31f2a56fccd
15.290323
65
0.546535
3.366667
false
false
false
false
ZwxWhite/V2EX
V2EX/Pods/PagingMenuController/Pod/Classes/MenuItemView.swift
2
4795
// // MenuItemView.swift // PagingMenuController // // Created by Yusuke Kita on 5/9/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit public class MenuItemView: UIView { public private(set) var titleLabel: UILabel! private var options: PagingMenuOptions! private var title: String! private var widthLabelConstraint: NSLayoutConstraint! // MARK: - Lifecycle internal init(title: String, options: PagingMenuOptions) { super.init(frame: CGRectZero) self.options = options self.title = title setupView() constructLabel() layoutLabel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } // MARK: - Constraints manager internal func updateLabelConstraints(size size: CGSize) { // set width manually to support ratotaion if case .SegmentedControl = options.menuDisplayMode { let labelSize = calculateLableSize(size) widthLabelConstraint.constant = labelSize.width } } // MARK: - Label changer internal func focusLabel(selected: Bool) { if case .RoundRect = options.menuItemMode { backgroundColor = UIColor.clearColor() } else { backgroundColor = selected ? options.selectedBackgroundColor : options.backgroundColor } titleLabel.textColor = selected ? options.selectedTextColor : options.textColor titleLabel.font = selected ? options.selectedFont : options.font // adjust label width if needed let labelSize = calculateLableSize() widthLabelConstraint.constant = labelSize.width } // MARK: - Constructor private func setupView() { if case .RoundRect = options.menuItemMode { backgroundColor = UIColor.clearColor() } else { backgroundColor = options.backgroundColor } translatesAutoresizingMaskIntoConstraints = false } private func constructLabel() { titleLabel = UILabel() titleLabel.text = title titleLabel.textColor = options.textColor titleLabel.font = options.font titleLabel.numberOfLines = 1 titleLabel.textAlignment = NSTextAlignment.Center titleLabel.userInteractionEnabled = true titleLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(titleLabel) } private func layoutLabel() { let viewsDictionary = ["label": titleLabel] let labelSize = calculateLableSize() let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[label]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) widthLabelConstraint = NSLayoutConstraint(item: titleLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: labelSize.width) widthLabelConstraint.active = true } // MARK: - Size calculator private func calculateLableSize(size: CGSize = UIScreen.mainScreen().bounds.size) -> CGSize { let labelSize = NSString(string: title).boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: titleLabel.font], context: nil).size let itemWidth: CGFloat switch options.menuDisplayMode { case let .Standard(widthMode, _, _): itemWidth = labelWidth(labelSize, widthMode: widthMode) case .SegmentedControl: itemWidth = size.width / CGFloat(options.menuItemCount) case let .Infinite(widthMode): itemWidth = labelWidth(labelSize, widthMode: widthMode) } let itemHeight = floor(labelSize.height) return CGSizeMake(itemWidth + calculateHorizontalMargin() * 2, itemHeight) } private func labelWidth(labelSize: CGSize, widthMode: PagingMenuOptions.MenuItemWidthMode) -> CGFloat { switch widthMode { case .Flexible: return ceil(labelSize.width) case let .Fixed(width): return width } } private func calculateHorizontalMargin() -> CGFloat { if case .SegmentedControl = options.menuDisplayMode { return 0.0 } return options.menuItemMargin } }
mit
ef01b096fe4043933da2769ebe632a55
34.783582
233
0.660897
5.621336
false
false
false
false
izrie/DKImagePickerController
DKImagePickerController/DKPopoverViewController.swift
1
6556
// // DKPopoverViewController.swift // DKImagePickerController // // Created by ZhangAo on 15/6/27. // Copyright (c) 2015年 ZhangAo. All rights reserved. // import UIKit class DKPopoverViewController: UIViewController { class func popoverViewController(viewController: UIViewController, fromView: UIView) { let window = UIApplication.sharedApplication().keyWindow! let popoverViewController = DKPopoverViewController() popoverViewController.contentViewController = viewController popoverViewController.fromView = fromView popoverViewController.showInView(window) window.rootViewController!.addChildViewController(popoverViewController) } class func dismissPopoverViewController() { let window = UIApplication.sharedApplication().keyWindow! for vc in window.rootViewController!.childViewControllers { if vc is DKPopoverViewController { (vc as! DKPopoverViewController).dismiss() } } } class DKPopoverView: UIView { var contentView: UIView! { didSet { contentView.layer.cornerRadius = 5 contentView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.addSubview(contentView) } } let arrowWidth: CGFloat = 20 let arrowHeight: CGFloat = 10 private let arrowImageView: UIImageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } func commonInit() { arrowImageView.image = self.arrowImage() self.addSubview(arrowImageView) } override func layoutSubviews() { super.layoutSubviews() self.arrowImageView.frame = CGRect(x: (self.bounds.width - self.arrowWidth) / 2, y: 0, width: arrowWidth, height: arrowHeight) self.contentView.frame = CGRect(x: 0, y: self.arrowHeight, width: self.bounds.width, height: self.bounds.height - arrowHeight) } func arrowImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(CGSize(width: arrowWidth, height: arrowHeight), false, UIScreen.mainScreen().scale) let context = UIGraphicsGetCurrentContext() UIColor.clearColor().setFill() CGContextFillRect(context, CGRect(x: 0, y: 0, width: arrowWidth, height: arrowHeight)) let arrowPath = CGPathCreateMutable() CGPathMoveToPoint(arrowPath, nil, arrowWidth / 2, 0) CGPathAddLineToPoint(arrowPath, nil, arrowWidth, arrowHeight) CGPathAddLineToPoint(arrowPath, nil, 0, arrowHeight) CGPathCloseSubpath(arrowPath) CGContextAddPath(context, arrowPath) CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextDrawPath(context, CGPathDrawingMode.Fill) let arrowImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return arrowImage } } var contentViewController: UIViewController! var fromView: UIView! private let popoverView = DKPopoverView() private var popoverViewHeight: CGFloat! override func loadView() { super.loadView() let backgroundView = UIControl(frame: self.view.frame) backgroundView.backgroundColor = UIColor.clearColor() backgroundView.addTarget(self, action: "dismiss", forControlEvents: .TouchUpInside) backgroundView.autoresizingMask = self.view.autoresizingMask self.view = backgroundView } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(popoverView) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil, completion: { (context) -> Void in let popoverY = self.fromView.convertPoint(self.fromView.frame.origin, toView: self.view).y + self.fromView.bounds.height self.popoverViewHeight = min(self.contentViewController.preferredContentSize.height + self.popoverView.arrowHeight, self.view.bounds.height - popoverY - 40) UIView.animateWithDuration(0.2, animations: { self.popoverView.frame = CGRect(x: 0, y: popoverY, width: self.view.bounds.width, height: self.popoverViewHeight) }) }) } func showInView(view: UIView) { let popoverY = self.fromView.convertPoint(self.fromView.frame.origin, toView: view).y + self.fromView.bounds.height self.popoverViewHeight = min(self.contentViewController.preferredContentSize.height + self.popoverView.arrowHeight, view.bounds.height - popoverY - 40) self.popoverView.frame = CGRect(x: 0, y: popoverY, width: view.bounds.width, height: popoverViewHeight) self.popoverView.contentView = self.contentViewController.view view.addSubview(self.view) self.popoverView.transform = CGAffineTransformScale(CGAffineTransformTranslate(self.popoverView.transform, 0, -(self.popoverViewHeight / 2)), 0.1, 0.1) UIView.animateWithDuration(0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1.3, options: [.CurveEaseInOut, .AllowUserInteraction], animations: { self.popoverView.transform = CGAffineTransformIdentity self.view.backgroundColor = UIColor(white: 0.4, alpha: 0.4) }, completion: nil) } func dismiss() { UIView.animateWithDuration(0.2, animations: { self.popoverView.transform = CGAffineTransformScale(CGAffineTransformTranslate(self.popoverView.transform, 0, -(self.popoverViewHeight / 2)), 0.01, 0.01) self.view.backgroundColor = UIColor.clearColor() }) { (result) -> Void in self.view.removeFromSuperview() self.removeFromParentViewController() } } }
mit
713c9b059e8bf2cce97af176cba57dd8
39.9625
172
0.642356
5.684302
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureNFT/Sources/FeatureNFTUI/Localization+FeatureNFTUI.swift
1
1770
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization // swiftlint:disable all // MARK: Groups extension LocalizationConstants { public enum NFT { public enum Screen { public enum List {} public enum Empty {} public enum Detail {} } } } // MARK: - AssetListView extension LocalizationConstants.NFT.Screen.List { public static let fetchingYourNFTs = NSLocalizedString( "Fetching Your NFTs", comment: "" ) public static let shopOnOpenSea = NSLocalizedString( "Shop on OpenSea", comment: "" ) } extension LocalizationConstants.NFT.Screen.Empty { public static let headline = NSLocalizedString( "To get started, transfer your NFTs", comment: "" ) public static let subheadline = NSLocalizedString( "Send from any wallet, or buy from a marketplace!", comment: "" ) public static let copyEthAddress = NSLocalizedString( "Copy Ethereum Address", comment: "" ) public static let copied = NSLocalizedString( "Copied!", comment: "" ) } // MARK: - AssetDetailView extension LocalizationConstants.NFT.Screen.Detail { public static let viewOnOpenSea = NSLocalizedString( "View on OpenSea", comment: "" ) public static let properties = NSLocalizedString( "Properties", comment: "" ) public static let creator = NSLocalizedString("Creator", comment: "") public static let about = NSLocalizedString("About", comment: "") public static let descripton = NSLocalizedString("Description", comment: "") public static let readMore = NSLocalizedString("Read More", comment: "") }
lgpl-3.0
f495ce116263cd1335b009406e53c614
23.569444
80
0.638779
4.88674
false
false
false
false
WickedColdfront/Slide-iOS
Pods/ImagePickerSheetController/ImagePickerSheetController/ImagePickerSheetController/Sheet/SheetController.swift
1
8665
// // SheetController.swift // ImagePickerSheetController // // Created by Laurin Brandner on 27/08/15. // Copyright © 2015 Laurin Brandner. All rights reserved. // import UIKit let sheetInset: CGFloat = 10 class SheetController: NSObject { fileprivate(set) lazy var sheetCollectionView: UICollectionView = { let layout = SheetCollectionViewLayout() let collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout) collectionView.dataSource = self collectionView.delegate = self collectionView.accessibilityIdentifier = "ImagePickerSheet" collectionView.backgroundColor = .clear collectionView.alwaysBounceVertical = false collectionView.register(SheetPreviewCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(SheetPreviewCollectionViewCell.self)) collectionView.register(SheetActionCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(SheetActionCollectionViewCell.self)) return collectionView }() var previewCollectionView: PreviewCollectionView fileprivate(set) var actions = [ImagePickerAction]() var actionHandlingCallback: (() -> ())? fileprivate(set) var previewHeight: CGFloat = 0 var numberOfSelectedAssets = 0 var preferredSheetHeight: CGFloat { return allIndexPaths().map { self.sizeForSheetItemAtIndexPath($0).height } .reduce(0, +) } // MARK: - Initialization init(previewCollectionView: PreviewCollectionView) { self.previewCollectionView = previewCollectionView super.init() } // MARK: - Data Source // These methods are necessary so that no call cycles happen when calculating some design attributes fileprivate func numberOfSections() -> Int { return 2 } fileprivate func numberOfItemsInSection(_ section: Int) -> Int { if section == 0 { return 1 } return actions.count } fileprivate func allIndexPaths() -> [IndexPath] { let s = numberOfSections() return (0 ..< s).map { (section: Int) -> (Int, Int) in (self.numberOfItemsInSection(section), section) } .flatMap { (numberOfItems: Int, section: Int) -> [IndexPath] in (0 ..< numberOfItems).map { (item: Int) -> IndexPath in IndexPath(item: item, section: section) } } } fileprivate func sizeForSheetItemAtIndexPath(_ indexPath: IndexPath) -> CGSize { let height: CGFloat = { if indexPath.section == 0 { return previewHeight } let actionItemHeight: CGFloat = 57 let insets = attributesForItemAtIndexPath(indexPath).backgroundInsets return actionItemHeight + insets.top + insets.bottom }() return CGSize(width: sheetCollectionView.bounds.width, height: height) } // MARK: - Design fileprivate func attributesForItemAtIndexPath(_ indexPath: IndexPath) -> (corners: RoundedCorner, backgroundInsets: UIEdgeInsets) { let cornerRadius: CGFloat = 13 let innerInset: CGFloat = 4 var indexPaths = allIndexPaths() guard indexPaths.first != indexPath else { return (.top(cornerRadius), UIEdgeInsets(top: 0, left: sheetInset, bottom: 0, right: sheetInset)) } let cancelIndexPath = actions.index { $0.style == ImagePickerActionStyle.cancel } .map { IndexPath(item: $0, section: 1) } if let cancelIndexPath = cancelIndexPath { if cancelIndexPath == indexPath { return (.all(cornerRadius), UIEdgeInsets(top: innerInset, left: sheetInset, bottom: sheetInset, right: sheetInset)) } indexPaths.removeLast() if indexPath == indexPaths.last { return (.bottom(cornerRadius), UIEdgeInsets(top: 0, left: sheetInset, bottom: innerInset, right: sheetInset)) } } else if indexPath == indexPaths.last { return (.bottom(cornerRadius), UIEdgeInsets(top: 0, left: sheetInset, bottom: sheetInset, right: sheetInset)) } return (.none, UIEdgeInsets(top: 0, left: sheetInset, bottom: 0, right: sheetInset)) } fileprivate func fontForAction(_ action: ImagePickerAction) -> UIFont { if action.style == .cancel { return UIFont.boldSystemFont(ofSize: 21) } return UIFont.systemFont(ofSize: 21) } // MARK: - Actions func reloadActionItems() { sheetCollectionView.reloadSections(IndexSet(integer: 1)) } func addAction(_ action: ImagePickerAction) { if action.style == .cancel { actions = actions.filter { $0.style != .cancel } } actions.append(action) if let index = actions.index(where: { $0.style == .cancel }) { let cancelAction = actions.remove(at: index) actions.append(cancelAction) } reloadActionItems() } func removeAllActions() { actions = [] reloadActionItems() } fileprivate func handleAction(_ action: ImagePickerAction) { actionHandlingCallback?() action.handle(numberOfSelectedAssets) } func handleCancelAction() { let cancelAction = actions.filter { $0.style == .cancel } .first if let cancelAction = cancelAction { handleAction(cancelAction) } else { actionHandlingCallback?() } } // MARK: - func setPreviewHeight(_ height: CGFloat, invalidateLayout: Bool) { previewHeight = height if invalidateLayout { sheetCollectionView.collectionViewLayout.invalidateLayout() } } } extension SheetController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return numberOfSections() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return numberOfItemsInSection(section) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: SheetCollectionViewCell if indexPath.section == 0 { let previewCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(SheetPreviewCollectionViewCell.self), for: indexPath) as! SheetPreviewCollectionViewCell previewCell.collectionView = previewCollectionView cell = previewCell } else { let action = actions[indexPath.item] let actionCell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(SheetActionCollectionViewCell.self), for: indexPath) as! SheetActionCollectionViewCell actionCell.textLabel.font = fontForAction(action) actionCell.textLabel.text = numberOfSelectedAssets > 0 ? action.secondaryTitle(numberOfSelectedAssets) : action.title cell = actionCell } cell.separatorVisible = (indexPath.section == 1) // iOS specific design (cell.roundedCorners, cell.backgroundInsets) = attributesForItemAtIndexPath(indexPath) cell.normalBackgroundColor = UIColor(white: 0.97, alpha: 1) cell.highlightedBackgroundColor = UIColor(white: 0.92, alpha: 1) cell.separatorColor = UIColor(white: 0.84, alpha: 1) return cell } } extension SheetController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return indexPath.section != 0 } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) handleAction(actions[indexPath.item]) } } extension SheetController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return sizeForSheetItemAtIndexPath(indexPath) } }
apache-2.0
9369c285027d4d816cbe0367840cf537
34.508197
192
0.631579
5.711272
false
false
false
false
BridgeTheGap/KRMathInputView
Example/Pods/KRMathInputView/KRMathInputView/Classes/MathInputView.swift
1
4789
// // MathInputView.swift // TestScript // // Created by Joshua Park on 31/01/2017. // Copyright © 2017 Knowre. All rights reserved. // import UIKit @objc public protocol MathInputViewDelegate: NSObjectProtocol { func mathInputView(_ MathInputView: MathInputView, didParse ink: [Any], latex: String) func mathInputView(_ MathInputView: MathInputView, didFailToParse ink: [Any], with error: NSError) } open class MathInputView: UIView, MathInkManagerDelegate { open weak var delegate: MathInputViewDelegate? public var isWritingMode: Bool = true { willSet { tapGestureRecognizer.isEnabled = !newValue longPressGestureRecognizer.isEnabled = !newValue } } open var manager = MathInkManager() @IBOutlet open weak var undoButton: UIButton? @IBOutlet open weak var redoButton: UIButton? private let tapGestureRecognizer = UITapGestureRecognizer() private let longPressGestureRecognizer = UILongPressGestureRecognizer() override public init(frame: CGRect) { super.init(frame: frame) setUp() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } private func setUp() { tapGestureRecognizer.addTarget(self, action: #selector(tapAction(_:))) tapGestureRecognizer.isEnabled = false addGestureRecognizer(tapGestureRecognizer) longPressGestureRecognizer.addTarget(self, action: #selector(longPressAction(_:))) longPressGestureRecognizer.isEnabled = false addGestureRecognizer(longPressGestureRecognizer) manager.delegate = self } // MARK: - Public override open func draw(_ rect: CGRect) { UIColor.black.setStroke() for ink in manager.ink { if let strokeInk = ink as? StrokeInk, rect.intersects(strokeInk.path.bounds) { strokeInk.path.stroke() } else { } } if let stroke = manager.buffer { stroke.stroke() } } // MARK: - Private private func selectNode(at point: CGPoint) -> Node? { guard let node = manager.selectNode(at: point) else { return nil } displaySelection(at: node.frame) return node } private func displaySelection(at: CGRect) { // TODO: Implement } private func showMenu(at: CGRect) { } private func showCursor(at: CGRect) { } private func register(touch: UITouch, isLast: Bool = false) { let rect = manager.inputStream(at: touch.location(in: self), previousPoint: touch.previousLocation(in: self), isLast: isLast) setNeedsDisplay(rect) } // MARK: - Touch override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!) } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!, isLast: true) manager.process() } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { register(touch: touches.first!, isLast: true) manager.process() } // MARK: - Target action @objc private func tapAction(_ sender: UITapGestureRecognizer) { guard let node = selectNode(at: sender.location(in: self)) else { return } showMenu(at: node.frame) } @objc private func longPressAction(_ sender: UILongPressGestureRecognizer) { guard let node = selectNode(at: sender.location(in: self)) else { return } showCursor(at: node.frame) } @IBAction public func undoAction(_ sender: UIButton?) { if let rect = manager.undo() { setNeedsDisplay(rect) } } @IBAction public func redoAction(_ sender: UIButton?) { if let rect = manager.redo() { setNeedsDisplay(rect) } } // MARK: - MyScriptParser delegate open func manager(_ manager: MathInkManager, didParseTreeToLaTex string: String) { delegate?.mathInputView(self, didParse: manager.ink, latex: string) } open func manager(_ manager: MathInkManager, didFailToParseWith error: NSError) { delegate?.mathInputView(self, didFailToParse: manager.ink, with: error) } open func manager(_ manager: MathInkManager, didUpdateHistory state: (undo: Bool, redo: Bool)) { } }
mit
beac4fc0a5286ade91005f602033d51f
29.890323
102
0.618421
5.050633
false
false
false
false
vector-im/vector-ios
Riot/Modules/CrossSigning/Banners/CrossSigningSetupBannerCell.swift
1
2793
/* Copyright 2020 New Vector Ltd 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 @objc protocol CrossSigningSetupBannerCellDelegate: AnyObject { func crossSigningSetupBannerCellDidTapCloseAction(_ cell: CrossSigningSetupBannerCell) } @objcMembers final class CrossSigningSetupBannerCell: MXKTableViewCell, Themable { // MARK: - Properties // MARK: Outlets @IBOutlet private weak var shieldImageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var subtitleLabel: UILabel! @IBOutlet private weak var closeButton: UIButton! // MARK: Public weak var delegate: CrossSigningSetupBannerCellDelegate? // MARK: - Overrides override class func defaultReuseIdentifier() -> String { return String(describing: self) } override class func nib() -> UINib { return UINib(nibName: String(describing: self), bundle: nil) } override func customizeRendering() { super.customizeRendering() let theme = ThemeService.shared().theme self.update(theme: theme) } // MARK: - Life cycle override func awakeFromNib() { super.awakeFromNib() // TODO: Image size is too small, use an higher resolution one. let shieldImage = Asset.Images.encryptionNormal.image.withRenderingMode(.alwaysTemplate) self.shieldImageView.image = shieldImage let closeImage = Asset.Images.closeBanner.image.withRenderingMode(.alwaysTemplate) self.closeButton.setImage(closeImage, for: .normal) self.titleLabel.text = VectorL10n.crossSigningSetupBannerTitle self.subtitleLabel.text = VectorL10n.crossSigningSetupBannerSubtitle } // MARK: - Public func update(theme: Theme) { self.shieldImageView.tintColor = theme.textPrimaryColor self.closeButton.tintColor = theme.textPrimaryColor self.titleLabel.textColor = theme.textPrimaryColor self.subtitleLabel.textColor = theme.textPrimaryColor } // MARK: - Actions @IBAction private func closeButtonAction(_ sender: Any) { self.delegate?.crossSigningSetupBannerCellDidTapCloseAction(self) } }
apache-2.0
372d4f0aedc6fe58a50821a8ed144dca
31.103448
96
0.697816
5.153137
false
false
false
false
vector-im/vector-ios
Riot/Modules/ServiceTerms/Modal/Modal/ServiceTermsModalTableHeaderView.swift
1
1704
// // Copyright 2021 New Vector Ltd // // 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 Reusable protocol ServiceTermsModalTableHeaderViewDelegate: AnyObject { func tableHeaderViewDidTapInformationButton() } class ServiceTermsModalTableHeaderView: UIView, NibLoadable, Themable { // MARK: - Properties weak var delegate: ServiceTermsModalTableHeaderViewDelegate? @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var serviceURLLabel: UILabel! // MARK: - Setup static func instantiate() -> Self { let view = Self.loadFromNib() view.translatesAutoresizingMaskIntoConstraints = false view.update(theme: ThemeService.shared().theme) return view } func update(theme: Theme) { titleLabel.font = theme.fonts.footnote titleLabel.textColor = theme.colors.secondaryContent serviceURLLabel.font = theme.fonts.callout serviceURLLabel.textColor = theme.colors.secondaryContent } // MARK: - Action @IBAction private func buttonAction(_ sender: Any) { delegate?.tableHeaderViewDidTapInformationButton() } }
apache-2.0
17566475e1efc06d5ddf7d8cd20d62e6
29.428571
75
0.704225
4.96793
false
false
false
false
vector-im/vector-ios
Riot/Modules/SetPinCode/EnterPinCode/EnterPinCodeViewModel.swift
1
8979
// File created from ScreenTemplate // $ createScreen.sh SetPinCode/EnterPinCode EnterPinCode /* Copyright 2020 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation final class EnterPinCodeViewModel: EnterPinCodeViewModelType { // MARK: - Properties // MARK: Private private let session: MXSession? private var originalViewMode: SetPinCoordinatorViewMode private var viewMode: SetPinCoordinatorViewMode private var initialPin: String = "" private var firstPin: String = "" private var currentPin: String = "" { didSet { self.viewDelegate?.enterPinCodeViewModel(self, didUpdatePlaceholdersCount: currentPin.count) } } private var numberOfFailuresDuringEnterPIN: Int = 0 // MARK: Public weak var viewDelegate: EnterPinCodeViewModelViewDelegate? weak var coordinatorDelegate: EnterPinCodeViewModelCoordinatorDelegate? private let pinCodePreferences: PinCodePreferences private let localAuthenticationService: LocalAuthenticationService // MARK: - Setup init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences) { self.session = session self.originalViewMode = viewMode self.viewMode = viewMode self.pinCodePreferences = pinCodePreferences self.localAuthenticationService = LocalAuthenticationService(pinCodePreferences: pinCodePreferences) } // MARK: - Public func process(viewAction: EnterPinCodeViewAction) { switch viewAction { case .loadData: self.loadData() case .digitPressed(let tag): self.digitPressed(tag) case .forgotPinPressed: self.viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: .forgotPin) case .cancel: self.coordinatorDelegate?.enterPinCodeViewModelDidCancel(self) case .pinsDontMatchAlertAction: // reset pins firstPin.removeAll() currentPin.removeAll() // go back to first state self.update(viewState: .choosePin) case .forgotPinAlertResetAction: self.coordinatorDelegate?.enterPinCodeViewModelDidCompleteWithReset(self, dueToTooManyErrors: false) case .forgotPinAlertCancelAction: // no-op break } } // MARK: - Private private func digitPressed(_ tag: Int) { if tag == -1 { // delete tapped if currentPin.isEmpty { return } else { currentPin.removeLast() // switch to setPin if blocked if viewMode == .notAllowedPin { // clear error UI update(viewState: viewState(for: originalViewMode)) // switch back to original flow viewMode = originalViewMode } } } else { // a digit tapped // switch to setPin if blocked if viewMode == .notAllowedPin { // clear old pin first currentPin.removeAll() // clear error UI update(viewState: viewState(for: originalViewMode)) // switch back to original flow viewMode = originalViewMode } // add new digit currentPin += String(tag) if currentPin.count == pinCodePreferences.numberOfDigits { switch viewMode { case .setPin, .setPinAfterLogin, .setPinAfterRegister: // choosing pin updateAfterPinSet() case .unlock, .confirmPinToDeactivate: // unlocking if currentPin != pinCodePreferences.pin { // no match updateAfterUnlockFailed() } else { // match // we can use biometrics anymore, if set pinCodePreferences.canUseBiometricsToUnlock = nil pinCodePreferences.resetCounters() // complete with a little delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.enterPinCodeViewModelDidComplete(self) } } case .changePin: // unlocking if initialPin.isEmpty && currentPin != pinCodePreferences.pin { // no match updateAfterUnlockFailed() } else if initialPin.isEmpty { // match or already unlocked // the user can choose a new Pin code initialPin = currentPin currentPin.removeAll() update(viewState: .choosePin) } else { // choosing pin updateAfterPinSet() } default: break } return } } } private func viewState(for mode: SetPinCoordinatorViewMode) -> EnterPinCodeViewState { switch mode { case .setPin: return .choosePin case .setPinAfterLogin: return .choosePinAfterLogin case .setPinAfterRegister: return .choosePinAfterRegister case .changePin: return .changePin default: return .inactive } } private func loadData() { switch viewMode { case .setPin, .setPinAfterLogin, .setPinAfterRegister: update(viewState: viewState(for: viewMode)) self.viewDelegate?.enterPinCodeViewModel(self, didUpdateCancelButtonHidden: pinCodePreferences.forcePinProtection) case .unlock: update(viewState: .unlock) case .confirmPinToDeactivate: update(viewState: .confirmPinToDisable) case .inactive: update(viewState: .inactive) case .changePin: update(viewState: .changePin) default: break } } private func update(viewState: EnterPinCodeViewState) { self.viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: viewState) } private func updateAfterUnlockFailed() { numberOfFailuresDuringEnterPIN += 1 pinCodePreferences.numberOfPinFailures += 1 if viewMode == .unlock && localAuthenticationService.shouldLogOutUser() { // log out user self.coordinatorDelegate?.enterPinCodeViewModelDidCompleteWithReset(self, dueToTooManyErrors: true) return } if numberOfFailuresDuringEnterPIN < pinCodePreferences.allowedNumberOfTrialsBeforeAlert { DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: .wrongPin) self.currentPin.removeAll() } } else { viewDelegate?.enterPinCodeViewModel(self, didUpdateViewState: .wrongPinTooManyTimes) numberOfFailuresDuringEnterPIN = 0 currentPin.removeAll() } } private func updateAfterPinSet() { if firstPin.isEmpty { // check if this PIN is allowed if pinCodePreferences.notAllowedPINs.contains(currentPin) { viewMode = .notAllowedPin update(viewState: .notAllowedPin) return } // go to next screen firstPin = currentPin currentPin.removeAll() update(viewState: .confirmPin) } else if firstPin == currentPin { // check first and second pins // complete with a little delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.enterPinCodeViewModel(self, didCompleteWithPin: self.firstPin) } } else { update(viewState: .pinsDontMatch) } } }
apache-2.0
09ca75fbf01f0371cd1efb1fbab7efcd
36.726891
126
0.571667
6.038332
false
false
false
false
tjw/swift
benchmark/single-source/SequenceAlgos.swift
3
4407
//===--- ArrayAppend.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // This benchmark tests closureless versions of min and max, both contains, // repeatElement and reduce, on a number of different sequence types. // To avoid too many little micro benchmarks, it measures them all together // for each sequence type. public let SequenceAlgos = [ BenchmarkInfo(name: "SequenceAlgosList", runFunction: run_SequenceAlgosList, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosArray", runFunction: run_SequenceAlgosArray, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosContiguousArray", runFunction: run_SequenceAlgosContiguousArray, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosRange", runFunction: run_SequenceAlgosRange, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosUnfoldSequence", runFunction: run_SequenceAlgosUnfoldSequence, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), BenchmarkInfo(name: "SequenceAlgosAnySequence", runFunction: run_SequenceAlgosAnySequence, tags: [.validation, .api], setUpFunction: { buildWorkload() }, tearDownFunction: nil), ] extension List: Sequence { struct Iterator: IteratorProtocol { var _list: List<Element> mutating func next() -> Element? { guard case let .node(x,xs) = _list else { return nil } _list = xs return x } } func makeIterator() -> Iterator { return Iterator(_list: self) } } extension List: Equatable where Element: Equatable { static func == (lhs: List<Element>, rhs: List<Element>) -> Bool { return lhs.elementsEqual(rhs) } } func benchmarkSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int { CheckResults(s.reduce(0, &+) == (n*(n-1))/2) let mn = s.min() let mx = s.max() CheckResults(mn == 0 && mx == n-1) CheckResults(s.starts(with: s)) } let n = 10_000 let r = 0..<(n*100) let l = List(0..<n) let c = ContiguousArray(0..<(n*100)) let a = Array(0..<(n*100)) let y = AnySequence(0..<n) let s = sequence(first: 0, next: { $0 < n&-1 ? $0&+1 : nil}) func buildWorkload() { _ = l.makeIterator() _ = c.makeIterator() _ = a.makeIterator() _ = y.makeIterator() _ = s.makeIterator() } func benchmarkEquatableSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int, S: Equatable { CheckResults(repeatElement(s, count: 1).contains(s)) CheckResults(!repeatElement(s, count: 1).contains { $0 != s }) } @inline(never) public func run_SequenceAlgosRange(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: r, n: r.count) benchmarkEquatableSequenceAlgos(s: r, n: r.count) } } @inline(never) public func run_SequenceAlgosArray(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: a, n: a.count) benchmarkEquatableSequenceAlgos(s: a, n: a.count) } } @inline(never) public func run_SequenceAlgosContiguousArray(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: c, n: c.count) benchmarkEquatableSequenceAlgos(s: c, n: c.count) } } @inline(never) public func run_SequenceAlgosAnySequence(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: y, n: n) } } @inline(never) public func run_SequenceAlgosUnfoldSequence(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: s, n: n) } } @inline(never) public func run_SequenceAlgosList(_ N: Int) { for _ in 0..<N { benchmarkSequenceAlgos(s: l, n: n) benchmarkEquatableSequenceAlgos(s: l, n: n) } } enum List<Element> { case end indirect case node(Element, List<Element>) init<S: BidirectionalCollection>(_ elements: S) where S.Element == Element { self = elements.reversed().reduce(.end) { .node($1,$0) } } }
apache-2.0
7c828f4ecf44a9535f0944d5293b02a7
32.135338
187
0.668255
3.782833
false
false
false
false
opensourcegit/CustomCollectionViews
Pod/Classes/BaseCollectionView.swift
1
4661
// // BaseCollectionView.swift // Pods // // Created by opensourcegit on 18/09/15. // // import Foundation import UIKit public class BaseCollectionView: UICollectionView { var data = [BaseCollectionSectionModel](); public func setCollectionViewData(data:[BaseCollectionSectionModel]){ self.data = data; dispatch_async(dispatch_get_main_queue(), { () -> Void in print("data reload count \(self.data.count)\n") self.reloadData(); }); } override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) self.setup() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup(); } override public func awakeFromNib() { super.awakeFromNib(); self.setup() } func setup(){ self.dataSource = self; self.delegate = self; } } extension BaseCollectionView:UICollectionViewDataSource{ public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ let sectionModel = data[section]; let count = sectionModel.items.count; println("count \(count)"); return count; } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{ let sectionModel = data[indexPath.section]; let cellModel = sectionModel.items[indexPath.item]; let cellIdentifier = cellModel.dynamicType.cellIdentifier(); let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell; if let cell = cell as? ReactiveView{ cell.bindViewModel(cellModel); } return cell } //MARK: optional public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int{ return data.count; } // The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: public func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView{ var reusableView : UICollectionReusableView? = nil if kind == UICollectionElementKindSectionHeader { let sectionModel = data[indexPath.section]; let reuseIdentifier = sectionModel.identifer!; reusableView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reuseIdentifier, forIndexPath: indexPath) as? UICollectionReusableView if let reusableView = reusableView as? ReactiveView { reusableView.bindViewModel(sectionModel); } } return reusableView! } } extension BaseCollectionView:UICollectionViewDelegateFlowLayout{ public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{ let sectionModel:BaseCollectionSectionModel = data[indexPath.section]; let cellModel = sectionModel.items[indexPath.item]; return CellSizer.shared.sizeThatFits(collectionView.bounds.size, viewModel: cellModel, cellClass: cellModel.cellClass()) } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets{ // // } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat{ // // } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat{ // // } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{ return CGSize(width: 100, height: 100); } // func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize{ // // } }
mit
8d92de5249ce2c545e6b251470baff9b
41
179
0.711006
6.053247
false
false
false
false
mxcl/swift-package-manager
Sources/PackageModel/Manifest.swift
2
2344
/* This source file is part of the Swift.org open source project Copyright 2015 - 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors ------------------------------------------------------------------------- This file defines the support for loading the Swift-based manifest files. */ import Basic import PackageDescription /** This contains the declarative specification loaded from package manifest files, and the tools for working with the manifest. */ public struct Manifest { /// The standard filename for the manifest. public static var filename = basename + ".swift" /// The standard basename for the manifest. public static var basename = "Package" /// The path of the manifest file. // // FIXME: This doesn't belong here, we want the Manifest to be purely tied // to the repository state, it shouldn't matter where it is. public let path: AbsolutePath /// The repository URL the manifest was loaded from. // // FIXME: This doesn't belong here, we want the Manifest to be purely tied // to the repository state, it shouldn't matter where it is. public let url: String /// The raw package description. public let package: PackageDescription.Package /// The raw product descriptions. public let products: [PackageDescription.Product] /// The version this package was loaded from, if known. public let version: Version? /// The name of the package. public var name: String { return package.name } public init(path: AbsolutePath, url: String, package: PackageDescription.Package, products: [PackageDescription.Product], version: Version?) { self.path = path self.url = url self.package = package self.products = products self.version = version } } extension Manifest { /// Returns JSON representation of this manifest. // Note: Right now we just return the JSON representation of the package, // but this can be expanded to include the details about manifest too. public func jsonString() -> String { return PackageDescription.jsonString(package: package) } }
apache-2.0
fe697447ad734934bc99ae2f83071c8a
32.485714
146
0.68302
4.934737
false
false
false
false
austinfitzpatrick/SwiftVG
SwiftVG/SwiftSVG/Views/SVGVectorImage Categories/SVGVectorImage+ColorReplacement.swift
1
1468
// // SVGVectorImage+ColorReplacement.swift // SwiftVG // // Created by Austin Fitzpatrick on 3/20/15. // Copyright (c) 2015 austinfitzpatrick. All rights reserved. // import UIKit protocol SVGColorReplaceable { func replaceColor(color: UIColor, withColor replacement:UIColor, includeGradients:Bool) } extension SVGGroup: SVGColorReplaceable { func replaceColor(color: UIColor, withColor replacement: UIColor, includeGradients:Bool) { for drawable in drawables { if let group = drawable as? SVGGroup { group.replaceColor(color, withColor: replacement, includeGradients:includeGradients) } else if let path = drawable as? SVGPath { path.replaceColor(color, withColor: replacement, includeGradients:includeGradients) } } } } extension SVGPath: SVGColorReplaceable { func replaceColor(color: UIColor, withColor replacement: UIColor, includeGradients:Bool) { if let fillColor = self.fill?.asColor(){ if fillColor == color { self.fill = replacement } } else if let fillGradient = self.fill?.asGradient() { if includeGradients { for stop in fillGradient.stops { if stop.color == color { fillGradient.removeStop(stop) fillGradient.addStop(stop.offset, color: replacement, opacity: 1.0) } } } } } }
mit
582164e190a4747bed4d3c3a4b839c45
33.952381
139
0.631471
4.690096
false
false
false
false
manchan/JinsMeme-Swift-Sample
JinsMemeDemo/ViewController.swift
1
5984
// // ViewController.swift // JinsMemeDemo // // Created by matz on 2015/11/21. // Copyright © 2015年 matz. All rights reserved. // import UIKit final class ViewController: UITableViewController, MEMELibDelegate { var peripherals:NSMutableArray! var dataViewCtl:MMDataViewController! var detailViewCtl:MMDataDetaileViewController! override func viewDidLoad() { super.viewDidLoad() MEMELib.sharedInstance().delegate = self self.peripherals = [] self.title = "MEME Demo" self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Scan", style: UIBarButtonItemStyle.plain, target: self, action: #selector(scanButtonPressed)) } func scanButtonPressed(){ let status:MEMEStatus = MEMELib.sharedInstance().startScanningPeripherals() self.checkMEMEStatus(status) } func memePeripheralFound(_ peripheral: CBPeripheral!, withDeviceAddress address: String!) { print("New Peripheral found \(peripheral.identifier.uuidString) \(address)") self.peripherals.add(peripheral) self.tableView.reloadData() } func memePeripheralConnected(_ peripheral: CBPeripheral!) { print("MEME Device Connected") self.navigationItem.rightBarButtonItem?.isEnabled = false self.tableView.isUserInteractionEnabled = false self.performSegue(withIdentifier: "DataViewSegue", sender: self) // Set Data Mode to Standard Mode MEMELib.sharedInstance().startDataReport() } func memePeripheralDisconnected(_ peripheral: CBPeripheral!) { print("MEME Device Disconnected") self.navigationItem.rightBarButtonItem?.isEnabled = true self.tableView.isUserInteractionEnabled = true self.dismiss(animated: true) { () -> Void in self.dataViewCtl = nil print("MEME Device Disconnected") } } func memeRealTimeModeDataReceived(_ data: MEMERealTimeData!) { guard let _ = self.dataViewCtl else { return } self.dataViewCtl.memeRealTimeModeDataReceived(data) RealtimeData.sharedInstance.memeRealTimeModeDataReceived(data) } func memeAppAuthorized(_ status: MEMEStatus) { self.checkMEMEStatus(status) } func memeCommand(_ response: MEMEResponse) { print("Command Response - eventCode: \(response.eventCode) - commandResult: \(response.commandResult)") switch (response.eventCode) { case 0x02: print("Data Report Started"); break; case 0x04: print("Data Report Stopped"); break; default: break; } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.peripherals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCellIdentifier", for: indexPath) let peripheral:CBPeripheral = self.peripherals.object(at: indexPath.row) as! CBPeripheral cell.textLabel?.text = peripheral.identifier.uuidString return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let peripheral:CBPeripheral = self.peripherals.object(at: indexPath.row) as! CBPeripheral let status:MEMEStatus = MEMELib.sharedInstance().connect(peripheral) self.checkMEMEStatus(status) print("Start connecting to MEME Device...") } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "DataViewSegue" { let naviCtl = segue.destination as! UINavigationController self.dataViewCtl = naviCtl.topViewController as! MMDataViewController } } func checkMEMEStatus(_ status:MEMEStatus) { if status == MEME_ERROR_APP_AUTH { let alertController = UIAlertController(title: "App Auth Failed", message: "Invalid Application ID or Client Secret ", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_ERROR_SDK_AUTH{ let alertController = UIAlertController(title: "SDK Auth Failed", message: "Invalid SDK. Please update to the latest SDK.", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_CMD_INVALID { let alertController = UIAlertController(title: "SDK Error", message: "Invalid Command", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_ERROR_BL_OFF { let alertController = UIAlertController(title: "Error", message: "Bluetooth is off.", preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler:nil) alertController.addAction(action) self.present(alertController, animated: true, completion: nil) } else if status == MEME_OK { print("Status: MEME_OK") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
933591f1cb10a8af7cb9b8957f193d99
37.587097
166
0.650894
5.111966
false
false
false
false
baberthal/SwiftCoreExt
CoreExtensions/DebugMacros.swift
1
1750
// // DebugMacros.swift // CoreExtensions // // Created by Morgan Lieberthal on 12/5/15. // Copyright © 2015 Morgan Lieberthal. All rights reserved. // import Foundation import Cocoa public func dLog(@autoclosure message: () -> String, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { #if DEBUG var path: String! if let fname = NSURL(string: filename) { path = fname.lastPathComponent } else { path = filename } NSLog("[\(path):\(line):\(column)] \(function) -- %@", message()) #endif } public func uLog(error: NSError, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { #if DEBUG let alert = NSAlert(error: error) alert.runModal() NSLog("[\(filename):\(line):\(column)] \(function) -- %@", error) #endif } public func aLog(@autoclosure message: () -> String, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { var path: String! if let fname = NSURL(string: filename) { path = fname.lastPathComponent } else { path = filename } NSLog("[\(path):\(line):\(column)] \(function) -- %@", message()) } public func eLog(@autoclosure message: () -> String, error: NSError, filename: String = __FILE__, function: StaticString = __FUNCTION__, line: UInt = __LINE__, column: UInt = __COLUMN__) { var path: String! if let fname = NSURL(string: filename) { path = fname.lastPathComponent } else { path = filename } NSLog("[\(path):\(line):\(column)] \(function) -- %@", message()) NSLog("An error occurred: %@", error) }
mit
57a19d2bccebb30f3dba1ba68d3b7179
33.313725
188
0.606061
3.975
false
false
false
false
yhyuan/WeatherMap
WeatherAroundUs/WeatherAroundUs/UIViewExtension.swift
9
1542
// // UIViewExtension.swift // PaperPlane // // Created by Kedan Li on 15/2/27. // Copyright (c) 2015年 Yu Wang. All rights reserved. // import QuartzCore import UIKit extension UIView { func rotate360Degrees(duration: CFTimeInterval = 1.0, completionDelegate: AnyObject? = nil) { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z") rotateAnimation.fromValue = 0.0 rotateAnimation.toValue = CGFloat(M_PI * 2.0) rotateAnimation.duration = duration if let delegate: AnyObject = completionDelegate { rotateAnimation.delegate = delegate } self.layer.addAnimation(rotateAnimation, forKey: nil) } func getTheImageOfTheView()->UIImage{ UIGraphicsBeginImageContext(self.bounds.size) self.layer.renderInContext(UIGraphicsGetCurrentContext()) var outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } func roundCorner(corners: UIRectCorner, radius: CGFloat) { let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSizeMake(radius, radius)) var mask = CAShapeLayer() mask.frame = self.bounds; mask.path = maskPath.CGPath; layer.mask = mask; } func roundCircle(){ let maskPath = UIBezierPath(ovalInRect:self.bounds) let mask = CAShapeLayer() mask.path = maskPath.CGPath layer.mask = mask } }
apache-2.0
3cfcdc721be836285d0e52fe07e6d8ea
31.787234
130
0.666234
4.888889
false
false
false
false
archembald/avajo-ios
avajo-ios/ProfileViewController.swift
1
1636
// // ProfileViewController.swift // avajo-ios // // Created by Alejandro Alvarez Martinez on 05/10/2015. // Copyright (c) 2015 Archembald. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet var imgProfilePicture: UIImageView! @IBOutlet var labelUsername: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.imgProfilePicture.layer.masksToBounds = true self.imgProfilePicture.layer.cornerRadius = self.imgProfilePicture.frame.height/2 // Get info from FB let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil){ // Process error println("Error: \(error)") } else { self.labelUsername.text = result.valueForKey("name") as? String // Set pic let fbid = result.valueForKey("id") as? String let url = NSURL(string: "https://graph.facebook.com/"+fbid!+"/picture?type=large") let data = NSData(contentsOfURL: url!) self.imgProfilePicture.image = UIImage(data: data!); } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
agpl-3.0
4c246616e51058181b9c2a12ed0211b4
30.461538
98
0.589242
5.065015
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/InsertMediaImageInfoView.swift
3
3115
import UIKit final class InsertMediaImageInfoView: UIView { @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var descriptionLabel: UILabel! @IBOutlet private weak var licenseLabel: UILabel! @IBOutlet private weak var licenseView: LicenseView! @IBOutlet private weak var moreInformationButton: UIButton! var moreInformationAction: ((URL) -> Void)? private var keepBackgroundClear = false private var moreInformationURL: URL? { didSet { moreInformationButton.isHidden = moreInformationURL == nil } } func configure(with searchResult: InsertMediaSearchResult, showImageDescription: Bool = true, showLicenseName: Bool = true, showMoreInformationButton: Bool = true, keepBackgroundClear: Bool = false, theme: Theme) { titleLabel.text = searchResult.displayTitle moreInformationURL = searchResult.imageInfo?.filePageURL if showImageDescription, let imageDescription = searchResult.imageInfo?.imageDescription { descriptionLabel.numberOfLines = 5 descriptionLabel.text = imageDescription } else { descriptionLabel.isHidden = true } moreInformationButton.isHidden = !showMoreInformationButton licenseView.licenseCodes = searchResult.imageInfo?.license?.code?.split(separator: "-").compactMap { String($0) } ?? [] licenseView.isHidden = licenseView.licenseCodes.isEmpty if showLicenseName { licenseLabel.text = searchResult.imageInfo?.license?.shortDescription } else { licenseLabel.isHidden = true } updateFonts() setNeedsLayout() self.keepBackgroundClear = keepBackgroundClear apply(theme: theme) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { titleLabel.font = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection) descriptionLabel.font = UIFont.wmf_font(.footnote, compatibleWithTraitCollection: traitCollection) licenseLabel.font = UIFont.wmf_font(.semiboldCaption2, compatibleWithTraitCollection: traitCollection) } @IBAction private func showMoreInformation(_ sender: Any) { guard let url = moreInformationURL else { assertionFailure("moreInformationURL should be set by now") return } moreInformationAction?(url) } } extension InsertMediaImageInfoView: Themeable { func apply(theme: Theme) { backgroundColor = keepBackgroundClear ? .clear : theme.colors.paperBackground titleLabel.textColor = theme.colors.primaryText descriptionLabel.textColor = theme.colors.primaryText licenseLabel.textColor = theme.colors.primaryText moreInformationButton.tintColor = theme.colors.link moreInformationButton.backgroundColor = backgroundColor licenseView.tintColor = theme.colors.primaryText } }
mit
7d68deaa28d897c0bcd071faae87869b
41.094595
218
0.710754
5.768519
false
false
false
false
P0ed/FireTek
Source/Scenes/Space/HUD/HUDWeaponNode.swift
1
1407
import SpriteKit final class WeaponNode: SKNode { static let cooldownSize = CGSize(width: 32, height: 8) let cooldownNode: CooldownNode let roundsLabel: SKLabelNode override init() { cooldownNode = CooldownNode() roundsLabel = SKLabelNode() roundsLabel.horizontalAlignmentMode = .right roundsLabel.verticalAlignmentMode = .center roundsLabel.fontSize = 6 roundsLabel.fontName = "Menlo" super.init() [cooldownNode, roundsLabel].forEach(addChild) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func layout(size: CGSize) { cooldownNode.position = CGPoint( x: size.width - WeaponNode.cooldownSize.width, y: (size.height - WeaponNode.cooldownSize.height) / 2 ) roundsLabel.position = CGPoint( x: size.width - WeaponNode.cooldownSize.width - 2, y: size.height / 2 ) } } final class CooldownNode: SKNode { let background: SKSpriteNode let progress: SKSpriteNode override init() { background = SKSpriteNode(color: SKColor(white: 0.5, alpha: 0.5), size: WeaponNode.cooldownSize) progress = SKSpriteNode(color: SKColor(white: 0.9, alpha: 0.9), size: WeaponNode.cooldownSize) background.anchorPoint = .zero progress.anchorPoint = .zero super.init() [background, progress].forEach(addChild) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
e2ff6617976d839935018fb74f3031bc
24.581818
98
0.730633
3.654545
false
false
false
false
IvanVorobei/Sparrow
sparrow/modules/request-permissions/managers/presenters/universal/controls/SPRequestPermissionTwiceControl.swift
1
8016
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei (hello@ivanvorobei.by) // // 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 SPRequestPermissionTwiceControl: UIButton, SPRequestPermissionTwiceControlInterface { var permission: SPRequestPermissionType var iconView: SPRequestPermissionIconView! var normalColor: UIColor var selectedColor: UIColor init(permissionType: SPRequestPermissionType, title: String, normalIconImage: UIImage, selectedIconImage: UIImage, normalColor: UIColor, selectedColor: UIColor) { self.permission = permissionType let renderingNormalIconImage = normalIconImage.withRenderingMode(.alwaysTemplate) let renderingSelectedIconImage = selectedIconImage.withRenderingMode(.alwaysTemplate) self.iconView = SPRequestPermissionIconView(iconImage: renderingNormalIconImage, selectedIconImage: renderingSelectedIconImage) self.normalColor = normalColor self.selectedColor = selectedColor super.init(frame: CGRect.zero) self.setTitle(title, for: UIControlState.normal) self.commonInit() //self.iconView.backgroundColor = UIColor.red } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { self.layer.borderWidth = 1 self.addSubview(self.iconView) self.titleLabel?.font = UIFont.init(name: SPRequestPermissionData.fonts.base() + "-Medium", size: 14) if UIScreen.main.bounds.width < 335 { self.titleLabel?.font = UIFont.init(name: SPRequestPermissionData.fonts.base() + "-Medium", size: 12) } self.titleLabel?.minimumScaleFactor = 0.5 self.titleLabel?.adjustsFontSizeToFitWidth = true self.setNormalState(animated: false) } func setNormalState(animated: Bool) { self.layer.borderColor = self.selectedColor.cgColor self.backgroundColor = self.normalColor self.setTitleColor(self.selectedColor, for: UIControlState.normal) self.iconView.setColor(self.selectedColor) self.iconView.setIconImageView(self.iconView.iconImage!) self.setTitleColor(self.selectedColor.withAlphaComponent(0.62), for: UIControlState.highlighted) } func setSelectedState(animated: Bool) { self.layer.borderColor = self.normalColor.cgColor if animated{ UIView.animate(withDuration: 0.4, animations: { self.backgroundColor = self.selectedColor }) } else { self.backgroundColor = self.selectedColor } var colorForTitle = self.normalColor if self.normalColor == UIColor.clear { colorForTitle = UIColor.white } self.setTitleColor(colorForTitle, for: UIControlState.normal) self.setTitleColor(colorForTitle.withAlphaComponent(0.62), for: UIControlState.highlighted) self.iconView.setSelectedState(with: self.normalColor) } internal func addAction(_ target: Any?, action: Selector) { self.addTarget(target, action: action, for: UIControlEvents.touchUpInside) } internal func addAsSubviewTo(_ view: UIView) { view.addSubview(self) } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.height / 2 let sideSize: CGFloat = self.frame.height * 0.45 let xTranslationIconView: CGFloat = self.frame.width * 0.075 iconView.frame = CGRect.init( x: xTranslationIconView, y: (self.frame.height - sideSize) / 2, width: sideSize, height: sideSize ) } } class SPRequestPermissionIconView: UIView { var imageView: UIImageView? var iconImage: UIImage? var selectedIconImage: UIImage? init(iconImage: UIImage, selectedIconImage: UIImage) { super.init(frame: CGRect.zero) self.imageView = UIImageView() self.imageView?.contentMode = .scaleAspectFit self.addSubview(imageView!) self.iconImage = iconImage self.selectedIconImage = selectedIconImage self.setIconImageView(self.iconImage!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setSelectedState(with color: UIColor = .white) { var settingColor = color if settingColor == UIColor.clear { settingColor = UIColor.white } self.setColor(settingColor) self.imageView?.layer.shadowRadius = 0 self.imageView?.layer.shadowOffset = CGSize.init(width: 0, height: 1) let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation") rotationAnimation.fromValue = 0.0 rotationAnimation.toValue = Double.pi * 2 rotationAnimation.duration = 0.18 rotationAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut) self.imageView?.layer.shouldRasterize = true self.imageView?.layer.rasterizationScale = UIScreen.main.scale self.imageView?.layer.add(rotationAnimation, forKey: nil) var blurView = UIView() if #available(iOS 9, *) { blurView = SPBlurView() } blurView.backgroundColor = UIColor.clear self.addSubview(blurView) blurView.frame = CGRect.init(x: 0, y: 0, width: self.frame.height, height: self.frame.height) blurView.center = (self.imageView?.center)! SPAnimation.animate(0.1, animations: { if #available(iOS 9, *) { if let view = blurView as? SPBlurView { view.setBlurRadius(1.2) } } }, options: UIViewAnimationOptions.curveEaseIn, withComplection: { SPAnimation.animate(0.1, animations: { if #available(iOS 9, *) { if let view = blurView as? SPBlurView { view.setBlurRadius(0) } } }, options: UIViewAnimationOptions.curveEaseOut, withComplection: { blurView.removeFromSuperview() }) }) delay(0.05, closure: { self.setIconImageView(self.selectedIconImage!) }) } func setColor(_ color: UIColor) { UIView.transition(with: self.imageView!, duration: 0.2, options: UIViewAnimationOptions.beginFromCurrentState, animations: { self.imageView?.tintColor = color }, completion: nil) } func setIconImageView(_ iconImageView: UIImage) { self.imageView?.image = iconImageView } override func layoutSubviews() { super.layoutSubviews() self.imageView?.frame = self.bounds } }
mit
ff5f13644c45c868411cfb274408685c
38.875622
166
0.656893
5.034548
false
false
false
false
hyperoslo/CollectionAnimations
Demo/Demo/ViewController.swift
1
3933
import UIKit class ViewController: UIViewController { var data1 = ["First 1", "First 2"] var data2 = ["Second 1", "Second 2"] var items = [String]() lazy var collectionView: UICollectionView = { [unowned self] in var frame = self.view.bounds frame.origin.y += 20 var collectionView = UICollectionView(frame: frame, collectionViewLayout: self.flowLayout) collectionView.delegate = self collectionView.dataSource = self collectionView.bounces = true collectionView.alwaysBounceVertical = true collectionView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth collectionView.backgroundColor = .lightTextColor() collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CellIdentifier") return collectionView }() lazy var flowLayout: CollectionViewFlowLayout = { var layout = CollectionViewFlowLayout() layout.sectionInset = UIEdgeInsetsMake(2.0, 2.0, 2.0, 2.0) return layout }() lazy var rightButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem( title: "Next", style: .Plain, target: self, action: "next") return button }() lazy var leftButton: UIBarButtonItem = { [unowned self] in let button = UIBarButtonItem( title: "Prev", style: .Plain, target: self, action: "prev") return button }() override func viewDidLoad() { super.viewDidLoad() title = "Items" navigationItem.leftBarButtonItem = self.leftButton navigationItem.leftBarButtonItem?.enabled = false navigationItem.rightBarButtonItem = self.rightButton navigationController?.hidesBarsWhenVerticallyCompact = true items = data1 view.addSubview(self.collectionView) } func prev() { items = data1 flowLayout.animator = FlyAnimator(appearingFrom: .Top, disappearingTo: .Back) reloadData(completion: { [unowned self] in self.navigationItem.leftBarButtonItem?.enabled = false self.navigationItem.rightBarButtonItem?.enabled = true }) } func next() { items = data2 flowLayout.animator = FlyAnimator(appearingFrom: .Back, disappearingTo: .Top) reloadData(completion: { [unowned self] in self.navigationItem.leftBarButtonItem?.enabled = true self.navigationItem.rightBarButtonItem?.enabled = false }) } private func reloadData(completion: (() -> Void)? = nil) { let indexPaths = [ NSIndexPath(forItem: 0, inSection: 0), NSIndexPath(forItem: 1, inSection: 0)] UIView.animateWithDuration(0.8, animations: { _ in self.collectionView.performBatchUpdates({ _ in self.collectionView.reloadItemsAtIndexPaths(indexPaths) }, completion: nil) }, completion: { _ in completion?() }) } } extension ViewController : UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ return self.items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) as! CollectionViewCell cell.setText(self.items[indexPath.row]) cell.layer.borderWidth = 0.5 cell.layer.borderColor = UIColor.lightGrayColor().CGColor cell.layer.cornerRadius = 4 cell.backgroundColor = UIColor.whiteColor() return cell } } extension ViewController : UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let width:CGFloat = self.view.bounds.size.width * 0.98 let height:CGFloat = 150.0 return CGSizeMake(width, height) } }
mit
5610f981d1c67cdfe6ffb50860cd5543
29.253846
128
0.709382
5.068299
false
false
false
false
machelix/MVCarouselCollectionView
MVCarouselCollectionView/MVCarouselCellScrollView.swift
1
4098
// MVCarouselCellScrollView.swift // // Copyright (c) 2015 Andrea Bizzotto (bizz84@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // Image loader closure type public typealias MVImageLoaderClosure = ((imageView: UIImageView, imagePath : String, completion: (newImage: Bool) -> ()) -> ()) class MVCarouselCellScrollView: UIScrollView, UIScrollViewDelegate { let MaximumZoom = 4.0 var cellSize : CGSize = CGSizeZero var maximumZoom = 0.0 var imagePath : String = "" { didSet { assert(self.imageLoader != nil, "Image loader must be specified") self.imageLoader?(imageView : self.imageView, imagePath: imagePath, completion: { (newImage) in self.resetZoom() }) } } var imageLoader: MVImageLoaderClosure? @IBOutlet weak private var imageView : UIImageView! override func awakeFromNib() { super.awakeFromNib() self.delegate = self self.imageView.contentMode = UIViewContentMode.ScaleAspectFit } func resetZoom() { if self.imageView.image == nil { return } var imageSize = self.imageView.image!.size // nothing to do if image is not set if CGSizeEqualToSize(imageSize, CGSizeZero) { return } // Stack overflow people suggest this, not sure if it applies to us self.imageView.contentMode = UIViewContentMode.Center if cellSize.width > imageSize.width && cellSize.height > imageSize.height { self.imageView.contentMode = UIViewContentMode.ScaleAspectFit } var cellAspectRatio : CGFloat = self.cellSize.width / self.cellSize.height var imageAspectRatio : CGFloat = imageSize.width / imageSize.height var cellAspectRatioWiderThanImage = cellAspectRatio > imageAspectRatio // Calculate Zoom // If image is taller, then make edge to edge height, else make edge to edge width var zoom = cellAspectRatioWiderThanImage ? cellSize.height / imageSize.height : cellSize.width / imageSize.width self.maximumZoomScale = zoom * CGFloat(zoomToUse()) self.minimumZoomScale = zoom self.zoomScale = zoom // Update content inset var adjustedContentWidth = cellSize.height * imageAspectRatio var horzContentInset = cellAspectRatioWiderThanImage ? 0.5 * (cellSize.width - adjustedContentWidth) : 0.0 var adjustedContentHeight = cellSize.width / imageAspectRatio var vertContentInset = !cellAspectRatioWiderThanImage ? 0.5 * (cellSize.height - adjustedContentHeight) : 0.0 self.contentInset = UIEdgeInsetsMake(vertContentInset, horzContentInset, vertContentInset, horzContentInset) } func zoomToUse() -> Double { return maximumZoom < 1.0 ? MaximumZoom : maximumZoom } func viewForZoomingInScrollView(scrollView : UIScrollView) -> UIView? { return self.imageView } }
mit
f3a0dbe7bb1a7f8c458102d2d72eac2b
40.393939
128
0.68448
5.207116
false
false
false
false
remlostime/OOD-Swift
factory/Factory.playground/Contents.swift
1
1497
//: Playground - noun: a place where people can play import Foundation protocol Currency { func symbol() -> String func code() -> String } class US: Currency { func symbol() -> String { return "$" } func code() -> String { return "USD" } } class Euro: Currency { func symbol() -> String { return "€" } func code() -> String { return "EUR" } } class China: Currency { func symbol() -> String { return "¥" } func code() -> String { return "CNY" } } class ErrorCurrency: Currency { func symbol() -> String { return "Error symbol" } func code() -> String { return "Error code" } } enum Country { case USA case China case Euro } class CurrencyFactory { static func getCurrency(_ country: Country) -> Currency { switch country { case .USA: return US() case .China: return China() case .Euro: return Euro() } } } let currency = CurrencyFactory.getCurrency(.China) currency.code() currency.symbol() // Reflection - Get class dynamiclly func classFromString(_ className: String) -> Currency { guard let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else { return ErrorCurrency() } guard let cls = NSClassFromString("\(namespace).\(className)") as? Currency else { return ErrorCurrency() } return cls } let className = "US" let currencyClass = classFromString(className) currencyClass.code() currencyClass.symbol()
gpl-3.0
544cbf873ec443aea712b7c718fd3fa9
15.23913
91
0.631191
3.92126
false
false
false
false
Venkat1128/ObjCProblemSet
Examples/Lesson 6/House_Swift_main/House_Swift_main/House.swift
1
494
// // House.swift // House_main_Swift // // Created by Gabrielle Miller-Messner on 5/9/16. // Copyright © 2016 Gabrielle Miller-Messner. All rights reserved. // import Foundation class House { var address = "555 Park Ave" let numberOfBedrooms = 3 var hasHotTub = false var hotTub: HotTub? init(address: String) { self.address = address self.hasHotTub = false } init() { self.hasHotTub = true self.hotTub = HotTub() } }
mit
95488492c2b2ce6acb1386d3e2d4e7f1
16.607143
67
0.610548
3.572464
false
false
false
false