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
brentsimmons/Evergreen
iOS/Settings/TimelineCustomizerViewController.swift
1
2548
// // TimelineCustomizerViewController.swift // NetNewsWire-iOS // // Created by Maurice Parker on 11/8/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit class TimelineCustomizerViewController: UIViewController { @IBOutlet weak var iconSizeSliderContainerView: UIView! @IBOutlet weak var iconSizeSlider: TickMarkSlider! @IBOutlet weak var numberOfLinesSliderContainerView: UIView! @IBOutlet weak var numberOfLinesSlider: TickMarkSlider! @IBOutlet weak var previewWidthConstraint: NSLayoutConstraint! @IBOutlet weak var previewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var previewContainerView: UIView! var previewController: TimelinePreviewTableViewController { return children.first as! TimelinePreviewTableViewController } override func viewDidLoad() { super.viewDidLoad() iconSizeSliderContainerView.layer.cornerRadius = 10 iconSizeSlider.value = Float(AppDefaults.shared.timelineIconSize.rawValue) iconSizeSlider.addTickMarks() numberOfLinesSliderContainerView.layer.cornerRadius = 10 numberOfLinesSlider.value = Float(AppDefaults.shared.timelineNumberOfLines) numberOfLinesSlider.addTickMarks() } override func viewWillAppear(_ animated: Bool) { super.viewDidAppear(animated) updatePreviewBorder() updatePreview() } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { updatePreviewBorder() updatePreview() } @IBAction func iconSizeChanged(_ sender: Any) { guard let iconSize = IconSize(rawValue: Int(iconSizeSlider.value.rounded())) else { return } AppDefaults.shared.timelineIconSize = iconSize updatePreview() } @IBAction func numberOfLinesChanged(_ sender: Any) { AppDefaults.shared.timelineNumberOfLines = Int(numberOfLinesSlider.value.rounded()) updatePreview() } } // MARK: Private private extension TimelineCustomizerViewController { func updatePreview() { let previewWidth: CGFloat = { if traitCollection.userInterfaceIdiom == .phone { return view.bounds.width } else { return view.bounds.width / 1.5 } }() previewWidthConstraint.constant = previewWidth previewHeightConstraint.constant = previewController.heightFor(width: previewWidth) previewController.reload() } func updatePreviewBorder() { if traitCollection.userInterfaceStyle == .dark { previewContainerView.layer.borderColor = UIColor.black.cgColor previewContainerView.layer.borderWidth = 1 } else { previewContainerView.layer.borderWidth = 0 } } }
mit
7ec3833b9b7957f1f90582970bc649af
27.3
94
0.776993
4.437282
false
false
false
false
iOS-Connect/parse-twitter-with-push
Parse-Twitter/Parse-Twitter/PostViewController.swift
1
1034
import UIKit import Parse import ParseUI class PostViewController: UIViewController { @IBOutlet weak var messageField: UITextField! @IBAction func postButton(_ sender: Any) { print("Message: \(messageField.text)") let postObject = PFObject(className:"Posts") postObject["message"] = messageField.text! postObject["userId"] = PFUser.current()?.objectId postObject["username"] = PFUser.current()?.username postObject["email"] = PFUser.current()?.email postObject["likes"] = [String]() postObject["deviceToken"] = PFUser.current()?["deviceToken"] ?? "" //likes postObject.saveInBackground { (success, error) in if (success) { print("succeed") UIApplication.shared.appDelegate.appController.postSucceed(self) } else { print("failed") } } } @IBAction func cancel(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } }
mit
0eb42bba74bb21d5ea60911d7ae76cb8
31.3125
80
0.60058
5.019417
false
false
false
false
EasySwift/EasySwift
EasySwift_iOS/Core/EZExtend+UIFont.swift
2
2339
// // EZExtend+UIFont.swift // medical // // Created by zhuchao on 15/4/28. // Copyright (c) 2015年 zhuchao. All rights reserved. // import UIKit // MARK: - UIFont extension UIFont { public enum FontType: String { case Regular = "Regular" case Bold = "Bold" case Light = "Light" case UltraLight = "UltraLight" case Italic = "Italic" case Thin = "Thin" case Book = "Book" case Roman = "Roman" case Medium = "Medium" case MediumItalic = "MediumItalic" case CondensedMedium = "CondensedMedium" case CondensedExtraBold = "CondensedExtraBold" case SemiBold = "SemiBold" case BoldItalic = "BoldItalic" case Heavy = "Heavy" } public enum FontName: String { case HelveticaNeue = "HelveticaNeue" case Helvetica = "Helvetica" case Futura = "Futura" case Menlo = "Menlo" case Avenir = "Avenir" case AvenirNext = "AvenirNext" case Didot = "Didot" case AmericanTypewriter = "AmericanTypewriter" case Baskerville = "Baskerville" case Geneva = "Geneva" case GillSans = "GillSans" case SanFranciscoDisplay = "SanFranciscoDisplay" case Seravek = "Seravek" } public class func PrintFontFamily (_ font: FontName) { let arr = UIFont.fontNames(forFamilyName: font.rawValue) for name in arr { print(name) } } public class func Font (_ str:String) -> UIFont? { var array = str.trimArray if array.count >= 2{ let font = array[1] as String if font == "system" { return UIFont.systemFont(ofSize: array[0].floatValue) }else{ return UIFont(name: array[1], size: array[0].floatValue) } }else if array.count == 1{ return UIFont.systemFont(ofSize: array[0].floatValue) } return nil } public class func Font (_ name: FontName, type: FontType, size: CGFloat) -> UIFont { return UIFont (name: name.rawValue + "-" + type.rawValue, size: size)! } public class func HelveticaNeue (_ type: FontType, size: CGFloat) -> UIFont { return Font(.HelveticaNeue, type: type, size: size) } }
apache-2.0
9e17af9dd8f354c9b7bb41e9239a036c
29.350649
88
0.573813
4.368224
false
false
false
false
i-schuetz/SwiftCharts
Examples/Examples/CoordsExample.swift
1
7104
// // CoordsExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class CoordsExample: UIViewController { fileprivate var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints = [(2, 2), (3, 1), (5, 9), (6, 7), (8, 10), (9, 9), (10, 15), (13, 8), (15, 20), (16, 17)].map{ChartPoint(x: ChartAxisValueInt($0.0), y: ChartAxisValueInt($0.1))} let xValues = ChartAxisValuesStaticGenerator.generateXAxisValuesWithChartPoints(chartPoints, minSegmentCount: 7, maxSegmentCount: 7, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let yValues = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: true) let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(view.bounds) var chartSettings = ExamplesDefaults.chartSettings // for now no zooming and panning here until ChartShowCoordsLinesLayer is improved to not scale the lines during zooming. chartSettings.trailing = 20 chartSettings.labelsToAxisSpacingX = 15 chartSettings.labelsToAxisSpacingY = 15 let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) let labelWidth: CGFloat = 70 let labelHeight: CGFloat = 30 let showCoordsTextViewsGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) let text = chartPoint.description let font = ExamplesDefaults.labelFont let x = min(screenLoc.x + 5, chart.bounds.width - text.width(font) - 5) let view = UIView(frame: CGRect(x: x, y: screenLoc.y - labelHeight, width: labelWidth, height: labelHeight)) let label = UILabel(frame: view.bounds) label.text = text label.font = ExamplesDefaults.labelFont view.addSubview(label) view.alpha = 0 UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: { view.alpha = 1 }, completion: nil) return view } let showCoordsLinesLayer = ChartShowCoordsLinesLayer<ChartPoint>(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints) let showCoordsTextLayer = ChartPointsSingleViewLayer<ChartPoint, UIView>(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: showCoordsTextViewsGenerator, mode: .custom, keepOnFront: true) // To preserve the offset of the notification views from the chart point they represent, during transforms, we need to pass mode: .custom along with this custom transformer. showCoordsTextLayer.customTransformer = {(model, view, layer) -> Void in guard let chart = layer.chart else {return} let text = model.chartPoint.description let screenLoc = layer.modelLocToScreenLoc(x: model.chartPoint.x.scalar, y: model.chartPoint.y.scalar) let x = min(screenLoc.x + 5, chart.bounds.width - text.width(ExamplesDefaults.labelFont) - 5) view.frame.origin = CGPoint(x: x, y: screenLoc.y - labelHeight) } let touchViewsGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) let s: CGFloat = 30 let view = HandlingView(frame: CGRect(x: screenLoc.x - s/2, y: screenLoc.y - s/2, width: s, height: s)) view.touchHandler = {[weak showCoordsLinesLayer, weak showCoordsTextLayer, weak chartPoint, weak chart] in guard let chartPoint = chartPoint, let chart = chart else {return} showCoordsLinesLayer?.showChartPointLines(chartPoint, chart: chart) showCoordsTextLayer?.showView(chartPoint: chartPoint, chart: chart) } return view } let touchLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: touchViewsGenerator, mode: .translate, keepOnFront: true) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor(red: 0.4, green: 0.4, blue: 1, alpha: 0.2), lineWidth: 3, animDuration: 0.7, animDelay: 0) let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModel]) let circleViewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let circleView = ChartPointEllipseView(center: chartPointModel.screenLoc, diameter: 24) circleView.animDuration = 1.5 circleView.fillColor = UIColor.white circleView.borderWidth = 5 circleView.borderColor = UIColor.blue return circleView } let chartPointsCircleLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: circleViewGenerator, displayDelay: 0, delayBetweenItems: 0.05, mode: .translate) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: settings) let chart = Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, showCoordsLinesLayer, chartPointsLineLayer, chartPointsCircleLayer, showCoordsTextLayer, touchLayer, ] ) view.addSubview(chart.view) self.chart = chart } }
apache-2.0
17ca25c201bdc9b98603ae2275ef6ff7
54.937008
264
0.669904
5.266123
false
false
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/HTHamburgerMenuTableViewController.swift
1
2997
// // HTHamburgerMenuTableViewController.swift // hackertracker // // Created by Christopher Mays on 7/28/18. // Copyright © 2018 Beezle Labs. All rights reserved. // import UIKit protocol HTHamburgerMenuTableViewControllerDelegate: AnyObject { func didSelectItem(item: HamburgerItem) } class HTHamburgerMenuTableViewController: UITableViewController { weak var delegate: HTHamburgerMenuTableViewControllerDelegate? let items: [HamburgerItem] var selectedItem: HamburgerItem? var conferenceName: String? init(hamburgerItems: [HamburgerItem]) { items = hamburgerItems super.init(style: UITableView.Style.plain) tableView.estimatedRowHeight = 254 tableView.register(UINib(nibName: "HTHamburgerHeaderTableViewCell", bundle: nil), forCellReuseIdentifier: "Header") tableView.register(UINib(nibName: "HTHamburgerItemTableViewCell", bundle: nil), forCellReuseIdentifier: "ItemCell") } func setSelectedItem(hamburgerItem: HamburgerItem) { selectedItem = hamburgerItem guard let index = items.firstIndex(where: { item -> Bool in return item == hamburgerItem }) else { return } tableView.selectRow(at: IndexPath(row: index + 1, section: 0), animated: false, scrollPosition: .none) } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.black } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let selectedItem = selectedItem { setSelectedItem(hamburgerItem: selectedItem) } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "Header") as! HTHamburgerHeaderTableViewCell return cell } else { let currentItem = items[indexPath.row - 1] let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as! HTHamburgerItemTableViewCell cell.titleText = currentItem.title // cell.iconImage = UIImage(named: currentItem.imageID) if let img = UIImage(systemName: currentItem.imageID) { cell.iconImage = img } else { cell.iconImage = UIImage(named: currentItem.imageID) } return cell } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count + 1 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { return } delegate?.didSelectItem(item: items[indexPath.row - 1]) } }
gpl-2.0
e9a09ddd97173c7b2d0d11e0d344dc86
33.045455
123
0.662216
5.165517
false
false
false
false
jhurray/SQLiteModel-Example-Project
iOS+SQLiteModel/Blogz4Dayz/ImageCollectionDelegate.swift
1
2461
// // ImageCollectionDelegate.swift // Blogz4Dayz // // Created by Jeff Hurray on 4/9/16. // Copyright © 2016 jhurray. All rights reserved. // import Foundation import UIKit import SQLiteModel import SQLite import NYTPhotoViewer class ImageCollectionDelegate : NSObject, ImageCollectionViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { weak var navController: UINavigationController? var blog: BlogModel? init(navController: UINavigationController?, blog: BlogModel? = nil) { self.navController = navController self.blog = blog } // MARK: ImageCollectionViewDelegate func imageCollectionViewDidTouchImage(image: NYTPhoto, fromImages: [NYTPhoto]) { let viewer = NYTPhotosViewController(photos: fromImages, initialPhoto: image) self.navController?.presentViewController(viewer, animated: true, completion: nil) } func imageCollectionViewWantsToAddImage() { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.allowsEditing = false navController!.presentViewController(imagePicker, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { let data: NSData = UIImageJPEGRepresentation(image, 0.1)! if let model = self.blog { var images: [ImageModel] = model => BlogModel.Images ImageModel.newInBackground([ImageModel.Data <- data], completion: { (newImage, error) -> Void in guard error == nil else { return } images.append(newImage!) model.setInBackground(BlogModel.Images, value: images, completion: { picker.dismissViewControllerAnimated(true, completion: nil) }) }) } else { ImageModel.newInBackground([ImageModel.Data <- data], completion: { (newImage, error) -> Void in picker.dismissViewControllerAnimated(true, completion: nil) }) } } @objc func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil) } }
mit
97256e4b90dcd86fab87cf5d90169731
35.716418
139
0.664634
5.515695
false
false
false
false
wordpress-mobile/WordPress-Shared-iOS
WordPressShared/Core/Logging/CocoaLumberjack.swift
1
5486
import Foundation import CocoaLumberjack // June 14 2017 - @astralbodies // Taken from CocoaLumberjack repository - reproduced to prevent issue with // CocoaPods and some weird bug with frameworks // Software License Agreement (BSD License) // // Copyright (c) 2014-2016, Deusty, LLC // All rights reserved. // // Redistribution and use of this software in source and binary forms, // with or without modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Neither the name of Deusty nor the names of its contributors may be used // to endorse or promote products derived from this software without specific // prior written permission of Deusty, LLC. import Foundation extension DDLogFlag { public static func from(_ logLevel: DDLogLevel) -> DDLogFlag { return DDLogFlag(rawValue: logLevel.rawValue) } public init(_ logLevel: DDLogLevel) { self = DDLogFlag(rawValue: logLevel.rawValue) } ///returns the log level, or the lowest equivalant. public func toLogLevel() -> DDLogLevel { if let ourValid = DDLogLevel(rawValue: rawValue) { return ourValid } else { if contains(.verbose) { return .verbose } else if contains(.debug) { return .debug } else if contains(.info) { return .info } else if contains(.warning) { return .warning } else if contains(.error) { return .error } else { return .off } } } } public var defaultDebugLevel = DDLogLevel.verbose public func resetDefaultDebugLevel() { defaultDebugLevel = DDLogLevel.verbose } public func _DDLogMessage(_ message: @autoclosure () -> String, level: DDLogLevel, flag: DDLogFlag, context: Int, file: StaticString, function: StaticString, line: UInt, tag: Any?, asynchronous: Bool, ddlog: DDLog) { if level.rawValue & flag.rawValue != 0 { // Tell the DDLogMessage constructor to copy the C strings that get passed to it. let logMessage = DDLogMessage(message: message(), level: level, flag: flag, context: context, file: String(describing: file), function: String(describing: function), line: line, tag: tag, options: [.copyFile, .copyFunction], timestamp: nil) ddlog.log(asynchronous: asynchronous, message: logMessage) } } public func DDLogDebug(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { _DDLogMessage(message(), level: level, flag: .debug, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) } public func DDLogInfo(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { _DDLogMessage(message(), level: level, flag: .info, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) } public func DDLogWarn(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { _DDLogMessage(message(), level: level, flag: .warning, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) } public func DDLogVerbose(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = true, ddlog: DDLog = DDLog.sharedInstance) { _DDLogMessage(message(), level: level, flag: .verbose, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) } public func DDLogError(_ message: @autoclosure () -> String, level: DDLogLevel = defaultDebugLevel, context: Int = 0, file: StaticString = #file, function: StaticString = #function, line: UInt = #line, tag: Any? = nil, asynchronous async: Bool = false, ddlog: DDLog = DDLog.sharedInstance) { _DDLogMessage(message(), level: level, flag: .error, context: context, file: file, function: function, line: line, tag: tag, asynchronous: async, ddlog: ddlog) } /// Returns a String of the current filename, without full path or extension. /// /// Analogous to the C preprocessor macro `THIS_FILE`. public func CurrentFileName(_ fileName: StaticString = #file) -> String { var str = String(describing: fileName) if let idx = str.range(of: "/", options: .backwards)?.upperBound { #if swift(>=4.0) str = String(str[idx...]) #else str = str.substring(from: idx) #endif } if let idx = str.range(of: ".", options: .backwards)?.lowerBound { #if swift(>=4.0) str = String(str.prefix(upTo: idx)) #else str = str.substring(to: idx) #endif } return str }
gpl-2.0
48180f3a171c531370ec1ed6fb1973a3
48.423423
292
0.681006
4.233025
false
false
false
false
BananosTeam/CreativeLab
Assistant/View/SideMenuTable/SideMenuViewController.swift
1
5002
// // SideMenuTableViewController.swift // Assistant // // Created by Bananos on 5/15/16. // Copyright © 2016 Bananos. All rights reserved. // import UIKit final class SideMenuViewController: UIViewController, StoryboardInstantiable, ENSideMenuDelegate, UITableViewDelegate, SRMDelegate, SRMRetriever { static let ControllerIdentifier = "SideMenuViewController" @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var teamNameLabel: UILabel! @IBOutlet weak var channelsTableView: ChannelsTableView! @IBOutlet weak var usersTableView: UsersTableView! @IBOutlet weak var fetchingUsersActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var fetchingChannelsActivityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() channelsTableView.delegate = self usersTableView.delegate = self channelsTableView.dataSource = channelsTableView usersTableView.dataSource = usersTableView SlackClient.currentClient?.delegate = self SlackClient.currentClient?.dataRetriever = self } // MARK: ENSideMenuDelegate func sideMenuShouldOpenSideMenu () -> Bool { return true } func sideMenuWillOpen() { if channelsTableView.indexPathForSelectedRow == nil && usersTableView.indexPathForSelectedRow == nil { channelsTableView.selectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: false, scrollPosition: .None) } guard let messagesVC = (sideMenuController() as? NavigationController)?.childViewControllers.first as? MessagesViewController else { return } messagesVC.typeMessageTextView.resignFirstResponder() } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView === usersTableView { channelsTableView.deselectSelectedChannel() handleUserSelectionAtIndex(indexPath.row) } else if tableView === channelsTableView { usersTableView.deselectSelectedUser() handleChannelSelectionAtIndex(indexPath.row) } ((sideMenuController() as? NavigationController)?.childViewControllers.first as? MessagesViewController)?.messagesTableView.reloadData() sideMenuController()?.sideMenu?.hideSideMenu() } private func handleUserSelectionAtIndex(index: Int) { guard let messagesVC = (sideMenuController() as? NavigationController)?.childViewControllers.first as? MessagesViewController else { return } messagesVC.currentOpenChannel = nil messagesVC.currentOpenChannelWithUser = DataPersistor.sharedPersistor.users[index] } private func handleChannelSelectionAtIndex(index: Int) { guard let messagesVC = (sideMenuController() as? NavigationController)?.childViewControllers.first as? MessagesViewController else { return } messagesVC.currentOpenChannel = DataPersistor.sharedPersistor.channels[index] messagesVC.currentOpenChannelWithUser = nil } // MARK: SRMDelegate func eventReceived(event: SlackEvent) { if case .Message(let message) = event { DataPersistor.sharedPersistor.addMessage(Message(slackMessage: message, messageType: .ToMe)) if let messagesVC = (sideMenuController() as? NavigationController)?.childViewControllers.first as? MessagesViewController { messagesVC.reloadLastMessage() } } } // MARK: SRMRetriever func setUsers(callback: [SlackUser]) { SlackClient.currentClient?.bot.slackUsers = callback DataPersistor.sharedPersistor.addUsers(callback) usersTableView.reloadData() let trello = TrelloInterface() trello.populateSlackUsersWIthTrelloMembers() fetchingUsersActivityIndicator.stopAnimating() } func setChannels(callback: [SlackChannel]) { DataPersistor.sharedPersistor.addChannels(callback) channelsTableView.reloadData() fetchingChannelsActivityIndicator.stopAnimating() } func setCurrentUser(callback: SlackUser?) { if let currentUser = callback { DataPersistor.sharedPersistor.setCurrentUser(currentUser) setCurrentUserName() } } func setTeam(callback: SlackTeam) { DataPersistor.sharedPersistor.setTeam(callback) setCurrentTeamName() } private func setCurrentUserName() { guard let currentUser = DataPersistor.sharedPersistor.currentUser else { return } usernameLabel.text = currentUser.slackName } private func setCurrentTeamName() { guard let currentTeam = DataPersistor.sharedPersistor.team else { return } teamNameLabel.text = currentTeam.name } }
mit
cabdfcc21fb9fd1918e1a3dc34b28a8f
38.377953
144
0.692661
5.989222
false
false
false
false
BrandonMA/SwifterUI
SwifterUI/SwifterUI/UILibrary/Views/SFButton.swift
1
4644
// // SFButton.swift // SwifterUI // // Created by brandon maldonado alonso on 06/02/18. // Copyright © 2018 Brandon Maldonado Alonso. All rights reserved. // import UIKit open class SFButton: UIButton, SFViewColorStyle, SFLayoutView { // MARK: - Instance Properties open var automaticallyAdjustsColorStyle: Bool = false open var useAlternativeColors: Bool = false open var setTextColor: Bool = true open var useAlternativeTextColor: Bool = false open var useClearBackground: Bool = false open var isTextPicker: Bool = false open var customConstraints: Constraints = [] public final var addTouchAnimations: Bool = false { didSet { if addTouchAnimations == true { addTarget(self, action: #selector(animateTouchDown(button:)), for: .touchDown) addTarget(self, action: #selector(touchUp(button:)), for: .touchUpInside) addTarget(self, action: #selector(touchUp(button:)), for: .touchDragExit) } else { removeTarget(self, action: #selector(animateTouchDown(button:)), for: .touchDown) removeTarget(self, action: #selector(touchUp(button:)), for: .touchUpInside) removeTarget(self, action: #selector(touchUp(button:)), for: .touchDragExit) } } } public final lazy var rightImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() public var touchUpInsideActions: [() -> Void] = [] public var touchDownActions: [() -> Void] = [] /** Easy way to set title for SFButton */ open var title: String? { get { return title(for: .normal) } set { return setTitle(newValue, for: .normal) } } // MARK: - Initializers public init(automaticallyAdjustsColorStyle: Bool = true, useAlternativeColors: Bool = false, frame: CGRect = .zero) { self.automaticallyAdjustsColorStyle = automaticallyAdjustsColorStyle self.useAlternativeColors = useAlternativeColors super.init(frame: frame) addTarget(self, action: #selector(touchUpInside), for: .touchUpInside) addTarget(self, action: #selector(touchDown), for: .touchDown) prepareSubviews() setConstraints() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Instance Methods public func prepareSubviews() { addSubview(rightImageView) if automaticallyAdjustsColorStyle { updateColors() } } public func setConstraints() { customConstraints.append(contentsOf: rightImageView.clipSides(exclude: [.left], margin: UIEdgeInsets(top: 12, left: 8, bottom: 12, right: 8), useSafeArea: false)) customConstraints.append(rightImageView.setWidth(SFDimension(value: 14))) } open func updateColors() { backgroundColor = isTextPicker ? colorStyle.contrastColor : useClearBackground ? .clear : useAlternativeColors ? colorStyle.mainColor : colorStyle.alternativeColor titleLabel?.backgroundColor = backgroundColor if setTextColor { if useAlternativeTextColor { tintColor = colorStyle.textColor setTitleColor(colorStyle.textColor, for: .normal) } else { tintColor = colorStyle.interactiveColor setTitleColor(colorStyle.interactiveColor, for: .normal) } } updateSubviewsColors() } @objc public final func animateTouchDown(button: UIButton) { titleLabel?.alpha = 0.7 } @objc public final func touchUp(button: UIButton) { UIView.animate(withDuration: 0.4) { self.titleLabel?.alpha = 1.0 button.transform = .identity } } public final func addTouchAction(for event: UIControl.Event = .touchUpInside, _ action: @escaping () -> Void) { switch event { case .touchUpInside: touchUpInsideActions.append(action) case .touchDown: touchDownActions.append(action) default: return } } @objc public final func touchUpInside() { touchUpInsideActions.forEach { $0() } } @objc public final func touchDown() { touchDownActions.forEach { $0() } } }
mit
f1be3b54d0344449eb6048c74ecd7cc5
32.164286
171
0.619642
5.246328
false
false
false
false
simonbs/Emcee
PlayersKit/Players/Player.swift
1
1113
// // Player.swift // NowScrobbling // // Created by Simon Støvring on 22/03/15. // Copyright (c) 2015 SimonBS. All rights reserved. // import Foundation public struct Track: Equatable { public let artistName: String public let trackName: String public let albumName: String public let artwork: NSImage? } public func ==(lhs: Track, rhs: Track) -> Bool { return lhs.artistName == rhs.artistName && lhs.trackName == rhs.trackName } public protocol PlayerDelegate { func playerDidChangeTrack(player: Player, track: Track) func playerDidPlay(player: Player) func playerDidPause(player: Player) func playerDidStop(player: Player) } public enum PlaybackState: String { case Playing = "Playing" case Paused = "Paused" case Stopped = "Stopped" } public protocol Player { static var bundleIdentifier: String { get } var playerBundleIdentifier: String { get } var delegate: PlayerDelegate? { get set } var isStarted: Bool { get } var currentTrack: Track? { get } var playbackState: PlaybackState { get } func start() func stop() }
mit
3c15627c9a25c638d37b8950be7c6372
24.272727
77
0.691547
4
false
false
false
false
pixelspark/catena
Sources/CatenaSQL/SQLTransaction.swift
1
6369
import Foundation import LoggerAPI import Ed25519 import CatenaCore public class SQLTransaction: Transaction, CustomDebugStringConvertible { public var hashValue: Int { return self.dataForSigning.hashValue } public static func ==(lhs: SQLTransaction, rhs: SQLTransaction) -> Bool { if let ls = lhs.signature, let rs = rhs.signature { return ls == rs } return lhs.counter == rhs.counter && lhs.invoker == rhs.invoker && lhs.dataForSigning == rhs.dataForSigning } public typealias CounterType = UInt64 public var invoker: CatenaCore.PublicKey public var database: SQLDatabase public var counter: CounterType public var statement: SQLStatement var signature: Data? = nil /** The maximum size of a transaction (as measured by `dataForSigning`) */ static let maximumSize = 1024 * 10 // 10 KiB enum SQLTransactionError: Error { case formatError case syntaxError } public init(statement: SQLStatement, invoker: CatenaCore.PublicKey, database: SQLDatabase, counter: CounterType = CounterType(0)) throws { self.invoker = invoker self.statement = statement self.counter = counter self.database = database } public required init(json: [String: Any]) throws { guard let tx = json["tx"] as? [String: Any] else { throw SQLTransactionError.formatError } guard let sql = tx["sql"] as? String else { throw SQLTransactionError.formatError } guard let database = tx["database"] as? String else { throw SQLTransactionError.formatError } guard let invoker = tx["invoker"] as? String else { throw SQLTransactionError.formatError } guard let counter = tx["counter"] as? Int else { throw SQLTransactionError.formatError } guard let invokerKey = PublicKey(string: invoker) else { throw SQLTransactionError.formatError } self.invoker = invokerKey self.statement = try SQLStatement(sql) self.counter = CounterType(counter) self.database = SQLDatabase(name: database) if let sig = json["signature"] as? String, let sigData = Data(base64Encoded: sig) { self.signature = sigData } } private var dataForSigning: Data { var d = Data() d.append(self.invoker.data) d.append(self.database.name.data(using: .utf8)!) d.appendRaw(self.counter.littleEndian) d.append(self.statement.sql(dialect: SQLStandardDialect()).data(using: .utf8)!) return d } @discardableResult public func sign(with privateKey: CatenaCore.PrivateKey) throws -> SQLTransaction { self.signature = try self.invoker.sign(data: self.dataForSigning, with: privateKey) return self } public var isSignatureValid: Bool { do { if let s = self.signature { let sd = self.dataForSigning // Check transaction size if sd.count > SQLTransaction.maximumSize { return false } return try self.invoker.verify(message: sd, signature: s) } return false } catch { return false } } public var json: [String: Any] { var json: [String: Any] = [ "tx": [ "sql": self.statement.sql(dialect: SQLStandardDialect()), "database": self.database.name, "counter": NSNumber(value: self.counter), "invoker": self.invoker.stringValue ] ] if let s = self.signature { json["signature"] = s.base64EncodedString() } return json } public var debugDescription: String { return "\(self.invoker.data.sha256.base64EncodedString())@\(self.counter)" } } fileprivate class SQLParameterVisitor: SQLVisitor { var parameters: [String: SQLExpression] = [:] func visit(expression: SQLExpression) throws -> SQLExpression { switch expression { case .unboundParameter(name: let s): self.parameters[s] = expression case .boundParameter(name: let s, value: let v): self.parameters[s] = v default: break } return expression } } fileprivate class SQLParameterBinder: SQLVisitor { let parameters: [String: SQLExpression] init(parameters: [String: SQLExpression]) { self.parameters = parameters } func visit(expression: SQLExpression) throws -> SQLExpression { switch expression { case .unboundParameter(name: let s): if let v = self.parameters[s] { return SQLExpression.boundParameter(name: s, value: v) } case .boundParameter(name: let s, value: _): if let v = self.parameters[s] { return .boundParameter(name: s, value: v) } default: break } return expression } } fileprivate class SQLParameterUnbinder: SQLVisitor { func visit(expression: SQLExpression) throws -> SQLExpression { switch expression { case .unboundParameter(name: _): return expression case .boundParameter(name: let s, value: _): return .unboundParameter(name: s) default: return expression } } } fileprivate class SQLVariableBinder: SQLVisitor { let variables: [String: SQLExpression] init(variables: [String: SQLExpression]) { self.variables = variables } func visit(expression: SQLExpression) throws -> SQLExpression { if case .variable(let s) = expression, let v = self.variables[s] { return v } return expression } } extension SQLStatement { /** All parameters present in this query. The value for an unbound parameter is an SQLExpression.unboundExpression. */ var parameters: [String: SQLExpression] { let v = SQLParameterVisitor() _ = try! self.visit(v) return v.parameters } /** Returns a version of this statement where all bound parameters are replaced with unbound ones (e.g. the values are removed). Unbound parameters in the original statement are left untouched. */ var unbound: SQLStatement { let b = SQLParameterUnbinder() return try! self.visit(b) } var templateHash: SHA256Hash { return SHA256Hash(of: self.unbound.sql(dialect: SQLStandardDialect()).data(using: .utf8)!) } /** Binds parameters in the query. Unbound parameters will be replaced with bound parameters if there is a corresponding value in the `parameters` dictionary. Bound parameters will have their values replaced with the values in the `parameter` dictionary. Bound and unbound parameters in the query remain unchanged if the `parameters` set does not have a new value for them. */ func bound(to parameters: [String: SQLExpression]) -> SQLStatement { let b = SQLParameterBinder(parameters: parameters) return try! self.visit(b) } func replacing(variables: [String: SQLExpression]) -> SQLStatement { let b = SQLVariableBinder(variables: variables) return try! self.visit(b) } }
mit
efe191d22c6cec1b66a26610281b6f50
27.306667
139
0.722562
3.718039
false
false
false
false
wrideout/SwiftRoller
SwiftRoller/ViewController.swift
1
2461
// // ViewController.swift // SwiftRoller // // Created by William Rideout on 12/21/15. // Copyright © 2015 William Rideout. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var resultField: NSTextField! @IBOutlet weak var d4Count: NSTextField! @IBOutlet weak var d6Count: NSTextField! @IBOutlet weak var d8Count: NSTextField! @IBOutlet weak var d10Count: NSTextField! @IBOutlet weak var dPerCount: NSTextField! @IBOutlet weak var d12Count: NSTextField! @IBOutlet weak var d20Count: NSTextField! @IBOutlet weak var modifier: NSTextField! @IBAction func rollButton(sender: AnyObject) { //let result : Int = 57 //let result = convertToInt(modifier.stringValue) let result = rollDice() resultField.stringValue = "Result: " + String(result) } func convertToInt(strVal: String) -> Int { let retVal: Int! = Int(strVal) if (retVal == nil) { return 0 } return retVal } func rollDice() -> Int { var result: Int = 0 result += rollDie(4, count:convertToInt(d4Count.stringValue)) result += rollDie(6, count:convertToInt(d6Count.stringValue)) result += rollDie(8, count:convertToInt(d8Count.stringValue)) result += rollDie(10, count:convertToInt(d10Count.stringValue)) result += rollDie(100, count:convertToInt(dPerCount.stringValue)) result += rollDie(12, count:convertToInt(d12Count.stringValue)) result += rollDie(20, count:convertToInt(d20Count.stringValue)) // If a modifier was included in this roll, then add it return result + convertToInt(modifier.stringValue) } func rollDie(max: Int, count: Int) -> Int { if (count == 0) { return 0 } var retVal: Int = 0 for var i = 0; i < count; i++ { if (max == 100) { retVal += (Int(arc4random_uniform(UInt32(10)) + 1) * 10) } else { retVal += Int(arc4random_uniform(UInt32(max)) + 1) } } return retVal } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: AnyObject? { didSet { // Update the view, if already loaded. } } }
mit
ddfbeb244600d39c805ac76f79aa3651
28.638554
73
0.597561
4.278261
false
false
false
false
mgsergio/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/ViatorCells/ViatorItemModel.swift
1
460
@objc(MWMViatorItemModel) final class ViatorItemModel: NSObject { let imageURL: URL let pageURL: URL let title: String let rating: Double let duration: String let price: String @objc init(imageURL: URL, pageURL: URL, title: String, rating: Double, duration: String, price: String) { self.imageURL = imageURL self.pageURL = pageURL self.title = title self.rating = rating self.duration = duration self.price = price } }
apache-2.0
ea8d3575dbd9bca5ee926651d4960ed1
24.555556
107
0.697826
3.931624
false
false
false
false
noprom/Cocktail-Pro
smartmixer/smartmixer/Common/Stars.swift
1
2482
// // Stars.swift // smartmixer // // Created by Koulin Yuan on 8/17/14. // Copyright (c) 2014 Smart Group. All rights reserved. // import UIKit @IBDesignable class Stars : UIView { @IBOutlet weak var star1: UIImageView! @IBOutlet weak var star2: UIImageView! @IBOutlet weak var star3: UIImageView! @IBOutlet weak var star4: UIImageView! @IBOutlet weak var star5: UIImageView! @IBInspectable var value: Int = 3 { didSet { refreshTo(value) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch: UITouch = touches as? UITouch { for index in 1...5 { let tview = self.valueForKey("star\(index)") as! UIView! if tview.pointInside(touch.locationInView(tview), withEvent: event) { refreshTo(index) break } } } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { dealWith(touches, withEvent: event) { index in self.refreshTo(index) } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { dealWith(touches, withEvent: event) { index in self.value = index } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { dealWith(touches, withEvent: event) { index in self.refreshTo(index) } } func refreshTo(value: Int) { if value < 0 || value > 5 { return } for index in 0...value { (self.valueForKey("star\((index+1))") as! UIImageView!)?.image = UIImage(named: "star_on.png") } for index in (value + 1)..<5 { (self.valueForKey("star\((index+1))") as! UIImageView!)?.image = UIImage(named: "star.png") } } func dealWith(touches: NSSet!, withEvent event: UIEvent!, callback: (index: Int) -> ()) { if let touch: UITouch = touches?.anyObject() as? UITouch { for index in 1...5 { let tview = self.valueForKey("star\(index)") as! UIView! if tview.pointInside(touch.locationInView(tview), withEvent: event) { callback(index: index) break } } } } }
apache-2.0
44f199bb2125a89d5026061dbb8a665f
28.2
106
0.535858
4.464029
false
false
false
false
MaxHasADHD/TraktKit
Common/Wrapper/Route.swift
1
2866
// // Route.swift // TraktKit // // Created by Maxamilian Litteral on 6/14/21. // Copyright © 2021 Maximilian Litteral. All rights reserved. // import Foundation public class Route<T: Codable> { public let path: String public let method: Method private let resultType: T.Type public let traktManager: TraktManager public let requiresAuthentication: Bool private var extended: [ExtendedType] = [] private var _page: Int? private var _limit: Int? private var filters = [FilterType]() private var searchType: SearchType? private var searchQuery: String? private var request: URLRequest { var query: [String: String] = [:] if !extended.isEmpty { query["extended"] = extended.queryString() } // pagination if let page = _page { query["page"] = page.description } if let limit = _limit { query["limit"] = limit.description } if let searchType { query["type"] = searchType.rawValue } if let searchQuery { query["query"] = searchQuery } // Filters if filters.isEmpty == false { for (key, value) in (filters.map { $0.value() }) { query[key] = value } } return traktManager.mutableRequest(forPath: path, withQuery: query, isAuthorized: requiresAuthentication, withHTTPMethod: method)! } public init(path: String, method: Method, requiresAuthentication: Bool = false, traktManager: TraktManager, resultType: T.Type = T.self) { self.path = path self.method = method self.requiresAuthentication = requiresAuthentication self.resultType = resultType self.traktManager = traktManager } public func extend(_ extended: ExtendedType...) -> Self { self.extended = extended return self } // MARK: - Pagination public func page(_ page: Int?) -> Self { self._page = page return self } public func limit(_ limit: Int?) -> Self { self._limit = limit return self } // MARK: - Filters public func filter(_ filter: TraktManager.Filter) -> Self { filters.append(filter) return self } public func type(_ type: SearchType?) -> Self { searchType = type return self } // MARK: - Search public func query(_ query: String?) -> Self { searchQuery = query return self } // MARK: - Perform public func perform() async throws -> T { try await traktManager.perform(request: request) } }
mit
77dc757e72be1c41941de2a87591c8ad
24.580357
142
0.547993
4.991289
false
false
false
false
devpunk/punknote
punknote/View/Basic/VToast.swift
1
4028
import UIKit class VToast:UIView { private static let kHeight:CGFloat = 52 private weak var timer:Timer? private let kAnimationDuration:TimeInterval = 0.4 private let kTimeOut:TimeInterval = 3.5 private let kFontSize:CGFloat = 17 private let kLabelMargin:CGFloat = 15 class func messageOrange(message:String) { VToast.message(message:message, color:UIColor.punkOrange) } class func messagePurple(message:String) { VToast.message(message:message, color:UIColor.punkPurple) } private class func message(message:String, color:UIColor) { DispatchQueue.main.async { let toast:VToast = VToast( message:message, color:color) let rootView:UIView = UIApplication.shared.keyWindow!.rootViewController!.view rootView.addSubview(toast) let screenHeight:CGFloat = UIScreen.main.bounds.size.height let remain:CGFloat = screenHeight - kHeight let top:CGFloat = remain / 2.0 NSLayoutConstraint.topToTop( view:toast, toView:rootView, constant:top) NSLayoutConstraint.equalsHorizontal( view:toast, toView:rootView) NSLayoutConstraint.height( view:toast, constant:kHeight) rootView.layoutIfNeeded() toast.animate(open:true) } } private convenience init(message:String, color:UIColor) { self.init() clipsToBounds = true backgroundColor = color alpha = 0 translatesAutoresizingMaskIntoConstraints = false let label:UILabel = UILabel() label.isUserInteractionEnabled = false label.translatesAutoresizingMaskIntoConstraints = false label.font = UIFont.bold(size:kFontSize) label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center label.numberOfLines = 0 label.backgroundColor = UIColor.clear label.text = message let button:UIButton = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.backgroundColor = UIColor.clear button.addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) addSubview(label) addSubview(button) NSLayoutConstraint.equalsVertical( view:label, toView:self) NSLayoutConstraint.equalsHorizontal( view:label, toView:self, margin:kLabelMargin) } func alertTimeOut(sender timer:Timer?) { timer?.invalidate() animate(open:false) } //MARK: actions func actionButton(sender button:UIButton) { button.isUserInteractionEnabled = false timer?.invalidate() alertTimeOut(sender:timer) } //MARK: private private func scheduleTimer() { self.timer = Timer.scheduledTimer( timeInterval:kTimeOut, target:self, selector:#selector(alertTimeOut(sender:)), userInfo:nil, repeats:false) } private func animate(open:Bool) { let alpha:CGFloat if open { alpha = 1 } else { alpha = 0 } UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.alpha = alpha }) { [weak self] (done:Bool) in if open { self?.scheduleTimer() } else { self?.removeFromSuperview() } } } }
mit
9235791b265590aa41d62a6943b5d811
25.853333
90
0.546922
5.617852
false
false
false
false
mapsme/omim
iphone/Maps/Bookmarks/BookmarksTabViewController.swift
4
1697
@objc(MWMBookmarksTabViewController) final class BookmarksTabViewController: TabViewController { @objc enum ActiveTab: Int { case user = 0 case catalog } private static let selectedIndexKey = "BookmarksTabViewController_selectedIndexKey" @objc public var activeTab: ActiveTab = ActiveTab(rawValue: UserDefaults.standard.integer(forKey: BookmarksTabViewController.selectedIndexKey)) ?? .user { didSet { UserDefaults.standard.set(activeTab.rawValue, forKey: BookmarksTabViewController.selectedIndexKey) } } private weak var coordinator: BookmarksCoordinator? @objc init(coordinator: BookmarksCoordinator?) { super.init(nibName: nil, bundle: nil) self.coordinator = coordinator } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let bookmarks = BMCViewController(coordinator: coordinator) let catalog = DownloadedBookmarksViewController(coordinator: coordinator) bookmarks.title = L("bookmarks") catalog.title = L("guides") viewControllers = [bookmarks, catalog] title = L("bookmarks_guides"); tabView.selectedIndex = activeTab.rawValue tabView.delegate = self } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) activeTab = ActiveTab(rawValue: tabView.selectedIndex ?? 0) ?? .user } } extension BookmarksTabViewController: TabViewDelegate { func tabView(_ tabView: TabView, didSelectTabAt index: Int) { let selectedTab = index == 0 ? "my" : "downloaded" Statistics.logEvent("Bookmarks_Tab_click", withParameters: [kStatValue : selectedTab]) } }
apache-2.0
46dbbc7af9a725a49cb288e7ad65a3b5
31.018868
104
0.735415
4.636612
false
false
false
false
ArsalanWahid/yemekye
yemekye/Models/Resturant.swift
1
1182
// // Resturant.swift // yemekye // // Created by Arsalan Wahid Asghar on 12/5/17. // Copyright © 2017 Arsalan Wahid Asghar. All rights reserved. // import UIKit class Resturant{ var name :String var menu : Menu var timing : [(String,String)] var resturantImage: UIImage var status: String var address: String var phoneNumber: String var rating: Int //The mighty Restuart Object //Failable as some parameteres cannot be nil init?(name: String,menu: Menu,timings:[(String,String)],resturantImage:UIImage, status:String, address:String, phonenumber:String,rating: Int) { //Resturant name cannot be nil guard !name.isEmpty else { return nil } //resturant address cannot be nil guard !address.isEmpty else{ return nil } //Set the Object Properties self.name = name self.menu = menu self.timing = timings self.resturantImage = resturantImage self.status = status self.address = address self.phoneNumber = phonenumber self.rating = rating } }
apache-2.0
ae46ae4889b1b3a1fb70f58bc95be6df
22.156863
148
0.605419
4.232975
false
false
false
false
waltflanagan/AdventOfCode
2015/AOC6.playground/Contents.swift
1
2394
//: Playground - noun: a place where people can play import UIKit enum Instruction { case On(CGPoint,CGPoint) case Off(CGPoint, CGPoint) case Toggle(CGPoint,CGPoint) init(string:String) { let components = string.componentsSeparatedByString(" ") switch components[0] { case "toggle": let points = Instruction.parseArguments(Array(components[1..<components.count])) self = .Toggle(points.0, points.1) default: let points = Instruction.parseArguments(Array(components[2..<components.count])) switch components[0] + components [1] { case "turnon": self = .On(points.0, points.1) case "turnoff": self = .Off(points.0, points.1) default: self = .Toggle(CGPointMake(0, 0), CGPointMake(0, 0)) } } } static func pointFromString(string: String) -> CGPoint { let numbers = string.componentsSeparatedByString(",") return CGPointMake(CGFloat(Int(numbers[0])!), CGFloat(Int(numbers[1])!)) } static func parseArguments(args: [String]) -> (CGPoint, CGPoint) { let first = pointFromString(args[0]) let second = pointFromString(args[2]) return (first,second) } } var lights = [[Bool]]() for _ in 0..<10 { var row = [Bool]() for _ in 0..<10 { row.append(false) } lights.append(row) } func set(value: Bool, first: CGPoint, second: CGPoint) { for x in Int(first.x)..<Int(second.x) { for y in Int(first.y)..<Int(second.y) { lights[x][y] = value } } } func toggle(first: CGPoint, second: CGPoint) { for x in Int(first.x)..<Int(second.x) { for y in Int(first.y)..<Int(second.y) { lights[x][y] = !lights[x][y] } } } let input = ["turn on 3,2 through 8,7"] let instructions = input.map { Instruction(string: $0) } for instruction in instructions { switch instruction { case .Toggle(let first, let second): toggle(first,second:second) case .On(let first, let second): set(true, first:first, second:second) case .Off(let first, let second): set(false, first:first, second:second) } } var count = 0 for row in lights { for light in row { if light { count += 1 } } } count
mit
c806152c920e2f5665ee09f46cb75dc0
21.584906
92
0.571429
3.781991
false
false
false
false
jkereako/InlinePicker
Source/Models/PickerViewCellModel.swift
1
1383
// // PickerViewCellModel.swift // InlinePicker // // Created by Jeff Kereakoglow on 4/18/16. // Copyright © 2016 Alexis Digital. All rights reserved. // import UIKit final class PickerViewCellModel: NSObject, CellModelType { let state = CellModelState.Open let rowIndex: Int var values:[String] let dataSource: [[String]] = PickerViewDataSource.dataSource init(rowIndex: Int) { self.rowIndex = rowIndex self.values = [String](count: dataSource.count, repeatedValue: "") // Initialize `values` to the first row in the data source so at least there is something. var i = 0 for component in dataSource { values[i] = component[0] i += 1 } super.init() } } extension PickerViewCellModel: UIPickerViewDataSource { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return dataSource.count } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return dataSource[component].count } } extension PickerViewCellModel: UIPickerViewDelegate { func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return dataSource[component][row] } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { values[component] = dataSource[component][row] } }
mit
ae2c70b8faeff152f82a394f6f820e85
25.576923
97
0.7178
4.401274
false
false
false
false
paperboy1109/Capstone
Capstone/StandardDeviationVC.swift
1
22310
// // StandardDeviationVC.swift // Capstone // // Created by Daniel J Janiak on 9/8/16. // Copyright © 2016 Daniel J Janiak. All rights reserved. // import UIKit import CoreData class StandardDeviationVC: UIViewController { // MARK: - Properties var dataTableEntries: [DataTableDatum]! let placeholderTableCell = DataTableViewCell() let pinchGestureRecognizer = UIPinchGestureRecognizer() var pinchGestureActive = false var initialTouchPoints: TouchPoints! var addNewCellByPinch = false var upperCellIndex = -100 var lowerCellIndex = -100 var pullDownGestureActive = false var sharedContext = CoreDataStack.sharedInstance().managedObjectContext var fetchedResultController: NSFetchedResultsController! // MARK: - Outlets @IBOutlet var bannerTextLabel: UILabel! @IBOutlet var dataTableView: UITableView! @IBOutlet var dividerView: UIView! @IBOutlet var bottomView: UIView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() dividerView.backgroundColor = ThemeColors.themeColor.color() bottomView.backgroundColor = ThemeColors.themeColor.color() pinchGestureRecognizer.addTarget(self, action: #selector(StandardDeviationVC.userDidPinch(_:))) dataTableView.addGestureRecognizer(pinchGestureRecognizer) dataTableView.dataSource = self dataTableView.delegate = self dataTableView.rowHeight = 64.0 dataTableView.backgroundColor = ThemeColors.lightGrey.color() dataTableEntries = [] /* Configure the initial banner text */ bannerTextLabel.font = UIFont(name: "PTSans-Regular", size: 21) bannerTextLabel.textAlignment = NSTextAlignment.Center bannerTextLabel.textColor = UIColor.darkGrayColor() updateBannerMessage() fetchPersistedData() loadSavedData() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) refreshPersistedData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ToDataSummary" { if let dataSummaryVC = segue.destinationViewController as? DataSummaryVC { guard self.dataTableEntries != nil else { return } dataSummaryVC.dataTableEntries = self.dataTableEntries! } } } // MARK: - Actions @IBAction func doneTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func plusMinusTapped(sender: UIButton) { /* Access the cell that contains the button */ var targetIndexPath: NSIndexPath! let currentButton = sender if let buttonStackView = currentButton.superview { if let buttonSuperview = buttonStackView.superview { if let currentCell = buttonSuperview.superview as? DataTableViewCell { /* Keep track of the cell's index */ targetIndexPath = dataTableView.indexPathForCell(currentCell) /* Update the model with the sign change */ var currentDatum = dataTableEntries[sender.tag] currentDatum.changeSignOfDatum() /* Update the cell */ currentCell.datum = currentDatum /* Update the model */ dataTableEntries[targetIndexPath.row] = currentDatum /* Animate constraint changes now that the moreInfoTextView has changed size and content */ UIView.animateWithDuration(0.1) { currentCell.contentView.layoutIfNeeded() } /* Force the table view to update */ dataTableView.beginUpdates() dataTableView.endUpdates() /* Sync the persisted data */ refreshPersistedData() } } } } // MARK: - Helpers private func blockGarbageIn(alertTitle: String, alertDescription: String, tableCell: DataTableViewCell?) { let alertView = UIAlertController(title: "\(alertTitle)", message: "\(alertDescription)", preferredStyle: UIAlertControllerStyle.Alert) alertView.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) in // Make UI changes if let cell = tableCell as DataTableViewCell! { self.deleteDataTableCell(cell.datum!) } }) ) self.presentViewController(alertView, animated: true, completion: nil) } func updateBannerMessage() { if dataTableEntries.count <= 2 { bannerTextLabel.text = "Pull downward to add data." } else { bannerTextLabel.text = "Pull downward to summarize the data. Pinch outward to add new data." } } func refreshPersistedData() { deleteAllPersistedData() for item in dataTableEntries { let coreDataDatum = NSEntityDescription.insertNewObjectForEntityForName("Datum", inManagedObjectContext: self.sharedContext) as! Datum coreDataDatum.text = item.datumText coreDataDatum.numericalValue = NSNumber(double: item.datumDoubleValue!) } CoreDataStack.sharedInstance().saveContext() } func loadSavedData() { let fetchRequest = NSFetchRequest(entityName: "Datum") do { let allPersistedData = try sharedContext.executeFetchRequest(fetchRequest) as! [Datum] for item in allPersistedData { sharedContext.deleteObject(item) let newDataTableDatum = DataTableDatum(textFieldText: item.text!) dataTableEntries.append(newDataTableDatum) } } catch { fatalError("Unable to load persisted data") } } func createAndLoadSampleData() { /* Create some example data */ let sampleData = ["1.0", "2.0", "3.0", "4.0", "5.0", "6.0", "7.0"] for item in sampleData { let newDatum = DataTableDatum(textFieldText: item) dataTableEntries.append(newDatum) } /* Persist this sample data set */ for item in dataTableEntries { let coreDataDatum = NSEntityDescription.insertNewObjectForEntityForName("Datum", inManagedObjectContext: self.sharedContext) as! Datum coreDataDatum.text = item.datumText coreDataDatum.numericalValue = NSNumber(double: item.datumDoubleValue!) } refreshPersistedData() } } // MARK: - Delegates for the table view extension StandardDeviationVC: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataTableEntries.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DatumCell", forIndexPath: indexPath) as! DataTableViewCell cell.delegate = self cell.backgroundColor = UIColor.whiteColor() cell.datum = dataTableEntries[indexPath.row] cell.plusMinusButton.tag = indexPath.row return cell } /* Incomplete pinch gestures will change background colors; give the user a way to return the color to white */ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)?.backgroundColor = UIColor.whiteColor() } } // MARK: - Delegate methods for the custom cell class extension StandardDeviationVC: DataTableViewCellDelegate { func cellDidBeginEditing(editingCell: DataTableViewCell) { let offsetWhileEditing = dataTableView.contentOffset.y - editingCell.frame.origin.y as CGFloat let cellsToMove = dataTableView.visibleCells as! [DataTableViewCell] for item in cellsToMove { UIView.animateWithDuration(0.4, animations: {() in /* Move the cell up relative to the scroll position of the table view */ item.transform = CGAffineTransformMakeTranslation(0, offsetWhileEditing) if item !== editingCell { item.alpha = 0.3 } }) } } func cellDidEndEditing(editingCell: DataTableViewCell) { let cellsToMove = dataTableView.visibleCells as! [DataTableViewCell] for item in cellsToMove { /* Return cells to their pre-editing position and restore opaque color */ UIView.animateWithDuration(0.3, animations: {() in item.transform = CGAffineTransformIdentity if item !== editingCell { item.alpha = 1.0 } }) } /* Don't insert empty cells into the table */ if editingCell.datum!.datumText == "" { deleteDataTableCell(editingCell.datum!) } /* Update the data model if the cell has valid data */ if let newDatum = editingCell.datum?.datumText { editingCell.datum?.updateDatumValue() } if let newDatumValue = editingCell.datum?.datumDoubleValue { } else { editingCell.backgroundColor = UIColor.redColor() blockGarbageIn("Invalid data", alertDescription: "Check that the value you entered is a valid number", tableCell: editingCell) } } func addDataTableCell() { /* By default, add a cell to the top of the table */ addDataTableCellAtIndex(0) } func addDataTableCellAtIndex(index: Int) { let newDatum = DataTableDatum(textFieldText: "") dataTableEntries.insert(newDatum, atIndex: index) dataTableView.reloadData() var newCell: DataTableViewCell let allVisibleCells = dataTableView.visibleCells as! [DataTableViewCell] for item in allVisibleCells { if item.datum === newDatum { newCell = item newCell.datumTextField.becomeFirstResponder() break } } updateBannerMessage() } func deleteDataTableCell(itemToRemove: DataTableDatum) { let indexOfItemToRemove = (dataTableEntries as NSArray).indexOfObject(itemToRemove) guard indexOfItemToRemove != NSNotFound else { return } dataTableEntries.removeAtIndex(indexOfItemToRemove) /* Update the table view */ dataTableView.beginUpdates() let indexPathOfItemToDelete = NSIndexPath(forRow: indexOfItemToRemove, inSection: 0) dataTableView.deleteRowsAtIndexPaths([indexPathOfItemToDelete], withRowAnimation: .Automatic) dataTableView.endUpdates() updateBannerMessage() } } // MARK: - UIScrollViewDelegate methods extension StandardDeviationVC { func scrollViewWillBeginDragging(scrollView: UIScrollView) { updateBannerMessage() pullDownGestureActive = scrollView.contentOffset.y <= 0.0 if dataTableEntries.count <= 2 { if pullDownGestureActive { placeholderTableCell.backgroundColor = ThemeColors.themeColor.color() /* User has pulled downward at the top of the table, add the placeholder cell */ dataTableView.insertSubview(placeholderTableCell, atIndex: 0) } } } func scrollViewDidScroll(scrollView: UIScrollView) { let scrollViewContentOffsetY = scrollView.contentOffset.y if dataTableEntries.count <= 2 && pullDownGestureActive && scrollView.contentOffset.y <= 0.0 { /* Re-position the placeholder cell as the user scrolls */ placeholderTableCell.frame = CGRect(x: 0, y: -dataTableView.rowHeight, width: dataTableView.frame.size.width, height: dataTableView.rowHeight) /* Give the placeholder cell a fade-in effect */ placeholderTableCell.alpha = min(1.0, (-1.0) * scrollViewContentOffsetY / dataTableView.rowHeight) } else if pullDownGestureActive && scrollView.contentOffset.y <= 0.0 { pullDownGestureActive = true } else { pullDownGestureActive = false } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { /* If the scroll-down gesture was far enough, add the placeholder cell to the collection of items in the table view */ if dataTableEntries.count <= 2 && pullDownGestureActive && (-1.0) * scrollView.contentOffset.y > dataTableView.rowHeight { addDataTableCell() updateBannerMessage() } else if pullDownGestureActive && (-1.0) * scrollView.contentOffset.y > dataTableView.rowHeight { /* Segue to the data summary scene */ //let dataSummaryVC = self.storyboard!.instantiateViewControllerWithIdentifier("DataSummary") as! DataSummaryVC //self.presentViewController(dataSummaryVC, animated: true, completion: nil) updateBannerMessage() self.performSegueWithIdentifier("ToDataSummary", sender: nil) self.refreshPersistedData() }else { pullDownGestureActive = false placeholderTableCell.removeFromSuperview() } } } // MARK: - pinch-to-add methods extension StandardDeviationVC { func userDidPinch(recognizer: UIPinchGestureRecognizer) { if recognizer.state == .Began { pinchStarted(recognizer) } if recognizer.state == .Changed && pinchGestureActive && recognizer.numberOfTouches() == 2 { pinchChanged(recognizer) } if recognizer.state == .Ended { pinchEnded(recognizer) } } func pinchStarted(recognizer: UIPinchGestureRecognizer) { initialTouchPoints = getNormalizedTouchPoints(recognizer) upperCellIndex = -100 lowerCellIndex = -100 let allVisibleCells = dataTableView.visibleCells as! [DataTableViewCell] for i in 0..<allVisibleCells.count { let cell = allVisibleCells[i] if viewContainsPoint(cell, point: initialTouchPoints.upper) { upperCellIndex = i cell.backgroundColor = UIColor.lightGrayColor() } if viewContainsPoint(cell, point: initialTouchPoints.lower) { lowerCellIndex = i cell.backgroundColor = UIColor.lightGrayColor() } } /* Are the cells neighbors? */ if abs(upperCellIndex - lowerCellIndex) == 1 { pinchGestureActive = true /* Insert the placeholder cell */ let precedingCell = allVisibleCells[upperCellIndex] placeholderTableCell.frame = CGRectOffset(precedingCell.frame, 0.0, dataTableView.rowHeight / 2.0) placeholderTableCell.backgroundColor = ThemeColors.themeColor.color() dataTableView.insertSubview(placeholderTableCell, atIndex: 0) } } func pinchChanged(recognizer: UIPinchGestureRecognizer) { let currentTouchPoints = getNormalizedTouchPoints(recognizer) /* Set the "size" of the pinch to be the smaller of the two distances the touch points have moved */ let upperDelta = currentTouchPoints.upper.y - initialTouchPoints.upper.y let lowerDelta = initialTouchPoints.lower.y - currentTouchPoints.lower.y let delta = -min(0, min(upperDelta, lowerDelta)) /* Re-position the cells to take the new cell into account */ let visibleCells = dataTableView.visibleCells as! [DataTableViewCell] for i in 0..<visibleCells.count { let cell = visibleCells[i] if i <= upperCellIndex { cell.transform = CGAffineTransformMakeTranslation(0, -delta) } if i >= lowerCellIndex { cell.transform = CGAffineTransformMakeTranslation(0, delta) } } /* Make the new cell more interactive */ let gapSize = delta * 2 let maxGapSize = min(gapSize, dataTableView.rowHeight) placeholderTableCell.transform = CGAffineTransformMakeScale(1.0, maxGapSize / dataTableView.rowHeight) placeholderTableCell.datum?.datumText = gapSize > dataTableView.rowHeight ? "Release to add item" : "Pull apart to add item" placeholderTableCell.alpha = min(1.0, gapSize / dataTableView.rowHeight) /* Should the new cell be added? */ addNewCellByPinch = gapSize > dataTableView.rowHeight } func pinchEnded(recognizer: UIPinchGestureRecognizer) { addNewCellByPinch = false /* Get rid of the placeholder cell */ placeholderTableCell.transform = CGAffineTransformIdentity placeholderTableCell.removeFromSuperview() if pinchGestureActive { pinchGestureActive = false /* Remove the space that was added when animating the insertion of the placeholder cell */ let visibleCells = self.dataTableView.visibleCells as! [DataTableViewCell] for cell in visibleCells { cell.transform = CGAffineTransformIdentity } /* Add a new cell to the table, and add the accompanying data structure */ let indexOffset = Int(floor(dataTableView.contentOffset.y / dataTableView.rowHeight)) addDataTableCellAtIndex(lowerCellIndex + indexOffset) } else { /* Return cells to their position before the pinch gesture occurred */ UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseInOut, animations: {() in let allVisibleCells = self.dataTableView.visibleCells as! [DataTableViewCell] for cell in allVisibleCells { cell.transform = CGAffineTransformIdentity } }, completion: nil) } } // MARK: - Helpers /* Make sure that point1 is the higher of the two on screen */ func getNormalizedTouchPoints(recognizer: UIGestureRecognizer) -> TouchPoints { var pointOne = recognizer.locationOfTouch(0, inView: dataTableView) var pointTwo = recognizer.locationOfTouch(1, inView: dataTableView) if pointOne.y > pointTwo.y { let temp = pointOne pointOne = pointTwo pointTwo = temp } return TouchPoints(upper: pointOne, lower: pointTwo) } /* Did a given point land within the frame ?*/ func viewContainsPoint(view: UIView, point: CGPoint) -> Bool { let frame = view.frame return (frame.origin.y < point.y) && (frame.origin.y + (frame.size.height) > point.y) } } // MARK: - Close the keyboard when the user taps outside the editng field extension StandardDeviationVC { override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } } extension StandardDeviationVC { override func prefersStatusBarHidden() -> Bool { return true } } // MARK: - CoreData delegate methods and helpers extension StandardDeviationVC: NSFetchedResultsControllerDelegate { func fetchPersistedData() { let fetchRequest = NSFetchRequest(entityName: "Datum") let sortDescriptors = NSSortDescriptor(key: "numericalValue", ascending: true) fetchRequest.sortDescriptors = [sortDescriptors] fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultController.delegate = self do { try fetchedResultController.performFetch() } catch { fatalError("Error in fetching records") } } func deleteAllPersistedData() { let fetchRequest = NSFetchRequest(entityName: "Datum") do { let allPersistedData = try sharedContext.executeFetchRequest(fetchRequest) as! [Datum] for item in allPersistedData { sharedContext.deleteObject(item) } } catch { fatalError("Unable to delete persisted data") } CoreDataStack.sharedInstance().saveContext() } }
mit
c9f1f26e9e0a8336b7f48b8553ea7a41
33.695179
171
0.595903
6.172939
false
false
false
false
prebid/prebid-mobile-ios
PrebidMobileTests/RenderingTests/Tests/PBMViewExposureTest.swift
1
14198
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import XCTest // MARK: - Extensions extension PBMViewExposure { convenience init(exposureFactor: Float, visibleRectangle: CGRect) { self.init(exposureFactor: exposureFactor, visibleRectangle: visibleRectangle, occlusionRectangles: nil as [NSValue]?) } convenience init(exposureFactor: Float, visibleRectangle: CGRect, occlusionRectangles: [CGRect]) { self.init(exposureFactor: exposureFactor, visibleRectangle: visibleRectangle, occlusionRectangles: occlusionRectangles.map(NSValue.init(cgRect:))) } } // MARK: - TestCase class PBMViewExposureTest: XCTestCase { // MARK: - Single obstruction // // 0 10 20 30 40 50 60 // ][___][___][___][___][___][___][__ // 0l +-----------+ // l |root | // l | +----------------------+ // l | |grandparent | // 10L_| | +------+ | // l | | |parent| | // l | | | | | // l | | +-----------+ | | // l | | |obstruction| | | // 20L_| +-|.........: | |---+ // l | | : : | | // l | | : : | | // l | | +.......|-+ | // l | | :view | | | // 30L_| +-----------+ | | // l | | | | // l | +---------+ | // l | | | | // l | | +------+ // 40L_| | // l +-----------+ // // no clipping // +---------------------+-------+-------+-------+-----------+---------+-------+ // | view | p-glob| p-loc | size | obstructed|unexposed|exposed| // +---------------------+-------+-------+-------+-----+-----+---------+-------+ // | *━┯ window | 0, 0 | 0, 0 | 56x42 | N/A | N/A | N/A | N/A | // | ┡━┯ root | 1, 1 | 1, 1 | 24x40 |12,14|12x14| 7/40 | 33/40 | // | │ ┗━┯ grandparent | 9, 5 | 8, 4 | 46x14 | 4,10|24x 4| 24/161 |137/161| // | │ ┗━┯ parent | 33, 9 | 24, 4 | 14x28 | 0, 6| 4x14| 1/7 | 6/7 | // | │ ┗━━ view | 21,25 |-12,16 | 20x 8 | 0, 0|16x 4| 2/5 | 3/5 | // | ┗━━ obstruction | 13,15 | 13,15 | 24x14 | N/A | N/A | N/A | N/A | // +---------------------+-------+-------+-------+-----+-----+---------+-------+ // // unexposed = obstructed.size.area / size.area // exposed = 1 - unexposed // // XCTAssertEqual(1 - 24/161.0, 137/161.0) // <--- XCTAssertEqual failed: ("0.8509316770186335") is not equal to ("0.8509316770186336") // // => use exact values from 'exposed' to build PBMViewExposure, otherwise 'isEqual' might fail due to rounding errors // // root.clipToBounds = true // => parent -- clipped out // +-------------+-------+-----+-----+-------+-----+-----+-------+-------+ // | view | size | visible | -area | obstructed| -area |exposed| // +-------------+-------+-----+-----+-------+-----+-----+-------+-------+ // | grandparent | 46x14 | 0, 0|16x14| 8/23 | 4,10|12x 4| 12/161| 44/161| // | view | 20x 8 | 0, 4| 4x 8| 1/5 | 0, 0| 0x 0| 1/10 | 1/10 | // +-------------+-------+-----+-----+-------+-----+-----+-------+-------+ // // parent.clipToBounds = true // +-------------+-------+-----+-----+-------+-----+-----+-------+-------+ // | view | size | visible | -area | obstructed| -area |exposed| // +-------------+-------+-----+-----+-------+-----+-----+-------+-------+ // | view | 20x 8 |12, 0| 8x 8| 2/5 |12, 0| 4x 4| 1/10 | 3/10 | // +-------------+-------+-----+-----+-------+-----+-----+-------+-------+ // // move obstruction to background // +-------------+-------+-----+-----+-------+ // | view | size | visible | -area | // +-------------+-------+-----+-----+-------+ // | obstruction | 24x14 |12, 4| 8x 6| 1/7 | // +-------------+-------+-----+-----+-------+ // func testSingleObstruction() { let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 560, height: 420)) let root = UIView(frame: CGRect(x: 10, y: 10, width: 240, height: 400)) let grandparent = UIView(frame: CGRect(x: 80, y: 40, width: 460, height: 140)) let parent = UIView(frame: CGRect(x: 240, y: 40, width: 140, height: 280)) let view = UIView(frame: CGRect(x: -120, y: 160, width: 200, height: 80)) let obstruction = UIView(frame: CGRect(x: 130, y: 150, width: 240, height: 140)) window.addSubview(root) root.addSubview(grandparent) grandparent.addSubview(parent) parent.addSubview(view) window.addSubview(obstruction) window.isHidden = false XCTAssertEqual(root.viewExposure, PBMViewExposure(exposureFactor: 33/40.0, visibleRectangle: CGRect(x: 0, y: 0, width: 240, height: 400), occlusionRectangles: [CGRect(x: 120, y: 140, width: 120, height: 140)])); XCTAssertEqual(grandparent.viewExposure, PBMViewExposure(exposureFactor: 137/161.0, visibleRectangle: CGRect(x: 0, y: 0, width: 460, height: 140), occlusionRectangles: [CGRect(x: 40, y: 100, width: 240, height: 40)])); XCTAssertEqual(parent.viewExposure, PBMViewExposure(exposureFactor: 6/7.0, visibleRectangle: CGRect(x: 0, y: 0, width: 140, height: 280), occlusionRectangles: [CGRect(x: 0, y: 60, width: 40, height: 140)])); XCTAssertEqual(view.viewExposure, PBMViewExposure(exposureFactor: 3/5.0, visibleRectangle: CGRect(x: 0, y: 0, width: 200, height: 80), occlusionRectangles: [CGRect(x: 0, y: 0, width: 160, height: 40)])); root.clipsToBounds = true // table 2 XCTAssertEqual(grandparent.viewExposure, PBMViewExposure(exposureFactor: 44/161.0, visibleRectangle: CGRect(x: 0, y: 0, width: 160, height: 140), occlusionRectangles: [CGRect(x: 40, y: 100, width: 120, height: 40)])); XCTAssertEqual(parent.viewExposure, .zero); XCTAssertEqual(view.viewExposure, PBMViewExposure(exposureFactor: 1/10.0, visibleRectangle: CGRect(x: 0, y: 40, width: 40, height: 40))); root.clipsToBounds = false parent.clipsToBounds = true // table 3 XCTAssertEqual(view.viewExposure, PBMViewExposure(exposureFactor: 3/10.0, visibleRectangle: CGRect(x: 120, y: 0, width: 80, height: 80), occlusionRectangles: [CGRect(x: 120, y: 0, width: 40, height: 40)])); obstruction.removeFromSuperview() window.insertSubview(obstruction, belowSubview: root) parent.clipsToBounds = false // table 4 XCTAssertEqual(obstruction.viewExposure, PBMViewExposure(exposureFactor: 1/7.0, visibleRectangle: CGRect(x: 120, y: 40, width: 80, height: 60))); } // MARK: - Composite hierarchy // // 0 10 20 30 40 50 60 // ][___][___][___][___][___][___][__ // 0l +-----------------------------+ // l |parent +-----------------+ | // l | |brother | | // l | +------|.............+ | | // 10L_| |adView| : | | // l | | +-----------------+ | // l | | +-----+ | | // l | | |X-btn| | | // l | | +-----+ +-----------+ | // 20L_| | |uncle : | | // l | | | : | | // l | | | : | | // l | | +-----------+ | // l | | | | // 30L_|+--------------------------+ | // l ||aunt +---------+ : | | // l || : |cousin | : | | // l || +......|.........|...+ | | // l || +---------+ | | // 40L_|+--------------------------+ | // l +-----------------------------+ // // no clipping // +---------------------+-------+-------+-------+-----------+-----------+-----------+---------+-----------+---------+ // | view | p-glob| p-loc | size | obstructed| obstructed| obstructed|unexposed| visible | exposed | // +---------------------+-------+-------+-------+-----+-----+-----+-----+-----+-----+---------+-----+-----+---------+ // | *━┯ window | 0, 0 | 0, 0 | 62x42 | : | : | : | N/A | N/A | N/A | // | ┡━┯ parent | 1, 1 | 1, 1 | 60x40 | 2,28:54x10|28,16:24x 8| : | 732/2400| 0, 0:60x40|1668/2400| // | │ ┡━━ adView | 7, 7 | 6, 6 | 42x28 |22,10:20x 8|14, 0:28x 4| 4, 6:12x 4| 320/1176| 0, 0:42x22| 604/1176| // | │ ┗━━ brother | 21, 3 | 20, 2 | 36x 8 | : | : | : | N/A | 0, 0:36x 8| 1 | // | │ ┗━━ X-btn | 11,13 | 10,12 | 12x 4 | : | : | : | N/A | 0, 0:12x 4| 1 | // | ┡━━ uncle | 29,17 | 29,17 | 24x 8 | : | : | : | N/A | 0, 0:24x 8| 1 | // | ┗━┯ aunt | 3,29 | 3,29 | 54x10 | : | : | : | N/A | 0, 0:54x10| 1 | // | ┗━━ cousin | 21,31 | 18, 2 | 20x 6 | : | : | : | N/A | 0, 0:20x 6| 1 | // +---------------------+-------+-------+-------+-----+-----+-----+-----+-----+-----+---------+-----+-----+---------+ // func testMultipleObstructions() { let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 620, height: 420)) let parent = UIView(frame: CGRect(x: 10, y: 10, width: 600, height: 400)) let adView = UIView(frame: CGRect(x: 60, y: 60, width: 420, height: 280)) let brother = UIView(frame: CGRect(x: 200, y: 20, width: 360, height: 80)) let xBtn = UIView(frame: CGRect(x: 100, y: 120, width: 120, height: 40)) let uncle = UIView(frame: CGRect(x: 290, y: 170, width: 240, height: 80)) let aunt = UIView(frame: CGRect(x: 30, y: 290, width: 540, height: 100)) let cousin = UIView(frame: CGRect(x: 180, y: 20, width: 200, height: 60)) window.addSubview(parent) parent.addSubview(adView) parent.addSubview(brother) parent.addSubview(xBtn) window.addSubview(uncle) window.addSubview(aunt) aunt.addSubview(cousin) window.isHidden = false XCTAssertEqual(parent.viewExposure, PBMViewExposure(exposureFactor: 1668/2400.0, visibleRectangle: CGRect(x: 0, y: 0, width: 600, height: 400), occlusionRectangles: [CGRect(x: 20, y: 280, width: 540, height: 100), CGRect(x: 280, y: 160, width: 240, height: 80)])); XCTAssertEqual(adView.viewExposure, PBMViewExposure(exposureFactor: 604/1176.0, visibleRectangle: CGRect(x: 0, y: 0, width: 420, height: 220), occlusionRectangles: [CGRect(x: 220, y: 100, width: 200, height: 80), CGRect(x: 140, y: 0, width: 280, height: 40), CGRect(x: 40, y: 60, width: 120, height: 40)])); XCTAssertEqual(brother.viewExposure, PBMViewExposure(exposureFactor: 1, visibleRectangle: CGRect(x: 0, y: 0, width: 360, height: 80))); XCTAssertEqual(xBtn.viewExposure, PBMViewExposure(exposureFactor: 1, visibleRectangle: CGRect(x: 0, y: 0, width: 120, height: 40))); XCTAssertEqual(uncle.viewExposure, PBMViewExposure(exposureFactor: 1, visibleRectangle: CGRect(x: 0, y: 0, width: 240, height: 80))); XCTAssertEqual(aunt.viewExposure, PBMViewExposure(exposureFactor: 1, visibleRectangle: CGRect(x: 0, y: 0, width: 540, height: 100))); XCTAssertEqual(cousin.viewExposure, PBMViewExposure(exposureFactor: 1, visibleRectangle: CGRect(x: 0, y: 0, width: 200, height: 60))); } }
apache-2.0
c1fbbf221728bf33f6c42c52afdc40d1
55.155378
139
0.396311
4.203698
false
false
false
false
jaouahbi/OMTextLayer
OMTextLayer/OMTextLayer.swift
1
21716
// // Copyright 2015 - Jorge Ouahbi // // 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. // // // OMTextLayer.swift // // Created by Jorge Ouahbi on 23/3/15. // // Description: // CALayer derived class that uses CoreText for draw a text. // // Versión 0.1 (29-3-2015) // Creation. // Versión 0.11 (29-3-2015) // Replaced paragraphStyle by a array of CTParagraphStyleSetting. // Versión 0.11 (15-5-2015) // Added font ligature // Versión 0.12 (1-9-2016) // Added font underline // Versión 0.12 (6-9-2016) // Updated to swift 3.0 // Versión 0.13 (22-9-2016) // Added code so that the text can follow an angle with a certain radius (Based on ArcTextView example by Apple) // Versión 0.14 (25-9-2016) // Added text to path helper function // Versión 0.15 (30-11-2016) // Added vertical alignment #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif import CoreGraphics import CoreText import CoreFoundation @objc class OMTextLayer : CALayer { // MARK: properties fileprivate(set) var fontRef:CTFont = CTFontCreateWithName("Helvetica" as CFString, 12.0, nil); var verticalCeter : Bool = true { didSet { setNeedsDisplay() } } var angleLenght : Double? { didSet { setNeedsDisplay() } } var radiusRatio : CGFloat = 0.0 { didSet { radiusRatio = clamp(radiusRatio, lower: 0, upper: 1.0) setNeedsDisplay() } } var underlineColor : UIColor? { didSet { setNeedsDisplay() } } var underlineStyle : CTUnderlineStyle = CTUnderlineStyle() { didSet { setNeedsDisplay() } } /// default 1: default ligatures, 0: no ligatures, 2: all ligatures var fontLigature:NSNumber = NSNumber(value: 1 as Int32) { didSet { setNeedsDisplay() } } var fontStrokeColor:UIColor = UIColor.lightGray { didSet { setNeedsDisplay() } } var fontStrokeWidth:Float = -3 { didSet { setNeedsDisplay() } } var string : String? = nil { didSet { setNeedsDisplay() } } var foregroundColor:UIColor = UIColor.black { didSet { setNeedsDisplay() } } var fontBackgroundColor:UIColor = UIColor.clear { didSet{ setNeedsDisplay() } } var lineBreakMode:CTLineBreakMode = .byCharWrapping { didSet{ setNeedsDisplay() } } var alignment: CTTextAlignment = CTTextAlignment.center { didSet{ setNeedsDisplay() } } var font: UIFont? = nil { didSet{ if let font = font { setFont(font, matrix: nil) } setNeedsDisplay() } } // MARK: constructors override init() { super.init() self.contentsScale = UIScreen.main.scale self.needsDisplayOnBoundsChange = true; // https://github.com/danielamitay/iOS-App-Performance-Cheatsheet/blob/master/QuartzCore.md //self.shouldRasterize = true //self.rasterizationScale = UIScreen.main.scale self.drawsAsynchronously = true self.allowsGroupOpacity = false } convenience init(string : String, alignmentMode:String = "center") { self.init() setAlignmentMode(alignmentMode) self.string = string } convenience init(string : String, font:UIFont ,alignmentMode:String = "center") { self.init() setAlignmentMode(alignmentMode) self.string = string setFont(font, matrix: nil) } override init(layer: Any) { super.init(layer: layer) if let other = layer as? OMTextLayer { self.string = other.string self.fontRef = other.fontRef self.fontStrokeColor = other.fontStrokeColor self.fontStrokeWidth = other.fontStrokeWidth self.foregroundColor = other.foregroundColor self.fontBackgroundColor = other.fontBackgroundColor self.lineBreakMode = other.lineBreakMode self.alignment = other.alignment self.underlineColor = other.underlineColor self.underlineStyle = other.underlineStyle } } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } // MARK: private helpers // // Add attributes to the String // func stringWithAttributes(_ string : String) -> CFAttributedString { return attributedStringWithAttributes(NSAttributedString(string : string)) } // // Add the attributes to the CFAttributedString // func attributedStringWithAttributes(_ attrString : CFAttributedString) -> CFAttributedString { let stringLength = CFAttributedStringGetLength(attrString) let range = CFRangeMake(0, stringLength) // // Create a mutable attributed string with a max length of 0. // The max length is a hint as to how much internal storage to reserve. // 0 means no hint. // let newString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0); // Copy the textString into the newly created attrString CFAttributedStringReplaceString (newString, CFRangeMake(0,0), CFAttributedStringGetString(attrString)); CFAttributedStringSetAttribute(newString, range, kCTForegroundColorAttributeName, foregroundColor.cgColor); if #available(iOS 10.0, *) { CFAttributedStringSetAttribute(newString, range, kCTBackgroundColorAttributeName, fontBackgroundColor.cgColor) } else { // Fallback on earlier versions }; CFAttributedStringSetAttribute(newString,range,kCTFontAttributeName,fontRef) // TODO: add more CTParagraphStyleSetting // CTParagraph let setting = [CTParagraphStyleSetting(spec: .alignment, valueSize: MemoryLayout.size(ofValue: alignment), value: &alignment), CTParagraphStyleSetting(spec: .lineBreakMode, valueSize: MemoryLayout.size(ofValue: lineBreakMode), value: &lineBreakMode)] CFAttributedStringSetAttribute(newString, range, kCTParagraphStyleAttributeName, CTParagraphStyleCreate(setting, setting.count)) CFAttributedStringSetAttribute(newString, range, kCTStrokeWidthAttributeName, NSNumber(value: fontStrokeWidth as Float)) CFAttributedStringSetAttribute(newString, range, kCTStrokeColorAttributeName, fontStrokeColor.cgColor) CFAttributedStringSetAttribute(newString, range, kCTLigatureAttributeName, fontLigature) CFAttributedStringSetAttribute(newString, range, kCTUnderlineStyleAttributeName, NSNumber(value: underlineStyle.rawValue as Int32)); if let underlineColor = underlineColor { CFAttributedStringSetAttribute(newString, range, kCTUnderlineColorAttributeName, underlineColor.cgColor); } // TODO: Add more attributes return newString! } // // Calculate the frame size of a String // func frameSize() -> CGSize { return frameSizeLengthFromAttributedString(NSAttributedString(string : self.string!)) } func frameSizeLengthFromAttributedString(_ attrString : NSAttributedString) -> CGSize { let attrStringWithAttributes = attributedStringWithAttributes(attrString) let stringLength = CFAttributedStringGetLength(attrStringWithAttributes) // Create the framesetter with the attributed string. let framesetter = CTFramesetterCreateWithAttributedString(attrStringWithAttributes); let targetSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) let frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter,CFRangeMake(0, stringLength), nil, targetSize, nil) return frameSize; } func setAlignmentMode(_ alignmentMode : String) { switch (alignmentMode) { case "center": alignment = CTTextAlignment.center case "left": alignment = CTTextAlignment.left case "right": alignment = CTTextAlignment.right case "justified": alignment = CTTextAlignment.justified case "natural": alignment = CTTextAlignment.natural default: alignment = CTTextAlignment.left } } fileprivate func setFont(_ fontName:String!, fontSize:CGFloat, matrix: UnsafePointer<CGAffineTransform>? = nil) { assert(fontSize > 0,"Invalid font size (fontSize ≤ 0)") assert(fontName.isEmpty == false ,"Invalid font name (empty)") if(fontSize > 0 && fontName != nil) { fontRef = CTFontCreateWithName(fontName as CFString, fontSize, matrix) } } fileprivate func setFont(_ font:UIFont, matrix: UnsafePointer<CGAffineTransform>? = nil) { setFont(font.fontName, fontSize: font.pointSize, matrix: matrix) } // MARK: overrides override func draw(in context: CGContext) { if let string = self.string { context.saveGState(); // Set the text matrix. context.textMatrix = CGAffineTransform.identity; // Core Text Coordinate System and Core Graphics are OSX style #if os(iOS) context.translateBy(x: 0, y: self.bounds.size.height); context.scaleBy(x: 1.0, y: -1.0); #endif var rect:CGRect = bounds if (radiusRatio == 0 && angleLenght == nil) { // Create a path which bounds the area where you will be drawing text. // The path need not be rectangular. let path = CGMutablePath(); // Add the atributtes to the String let attrStringWithAttributes = stringWithAttributes(string) // Create the framesetter with the attributed string. let framesetter = CTFramesetterCreateWithAttributedString(attrStringWithAttributes); if verticalCeter { let boundingBox = CTFontGetBoundingBox(fontRef); // Get the position on the y axis (middle) let midHeight = (rect.size.height * 0.5) - boundingBox.size.height * 0.5 rect = CGRect(x:0, y:midHeight, width:rect.size.width, height:boundingBox.size.height) } // add the rect for the frame path.addRect(rect); // Create a frame. let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, nil); // Draw the specified frame in the given context. CTFrameDraw(frame, context); // context.flush() } else { drawWithArc(context: context, rect:rect) } context.restoreGState() } super.draw(in: context) } } struct GlyphArcInfo { var width:CGFloat; var angle:CGFloat; // in radians }; extension OMTextLayer { func createLine() -> CTLine? { if let string = string { return CTLineCreateWithAttributedString(self.stringWithAttributes(string)) } return nil; } func getRunFont(_ run:CTRun) -> CTFont { let dict = CTRunGetAttributes(run) as NSDictionary let runFont: CTFont = dict.object(forKey: String(kCTFontAttributeName)) as! CTFont return runFont; } func createPathFromStringWithAttributes() -> UIBezierPath? { OMLog.printd("\(self.name ?? ""): createPathFromStringWithAttributes()") if let line = createLine() { let letters = CGMutablePath() let runArray = CTLineGetGlyphRuns(line) as NSArray let run: CTRun = runArray[0] as! CTRun let runFont: CTFont = getRunFont(run) let glyphCount = CTRunGetGlyphCount(run) for runGlyphIndex in 0 ..< glyphCount { let thisGlyphRange = CFRangeMake(runGlyphIndex, 1) var glyph = CGGlyph() var position = CGPoint.zero CTRunGetGlyphs(run, thisGlyphRange, &glyph) CTRunGetPositions(run, thisGlyphRange, &position) var affine = CGAffineTransform.identity let letter = CTFontCreatePathForGlyph(runFont, glyph, &affine) if let letter = letter { let lettersAffine = CGAffineTransform(translationX: position.x, y: position.y) letters.addPath(letter,transform:lettersAffine); } } let path = UIBezierPath() path.move(to: CGPoint.zero) path.append(UIBezierPath(cgPath: letters)) return path } return nil; } } extension OMTextLayer { func prepareGlyphArcInfo(line:CTLine, glyphCount:CFIndex, angle:Double) -> [GlyphArcInfo] { assert(glyphCount > 0); let runArray = CTLineGetGlyphRuns(line) as Array var glyphArcInfo : [GlyphArcInfo] = [] glyphArcInfo.reserveCapacity(glyphCount) // Examine each run in the line, updating glyphOffset to track how far along the run is in terms of glyphCount. var glyphOffset:CFIndex = 0; for run in runArray { let runGlyphCount = CTRunGetGlyphCount(run as! CTRun); // Ask for the width of each glyph in turn. for runGlyphIndex in 0 ..< runGlyphCount { let i = runGlyphIndex + glyphOffset let runGlyphRange = CFRangeMake(runGlyphIndex, 1) let runTypographicWidth = CGFloat(CTRunGetTypographicBounds(run as! CTRun, runGlyphRange, nil, nil, nil)) let newGlyphArcInfo = GlyphArcInfo(width:runTypographicWidth,angle:0) glyphArcInfo.insert(newGlyphArcInfo, at:i) } glyphOffset += runGlyphCount; } let lineLength = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil)) var info = glyphArcInfo.first! var prevHalfWidth:CGFloat = info.width / 2.0; info.angle = (prevHalfWidth / lineLength) * CGFloat(angleLenght!) var angleArc = info.angle // Divide the arc into slices such that each one covers the distance from one glyph's center to the next. for lineGlyphIndex:CFIndex in 1 ..< glyphCount { let halfWidth = glyphArcInfo[lineGlyphIndex].width / 2.0; let prevCenterToCenter:CGFloat = prevHalfWidth + halfWidth; let glyphAngle = (prevCenterToCenter / lineLength) * CGFloat(angleLenght!) angleArc += glyphAngle //OMLog.printd("\(self.name ?? ""): #\(lineGlyphIndex) angle : \(CPCAngle.format(Double(glyphAngle))) arc length :\(CPCAngle.format(Double(angleArc)))") glyphArcInfo[lineGlyphIndex].angle = glyphAngle prevHalfWidth = halfWidth } return glyphArcInfo; } func drawWithArc(context:CGContext, rect:CGRect) { OMLog.printd("\(self.name ?? ""): drawWithArc(\(rect))") if let string = string, let angle = self.angleLenght { let attributeString = self.stringWithAttributes(string) let line = CTLineCreateWithAttributedString(attributeString) let glyphCount:CFIndex = CTLineGetGlyphCount(line); if glyphCount == 0 { OMLog.printw("\(self.name ?? ""): 0 glyphs \(attributeString))") return; } let glyphArcInfo = prepareGlyphArcInfo(line: line,glyphCount: glyphCount,angle: angle) if glyphArcInfo.count > 0 { // Move the origin from the lower left of the view nearer to its center. context.saveGState(); context.translateBy(x: rect.midX, y: rect.midY) // Rotate the context 90 degrees counterclockwise. context.rotate(by: CGFloat(M_PI_2)); // Now for the actual drawing. The angle offset for each glyph relative to the previous glyph has already been // calculated; with that information in hand, draw those glyphs overstruck and centered over one another, making sure // to rotate the context after each glyph so the glyphs are spread along a semicircular path. var textPosition = CGPoint(x:0.0,y: self.radiusRatio * minRadius(rect.size)); context.textPosition = textPosition let runArray = CTLineGetGlyphRuns(line); let runCount = CFArrayGetCount(runArray); var glyphOffset:CFIndex = 0; for runIndex:CFIndex in 0 ..< runCount { let run = (runArray as NSArray)[runIndex] let runGlyphCount:CFIndex = CTRunGetGlyphCount(run as! CTRun); for runGlyphIndex:CFIndex in 0 ..< runGlyphCount { let glyphRange:CFRange = CFRangeMake(runGlyphIndex, 1); let angleRotation:CGFloat = -(glyphArcInfo[runGlyphIndex + glyphOffset].angle); //OMLog.printd("\(self.name ?? ""): run glyph#\(runGlyphIndex) angle rotation : \(CPCAngle.format(Double(angleRotation)))"); context.rotate(by: angleRotation); // Center this glyph by moving left by half its width. let glyphWidth:CGFloat = glyphArcInfo[runGlyphIndex + glyphOffset].width; let halfGlyphWidth:CGFloat = glyphWidth / 2.0; let positionForThisGlyph:CGPoint = CGPoint(x:textPosition.x - halfGlyphWidth, y:textPosition.y); // Glyphs are positioned relative to the text position for the line, // so offset text position leftwards by this glyph's width in preparation for the next glyph. textPosition.x -= glyphWidth; var textMatrix = CTRunGetTextMatrix(run as! CTRun) textMatrix.tx = positionForThisGlyph.x; textMatrix.ty = positionForThisGlyph.y; context.textMatrix = textMatrix; CTRunDraw(run as! CTRun, context, glyphRange); } glyphOffset += runGlyphCount; } context.restoreGState(); } } } }
apache-2.0
e8c85faa2bb042a082990ef1acde31df
34.179903
164
0.543997
5.742328
false
false
false
false
noprom/swiftmi-app
swiftmi/swiftmi/MyController.swift
2
4192
// // MyController.swift // swiftmi // // Created by yangyin on 15/4/14. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit import Kingfisher import Alamofire import SwiftyJSON class MyController: UITableViewController { var profileHeaderView:ProfileHeaderView? var currentUser:Users? @IBOutlet weak var logoutCell: UITableViewCell! @IBOutlet weak var signatureLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! override func viewDidAppear(animated: Bool) { loadCurrentUser() self.clearAllNotice() } private func loadCurrentUser() { if currentUser == nil { let token = KeychainWrapper.stringForKey("token") if token != nil { let dalUser = UsersDal() currentUser = dalUser.getCurrentUser() } if currentUser != nil { self.profileHeaderView?.setData(self.currentUser!) self.emailLabel.text = self.currentUser?.email self.signatureLabel.text = self.currentUser?.signature self.logoutCell.hidden = false }else { self.logoutCell.hidden = true } } } override func viewDidLoad() { super.viewDidLoad() self.setView() } func setView() { self.profileHeaderView = ProfileHeaderView.viewFromNib()! self.profileHeaderView?.frame = CGRectMake(0,0,self.view.frame.width,280); self.tableView.tableHeaderView = self.profileHeaderView! self.profileHeaderView?.tapLoginCallBack = { let toViewController:LoginController = Utility.GetViewController("loginController") self.navigationController?.pushViewController(toViewController, animated: true) return true } } private func logout() { if KeychainWrapper.hasValueForKey("token") { KeychainWrapper.removeObjectForKey("token") self.currentUser = nil Router.token = "" } self.emailLabel.text = "" self.signatureLabel.text = "" self.profileHeaderView?.resetData() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func scrollViewDidScroll(scrollView: UIScrollView) { self.profileHeaderView?.scrollViewDidScroll(scrollView) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 2 && indexPath.row == 0 { self.logout() } else if indexPath.section == 1 && indexPath.row == 0 { let url = NSURL(string: "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=993402332") UIApplication.sharedApplication().openURL(url!) //self.logout() /* var webViewController:WebViewController = Utility.GetViewController("webViewController") webViewController.webUrl = "http://www.swiftmi.com/timeline" webViewController.title = " 关于Swift迷 " webViewController.isPop = true self.navigationController?.pushViewController(webViewController, animated: 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. } */ }
mit
1b001a2a9c4abb4ec7b83d568d61079b
26.708609
151
0.578394
5.700272
false
false
false
false
kenny2006cen/GYXMPP
HMModules/HMBaseKit/HMBaseKit/Classes/HMExtension/UIView+Extension.swift
1
12051
// // UIView+Extension.swift // HMBaseKit // // Created by Ko Lee on 2019/8/21. // import UIKit public extension UIView { ///初始化View 设置背景颜色 class func hm_view(_ backgroundColor: UIColor) -> Self { return hm_basekit_view(backgroundColor) } ///初始化View 设置背景颜色、圆角 class func hm_view(_ backgroundColor: UIColor, _ cornerRadius: CGFloat) -> Self { return hm_basekit_view(backgroundColor, cornerRadius) } ///设置View 背景颜色、圆角 func hm_view(_ backgroundColor: UIColor, _ cornerRadius: CGFloat) { hm_basekit_view(backgroundColor, cornerRadius) } /// 水平渐变 func hm_horizontalGradientLayer(_ startColor: UIColor, _ endColor: UIColor, _ cornerRadius:CGFloat) { hm_basekit_horizontalGradientLayer(startColor, endColor, cornerRadius) } /// 垂直渐变 func hm_verticalGradientLayer(_ startColor: UIColor, _ endColor: UIColor, _ cornerRadius:CGFloat) { hm_basekit_verticalGradientLayer(startColor, endColor, cornerRadius) } ///设置多角圆角 func hm_roundingCorner(_ corners: UIRectCorner, _ radii: CGFloat) { hm_basekit_roundingCorner(corners, radii) } ///给View添加阴影 func hm_shadow( _ shadowColor:UIColor, _ shadowOffset:CGSize, _ shadowOpacity:Float, _ shadowRadius:CGFloat, _ cornerRadius:CGFloat) { hm_basekit_shadow(shadowColor, shadowOffset, shadowOpacity, shadowRadius, cornerRadius) } ///给View添加阴影和边框 func hm_shadowBorder( _ shadowColor:UIColor, _ shadowOffset:CGSize, _ shadowOpacity:Float, _ shadowRadius:CGFloat, _ cornerRadius:CGFloat, _ borderColor: UIColor) { hm_basekit_shadowBorder(shadowColor, shadowOffset, shadowOpacity, shadowRadius, cornerRadius,borderColor) } ///获取当前View的控制器 func hm_viewGetcurrentVC() -> UIViewController? { return hm_basekit_viewGetcurrentVC() } ///view转图片 func hm_viewToImage() -> UIImage { return hm_basekit_viewToImage() } /// 点击手势(默认代理和target相同) func hm_tapGesture(_ target: Any?,_ action: Selector,_ numberOfTapsRequired: Int = 1) { hm_basekit_tapGesture(target, action, numberOfTapsRequired) } /// 长按手势(默认代理和target相同) func hm_longGesture(_ target: Any?,_ action: Selector,_ minDuration: TimeInterval = 0.5) { hm_basekit_longGesture(target, action, minDuration) } /// 部分圆角 func hm_partOfRadius(_ corners: UIRectCorner,_ radius: CGFloat) { hm_basekit_partOfRadius(corners, radius) } /// 截图(带导航则用导航控制器的view或keywindow) func hm_screenshotImage() -> UIImage? { return hm_basekit_screenshotImage() } } //MARK: --- 获取值 public extension UIView { var height:CGFloat { get { return frame.height } set(newValue){ var tempFrame = self.frame tempFrame.size.height = newValue self.frame = tempFrame } } var width:CGFloat { get{ return frame.width } set(newValue){ var tempFrame = frame tempFrame.size.width = newValue frame = tempFrame } } var x:CGFloat { get{ return frame.origin.x } set(newValue){ var tempFrame = frame tempFrame.origin.x = newValue frame = tempFrame } } var centerX:CGFloat { get{ return center.x } set(newValue){ var tempCenter = center tempCenter.x = newValue center = tempCenter } } var centerY:CGFloat { get{ return center.y } set(newValue){ var tempCenter = center tempCenter.y = newValue center = tempCenter } } var y:CGFloat { get{ return frame.origin.y } set(newValue){ var tempFrame = frame tempFrame.origin.y = newValue frame = tempFrame } } /// left值 var left: CGFloat { get { return frame.origin.x } set { var tempFrame = frame tempFrame.origin.x = newValue frame = tempFrame } } /// top值 var top: CGFloat { get { return frame.origin.y } set { var tempFrame = frame tempFrame.origin.y = newValue frame = tempFrame } } /// right值 var right: CGFloat { get { return frame.origin.x + frame.size.width } set { var tempFrame = frame tempFrame.origin.x = newValue - frame.size.width frame = tempFrame } } /// bottom值 var bottom: CGFloat { get { return frame.origin.y + frame.size.height } set { var tempFrame = frame tempFrame.origin.y = newValue - frame.size.height frame = tempFrame } } /// size值 var size: CGSize { get { return frame.size } set { var tempFrame = frame tempFrame.size = newValue frame = tempFrame } } /// origin值 var origin: CGPoint { get { return frame.origin } set { var tempFrame = frame tempFrame.origin = newValue frame = tempFrame } } } //MARK: --- 创建View fileprivate extension UIView { class func hm_basekit_view(_ backgroundColor: UIColor) -> Self { let view = self.init() view.backgroundColor = backgroundColor return view } class func hm_basekit_view(_ backgroundColor: UIColor, _ cornerRadius: CGFloat) -> Self { let view = hm_basekit_view(backgroundColor) view.layer.masksToBounds = true view.layer.cornerRadius = cornerRadius return view } func hm_basekit_view(_ backgroundColor: UIColor, _ cornerRadius: CGFloat) { self.backgroundColor = backgroundColor self.layer.masksToBounds = true self.layer.cornerRadius = cornerRadius } } //MARK: --- 常用的方法 fileprivate extension UIView { /// 点击手势(默认代理和target相同) func hm_basekit_tapGesture(_ target: Any?,_ action: Selector,_ numberOfTapsRequired: Int = 1) { let tapGesture = UITapGestureRecognizer(target: target, action: action) tapGesture.numberOfTapsRequired = numberOfTapsRequired tapGesture.delegate = target as? UIGestureRecognizerDelegate self.isUserInteractionEnabled = true self.addGestureRecognizer(tapGesture) } /// 长按手势(默认代理和target相同) func hm_basekit_longGesture(_ target: Any?,_ action: Selector,_ minDuration: TimeInterval = 0.5) { let longGesture = UILongPressGestureRecognizer(target: target, action: action) longGesture.minimumPressDuration = minDuration longGesture.delegate = target as? UIGestureRecognizerDelegate self.isUserInteractionEnabled = true self.addGestureRecognizer(longGesture) } /// 部分圆角 func hm_basekit_partOfRadius(_ corners: UIRectCorner,_ radius: CGFloat) { let shapeLayer = CAShapeLayer() shapeLayer.frame = self.bounds shapeLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)).cgPath self.layer.mask = shapeLayer } /// 截图(带导航则用导航控制器的view或keywindow) func hm_basekit_screenshotImage() -> UIImage? { UIGraphicsBeginImageContext(self.bounds.size) if self.responds(to: #selector(UIView.drawHierarchy(in:afterScreenUpdates:))) { self.drawHierarchy(in: self.bounds, afterScreenUpdates: false) } else if self.layer.responds(to: #selector(CALayer.render(in:) )) { self.layer.render(in: UIGraphicsGetCurrentContext()!) } else { return nil } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } ///设置圆角或者边框 func hm_basekit_borderRadius(_ cornerRadius: CGFloat, _ masksToBounds: Bool, _ borderColor:UIColor = .clear, _ borderWidth: CGFloat = 0.0) { self.layer.masksToBounds = masksToBounds self.layer.cornerRadius = cornerRadius self.layer.borderColor = borderColor.cgColor self.layer.borderWidth = borderWidth } /// 水平渐变 func hm_basekit_horizontalGradientLayer(_ startColor: UIColor, _ endColor: UIColor, _ cornerRadius:CGFloat) { let gradient = CAGradientLayer() gradient.frame = self.bounds gradient.colors = [startColor.cgColor, endColor.cgColor] gradient.startPoint = CGPoint(x: 0, y: 0) gradient.endPoint = CGPoint(x: 1, y: 0) gradient.cornerRadius = cornerRadius self.layer.insertSublayer(gradient, at: 0) } /// 垂直渐变 func hm_basekit_verticalGradientLayer(_ startColor: UIColor, _ endColor: UIColor, _ cornerRadius:CGFloat) { let gradient = CAGradientLayer() gradient.frame = self.bounds gradient.colors = [startColor.cgColor, endColor.cgColor] gradient.startPoint = CGPoint(x: 0, y: 0) gradient.endPoint = CGPoint(x: 0, y: 1) gradient.cornerRadius = cornerRadius self.layer.insertSublayer(gradient, at: 0) } func hm_basekit_roundingCorner(_ corners: UIRectCorner, _ radii: CGFloat) { let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii)) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds maskLayer.path = maskPath.cgPath self.layer.mask = maskLayer } ///给View添加阴影 func hm_basekit_shadow( _ shadowColor:UIColor, _ shadowOffset:CGSize, _ shadowOpacity:Float, _ shadowRadius:CGFloat, _ cornerRadius:CGFloat) { self.layer.shadowColor = shadowColor.cgColor self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = shadowRadius self.layer.shadowOffset = shadowOffset self.layer.cornerRadius = cornerRadius } ///给View添加阴影和边框 func hm_basekit_shadowBorder( _ shadowColor:UIColor, _ shadowOffset:CGSize, _ shadowOpacity:Float, _ shadowRadius:CGFloat, _ cornerRadius:CGFloat, _ borderColor: UIColor) { self.layer.shadowColor = shadowColor.cgColor self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = shadowRadius self.layer.shadowOffset = shadowOffset self.layer.cornerRadius = cornerRadius self.layer.borderColor = borderColor.cgColor self.layer.borderWidth = 1.0 } ///获取当前View的控制器 func hm_basekit_viewGetcurrentVC() -> UIViewController? { var nextResponder: UIResponder? = self repeat { nextResponder = nextResponder?.next if let viewController = nextResponder as? UIViewController { return viewController } } while nextResponder != nil return nil } func hm_basekit_viewToImage() -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } }
mit
4635141a716ee73fbbb5d89cedfc8f07
29.736148
176
0.608464
4.857798
false
false
false
false
MacRemote/RemoteFoundation
MRFoundation/MRRemoteControlServer.swift
1
6110
// // MRRemoteControlServer.swift // Remote Foundation // // Created by Tom Hu on 6/13/15. // Copyright (c) 2015 Tom Hu. All rights reserved. // import Foundation import CocoaAsyncSocket // TODO: Consider about handling disconnection/error #if os(iOS) import UIKit #endif // MARK: - Server Delegate Protocol // TODO: Complete this protocol @objc public protocol MRRemoteControlServerDelegate { @objc optional func remoteControlServerDidReceiveEvent(event: MREvent) } public class MRRemoteControlServer: NSObject, NSNetServiceDelegate, GCDAsyncSocketDelegate { // MARK: - Singleton public static let sharedServer: MRRemoteControlServer = MRRemoteControlServer() // MARK: - Delegate public weak var delegate: MRRemoteControlServerDelegate? // MARK: - Member Variables private(set) var service: NSNetService! private(set) var socket: GCDAsyncSocket! // MARK: - Life Circle private override init() { print("Server init") super.init() } deinit { print("Server deinit") stopBroadCasting() disconnect() } public func startBroadCasting(port aPort: UInt16 = 0) { self.socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) do { try self.socket.acceptOnPort(aPort) var deviceName: String = "Default Name" #if os(iOS) deviceName = UIDevice.currentDevice().name #elseif os(OSX) if let name = NSHost.currentHost().name { deviceName = name } #endif self.service = NSNetService(domain: "", type: "_macremote._tcp.", name: "", port: Int32(self.socket.localPort)) if #available(iOS 7.0, OSX 10.10, *) { print("includes peer to peer") self.service.includesPeerToPeer = true } self.service.delegate = self self.service.publish() } catch let error as NSError { print("Unable to create socket. Error \(error)") } } public func disconnect() { self.socket.disconnect() self.socket.delegate = nil self.socket = nil } public func stopBroadCasting() { self.service.stop() self.service.delegate = nil self.service = nil self.disconnect() } // MARK: - GCDAsyncSocketDelegate public func socket(sock: GCDAsyncSocket!, didAcceptNewSocket newSocket: GCDAsyncSocket!) { print("Accepted new socket") self.socket = newSocket // Read Header self.socket.readDataToLength(UInt(sizeof(MRHeaderSizeType)), withTimeout: -1.0, tag: MRPacketTag.Header.rawValue) } public func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) { print("Disconnected: error \(err)") if err != nil { self.socket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) do { try self.socket.acceptOnPort(UInt16(self.service.port)) print("Re listen") } catch let error as NSError { print("Error: \(error)") } } } public func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { // println("Read data") if data.length == sizeof(MRHeaderSizeType) { // Header let bodyLength: MRHeaderSizeType = parseHeader(data) // Read Body sock.readDataToLength(UInt(bodyLength), withTimeout: -1, tag: MRPacketTag.Body.rawValue) } else { // Body if let body = NSString(data: data, encoding: NSUTF8StringEncoding) { print("Body: \(body)") // Handle ios notification } else if let event = MREvent(data: data) { print("Event: \(event)") // Handle event self.delegate?.remoteControlServerDidReceiveEvent?(event) } // Read Header sock.readDataToLength(UInt(sizeof(MRHeaderSizeType)), withTimeout: -1, tag: MRPacketTag.Header.rawValue) } } public func socket(sock: GCDAsyncSocket!, didWriteDataWithTag tag: Int) { print("Wrote data with tag: \(tag)") } // MARK: NSNetServiceDelegate public func netServiceWillPublish(sender: NSNetService) { print("Net Service Will Publish!") } public func netServiceDidPublish(sender: NSNetService) { print("Net Service Did Publish!") print("Service Name: \(sender.name)") print("Port: \(sender.port)") } public func netService(sender: NSNetService, didNotPublish errorDict: [String : NSNumber]) { print("Net Service Did Not Publish!") print("Error: \(errorDict)") } public func netServiceWillResolve(sender: NSNetService) { print("Net Service Will Resolve!") } public func netServiceDidResolveAddress(sender: NSNetService) { print("Net Service Did Resolve Address!") print("Sender: \(sender)") } public func netService(sender: NSNetService, didNotResolve errorDict: [String : NSNumber]) { print("Net Service Did Not Resolve!") print("Error: \(errorDict)") } public func netServiceDidStop(sender: NSNetService) { print("Net Service Did Stop!") } public func netService(sender: NSNetService, didUpdateTXTRecordData data: NSData) { print("Net Service Did Update TXT Record Data!") print("Data: \(data)") } public func netService(sender: NSNetService, didAcceptConnectionWithInputStream inputStream: NSInputStream, outputStream: NSOutputStream) { print("Net Service Did Accept Connection With Input Stream!") print("Input Stream: \(inputStream)") print("Output Stream: \(outputStream)") } }
mit
c133a51f8d25efa906776ab2e2dc3302
30.333333
143
0.599509
4.891914
false
false
false
false
IvanVorobei/RequestPermission
Source/SPPermission/Dialog/Views/SPPermissionIconView.swift
2
4952
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPPermissionIconView: UIView { var type: IconType { didSet { self.setNeedsDisplay() } } var whiteColor = SPPermissionStyle.DefaultColors.white { didSet { self.setNeedsDisplay() } } var lightColor = SPPermissionStyle.DefaultColors.lightIcon { didSet { self.setNeedsDisplay() } } var mediumColor = SPPermissionStyle.DefaultColors.mediumIcon { didSet { self.setNeedsDisplay() } } var darkColor = SPPermissionStyle.DefaultColors.darkIcon { didSet { self.setNeedsDisplay() } } init() { self.type = .ball super.init(frame: CGRect.zero) self.commonInit() } init(type: IconType) { self.type = type super.init(frame: CGRect.zero) self.commonInit() } private func commonInit() { self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) switch type { case .camera: SPPermissionDraw.PermissionPack.drawCamera(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .photoLibrary: SPPermissionDraw.PermissionPack.drawPhotoLibrary(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .ball: SPPermissionDraw.PermissionPack.drawBall(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .micro: SPPermissionDraw.PermissionPack.drawMicro(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .book: SPPermissionDraw.PermissionPack.drawBook(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .documents: SPPermissionDraw.PermissionPack.drawDocuments(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .calendar: SPPermissionDraw.PermissionPack.drawCalendar(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .compass: SPPermissionDraw.PermissionPack.drawCompass(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .headphones: SPPermissionDraw.PermissionPack.drawHeadphones(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break case .windmill: SPPermissionDraw.PermissionPack.drawWindmill(frame: rect, resizing: .aspectFit, white: self.whiteColor, light: self.lightColor, medium: self.mediumColor, dark: self.darkColor) break } } public enum IconType { case camera case photoLibrary case ball case micro case calendar case book case documents case compass case headphones case windmill } }
mit
7d57cc1f240d0cf8ae826f0f0955992d
38.608
191
0.664512
4.820837
false
false
false
false
J-Mendes/Weather
Weather/WeatherUITests/SettingsTableViewControllerUITest.swift
1
3002
// // SettingsTableViewControllerUITest.swift // Weather // // Created by Jorge Mendes on 07/07/2017. // Copyright © 2017 Jorge Mendes. All rights reserved. // import XCTest class SettingsTableViewControllerUITest: XCTestCase { fileprivate var app: XCUIApplication! override func setUp() { super.setUp() continueAfterFailure = false self.app = XCUIApplication() self.app.launch() self.app.navigationBars.buttons["settings"].tap() } override func tearDown() { self.app = nil super.tearDown() } func testSettingsTitleExists() { let navigationBar: XCUIElement = self.app.navigationBars[TextUtils.localizedString("settings")] XCTAssert(navigationBar.exists) } func testTableViewHasCells() { XCTAssertTrue(self.app.tables.cells.count > 0) } func testLocationTitleExists() { let locationTitle: XCUIElement = self.app.tables.staticTexts[TextUtils.localizedString("location")] XCTAssert(locationTitle.exists) } func testUnitSectionTitleExists() { let unitTitle: XCUIElement = self.app.tables.staticTexts[TextUtils.localizedString("unit")] XCTAssert(unitTitle.exists) } func testImperialTitleExists() { let imperialTitle: XCUIElement = self.app.tables.staticTexts[TextUtils.localizedString("imperial")] XCTAssert(imperialTitle.exists) } func testMetricTitleExists() { let metricTitle: XCUIElement = self.app.tables.staticTexts[TextUtils.localizedString("metric")] XCTAssert(metricTitle.exists) } func testBackButtonExists() { let backButton: XCUIElement = self.app.navigationBars.buttons.element(boundBy: 0) XCTAssert(backButton.exists) } // MARK: Actions func testBackButton() { self.app.navigationBars.buttons.element(boundBy: 0).tap() XCTAssertTrue(self.app.navigationBars.staticTexts.count > 0) } func testImperialUnitsChange() { self.app.tables.staticTexts[TextUtils.localizedString("imperial")].tap() self.app.navigationBars.buttons.element(boundBy: 0).tap() sleep(3) let unitView: XCUIElement = self.app.tables.staticTexts["F"] XCTAssert(unitView.exists) } func testMetricUnitsChange() { self.app.tables.staticTexts[TextUtils.localizedString("metric")].tap() self.app.navigationBars.buttons.element(boundBy: 0).tap() sleep(3) let unitView: XCUIElement = self.app.tables.staticTexts["C"] XCTAssert(unitView.exists) } func testNavigateToLocation() { self.app.tables.staticTexts[TextUtils.localizedString("location")].tap() let navigationBar: XCUIElement = self.app.navigationBars[TextUtils.localizedString("location")] XCTAssert(navigationBar.exists) } }
gpl-3.0
af7d3bb00d8d179de0c7d285ccaa2bfe
29.313131
107
0.651783
4.8016
false
true
false
false
mactive/rw-courses-note
AdvancedSwift3/AdvanceSwift3_rw70.playground/Pages/CustomOperator_CGPoint.xcplaygroundpage/Contents.swift
1
1615
//: Playground - noun: a place where people can play import UIKit import UIKit extension CGPoint { static func *(lhs: CGPoint, rhs: CGAffineTransform) -> CGPoint { return lhs.applying(rhs) } } extension CGAffineTransform { static func *(lhs: CGAffineTransform, rhs:CGAffineTransform) -> CGAffineTransform { return lhs.concatenating(rhs) } } func *(points: [CGPoint], transform: CGAffineTransform) -> [CGPoint] { return points.map{ $0 * transform} } import PlaygroundSupport extension UIBezierPath { convenience init(from points:[CGPoint]) { self.init() guard let first = points.first else { return } move(to: first) for point in points.dropFirst() { addLine(to: point) } close() } } let points: [CGPoint] = [ CGPoint(x: -1, y: -1), CGPoint(x: 1, y: -1), CGPoint(x: 1, y: 1), CGPoint(x: 0, y: 2), CGPoint(x: -1, y: 1) ] // 放大 30倍 let modelToScale = CGAffineTransform(scaleX: 30, y: 30) // 旋转 180/8 degree let scaleToRotated = CGAffineTransform(rotationAngle: .pi/8) // 向左向右移动各100 let rotatedToTranslated = CGAffineTransform(translationX: 100, y:100) let scaledRotatedAndTranslated = points * modelToScale * scaleToRotated * rotatedToTranslated let path = UIBezierPath(from: scaledRotatedAndTranslated) let layer = CAShapeLayer() layer.path = path.cgPath layer.strokeColor = UIColor.cyan.cgColor let view = UIView(frame: CGRect(x:0, y:0, width: 200, height:200)) view.layer.addSublayer(layer) PlaygroundPage.current.liveView = view
mit
a6f28485dc299e30672c6eb3749c67dc
22.397059
93
0.668133
3.743529
false
false
false
false
skedgo/tripkit-ios
Examples/TripKitUIExample/Autocompleter/InMemoryFavoriteManager.swift
1
2051
// // InMemoryFavoriteManager.swift // TripKitUIExample // // Created by Kuan Lun Huang on 3/12/19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import Foundation import MapKit import TripKitUI class InMemoryFavoriteManager { struct Favorite: Hashable { let annotation: MKAnnotation func hash(into hasher: inout Hasher) { if let hashable = annotation as? AnyHashable { hasher.combine(hashable) } else { hasher.combine(annotation.description) } } } static let shared = InMemoryFavoriteManager() var favorites: [Favorite] = [] func hasFavorite(for annotation: MKAnnotation) -> Bool { return favorite(for: annotation) != nil } func toggleFavorite(for annotation: MKAnnotation) { if let favorite = favorite(for: annotation) { remove(favorite) } else { add(annotation) } } private func add(_ annotation: MKAnnotation) { guard !hasFavorite(for: annotation) else { print("The favorite already exists, skipping") return } print("Adding a favorite") favorites.append(Favorite(annotation: annotation)) } private func remove(_ favorite: Favorite) { guard let index = favorites.firstIndex(of: favorite) else { print("Trying to remove a non-existent favorite") return } print("Removing a favorite: \(favorite)") favorites.remove(at: index) } private func favorite(for annotation: MKAnnotation) -> Favorite? { if let aStop = annotation as? TKUIStopAnnotation { return favorites.first { ($0.annotation as? TKUIStopAnnotation)?.stopCode == aStop.stopCode } } else { return nil } } } extension InMemoryFavoriteManager.Favorite: Equatable { static func == (lhs: InMemoryFavoriteManager.Favorite, rhs: InMemoryFavoriteManager.Favorite) -> Bool { return lhs.annotation.coordinate.latitude == rhs.annotation.coordinate.latitude && lhs.annotation.coordinate.longitude == rhs.annotation.coordinate.longitude } }
apache-2.0
1a0e8b7b41428f0a0c7c78de2a1701d5
24.625
161
0.676585
4.555556
false
false
false
false
AlanEnjoy/Live
Live/Live/Classes/Main/Model/AnchorModel.swift
1
839
// // AnchorModel.swift // Live // // Created by Alan's Macbook on 2017/7/7. // Copyright © 2017年 zhushuai. All rights reserved. // import UIKit class AnchorModel: NSObject { ///房间ID var room_id : Int = 0 ///间图片对应URL var vertical_src : String = "" ///判断是手机直播还是电脑直播 ///0:电脑直播 1:手机直播 var isVertical : Int = 0 ///房间名称 var room_name : String = "" ///主播昵称 var nickname : String = "" ///观看人数 var online : Int = 0 ///所在城市 var anchor_city : String = " " init(dict : [String : NSObject]){ super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
mit
722435e56245293b93a7ce54c5437edf
16
72
0.525401
3.816327
false
false
false
false
apple/swift-format
Sources/SwiftFormatCore/LegacyTriviaBehavior.swift
1
1799
import SwiftSyntax /// Rewrites the trivia on tokens in the given source file to restore the legacy trivia behavior /// before https://github.com/apple/swift-syntax/pull/985 was merged. /// /// Eventually we should get rid of this and update the core formatting code to adjust to the new /// behavior, but this workaround lets us keep the current implementation without larger changes. public func restoringLegacyTriviaBehavior(_ sourceFile: SourceFileSyntax) -> SourceFileSyntax { return LegacyTriviaBehaviorRewriter().visit(sourceFile) } private final class LegacyTriviaBehaviorRewriter: SyntaxRewriter { /// Trivia that was extracted from the trailing trivia of a token to be prepended to the leading /// trivia of the next token. private var pendingLeadingTrivia: Trivia? override func visit(_ token: TokenSyntax) -> TokenSyntax { var token = token if let pendingLeadingTrivia = pendingLeadingTrivia { token = token.withLeadingTrivia(pendingLeadingTrivia + token.leadingTrivia) self.pendingLeadingTrivia = nil } if token.nextToken != nil, let firstIndexToMove = token.trailingTrivia.firstIndex(where: shouldTriviaPieceBeMoved) { pendingLeadingTrivia = Trivia(pieces: Array(token.trailingTrivia[firstIndexToMove...])) token = token.withTrailingTrivia(Trivia(pieces: Array(token.trailingTrivia[..<firstIndexToMove]))) } return token } } /// Returns a value indicating whether the given trivia piece should be moved from a token's /// trailing trivia to the leading trivia of the following token to restore the legacy trivia /// behavior. private func shouldTriviaPieceBeMoved(_ piece: TriviaPiece) -> Bool { switch piece { case .spaces, .tabs, .unexpectedText: return false default: return true } }
apache-2.0
292ffa4491219629358ca5bb8df51a39
39.886364
98
0.752084
4.797333
false
false
false
false
Acidburn0zzz/firefox-ios
Extensions/Today/ButtonWithSublabel.swift
1
1820
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit class ButtonWithSublabel: UIButton { lazy var subtitleLabel = UILabel() lazy var label = UILabel() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } convenience init() { self.init(frame: .zero) } override init(frame: CGRect) { super.init(frame: frame) performLayout() } fileprivate func performLayout() { let buttonImage = self.imageView! self.titleLabel?.removeFromSuperview() addSubview(self.label) addSubview(self.subtitleLabel) buttonImage.adjustsImageSizeForAccessibilityContentSizeCategory = true buttonImage.contentMode = .scaleAspectFit buttonImage.snp.makeConstraints { make in make.left.centerY.equalTo(10) make.width.equalTo(self.label.snp.height) } self.label.snp.makeConstraints { make in make.left.equalTo(buttonImage.snp.right).offset(10) make.trailing.top.equalTo(self) } self.label.numberOfLines = 2 self.label.lineBreakMode = .byWordWrapping label.sizeToFit() self.subtitleLabel.lineBreakMode = .byTruncatingTail self.subtitleLabel.snp.makeConstraints { make in make.bottom.equalTo(self).inset(10) make.top.equalTo(self.label.snp.bottom) make.leading.trailing.equalTo(self.label) } } override func setTitle(_ text: String?, for state: UIControl.State) { self.label.text = text super.setTitle(text, for: state) } }
mpl-2.0
5701a97134946e153cb8c9033d309e98
32.090909
78
0.643407
4.482759
false
false
false
false
practicalswift/swift
test/decl/protocol/req/func.swift
13
7741
// RUN: %target-typecheck-verify-swift -enable-objc-interop // Test function requirements within protocols, as well as conformance to // said protocols. // Simple function protocol P1 { func f0() } // Simple match struct X1a : P1 { func f0() {} } // Simple match selecting among two overloads. struct X1b : P1 { func f0() -> Int {} func f0() {} } // Function with an associated type protocol P2 { associatedtype Assoc : P1 // expected-note{{ambiguous inference of associated type 'Assoc': 'X1a' vs. 'X1b'}} // expected-note@-1{{protocol requires nested type 'Assoc'}} func f1(_ x: Assoc) // expected-note{{protocol requires function 'f1' with type '(X2w.Assoc) -> ()'}} expected-note{{protocol requires function 'f1' with type '(X2y.Assoc) -> ()'}} } // Exact match. struct X2a : P2 { typealias Assoc = X1a func f1(_ x: X1a) {} } // Select among overloads. struct X2d : P2 { typealias Assoc = X1a func f1(_ x: Int) { } func f1(_ x: X1a) { } } struct X2e : P2 { typealias Assoc = X1a func f1(_ x: X1b) { } func f1(_ x: X1a) { } } // Select among overloads distinguished by name. struct X2f : P2 { typealias Assoc = X1a func f1(y: X1a) { } func f1(_ x: X1a) { } } // Infer associated type from function parameter struct X2g : P2 { func f1(_ x: X1a) { } } // Static/non-static mismatch. struct X2w : P2 { // expected-error{{type 'X2w' does not conform to protocol 'P2'}} typealias Assoc = X1a static func f1(_ x: X1a) { } // expected-note{{candidate operates on a type, not an instance as required}} } // Deduction of type that doesn't meet requirements struct X2x : P2 { // expected-error{{type 'X2x' does not conform to protocol 'P2'}} func f1(x: Int) { } } // Mismatch in parameter types struct X2y : P2 { // expected-error{{type 'X2y' does not conform to protocol 'P2'}} typealias Assoc = X1a func f1(x: X1b) { } } // Ambiguous deduction struct X2z : P2 { // expected-error{{type 'X2z' does not conform to protocol 'P2'}} func f1(_ x: X1a) { } // expected-note{{matching requirement 'f1' to this declaration inferred associated type to 'X1a'}} func f1(_ x: X1b) { } // expected-note{{matching requirement 'f1' to this declaration inferred associated type to 'X1b'}} } // Protocol with prefix unary function prefix operator ~~ protocol P3 { associatedtype Assoc : P1 static prefix func ~~(_: Self) -> Assoc // expected-note{{protocol requires function '~~' with type '(X3z) -> X3z.Assoc'}} } // Global operator match struct X3a : P3 { typealias Assoc = X1a } prefix func ~~(_: X3a) -> X1a {} // FIXME: Add example with overloaded prefix/postfix // Prefix/postfix mismatch. struct X3z : P3 { // expected-error{{type 'X3z' does not conform to protocol 'P3'}} typealias Assoc = X1a } postfix func ~~(_: X3z) -> X1a {} // expected-note{{candidate is postfix, not prefix as required}} // Protocol with postfix unary function postfix operator ~~ protocol P4 { associatedtype Assoc : P1 static postfix func ~~ (_: Self) -> Assoc // expected-note{{protocol requires function '~~' with type '(X4z) -> X4z.Assoc'}} } // Global operator match struct X4a : P4 { typealias Assoc = X1a } postfix func ~~(_: X4a) -> X1a {} // Prefix/postfix mismatch. struct X4z : P4 { // expected-error{{type 'X4z' does not conform to protocol 'P4'}} typealias Assoc = X1a } prefix func ~~(_: X4z) -> X1a {} // expected-note{{candidate is prefix, not postfix as required}} // Objective-C protocol @objc protocol P5 { func f2(_ x: Int, withInt a: Int) func f2(_ x: Int, withOtherInt a: Int) } // Exact match. class X5a : P5 { @objc func f2(_ x: Int, withInt a: Int) {} @objc func f2(_ x: Int, withOtherInt a: Int) {} } // Body parameter names can vary. class X5b : P5 { @objc func f2(_ y: Int, withInt a: Int) {} @objc func f2(_ y: Int, withOtherInt a: Int) {} } class X5c : P5 { @objc func f2(_ y: Int, withInt b: Int) {} @objc func f2(_ y: Int, withOtherInt b: Int) {} } // Names need to match up for an Objective-C protocol as well. class X5d : P5 { @objc(f2WithY:withInt:) func f2(_ y: Int, withInt a: Int) {} // expected-error {{Objective-C method 'f2WithY:withInt:' provided by method 'f2(_:withInt:)' does not match the requirement's selector ('f2:withInt:')}} @objc(f2WithY:withOtherValue:) func f2(_ y: Int, withOtherInt a: Int) {} // expected-error{{Objective-C method 'f2WithY:withOtherValue:' provided by method 'f2(_:withOtherInt:)' does not match the requirement's selector ('f2:withOtherInt:')}} } // Distinguish names within tuple arguments. typealias T0 = (x: Int, y: String) typealias T1 = (xx: Int, y: String) func f(_ args: T0) { } func f(_ args: T1) { } f(T0(1, "Hi")) infix operator ~>> : MaxPrecedence precedencegroup MaxPrecedence { higherThan: BitwiseShiftPrecedence } func ~>> (x: Int, args: T0) {} func ~>> (x: Int, args: T1) {} 3~>>T0(1, "Hi") 3~>>T1(2, "Hi") protocol Crankable { static func ~>> (x: Self, args: T0) static func ~>> (x: Self, args: T1) } extension Int : Crankable {} // Invalid witnesses. protocol P6 { func foo(_ x: Int) func bar(x: Int) // expected-note{{protocol requires function 'bar(x:)' with type '(Int) -> ()'}} } struct X6 : P6 { // expected-error{{type 'X6' does not conform to protocol 'P6'}} func foo(_ x: Missing) { } // expected-error{{use of undeclared type 'Missing'}} func bar() { } } protocol P6Ownership { func thunk__shared(_ x: __shared Int) func mismatch__shared(_ x: Int) func mismatch__owned(x: Int) func thunk__owned__owned(x: __owned Int) __consuming func inherits__consuming(x: Int) func mismatch__consuming(x: Int) __consuming func mismatch__consuming_mutating(x: Int) // expected-note {{protocol requires function 'mismatch__consuming_mutating(x:)' with type '(Int) -> ()'}} mutating func mismatch__mutating_consuming(x: Int) } struct X6Ownership : P6Ownership { // expected-error{{type 'X6Ownership' does not conform to protocol 'P6Ownership'}} func thunk__shared(_ x: Int) { } // OK func mismatch__shared(_ x: __shared Int) { } // OK func mismatch__owned(x: __owned Int) { } // OK func thunk__owned__owned(x: Int) { } // OK func inherits__consuming(x: Int) { } // OK __consuming func mismatch__consuming(x: Int) { } // OK mutating func mismatch__consuming_mutating(x: Int) { } // expected-note {{candidate is marked 'mutating' but protocol does not allow it}} __consuming func mismatch__mutating_consuming(x: Int) { } // OK - '__consuming' acts as a counterpart to 'nonmutating' } protocol P7 { func foo(_ x: Blarg) // expected-error{{use of undeclared type 'Blarg'}} } struct X7 : P7 { } // Selecting the most specialized witness. prefix operator %%% protocol P8 { func foo() } prefix func %%% <T : P8>(x: T) -> T { } protocol P9 : P8 { static prefix func %%% (x: Self) -> Self } struct X9 : P9 { func foo() {} } prefix func %%%(x: X9) -> X9 { } protocol P10 { associatedtype Assoc func bar(_ x: Assoc) } struct X10 : P10 { typealias Assoc = Int func bar(_ x: Int) { } func bar<T>(_ x: T) { } } protocol P11 { static func ==(x: Self, y: Self) -> Bool } protocol P12 { associatedtype Index : P1 // expected-note{{unable to infer associated type 'Index' for protocol 'P12'}} func getIndex() -> Index } struct XIndexType : P11 { } struct X12 : P12 { // expected-error{{type 'X12' does not conform to protocol 'P12'}} func getIndex() -> XIndexType { return XIndexType() } // expected-note{{candidate would match and infer 'Index' = 'XIndexType' if 'XIndexType' conformed to 'P1'}} } func ==(x: X12.Index, y: X12.Index) -> Bool { return true } protocol P13 {} protocol P14 { static prefix func %%%(_: Self.Type) } prefix func %%%<P: P13>(_: P.Type) { } struct X13: P14, P13 { }
apache-2.0
bf3cd2427d99b2308e41a5640a3da4cf
26.74552
244
0.651595
3.108835
false
false
false
false
mergesort/Communicado
Sources/Communicado/UIViewController+Sharing.swift
1
15713
import UIKit import MessageUI import Photos import Social import ObjectiveC.runtime /// A value returned for when sharing events occur. /// - success: Whether or not the share was successful or failed. /// - sharingService: A `UIActivityType` for which specific service was attempting to be shared. public typealias ShareResult = (success: Bool, sharingService: UIActivity.ActivityType) /// A unified completion handler after a share event occurs. public typealias SharingCompletedEvent = (ShareResult) -> Void /// A protocol for defining where the share functionality for `UIViewController`s exists. public protocol SharingCapableViewController: UIViewController {} public extension SharingCapableViewController { /// Share using UIActivityViewController. /// /// - Parameter parameters: Parameters that are applicable for sharing when using UIActivityViewController. func share(_ parameters: ActivityShareParameters) { self.shareIfPossible(destination: parameters.shareDestination) { let activityController = UIActivityViewController(activityItems: parameters.activityItems, applicationActivities: parameters.applicationActivites) activityController.excludedActivityTypes = parameters.excludedActivityTypes activityController.completionWithItemsHandler = { activityType, completed, returnedItems, activityError in parameters.completionItemsHandler?(activityType, completed, returnedItems, activityError) let sharingService = activityType ?? UIActivity.ActivityType.cancelled self.sharingCompleted?((success: (completed && activityError == nil), sharingService: sharingService)) } if UIDevice.current.userInterfaceIdiom == .pad { activityController.modalPresentationStyle = .popover self.present(activityController, animated: true, completion: nil) if let controller = activityController.popoverPresentationController { controller.permittedArrowDirections = .any controller.sourceView = parameters.sourceView } } else { self.present(activityController, animated: true, completion: nil) } } } /// Share to the Messages app. /// /// - Parameter parameters: Parameters that are applicable for sharing to Messages. func share(_ parameters: MessagesShareParameters) { self.shareIfPossible(destination: parameters.shareDestination) { self.temporarySharingBarButtonItemAttributes = UIBarButtonItem.appearance().titleTextAttributes(for: .normal) UIBarButtonItem.appearance().setTitleTextAttributes(self.sharingBarButtonItemAttributes, for: .normal) if let backgroundColor = self.sharingBackgroundColor { self.temporarySharingBackgroundImage = UINavigationBar.appearance().backgroundImage(for: UIBarMetrics.default) UINavigationBar.appearance().setBackgroundImage(UIImage(color: backgroundColor), for: UIBarMetrics.default) } let messageController = MFMessageComposeViewController() messageController.messageComposeDelegate = self messageController.body = parameters.message parameters.attachments?.forEach { attachment in messageController.addAttachmentData(attachment.data, typeIdentifier: attachment.attachmentType.identifier, filename: attachment.filename) } self.present(messageController, animated: true, completion: nil) } } /// Share to the Mail app. /// /// - Parameter parameters: Parameters that are applicable for sharing to Mail. func share(_ parameters: MailShareParameters) { self.shareIfPossible(destination: parameters.shareDestination) { self.temporarySharingBarButtonItemAttributes = UIBarButtonItem.appearance().titleTextAttributes(for: .normal) UIBarButtonItem.appearance().setTitleTextAttributes(self.sharingBarButtonItemAttributes, for: .normal) if let backgroundColor = self.sharingBackgroundColor { self.temporarySharingBackgroundImage = UINavigationBar.appearance().backgroundImage(for: UIBarMetrics.default) UINavigationBar.appearance().setBackgroundImage(UIImage(color: backgroundColor), for: UIBarMetrics.default) } let mailController = MFMailComposeViewController() mailController.navigationBar.titleTextAttributes = self.sharingTitleTextAttributes mailController.mailComposeDelegate = self mailController.setSubject(parameters.subject ?? "") mailController.setMessageBody(parameters.message ?? "", isHTML: parameters.isHTML) mailController.setToRecipients(parameters.toRecepients) mailController.setCcRecipients(parameters.ccRecepients) mailController.setBccRecipients(parameters.bccRecepients) parameters.attachments?.forEach { attachment in mailController.addAttachmentData(attachment.data, mimeType: attachment.attachmentType.identifier, fileName: attachment.filename) } self.present(mailController, animated: true, completion: nil) } } /// Share to a social network. /// This includes SocialNetwork.twitter, .facebook, .sinaWeibo, and .tencentWeibo. /// /// - Parameter parameters: Parameters that are applicable for sharing to a social network. @available(iOS, deprecated: 11.0) func share(_ parameters: SocialShareParameters) { self.shareIfPossible(destination: parameters.network) { let destination = parameters.network if let composeController = SLComposeViewController(forServiceType: destination.name) { composeController.setInitialText(parameters.message) parameters.urls.flatMap { $0 }?.lazy.forEach({ composeController.add($0) }) parameters.images.flatMap { $0 }?.lazy.forEach({ composeController.add($0) }) composeController.completionHandler = { result in let succeeded = (result == SLComposeViewControllerResult.done) self.sharingCompleted?((success: succeeded, sharingService: destination.activityType)) self.dismiss(animated: true, completion: nil) } self.present(composeController, animated: true, completion: nil) } } } /// Share to the user's pasteboard. /// /// - Parameter parameters: Parameters that are applicable for sharing to the pasteboard. func share(_ parameters: PasteboardShareParameters) { self.shareIfPossible(destination: parameters.shareDestination) { if let string = parameters.string { UIPasteboard.general.string = string } if let url = parameters.url { UIPasteboard.general.url = url } if let image = parameters.image { UIPasteboard.general.image = image } } } /// Share to the user's photo library. /// /// - Parameter parameters: Parameters that are applicable for sharing to the photo library. func share(_ parameters: PhotosShareParameters) { PHPhotoLibrary.shared().performChanges({ let changeRequest = PHAssetChangeRequest.creationRequestForAsset(from: parameters.image) changeRequest.creationDate = Date() }) { success, error in let saved = (error == nil && success) let activity = parameters.shareDestination.activityType self.sharingCompleted?((success: saved, sharingService: activity)) } } } extension UIViewController: MFMailComposeViewControllerDelegate { public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { // Reset the UIAppearance styles to what they were before we started UINavigationBar.appearance().setBackgroundImage(self.temporarySharingBackgroundImage, for: UIBarMetrics.default) if let temporarySharingBarButtonItemAttributes = self.temporarySharingBarButtonItemAttributes as? [NSAttributedString.Key : Any] { UIBarButtonItem.appearance().setTitleTextAttributes(temporarySharingBarButtonItemAttributes, for: .normal) } self.temporarySharingBackgroundImage = nil self.temporarySharingBarButtonItemAttributes = nil controller.dismiss(animated: true, completion: nil) let success = (result == MFMailComposeResult.sent || result == MFMailComposeResult.saved) let mailDestination = MailShareDestination() self.sharingCompleted?((success: success, sharingService: mailDestination.activityType)) } } extension UIViewController: MFMessageComposeViewControllerDelegate { public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) { // Reset the UIAppearance styles to what they were before we started UINavigationBar.appearance().setBackgroundImage(self.temporarySharingBackgroundImage, for: UIBarMetrics.default) if let temporarySharingBarButtonItemAttributes = self.temporarySharingBarButtonItemAttributes as? [NSAttributedString.Key : Any] { UIBarButtonItem.appearance().setTitleTextAttributes(temporarySharingBarButtonItemAttributes, for: .normal) } self.temporarySharingBackgroundImage = nil self.temporarySharingBarButtonItemAttributes = nil controller.dismiss(animated: true, completion: nil) let success = (result == MessageComposeResult.sent) let messagesDestination = MessagesShareDestination() self.sharingCompleted?((success: success, sharingService: messagesDestination.activityType)) } } private extension UIViewController { /// A method that determines whether we can currently share to a specified ShareDestination. /// /// - Parameter destination: The ShareDestination whose availability we should check. /// - Parameter canShareAction: The action to take if you can indeed share to a destination. func shareIfPossible(destination: ShareDestination, canShareAction: () -> Void) { if destination.canShare { canShareAction() } else { self.sharingCompleted?((success: false, sharingService: destination.activityType)) } } } // MARK: Associated objects public extension UIViewController { private enum AssociatedObjectKeys { static var sharingBarButtonItemAttributes = "UIViewController.sharingBarButtonItemAttributes" static var sharingTitleTextAttributes = "UIViewController.sharingTitleTextAttributes" static var sharingBackgroundColor = "UIViewController.sharingBackgroundColor" static var sharingCompleted = "UIViewController.sharingCompleted" static var temporarySharingBarButtonItemAttributes = "UIViewController.temporarySharingBarButtonItemAttributes" static var temporarySharingBackgroundImage = "UIViewController.temporarySharingBackgroundImage" } /// A property for configuring the `backgroundColor` on `MFMailComposeViewController` or `MFMessageComposeViewController`. var sharingBackgroundColor: UIColor? { get { return objc_getAssociatedObject(self, &AssociatedObjectKeys.sharingBackgroundColor) as? UIColor } set { objc_setAssociatedObject(self, &AssociatedObjectKeys.sharingBackgroundColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// A property for configuring the `titleTextAttributes` on `MFMailComposeViewController`. /// Unfortunately this does not work on `MFMessageComposeViewController`. var sharingTitleTextAttributes: [ NSAttributedString.Key : Any ]? { get { return objc_getAssociatedObject(self, &AssociatedObjectKeys.sharingTitleTextAttributes) as? [ NSAttributedString.Key : Any ] } set { objc_setAssociatedObject(self, &AssociatedObjectKeys.sharingTitleTextAttributes, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// A property for configuring the `barButtonItemAttributes` on `MFMailComposeViewController` or `MFMessageComposeViewController`. var sharingBarButtonItemAttributes: [ NSAttributedString.Key : Any ]? { get { return objc_getAssociatedObject(self, &AssociatedObjectKeys.sharingBarButtonItemAttributes) as? [ NSAttributedString.Key : Any ] } set { objc_setAssociatedObject(self, &AssociatedObjectKeys.sharingBarButtonItemAttributes, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// A closure that fires when a sharing event completes, whether it is succeeds or fails. var sharingCompleted: SharingCompletedEvent? { get { guard let box = objc_getAssociatedObject(self, &AssociatedObjectKeys.sharingCompleted) as? SharingCompletedEventBox else { return nil } return box.event } set { objc_setAssociatedObject(self, &AssociatedObjectKeys.sharingCompleted, SharingCompletedEventBox(event: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: Temporary properties which are used to store in between presenting // `MFMailComposeViewController` and `MFMessageComposeViewController` since they require delegate // callbacks. /// A temporary store for the original `UINavigationBar.backgroundImage` while we are presenting a /// `MFMailComposeViewController` or `MFMessageComposeViewController`, to be restored after use. fileprivate var temporarySharingBackgroundImage: UIImage? { get { return objc_getAssociatedObject(self, &AssociatedObjectKeys.temporarySharingBackgroundImage) as? UIImage } set { objc_setAssociatedObject(self, &AssociatedObjectKeys.temporarySharingBackgroundImage, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// A temporary store for the original `titleTextAttributes` while we are presenting a /// `MFMailComposeViewController` or `MFMessageComposeViewController`, to be restored after use. var temporarySharingBarButtonItemAttributes: [ AnyHashable : Any ]? { get { return objc_getAssociatedObject(self, &AssociatedObjectKeys.temporarySharingBarButtonItemAttributes) as? [ AnyHashable : Any ] } set { objc_setAssociatedObject(self, &AssociatedObjectKeys.temporarySharingBarButtonItemAttributes, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } /// UIImage extension to create an image from specified color private extension UIImage { convenience init?(color: UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) defer { UIGraphicsEndImageContext() } color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } } // Boxing so we can store the sharingCompleted closure on UIViewController private class SharingCompletedEventBox { var event: SharingCompletedEvent? init(event: SharingCompletedEvent?) { self.event = event } }
mit
4099bb59fca5991c0e18aedd1c8d2b65
46.471299
161
0.708012
6.145092
false
false
false
false
Mimieam/LearningSwift
YouOweMe/ViewController.swift
1
3061
// // ViewController.swift // YouOweMe // // Created by Aman Miezan Echimane on 10/19/14. // Copyright (c) 2014 Monster. All rights reserved. // import UIKit class Debt { var amount: Double var description: String var createdOn: NSDate var isPaidOff: Bool var paidOn:NSDate? init (amount:Double , description: String){ self.amount = amount self.description = description self.createdOn = NSDate() self.isPaidOff = false self.paidOn = nil } } // you owe me class Person { var name: String = "" var accountNumber: Double = 0.0 var debtors:[String:Dictionary<String, Double>] init(name:String, accountNumber:Double){ self.name = name self.accountNumber = accountNumber self.debtors = Dictionary<String, Dictionary<String,Double>>() } func addNewDebt(name:String, description:String, amount:Double){ if (debtors[name] != nil) { self.debtors[name]?.updateValue(amount, forKey: description) } else { self.debtors[name] = [description:amount] } } func getTabFor(name:String) -> [String:Double]{ if debtors[name] != nil { return self.debtors[name]! } else { return ["": 0] } } func getTabTotal(name:String) -> Double{ if debtors[name] != nil { var total = 0.0 for (key,value)in debtors[name]! { print(key, value) total += value } return total } return 0.0 } } class ViewController: UIViewController { var counter = 1 @IBOutlet weak var HWtextfield: UITextField! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var pictureBG: UIImageView! @IBOutlet weak var textLabel: UILabel! var me = Person(name: "miezan", accountNumber: 3332.4) @IBAction func helloworld_button(sender: AnyObject) { print("hello world again !!") HWtextfield.text = "Yo man " textLabel.text = ""+String(counter) counter++ me.addNewDebt("Mangny", description: "elecric bill october" ,amount: 32) me.addNewDebt("Cynthia", description: "Insurance bill october" ,amount: 4) me.addNewDebt("Cynthia", description: "Insurance bill November" ,amount: 5) for x in me.debtors.keys{ print(x) print(me.debtors[x]) } me.getTabFor("Many") me.getTabTotal("Cynthia") me.getTabTotal("Mangny") print(me.name) print(me.accountNumber) } override func viewDidLoad() { super.viewDidLoad() print("Hello world") // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
61f2ac6c6eb3d3275235ba2eb52b544e
24.090164
83
0.572689
4.263231
false
false
false
false
imkevinxu/Spring
Spring/SpringLabel.swift
1
2965
// // SpringLabel.swift // https://github.com/MengTo/Spring // // The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit public class SpringLabel: UILabel, Springable { // MARK: Advanced Values @IBInspectable public var animation: String = "" @IBInspectable public var curve: String = "" @IBInspectable public var autostart: Bool = false @IBInspectable public var autohide: Bool = false @IBInspectable public var delay: CGFloat = 0 @IBInspectable public var duration: CGFloat = 0.7 @IBInspectable public var force: CGFloat = 1 @IBInspectable public var damping: CGFloat = 0.7 @IBInspectable public var velocity: CGFloat = 0.7 @IBInspectable public var rotateDegrees: CGFloat = 0 @IBInspectable public var repeatCount: Float = 1 // MARK: Basic Values @IBInspectable public var x: CGFloat = 0 @IBInspectable public var y: CGFloat = 0 @IBInspectable public var scaleX: CGFloat = 1 @IBInspectable public var scaleY: CGFloat = 1 @IBInspectable public var rotate: CGFloat = 0 public var opacity: CGFloat = 1 public var animateFrom: Bool = false lazy private var spring: Spring = Spring(self) // MARK: - View Lifecycle override public func awakeFromNib() { super.awakeFromNib() self.spring.customAwakeFromNib() } override public func didMoveToWindow() { super.didMoveToWindow() self.spring.customDidMoveToWindow() } // MARK: - Animation Methods public func animate() { self.spring.animate() } public func animateNext(completion: () -> ()) { self.spring.animateNext(completion) } public func animateTo() { self.spring.animateTo() } public func animateToNext(completion: () -> ()) { self.spring.animateToNext(completion) } }
mit
07aa59ce44d7a93ee8bef9a14b12da58
33.091954
82
0.699831
4.512938
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/ArticlePlaceView.swift
1
22914
import UIKit import WMF #if OSM import Mapbox #else import MapKit #endif protocol ArticlePlaceViewDelegate: NSObjectProtocol { func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView) } class ArticlePlaceView: MapAnnotationView { static let smallDotImage = #imageLiteral(resourceName: "places-dot-small") static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium") static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque") static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium") static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque") static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium") static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque") static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large") static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque") static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ") static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium") static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large") static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium") static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large") public weak var delegate: ArticlePlaceViewDelegate? var imageView: UIView! private var imageImageView: UIImageView! private var imageImagePlaceholderView: UIImageView! private var imageOutlineView: UIView! private var imageBackgroundView: UIView! private var selectedImageView: UIView! private var selectedImageImageView: UIImageView! private var selectedImageImagePlaceholderView: UIImageView! private var selectedImageOutlineView: UIView! private var selectedImageBackgroundView: UIView! private var dotView: UIView! private var groupView: UIView! private var countLabel: UILabel! private var dimension: CGFloat! private var collapsedDimension: CGFloat! var groupDimension: CGFloat! var imageDimension: CGFloat! var selectedImageButton: UIButton! private var alwaysShowImage = false private let selectionAnimationDuration = 0.3 private let springDamping: CGFloat = 0.5 private let crossFadeRelativeHalfDuration: TimeInterval = 0.1 private let alwaysRasterize = true // set this or rasterize on animations, not both private let rasterizeOnAnimations = false override func setup() { selectedImageView = UIView() imageView = UIView() selectedImageImageView = UIImageView() imageImageView = UIImageView() selectedImageImageView.accessibilityIgnoresInvertColors = true imageImageView.accessibilityIgnoresInvertColors = true countLabel = UILabel() dotView = UIView() groupView = UIView() imageOutlineView = UIView() selectedImageOutlineView = UIView() imageBackgroundView = UIView() selectedImageBackgroundView = UIView() selectedImageButton = UIButton() imageImagePlaceholderView = UIImageView() selectedImageImagePlaceholderView = UIImageView() let scale = ArticlePlaceView.mediumDotImage.scale let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage collapsedDimension = ArticlePlaceView.smallDotImage.size.width groupDimension = ArticlePlaceView.mediumDotImage.size.width dimension = largeOpaqueDotOutlineImage.size.width imageDimension = mediumOpaqueDotOutlineImage.size.width let gravity = CALayerContentsGravity.bottomRight isPlaceholderHidden = false frame = CGRect(x: 0, y: 0, width: dimension, height: dimension) dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension) dotView.layer.contentsGravity = gravity dotView.layer.contentsScale = scale dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) addSubview(dotView) groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension) groupView.layer.contentsGravity = gravity groupView.layer.contentsScale = scale groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage addSubview(groupView) imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension) imageView.layer.rasterizationScale = scale addSubview(imageView) imageBackgroundView.frame = imageView.bounds imageBackgroundView.layer.contentsGravity = gravity imageBackgroundView.layer.contentsScale = scale imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage imageView.addSubview(imageBackgroundView) imageImagePlaceholderView.frame = imageView.bounds imageImagePlaceholderView.contentMode = .center imageImagePlaceholderView.image = mediumPlaceholderImage imageView.addSubview(imageImagePlaceholderView) var inset: CGFloat = 3.5 var imageViewFrame = imageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) imageImageView.frame = imageViewFrame imageImageView.contentMode = .scaleAspectFill imageImageView.layer.masksToBounds = true imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5 imageImageView.backgroundColor = UIColor.white imageView.addSubview(imageImageView) imageOutlineView.frame = imageView.bounds imageOutlineView.layer.contentsGravity = gravity imageOutlineView.layer.contentsScale = scale imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage imageView.addSubview(imageOutlineView) selectedImageView.bounds = bounds selectedImageView.layer.rasterizationScale = scale addSubview(selectedImageView) selectedImageBackgroundView.frame = selectedImageView.bounds selectedImageBackgroundView.layer.contentsGravity = gravity selectedImageBackgroundView.layer.contentsScale = scale selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage selectedImageView.addSubview(selectedImageBackgroundView) selectedImageImagePlaceholderView.frame = selectedImageView.bounds selectedImageImagePlaceholderView.contentMode = .center selectedImageImagePlaceholderView.image = largePlaceholderImage selectedImageView.addSubview(selectedImageImagePlaceholderView) inset = imageDimension > 40 ? 3.5 : 5.5 imageViewFrame = selectedImageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)) imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset) selectedImageImageView.frame = imageViewFrame selectedImageImageView.contentMode = .scaleAspectFill selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5 selectedImageImageView.layer.masksToBounds = true selectedImageImageView.backgroundColor = UIColor.white selectedImageView.addSubview(selectedImageImageView) selectedImageOutlineView.frame = selectedImageView.bounds selectedImageOutlineView.layer.contentsGravity = gravity selectedImageOutlineView.layer.contentsScale = scale selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage selectedImageView.addSubview(selectedImageOutlineView) selectedImageButton.frame = selectedImageView.bounds selectedImageButton.accessibilityTraits = UIAccessibilityTraits.none selectedImageView.addSubview(selectedImageButton) countLabel.frame = groupView.bounds countLabel.textColor = UIColor.white countLabel.textAlignment = .center countLabel.font = UIFont.boldSystemFont(ofSize: 16) groupView.addSubview(countLabel) prepareForReuse() super.setup() updateLayout() update(withArticlePlace: annotation as? ArticlePlace) } func set(alwaysShowImage: Bool, animated: Bool) { self.alwaysShowImage = alwaysShowImage let scale = collapsedDimension/imageDimension let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale) if alwaysShowImage { loadImage() imageView.alpha = 0 imageView.isHidden = false dotView.alpha = 1 dotView.isHidden = false imageView.transform = imageViewScaleDownTransform dotView.transform = CGAffineTransform.identity } else { dotView.transform = dotViewScaleUpTransform imageView.transform = CGAffineTransform.identity imageView.alpha = 1 imageView.isHidden = false dotView.alpha = 0 dotView.isHidden = false } let transforms = { if alwaysShowImage { self.imageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform } else { self.imageView.transform = imageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity } } let fadesIn = { if alwaysShowImage { self.imageView.alpha = 1 } else { self.dotView.alpha = 1 } } let fadesOut = { if alwaysShowImage { self.dotView.alpha = 0 } else { self.imageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.imageView.layer.shouldRasterize = false } guard let articlePlace = self.annotation as? ArticlePlace else { return } self.updateDotAndImageHiddenState(with: articlePlace.articles.count) } if animated { if alwaysShowImage { UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } override func didMoveToSuperview() { super.didMoveToSuperview() guard superview != nil else { selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) return } selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside) } @objc func selectedImageViewWasTapped(_ sender: UIButton) { delegate?.articlePlaceViewWasTapped(self) } var zPosition: CGFloat = 1 { didSet { guard !isSelected else { return } layer.zPosition = zPosition } } var isPlaceholderHidden: Bool = true { didSet { selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden imageImagePlaceholderView.isHidden = isPlaceholderHidden imageImageView.isHidden = !isPlaceholderHidden selectedImageImageView.isHidden = !isPlaceholderHidden } } private var shouldRasterize = false { didSet { imageView.layer.shouldRasterize = shouldRasterize selectedImageView.layer.shouldRasterize = shouldRasterize } } private var isImageLoaded = false func loadImage() { guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else { return } if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = true let article = articlePlace.articles[0] if let thumbnailURL = article.thumbnailURL { imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in if self.alwaysRasterize { self.shouldRasterize = true } }, success: { self.selectedImageImageView.image = self.imageImageView.image self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect self.isPlaceholderHidden = true if self.alwaysRasterize { self.shouldRasterize = true } }) } } func update(withArticlePlace articlePlace: ArticlePlace?) { let articleCount = articlePlace?.articles.count ?? 1 switch articleCount { case 0: zPosition = 1 isPlaceholderHidden = false imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more") accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles") case 1: zPosition = 1 isImageLoaded = false if isSelected || alwaysShowImage { loadImage() } accessibilityLabel = articlePlace?.articles.first?.displayTitle default: zPosition = 2 let countString = "\(articleCount)" countLabel.text = countString accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group\n{{Identical|Article}}"), countString) } updateDotAndImageHiddenState(with: articleCount) } func updateDotAndImageHiddenState(with articleCount: Int) { switch articleCount { case 0: fallthrough case 1: imageView.isHidden = !alwaysShowImage dotView.isHidden = alwaysShowImage groupView.isHidden = true default: imageView.isHidden = true dotView.isHidden = true groupView.isHidden = false } } #if OSM override var annotation: MGLAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #else override var annotation: MKAnnotation? { didSet { guard isSetup, let articlePlace = annotation as? ArticlePlace else { return } update(withArticlePlace: articlePlace) } } #endif override func prepareForReuse() { super.prepareForReuse() if alwaysRasterize { shouldRasterize = false } isPlaceholderHidden = false isImageLoaded = false delegate = nil imageImageView.wmf_reset() selectedImageImageView.wmf_reset() countLabel.text = nil set(alwaysShowImage: false, animated: false) setSelected(false, animated: false) alpha = 1 transform = CGAffineTransform.identity } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) guard let place = annotation as? ArticlePlace, place.articles.count == 1 else { selectedImageView.alpha = 0 return } let dotScale = collapsedDimension/dimension let imageViewScale = imageDimension/dimension let scale = alwaysShowImage ? imageViewScale : dotScale let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale) let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale) let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale) layer.zPosition = 3 if selected { loadImage() selectedImageView.transform = selectedImageViewScaleDownTransform dotView.transform = CGAffineTransform.identity imageView.transform = CGAffineTransform.identity selectedImageView.alpha = 0 imageView.alpha = 1 dotView.alpha = 1 } else { selectedImageView.transform = CGAffineTransform.identity dotView.transform = dotViewScaleUpTransform imageView.transform = imageViewScaleUpTransform selectedImageView.alpha = 1 imageView.alpha = 0 dotView.alpha = 0 } let transforms = { if selected { self.selectedImageView.transform = CGAffineTransform.identity self.dotView.transform = dotViewScaleUpTransform self.imageView.transform = imageViewScaleUpTransform } else { self.selectedImageView.transform = selectedImageViewScaleDownTransform self.dotView.transform = CGAffineTransform.identity self.imageView.transform = CGAffineTransform.identity } } let fadesIn = { if selected { self.selectedImageView.alpha = 1 } else { self.imageView.alpha = 1 self.dotView.alpha = 1 } } let fadesOut = { if selected { self.imageView.alpha = 0 self.dotView.alpha = 0 } else { self.selectedImageView.alpha = 0 } } if (animated && rasterizeOnAnimations) { shouldRasterize = true } let done = { if (animated && self.rasterizeOnAnimations) { self.shouldRasterize = false } if !selected { self.layer.zPosition = self.zPosition } } if animated { let duration = 2*selectionAnimationDuration if selected { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil) UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut) }) { (didFinish) in done() } } else { UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: { UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms) UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn) UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut) }) { (didFinish) in done() } } } else { transforms() fadesIn() fadesOut() done() } } func updateLayout() { let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height) selectedImageView.center = center imageView.center = center dotView.center = center groupView.center = center } override var frame: CGRect { didSet { guard isSetup else { return } updateLayout() } } override var bounds: CGRect { didSet { guard isSetup else { return } updateLayout() } } }
mit
a83602ddba339eae047260228145a9a3
41.044037
280
0.645239
6.241896
false
false
false
false
meninsilicium/apple-swifty
Set.swift
1
4020
// // author: fabrice truillot de chambrier // created: 12.02.2015 // // license: see license.txt // // © 2015-2015, men in silicium sàrl // import class Foundation.NSObject import class Foundation.NSSet import class Foundation.NSMutableSet // MARK: Set // Iterable extension Set : Iterable_ { func foreach( @noescape function: (T) -> Void ) { for element in self { function( element ) } } func foreach( @noescape function: (Int, T) -> Void ) { for (index, element) in Swift.enumerate( self ) { function( index, element ) } } } // Enumerable extension Set : Enumerable_ { func enumerate( @noescape function: (Int, ValueType) -> Bool ) { for (index, element) in Swift.enumerate( self ) { let next = function( index, element ) if !next { break } } } } /// Set extension providing the usual monad functions // MARK: Functor extension Set : Functor_ { typealias ValueType = T typealias MappedType = HashableConstraint typealias MappedFunctorType = Set<MappedType> // functor map, <^> func map<R: Hashable>( @noescape transform: (T) -> R ) -> Set<R> { var set = Set<R>() for element in self { set.insert( transform( element ) ) } return set } } // Pointed extension Set : Pointed_ { static func pure( value: T ) -> Set<T> { return Set( CollectionOfOne( value ) ) } init( _ value: T ) { self.init( CollectionOfOne( value ) ) } } // Applicative extension Set : Applicative_ { typealias ApplicativeType = [(T) -> MappedType] // applicative apply, <*> static func apply<R>( transform: [(T) -> R], value: Set<T> ) -> Set<R> { var set = Set<R>() var transformGenerator = transform.generate() var valueGenerator = value.generate() while true { if let transformElement = transformGenerator.next(), let valueElement = valueGenerator.next() { set.insert( transformElement( valueElement ) ) } else { break } } return set } } // applicative apply, <*> // using the default implementation // Monad extension Set : Monad_ { // monad bind, >>- func fmap<R>( @noescape transform: (T) -> Set<R> ) -> Set<R> { return Set<R>.flatten( self.map( transform ) ) } // flatten static func flatten( value: Set<Set<T>> ) -> Set<T> { var set = Set<T>() for element in value { set.unionInPlace( element ) } return set } } // monad bind, >>- /* public func >>-<T, R>( value: Set<T>, transform: (T) -> Set<R> ) -> Set<R> { return value.fmap( transform ) } public func -<<<T, R>( transform: (T) -> Set<R>, value: Set<T> ) -> Set<R> { return value.fmap( transform ) } */ // MARK: HashableConstraint // used to express the Hashable constraint of Set elements class HashableConstraint : Hashable { var hashValue: Int { return 0 } } func ==( lhs: HashableConstraint, rhs: HashableConstraint ) -> Bool { return true } // MARK: - // MARK: NSSet // Functor extension NSSet : Functor { public func map( @noescape transform: (AnyObject) -> AnyObject ) -> NSSet { var set = NSMutableSet() for value in self { set.addObject( transform( value ) ) } return set } } public func <^>( set: NSSet, @noescape transform: (AnyObject) -> AnyObject ) -> NSSet { return set.map( transform ) } // Monad extension NSSet : MonadSpecifics { typealias MappedType = AnyObject // monad bind, >>- public func fmap( @noescape transform: (AnyObject) -> NSSet ) -> NSSet { return NSSet.flatten( self.map( transform ) ) } // flatten public static func flatten( value: NSSet ) -> NSSet { var set = NSMutableSet() for element in value { switch element { case let element as NSSet: set.unionSet( element as! Set<NSObject> ) default: set.unionSet( element as! Set<NSObject> ) } } return set } } public func >>-( value: NSSet, @noescape transform: (AnyObject) -> NSSet ) -> NSSet { return value.fmap( transform ) } public func -<<( @noescape transform: (AnyObject) -> NSSet, value: NSSet ) -> NSSet { return value.fmap( transform ) }
mpl-2.0
83b64fb08dc1a2e57cee146eb1fb9dbd
17.180995
98
0.637133
3.229904
false
false
false
false
GianniCarlo/Audiobook-Player
BookPlayerWidget/TodayViewController.swift
1
2531
// // TodayViewController.swift // BookPlayerWidget // // Created by Gianni Carlo on 4/24/19. // Copyright © 2019 Tortuga Power. All rights reserved. // import BookPlayerKit import NotificationCenter import UIKit class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var artworkImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var chapterLabel: UILabel! @IBOutlet weak var playButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.artworkImageView.layer.cornerRadius = 4.0 self.artworkImageView.layer.masksToBounds = true self.artworkImageView.clipsToBounds = true self.artworkImageView.layer.borderWidth = 0.5 self.artworkImageView.layer.borderColor = UIColor.textColor.withAlphaComponent(0.2).cgColor } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.updateBookDetails() } func updateBookDetails() { guard let library = try? DataManager.getLibrary(), let book = library.lastPlayedBook else { return } self.titleLabel.text = book.title self.authorLabel.text = book.author if let chapter = book.currentChapter { self.chapterLabel.text = chapter.title self.chapterLabel.isHidden = false } else { self.chapterLabel.isHidden = true } guard let theme = library.currentTheme else { return } self.artworkImageView.image = book.getArtwork(for: theme) let titleColor = theme.primaryColor self.view.backgroundColor = theme.systemBackgroundColor.withAlpha(newAlpha: 0.5) self.authorLabel.textColor = theme.primaryColor self.titleLabel.textColor = titleColor self.chapterLabel.textColor = titleColor self.playButton.tintColor = theme.linkColor } func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { self.updateBookDetails() completionHandler(NCUpdateResult.newData) } @IBAction func togglePlay(_ sender: UIButton) { let parameter = URLQueryItem(name: "showPlayer", value: "true") let actionString = CommandParser.createActionString(from: .play, parameters: [parameter]) self.extensionContext?.open(URL(string: actionString)!, completionHandler: nil) } }
gpl-3.0
b0e105fd302e8d89a96024d7ee5ec9a1
32.733333
99
0.691304
4.941406
false
false
false
false
francisceioseph/Swift-Files-App
Swift-Files/FileHelper.swift
1
3140
// // FileHelper.swift // Swift-Files // // Created by Francisco José A. C. Souza on 24/12/15. // Copyright © 2015 Francisco José A. C. Souza. All rights reserved. // import UIKit class FileHelper: NSObject { static let sharedInstance = FileHelper() let fileManager = NSFileManager.defaultManager() func createPlainTextFileWithName(name: String) -> Bool{ let filePath = self.documentsFolder().stringByAppendingString("/\(name).txt") return fileManager.createFileAtPath(filePath, contents: nil , attributes: nil) } func readPlainTextWithName(name: String) throws -> String? { let filePath = self.documentsFolder().stringByAppendingString("/\(name).txt") let fileContent:String? = try String(contentsOfFile: filePath) return fileContent } func savePlainTextFileWithName(name: String, fileContent: String) -> Bool { let filePath = self.documentsFolder().stringByAppendingString("/\(name).txt") let fileData = fileContent.dataUsingEncoding(NSUTF8StringEncoding) return fileManager.createFileAtPath(filePath, contents: fileData , attributes: nil) } func deletePlainTextFileWithName(name: String) throws{ let filePath = self.documentsFolder().stringByAppendingString("/\(name).txt") try fileManager.removeItemAtPath(filePath) } //MARK: - Plist Text File func createPlistFileWithName(name: String) -> Bool{ let filePath = self.documentsFolder().stringByAppendingString("/\(name).plist") return fileManager.createFileAtPath(filePath, contents: nil , attributes: nil) } func readPlistWithName(name: String) -> NSMutableArray? { let filePath = self.documentsFolder().stringByAppendingString("/\(name).plist") var fileContent: NSMutableArray? if self.fileManager.fileExistsAtPath(filePath) { if let array = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? NSMutableArray{ fileContent = array } else { fileContent = NSMutableArray() } } return fileContent } func savePlistFileWithName(name: String, fileContent: NSMutableArray) -> Bool { let filePath = self.documentsFolder().stringByAppendingString("/\(name).plist") let fileData = NSKeyedArchiver.archivedDataWithRootObject(fileContent) let result = fileManager.createFileAtPath(filePath, contents: fileData , attributes: nil) return result } func deletePlistFileWithName(name: String) throws{ let filePath = self.documentsFolder().stringByAppendingString("/\(name).plist") try fileManager.removeItemAtPath(filePath) } private func documentsFolder () -> String{ let folders = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) return folders.first! } }
mit
967592dcb2cce9c5f5167575dd9a9ec0
31.6875
100
0.638508
5.798521
false
false
false
false
sonnygauran/trailer
PocketTrailer/RepoSettingsViewController.swift
1
3167
import UIKit class RepoSettingsViewController: UITableViewController { var repo: Repo? var allPrsIndex: Int = -1 var allIssuesIndex: Int = -1 private var settingsChangedTimer: PopTimer! override func viewDidLoad() { super.viewDidLoad() if repo == nil { title = "All Repos..." } settingsChangedTimer = PopTimer(timeInterval: 1.0) { DataManager.postProcessAllItems() popupManager.getMasterController().reloadDataWithAnimation(true) } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return RepoDisplayPolicy.labels.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! if repo == nil { if indexPath.section == 0 { cell.accessoryType = (allPrsIndex==indexPath.row) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None } else { cell.accessoryType = (allIssuesIndex==indexPath.row) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None } } else { if indexPath.section == 0 { cell.accessoryType = (repo?.displayPolicyForPrs?.integerValue==indexPath.row) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None } else { cell.accessoryType = (repo?.displayPolicyForIssues?.integerValue==indexPath.row) ? UITableViewCellAccessoryType.Checkmark : UITableViewCellAccessoryType.None } } cell.selectionStyle = cell.accessoryType==UITableViewCellAccessoryType.Checkmark ? UITableViewCellSelectionStyle.None : UITableViewCellSelectionStyle.Default cell.textLabel?.text = RepoDisplayPolicy.labels[indexPath.row] cell.textLabel?.textColor = RepoDisplayPolicy.colors[indexPath.row] return cell } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section==0 ? "Pull Requests" : "Issues" } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if repo == nil { if indexPath.section == 0 { allPrsIndex = indexPath.row for r in Repo.allItemsOfType("Repo", inMoc: mainObjectContext) as! [Repo] { r.displayPolicyForPrs = allPrsIndex if allPrsIndex != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } } } else { allIssuesIndex = indexPath.row for r in Repo.allItemsOfType("Repo", inMoc: mainObjectContext) as! [Repo] { r.displayPolicyForIssues = allIssuesIndex if allIssuesIndex != RepoDisplayPolicy.Hide.rawValue { r.resetSyncState() } } } } else if indexPath.section == 0 { repo?.displayPolicyForPrs = indexPath.row if indexPath.row != RepoDisplayPolicy.Hide.rawValue { repo?.resetSyncState() } } else { repo?.displayPolicyForIssues = indexPath.row if indexPath.row != RepoDisplayPolicy.Hide.rawValue { repo?.resetSyncState() } } tableView.reloadData() app.preferencesDirty = true DataManager.saveDB() settingsChangedTimer.push() } }
mit
a13727c689c7e10aec7d3fefcd911b8a
34.188889
161
0.744553
4.326503
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/06601-swift-type-walk.swift
11
657
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<U : B<T>: a { func a<I : B class d<I : a protocol c : f { func f b let g: B<T>: a { struct g<I : f { func f: A") } class B<g : d protocol c { struct A { protocol A { struct g<H : a { } class B<T where T>: f { func f protocol A : a { } class B<H : d = c { } class d<T>: a<H : String = c { func a<U : e : d<I : d = c : c: d<U : c: d = c : a { let c { class d<g : B<U : B<H : String = T>: d = c { var f: a<U : d<h = c : d: a { if true { struct A { b let c { struct A : a { class B<H
mit
a6963d573e90b2d8ecc4735ee1a6a146
19.53125
87
0.572298
2.442379
false
true
false
false
BBRick/wp
wp/Scenes/Home/CSCycleView/CSCycleView.swift
2
7390
// // CSCycleView.swift // Swift3InfiniteRotate // // Created by macbook air on 16/12/17. // Copyright © 2016年 yundian. All rights reserved. // import UIKit import Kingfisher private let kCellId = "kCellId" //代理 protocol CSCycleViewDelegate : class { func clickedCycleView(_ cycleView : CSCycleView, selectedIndex index: Int) } class CSCycleView: UIView { //MARK: -- 自定义属性 fileprivate var titles: [String]? fileprivate var images: [String]? fileprivate var cycleTimer : Timer? weak var delegate : CSCycleViewDelegate? //MARK: -- 懒加载 fileprivate lazy var collectionView : UICollectionView = {[weak self] in //创建collectionView let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: self!.bounds, collectionViewLayout: layout) collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(CSCycleCell.self, forCellWithReuseIdentifier: kCellId) return collectionView }() lazy var pageControl : UIPageControl = {[weak self] in let pageControl = UIPageControl(frame: CGRect(x: self!.bounds.width / 2, y: self!.bounds.height - 20, width: self!.bounds.width / 2, height: 20)) pageControl.pageIndicatorTintColor = .orange pageControl.currentPageIndicatorTintColor = .green //让pageCotrol靠右显示 pageControl.numberOfPages = self!.images?.count ?? 0 let pointSize = pageControl.size(forNumberOfPages: self!.images?.count ?? 0) //靠右显示 // pageControl.bounds = CGRect(x: -(pageControl.bounds.width - pointSize.width) / 2 + 10, y: pageControl.bounds.height - 20, width: pageControl.bounds.width / 2, height: 20) //中间显示 pageControl.bounds = CGRect(x: pageControl.bounds.width / 2 , y: pageControl.bounds.height - 20, width: pageControl.bounds.width / 2, height: 20) return pageControl }() override func layoutSubviews() { //设置layout(获取的尺寸准确,所以在这里设置) let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true //设置该空间不随着父控件的拉伸而拉伸 autoresizingMask = UIViewAutoresizing() } //MARK: -- 构造函数 init(frame: CGRect, images: [String], titles : [String] = []) { self.images = images self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeCycleTimer() print("CSCycleView销毁了") } } //MARK: -- 设置UI界面 extension CSCycleView { fileprivate func setupUI() { addSubview(collectionView) addSubview(pageControl) //添加定时器。先移除再添加 collectionView.reloadData() removeCycleTimer() addCycleTimer() //滚动到该位置(让用户最开始就可以向左滚动) collectionView.setContentOffset(CGPoint(x: collectionView.bounds.width * CGFloat((images?.count)!) * 10, y: 0), animated: true) //点击事件 self.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector (tapGes(tap:))) self.addGestureRecognizer(tap) } } //MARK: -- UICollectionViewDataSource extension CSCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (images?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! CSCycleCell if (titles?.count)! > 0 { cell.titleLabel.text = titles?[indexPath.row % titles!.count] } var header : String? if images![indexPath.row % images!.count].characters.count >= 4 { header = (images![indexPath.row % images!.count] as NSString).substring(to: 4) } if header == "http" { // let url = NSURL(string: images![indexPath.row % images!.count]) // let data = NSData(contentsOf: url! as URL) // cell.iconImageView.image = UIImage(data: data as! Data) let url = URL(string: images![indexPath.row % images!.count]) cell.iconImageView.kf.setImage(with: url) }else { cell.iconImageView.image = UIImage(named: images![indexPath.row % images!.count]) } return cell } } //MARK: -- UICollectionViewDelegate extension CSCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (images?.count ?? 0) } //当用户拖拽时,移除定时器 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } //停止拖拽,加入定时器 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } //MARK: -- 时间控制器 extension CSCycleView { fileprivate func addCycleTimer() { // cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true) weak var weakSelf = self//解决循环引用 if #available(iOS 10.0, *) { cycleTimer = Timer(timeInterval: 3.0, repeats: true, block: {(timer) in weakSelf!.scrollToNextPage() }) } else { // Fallback on earlier versions } cycleTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true) } fileprivate func removeCycleTimer() { cycleTimer?.invalidate()//移除 cycleTimer = nil } @objc fileprivate func scrollToNextPage() { let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width //滚动到该位置 collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } } //MARK: -- YLCycleViewDelegate extension CSCycleView { @objc fileprivate func tapGes(tap: UITapGestureRecognizer) { guard (tap.view as? CSCycleView) != nil else { return } if (delegate != nil) { delegate?.clickedCycleView(self, selectedIndex: pageControl.currentPage) } print("点击了第: \(pageControl.currentPage)页") } }
apache-2.0
6c25afa5c7829a0d41272590cc6aa4b4
34.742424
180
0.637982
4.873967
false
false
false
false
leotao2014/RTPhotoBrowser
RTPhotoBrowser/RTPhotoBrowserConfig.swift
1
494
// // RTPhotoBrowserConfig.swift // RTPhotoBrowser // // Created by leotao on 2017/5/30. // Copyright © 2017年 leotao. All rights reserved. // import Foundation import UIKit class RTPhotoBrowserConfig { static let defaulConfig = RTPhotoBrowserConfig(); var placeHolderImage = UIImage(named: "rt-placeholder"); var loadFailImage = UIImage(named: "rt-fail"); var footerHeight:CGFloat = 49.0; var headerHeight:CGFloat = 64.0; var shouldSupportRotate = true; }
apache-2.0
c59a7649f1ef09d47835cc6e9aa15dc4
23.55
60
0.706721
3.748092
false
true
false
false
NqiOS/DYTV-swift
DYTV/DYTV/Classes/Main/Controller/NQAnchorViewController.swift
1
5204
// // NQAnchorViewController.swift // DYTV // // Created by djk on 17/3/10. // Copyright © 2017年 NQ. All rights reserved. // import UIKit // MARK:- 定义常量 private let kItemMargin : CGFloat = 10 private let kHeaderViewH : CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let kHeaderViewID = "kHeaderViewID" let kPrettyCellID = "kPrettyCellID" let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 let kNormalItemH = kNormalItemW * 3 / 4 let kPrettyItemH = kNormalItemW * 4 / 3 // MARK:- 定义NQAnchorViewController类 class NQAnchorViewController: NQBaseViewController { // MARK:- 定义属性 var baseVM : NQBaseViewModel! // MARK:- 懒加载属性 lazy var collectionView : UICollectionView = {[unowned self] in //1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self //把当前控制器的view添加到不同大小的其他view里时,设置自动拉伸大小 collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "NQCollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "NQCollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "NQCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() override func viewDidLoad() { super.viewDidLoad() //设置UI setupUI() //请求数据 loadData() } } // MARK:- 设置UI界面 extension NQAnchorViewController{ override func setupUI(){ //1.给父类中内容View的引用进行赋值 contentView = collectionView //2.添加collectionView view.addSubview(collectionView) //3.调用super.setupUI() super.setupUI() } } // MARK:- 请求数据 extension NQAnchorViewController{ func loadData(){ } } // MARK:- 遵守UICollectionView的数据源 extension NQAnchorViewController : UICollectionViewDataSource{ func numberOfSections(in collectionView: UICollectionView) -> Int { if baseVM == nil { return 3 } return baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if baseVM == nil { return 5 } return baseVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! NQCollectionNormalCell if baseVM == nil { return cell } cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath)as! NQCollectionHeaderView if baseVM == nil { return headerView } headerView.group = baseVM.anchorGroups[indexPath.section] return headerView } } // MARK:- 遵守UICollectionView的代理协议 extension NQAnchorViewController : UICollectionViewDelegate{ func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { //1.取出对应的主播信息 let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] //2.判断是秀场房间&普通房间 anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc() } private func presentShowRoomVc(){ //1.创建showRoomVc let showRoomVc = NQRoomShowViewController() //2.以Modal方式弹出 present(showRoomVc, animated: true, completion: nil) } private func pushNormalRoomVc(){ //1.创建NormalRoomVc let normalRoomVc = NQRoomNormalViewController() //2.以Push方式弹出 navigationController?.pushViewController(normalRoomVc, animated: true) } }
mit
779098df5c81a11612bb92206dda1d86
32.425676
188
0.678593
5.589831
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Classes/Reusable/UI/ByuViewController2.swift
1
3205
// // ByuViewController2.swift // byuSuite // // Created by Nathan Johnson on 4/10/17. // Copyright © 2017 Brigham Young University. All rights reserved. // import UIKit class ByuViewController2: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.byuBackground extendedLayoutIncludesOpaqueBars = true } //MARK: - Methods func displayActionSheet(from item: Any, title: String? = nil, actions: [UIAlertAction], cancelActionHandler: ((UIAlertAction?) -> Void)? = nil) { let actionSheet = UIAlertController(title: title, message: nil, preferredStyle: .actionSheet) for action in actions { actionSheet.addAction(action) } actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancelActionHandler)) if let barButton = item as? UIBarButtonItem { actionSheet.popoverPresentationController?.barButtonItem = barButton } else if let view = item as? UIView { actionSheet.popoverPresentationController?.sourceView = view actionSheet.popoverPresentationController?.sourceRect = view.bounds } present(actionSheet, animated: true, completion: nil) } func displayPhoneAction(from item: Any, title: String? = "Call", phoneNumber: String) { displayActionSheet(from: item, title: nil, actions: [ UIAlertAction(title: title, style: .default, handler: { (_) in if let phoneUrl = URL(string: "tel://\(phoneNumber)") { UIApplication.shared.openURL(phoneUrl) } }) ]) } } extension ByuViewController2: UITableViewDelegate { //This method will not get called unless tableView(_:titleForHeaderInSection:) is implemented and does not return nil func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let dataSource = self as? UITableViewDataSource else { return nil } if tableView.style == .plain { let frame = CGRect(x: 8, y: 0, width: tableView.bounds.size.width, height: self.tableView(tableView, heightForHeaderInSection: section)) let headerView = UIView(frame: frame) headerView.backgroundColor = UIColor.byuTableSectionHeaderBackground let label = UILabel(frame: headerView.frame) label.backgroundColor = UIColor.clear label.textColor = UIColor.byuTableSectionHeader label.text = dataSource.tableView!(tableView, titleForHeaderInSection: section) label.font = UIFont.byuTableViewHeader headerView.addSubview(label) return headerView } return nil } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let dataSource = self as? UITableViewDataSource else { return UITableViewAutomaticDimension } if dataSource.tableView?(tableView, titleForHeaderInSection: section) != nil && tableView.style == .plain { return 20 } return UITableViewAutomaticDimension } }
apache-2.0
a983b1fd8fb1b9b9723113f2977f2af6
38.073171
149
0.663233
5.331115
false
false
false
false
dasdom/DHTweak
Tweaks/Tweaks/SwitchTableViewCell.swift
1
1583
// // SwitchTableViewCell.swift // TweaksDemo // // Created by dasdom on 29.09.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import UIKit class SwitchTableViewCell: UITableViewCell { let nameLabel: UILabel let valueSwitch: UISwitch override init(style: UITableViewCellStyle, reuseIdentifier: String?) { nameLabel = { let label = UILabel() label.setTranslatesAutoresizingMaskIntoConstraints(false) return label }() valueSwitch = { let valueSwitch = UISwitch() valueSwitch.setTranslatesAutoresizingMaskIntoConstraints(false) return valueSwitch }() super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(nameLabel) contentView.addSubview(valueSwitch) let views = ["nameLabel" : nameLabel, "valueSwitch" : valueSwitch] contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-10-[nameLabel]-5-[valueSwitch]-10-|", options: .AlignAllCenterY, metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[nameLabel]|", options: nil, metrics: nil, views: views)) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
2dd1b7cb900a212713683390c7b614b4
31.306122
178
0.662666
5.439863
false
false
false
false
brave/browser-ios
Client/Frontend/Login Management/LoginListViewController.swift
1
20934
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit import Storage import Shared private struct LoginListUX { static let RowHeight: CGFloat = 58 static let SearchHeight: CGFloat = 58 static let selectionButtonFont = UIFont.systemFont(ofSize: 16) static let selectionButtonTextColor = UIColor.white static let selectionButtonBackground = UIConstants.HighlightBlue static let NoResultsFont: UIFont = UIFont.systemFont(ofSize: 16) static let NoResultsTextColor: UIColor = UIColor.lightGray } private extension UITableView { var allIndexPaths: [IndexPath] { return (0..<self.numberOfSections).flatMap { sectionNum in (0..<self.numberOfRows(inSection: sectionNum)).map { IndexPath(row: $0, section: sectionNum) } } } } private let LoginCellIdentifier = "LoginCell" class LoginListViewController: UIViewController { fileprivate lazy var loginSelectionController: ListSelectionController = { return ListSelectionController(tableView: self.tableView) }() fileprivate lazy var loginDataSource: LoginCursorDataSource = { return LoginCursorDataSource() }() fileprivate let profile: Profile fileprivate let searchView = SearchInputView() fileprivate var activeLoginQuery: Success? fileprivate let loadingStateView = LoadingLoginsView() // Titles for selection/deselect/delete buttons fileprivate let deselectAllTitle = Strings.DeselectAll fileprivate let selectAllTitle = Strings.SelectAll fileprivate let deleteLoginTitle = Strings.Delete fileprivate lazy var selectionButton: UIButton = { let button = UIButton() button.titleLabel?.font = LoginListUX.selectionButtonFont button.setTitle(self.selectAllTitle, for: .normal) button.setTitleColor(LoginListUX.selectionButtonTextColor, for: .normal) button.backgroundColor = LoginListUX.selectionButtonBackground button.addTarget(self, action: #selector(LoginListViewController.SELdidTapSelectionButton), for: .touchUpInside) return button }() fileprivate var selectionButtonHeightConstraint: Constraint? fileprivate var selectedIndexPaths = [IndexPath]() fileprivate let tableView = UITableView() weak var settingsDelegate: SettingsDelegate? init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(LoginListViewController.SELreloadLogins), name: NotificationDataRemoteLoginChangesWereApplied, object: nil) automaticallyAdjustsScrollViewInsets = false self.view.backgroundColor = UIColor.white navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(LoginListViewController.SELedit)) self.title = Strings.Logins searchView.delegate = self tableView.register(LoginTableViewCell.self, forCellReuseIdentifier: LoginCellIdentifier) view.addSubview(searchView) view.addSubview(tableView) view.addSubview(loadingStateView) view.addSubview(selectionButton) loadingStateView.isHidden = true searchView.snp.makeConstraints { make in make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint make.left.right.equalTo(self.view) make.height.equalTo(LoginListUX.SearchHeight) } tableView.snp.makeConstraints { make in make.top.equalTo(searchView.snp.bottom) make.left.right.equalTo(self.view) make.bottom.equalTo(self.selectionButton.snp.top) } selectionButton.snp.makeConstraints { make in make.left.right.bottom.equalTo(self.view) make.top.equalTo(self.tableView.snp.bottom) make.bottom.equalTo(self.view) selectionButtonHeightConstraint = make.height.equalTo(0).constraint } loadingStateView.snp.makeConstraints { make in make.edges.equalTo(tableView) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.accessibilityIdentifier = "Login List" tableView.dataSource = loginDataSource tableView.allowsMultipleSelectionDuringEditing = true tableView.delegate = self tableView.tableFooterView = UIView() KeyboardHelper.defaultHelper.addDelegate(self) searchView.isEditing ? loadLogins(searchView.inputField.text) : loadLogins() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.loginDataSource.emptyStateView.searchBarHeight = searchView.frame.height self.loadingStateView.searchBarHeight = searchView.frame.height } deinit { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) notificationCenter.removeObserver(self, name: NotificationDataLoginDidChange, object: nil) } fileprivate func toggleDeleteBarButton() { // Show delete bar button item if we have selected any items if loginSelectionController.selectedCount > 0 { if (navigationItem.rightBarButtonItem == nil) { navigationItem.rightBarButtonItem = UIBarButtonItem(title: deleteLoginTitle, style: .plain, target: self, action: #selector(LoginListViewController.SELdelete)) navigationItem.rightBarButtonItem?.tintColor = UIColor.red } } else { navigationItem.rightBarButtonItem = nil } } fileprivate func toggleSelectionTitle() { if loginSelectionController.selectedCount == loginDataSource.allLogins.count { selectionButton.setTitle(deselectAllTitle, for: .normal) } else { selectionButton.setTitle(selectAllTitle, for: .normal) } } @discardableResult fileprivate func loadLogins(_ query: String? = nil) -> Success { loadingStateView.isHidden = false let query = profile.logins.searchLoginsWithQuery(query).bindQueue(DispatchQueue.main, f: reloadTableWithResult) activeLoginQuery = query return query } fileprivate func reloadTableWithResult(_ result: Maybe<Cursor<Login>>) -> Success { loadingStateView.isHidden = true loginDataSource.allLogins = result.successValue?.asArray() ?? [] tableView.reloadData() activeLoginQuery = nil if loginDataSource.count > 0 { navigationItem.rightBarButtonItem?.isEnabled = true } else { navigationItem.rightBarButtonItem?.isEnabled = false } return succeed() } } // MARK: - Selectors extension LoginListViewController { @objc func SELreloadLogins() { loadLogins() } @objc func SELedit() { navigationItem.rightBarButtonItem = nil navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(LoginListViewController.SELcancel)) selectionButtonHeightConstraint?.update(offset: UIConstants.ToolbarHeight) self.view.layoutIfNeeded() tableView.setEditing(true, animated: true) } @objc func SELcancel() { // Update selection and select all button loginSelectionController.deselectAll() toggleSelectionTitle() selectionButtonHeightConstraint?.update(offset: 0) self.view.layoutIfNeeded() tableView.setEditing(false, animated: true) navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(LoginListViewController.SELedit)) } @objc func SELdelete() { profile.logins.hasSyncedLogins().uponQueue(DispatchQueue.main) { yes in let deleteAlert = UIAlertController.deleteLoginAlertWithDeleteCallback({ [unowned self] _ in // Delete here let guidsToDelete = self.loginSelectionController.selectedIndexPaths.map { indexPath in self.loginDataSource.loginAtIndexPath(indexPath)!.guid } self.profile.logins.removeLoginsWithGUIDs(guidsToDelete).uponQueue(DispatchQueue.main) { _ in self.SELcancel() self.loadLogins() } }, hasSyncedLogins: yes.successValue ?? true) self.present(deleteAlert, animated: true, completion: nil) } } @objc func SELdidTapSelectionButton() { // If we haven't selected everything yet, select all if loginSelectionController.selectedCount < loginDataSource.count { // Find all unselected indexPaths let unselectedPaths = tableView.allIndexPaths.filter { indexPath in return !loginSelectionController.indexPathIsSelected(indexPath) } loginSelectionController.selectIndexPaths(unselectedPaths) unselectedPaths.forEach { indexPath in self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } } // If everything has been selected, deselect all else { loginSelectionController.deselectAll() tableView.allIndexPaths.forEach { indexPath in self.tableView.deselectRow(at: indexPath, animated: true) } } toggleSelectionTitle() toggleDeleteBarButton() } } // MARK: - UITableViewDelegate extension LoginListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { // Force the headers to be hidden return 0 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return LoginListUX.RowHeight } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { return .none } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView.isEditing { loginSelectionController.selectIndexPath(indexPath) toggleSelectionTitle() toggleDeleteBarButton() } else { tableView.deselectRow(at: indexPath, animated: true) let login = loginDataSource.loginAtIndexPath(indexPath)! let detailViewController = LoginDetailViewController(profile: profile, login: login) detailViewController.settingsDelegate = settingsDelegate navigationController?.pushViewController(detailViewController, animated: true) } } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if tableView.isEditing { loginSelectionController.deselectIndexPath(indexPath) toggleSelectionTitle() toggleDeleteBarButton() } } } // MARK: - KeyboardHelperDelegate extension LoginListViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { let coveredHeight = state.intersectionHeightForView(tableView) tableView.contentInset.bottom = coveredHeight } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { tableView.contentInset.bottom = 0 } } // MARK: - SearchInputViewDelegate extension LoginListViewController: SearchInputViewDelegate { @objc func searchInputView(_ searchView: SearchInputView, didChangeTextTo text: String) { loadLogins(text) } @objc func searchInputViewBeganEditing(_ searchView: SearchInputView) { // Trigger a cancel for editing SELcancel() // Hide the edit button while we're searching navigationItem.rightBarButtonItem = nil loadLogins() } @objc func searchInputViewFinishedEditing(_ searchView: SearchInputView) { // Show the edit after we're done with the search navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(LoginListViewController.SELedit)) loadLogins() } } /// Controller that keeps track of selected indexes fileprivate class ListSelectionController: NSObject { fileprivate unowned let tableView: UITableView fileprivate(set) var selectedIndexPaths = [IndexPath]() var selectedCount: Int { return selectedIndexPaths.count } init(tableView: UITableView) { self.tableView = tableView super.init() } func selectIndexPath(_ indexPath: IndexPath) { selectedIndexPaths.append(indexPath) } func indexPathIsSelected(_ indexPath: IndexPath) -> Bool { return selectedIndexPaths.contains(indexPath) { path1, path2 in return path1.row == path2.row && path1.section == path2.section } } func deselectIndexPath(_ indexPath: IndexPath) { guard let foundSelectedPath = (selectedIndexPaths.filter { $0.row == indexPath.row && $0.section == indexPath.section }).first, let indexToRemove = selectedIndexPaths.index(of: foundSelectedPath) else { return } selectedIndexPaths.remove(at: indexToRemove) } func deselectAll() { selectedIndexPaths.removeAll() } func selectIndexPaths(_ indexPaths: [IndexPath]) { selectedIndexPaths += indexPaths } } /// Data source for handling LoginData objects from a Cursor fileprivate class LoginCursorDataSource: NSObject, UITableViewDataSource { var count: Int { return allLogins.count } fileprivate var allLogins: [Login] = [] { didSet { computeLoginSections() } } fileprivate let emptyStateView = NoLoginsView() fileprivate var sections = [Character: [Login]]() fileprivate var titles = [Character]() fileprivate func loginsForSection(_ section: Int) -> [Login]? { let titleForSectionIndex = titles[section] return sections[titleForSectionIndex] } func loginAtIndexPath(_ indexPath: IndexPath) -> Login? { let titleForSectionIndex = titles[indexPath.section] return sections[titleForSectionIndex]?[indexPath.row] } @objc func numberOfSections(in tableView: UITableView) -> Int { let numOfSections = sections.count if numOfSections == 0 { tableView.backgroundView = emptyStateView tableView.separatorStyle = .none } else { tableView.backgroundView = nil tableView.separatorStyle = .singleLine } return numOfSections } @objc func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return loginsForSection(section)?.count ?? 0 } @objc func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: LoginCellIdentifier, for: indexPath) as! LoginTableViewCell let login = loginAtIndexPath(indexPath)! cell.style = .noIconAndBothLabels cell.updateCellWithLogin(login) return cell } @objc func sectionIndexTitles(for tableView: UITableView) -> [String]? { return titles.map { String($0) } } @objc func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return titles.index(of: Character(title)) ?? 0 } @objc func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return String(titles[section]) } fileprivate func computeLoginSections() { titles.removeAll() sections.removeAll() guard allLogins.count > 0 else { return } // Precompute the baseDomain, host, and hostname values for sorting later on. At the moment // baseDomain() is a costly call because of the ETLD lookup tables. var domainLookup = [GUID: (baseDomain: String?, host: String?, hostname: String)]() allLogins.forEach { login in domainLookup[login.guid] = ( login.hostname.asURL?.baseDomain, login.hostname.asURL?.host, login.hostname ) } // Rules for sorting login URLS: // 1. Compare base domains // 2. If bases are equal, compare hosts // 3. If login URL was invalid, revert to full hostname func sortByDomain(_ loginA: Login, loginB: Login) -> Bool { guard let domainsA = domainLookup[loginA.guid], let domainsB = domainLookup[loginB.guid] else { return false } guard let baseDomainA = domainsA.baseDomain, let baseDomainB = domainsB.baseDomain, let hostA = domainsA.host, let hostB = domainsB.host else { return domainsA.hostname < domainsB.hostname } if baseDomainA == baseDomainB { return hostA < hostB } else { return baseDomainA < baseDomainB } } // Temporarily insert titles into a Set to get duplicate removal for 'free'. var titleSet = Set<Character>() allLogins.forEach { login in // Fallback to hostname if we can't extract a base domain. let sortBy = login.hostname.asURL?.baseDomain?.uppercased() ?? login.hostname let sectionTitle = sortBy.characters.first ?? Character("") titleSet.insert(sectionTitle) var logins = sections[sectionTitle] ?? [] logins.append(login) logins.sort(by: sortByDomain) sections[sectionTitle] = logins } titles = Array(titleSet).sorted() } subscript(index: Int) -> Login { get { return allLogins[index] } } } /// Empty state view when there is no logins to display. fileprivate class NoLoginsView: UIView { // We use the search bar height to maintain visual balance with the whitespace on this screen. The // title label is centered visually using the empty view + search bar height as the size to center with. var searchBarHeight: CGFloat = 0 { didSet { setNeedsUpdateConstraints() } } lazy var titleLabel: UILabel = { let label = UILabel() label.font = LoginListUX.NoResultsFont label.textColor = LoginListUX.NoResultsTextColor label.text = Strings.NoLoginsFound return label }() override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) } fileprivate override func updateConstraints() { super.updateConstraints() titleLabel.snp.remakeConstraints { make in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-(searchBarHeight / 2)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } /// View to display to the user while we are loading the logins fileprivate class LoadingLoginsView: UIView { var searchBarHeight: CGFloat = 0 { didSet { setNeedsUpdateConstraints() } } lazy var indicator: UIActivityIndicatorView = { let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) indicator.hidesWhenStopped = false return indicator }() override init(frame: CGRect) { super.init(frame: frame) addSubview(indicator) backgroundColor = UIColor.white indicator.startAnimating() } fileprivate override func updateConstraints() { super.updateConstraints() indicator.snp.remakeConstraints { make in make.centerX.equalTo(self) make.centerY.equalTo(self).offset(-(searchBarHeight / 2)) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mpl-2.0
95e9b8b2d41e2325d658a5120f487437
34.602041
175
0.669246
5.567553
false
false
false
false
universonic/shadowsocks-macos
Shadowsocks/ProxyInterfacesViewCtrl.swift
1
2426
// // ProxyInterfacesTableViewCtrl.swift // Shadowsocks // // Created by 邱宇舟 on 2017/3/17. // Copyright 2019 Shadowsocks Community. All rights reserved. // import Cocoa import RxCocoa import RxSwift class ProxyInterfacesViewCtrl: NSViewController, NSTableViewDataSource, NSTableViewDelegate { var networkServices: NSArray! var selectedNetworkServices: NSMutableSet! @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var autoConfigCheckBox: NSButton! override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard if let services = defaults.array(forKey: "Proxy4NetworkServices") { selectedNetworkServices = NSMutableSet(array: services) } else { selectedNetworkServices = NSMutableSet() } networkServices = ProxyConfTool.networkServicesList() as NSArray? tableView.reloadData() } //-------------------------------------------------- // For NSTableViewDataSource func numberOfRows(in tableView: NSTableView) -> Int { if networkServices != nil { return networkServices.count } return 0; } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn? , row: Int) -> Any? { let cell = tableColumn!.dataCell as! NSButtonCell let networkService = networkServices[row] as! [String: Any] let key = networkService["key"] as! String if selectedNetworkServices.contains(key) { cell.state = .on } else { cell.state = .off } let userDefinedName = networkService["userDefinedName"] as! String cell.title = userDefinedName return cell } func tableView(_ tableView: NSTableView, setObjectValue object: Any? , for tableColumn: NSTableColumn?, row: Int) { let networkService = networkServices[row] as! [String: Any] let key = networkService["key"] as! String // NSLog("%d", object!.integerValue) if (object! as AnyObject).intValue == 1 { selectedNetworkServices.add(key) } else { selectedNetworkServices.remove(key) } UserDefaults.standard.set(selectedNetworkServices.allObjects, forKey: "Proxy4NetworkServices") } }
gpl-3.0
9bf6da0ca76dfc6badb1f305b5618546
31.266667
93
0.616942
5.365854
false
false
false
false
laszlokorte/reform-swift
ReformExpression/ReformExpression/Sheet.swift
1
7155
// // Sheet.swift // ExpressionEngine // // Created by Laszlo Korte on 07.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // public enum DefinitionValue { case primitive(Value) case array([Value]) case expr(Expression) case invalid(String, ShuntingYardError) } extension DefinitionValue { func collectedDependencies() -> Set<ReferenceId> { switch self { case .expr(let expr): return expr.collectedDependencies() default: return Set<ReferenceId>() } } } extension DefinitionValue { fileprivate func withSubstitutedReference(_ reference: ReferenceId, value: Value) -> DefinitionValue { switch self { case .expr(let expr): return .expr(expr.withSubstitutedReference(reference, value: value)) default: return self } } } extension Expression { fileprivate func withSubstitutedReference(_ reference: ReferenceId, value: Value) -> Expression { switch self { case .constant(let v): return .constant(v) case .namedConstant(let name, let v): return .namedConstant(name, v) case .reference(let id) where id == reference: return .constant(value) case .reference(let id): return .reference(id: id) case .unary(let op, let sub): return .unary(op, sub.withSubstitutedReference(reference, value: value)) case .binary(let op, let left, let right): return .binary(op, left.withSubstitutedReference(reference, value: value), right.withSubstitutedReference(reference, value: value)) case .call(let op, let args): return .call(op, args.map { $0.withSubstitutedReference(reference, value: value) }) } } } extension Expression { func collectedDependencies() -> Set<ReferenceId> { switch self { case .reference(let id): var set = Set<ReferenceId>() set.insert(id) return set case .unary(_, let sub): return sub.collectedDependencies() case .binary(_, let left, let right): return left.collectedDependencies().union(right.collectedDependencies()) case .call(_, let args): return args.reduce(Set<ReferenceId>()) { acc, next in acc.union(next.collectedDependencies()) } default: return Set<ReferenceId>() } } } final public class Definition { let id: ReferenceId var name: String var value : DefinitionValue init(id: ReferenceId, name: String, value : DefinitionValue) { self.id = id self.name = name self.value = value } } extension Definition { fileprivate func replaceOccurencesOf(_ reference: ReferenceId, with: Value) { value = value.withSubstitutedReference(reference, value: with) } } protocol DefinitionSheet { var sortedDefinitions : [Definition] { get } func definitionWithName(_ name: String) -> Definition? func definitionWithId(_ id: ReferenceId) -> Definition? } public protocol Sheet : class { var sortedDefinitions : (Set<ReferenceId>, [Definition]) { get } var referenceIds : Set<ReferenceId> { get } func definitionWithName(_ name:String) -> Definition? func definitionWithId(_ id:ReferenceId) -> Definition? func replaceOccurencesOf(_ reference: ReferenceId, with: Value) } public protocol EditableSheet : Sheet { func addDefinition(_ definition: Definition) func removeDefinition(_ definition: ReferenceId) } public final class BaseSheet : EditableSheet { private var definitions: [Definition] = [] public init() { } public var referenceIds : Set<ReferenceId> { return Set(definitions.map { $0.id }) } public var sortedDefinitions : (Set<ReferenceId>, [Definition]) { return sortDefinitions(definitions) } public func definitionWithName(_ name:String) -> Definition? { for def in definitions { if def.name == name { return def } } return nil } public func definitionWithId(_ id:ReferenceId) -> Definition? { for def in definitions { if def.id == id { return def } } return nil } public func replaceOccurencesOf(_ reference: ReferenceId, with: Value) { for def in definitions { def.replaceOccurencesOf(reference, with: with) } } public func addDefinition(_ definition: Definition) { definitions.append(definition) } public func removeDefinition(_ id: ReferenceId) { if let index = definitions.index(where: { $0.id == id }) { definitions.remove(at: index) } } } public final class DerivedSheet : EditableSheet { private var definitions: [Definition] = [] private let baseSheet : Sheet init(base: Sheet) { self.baseSheet = base } public var referenceIds : Set<ReferenceId> { return Set(definitions.map { $0.id }).union(baseSheet.referenceIds) } public var sortedDefinitions : (Set<ReferenceId>, [Definition]) { return sortDefinitions(referenceIds.flatMap({ definitionWithId($0) })) } public func definitionWithName(_ name:String) -> Definition? { for def in definitions { if def.name == name { return def } } return baseSheet.definitionWithName(name) } public func definitionWithId(_ id:ReferenceId) -> Definition? { for def in definitions { if def.id == id { return def } } return baseSheet.definitionWithId(id) } public func replaceOccurencesOf(_ reference: ReferenceId, with: Value) { for def in definitions { def.replaceOccurencesOf(reference, with: with) } } public func addDefinition(_ definition: Definition) { definitions.append(definition) } public func removeDefinition(_ id: ReferenceId) { if let index = definitions.index(where: { $0.id == id }) { definitions.remove(at: index) } } } func sortDefinitions(_ definitions: [Definition]) -> (Set<ReferenceId>, [Definition]) { var nodes = [ReferenceId:Node<ReferenceId, Definition>]() var duplicates = Set<ReferenceId>() for d in definitions { if nodes.keys.contains(d.id) { duplicates.insert(d.id) } else { nodes[d.id] = Node(id: d.id, data: d) } } for (_, node) in nodes { let dependencies = node.data.value.collectedDependencies().flatMap({ nodes[$0] }) for d in dependencies { d.outgoing.insert(node) } } return (duplicates, topologicallySorted(Array(nodes.values)).map { node -> Definition in return node.data }) }
mit
aa87f4ec565030415706172de864c047
27.054902
143
0.595611
4.722112
false
false
false
false
qutheory/vapor
Tests/VaporTests/ClientTests.swift
1
5234
import Vapor import XCTest final class ClientTests: XCTestCase { func testClientConfigurationChange() throws { let app = Application(.testing) defer { app.shutdown() } app.http.client.configuration.redirectConfiguration = .disallow app.get("redirect") { $0.redirect(to: "foo") } try app.server.start(address: .hostname("localhost", port: 8080)) defer { app.server.shutdown() } let res = try app.client.get("http://localhost:8080/redirect").wait() XCTAssertEqual(res.status, .seeOther) } func testClientConfigurationCantBeChangedAfterClientHasBeenUsed() throws { let app = Application(.testing) defer { app.shutdown() } app.http.client.configuration.redirectConfiguration = .disallow app.get("redirect") { $0.redirect(to: "foo") } try app.server.start(address: .hostname("localhost", port: 8080)) defer { app.server.shutdown() } _ = try app.client.get("http://localhost:8080/redirect").wait() app.http.client.configuration.redirectConfiguration = .follow(max: 1, allowCycles: false) let res = try app.client.get("http://localhost:8080/redirect").wait() XCTAssertEqual(res.status, .seeOther) } func testClientResponseCodable() throws { let app = Application(.testing) defer { app.shutdown() } let res = try app.client.get("https://httpbin.org/json").wait() let encoded = try JSONEncoder().encode(res) let decoded = try JSONDecoder().decode(ClientResponse.self, from: encoded) XCTAssertEqual(res, decoded) } func testClientBeforeSend() throws { let app = Application() defer { app.shutdown() } try app.boot() let res = try app.client.post("http://httpbin.org/anything") { req in try req.content.encode(["hello": "world"]) }.wait() struct HTTPBinAnything: Codable { var headers: [String: String] var json: [String: String] } let data = try res.content.decode(HTTPBinAnything.self) XCTAssertEqual(data.json, ["hello": "world"]) XCTAssertEqual(data.headers["Content-Type"], "application/json; charset=utf-8") } func testBoilerplateClient() throws { let app = Application(.testing) defer { app.shutdown() } app.get("foo") { req -> EventLoopFuture<String> in return req.client.get("https://httpbin.org/status/201").map { res in XCTAssertEqual(res.status.code, 201) req.application.running?.stop() return "bar" }.flatMapErrorThrowing { req.application.running?.stop() throw $0 } } try app.boot() try app.start() let res = try app.client.get("http://localhost:8080/foo").wait() XCTAssertEqual(res.body?.string, "bar") try app.running?.onStop.wait() } func testApplicationClientThreadSafety() throws { let app = Application(.testing) defer { app.shutdown() } let startingPistol = DispatchGroup() startingPistol.enter() startingPistol.enter() let finishLine = DispatchGroup() finishLine.enter() Thread.async { startingPistol.leave() startingPistol.wait() XCTAssert(type(of: app.http.client.shared) == HTTPClient.self) finishLine.leave() } finishLine.enter() Thread.async { startingPistol.leave() startingPistol.wait() XCTAssert(type(of: app.http.client.shared) == HTTPClient.self) finishLine.leave() } finishLine.wait() } func testCustomClient() throws { let app = Application(.testing) defer { app.shutdown() } app.clients.use(.custom) _ = try app.client.get("https://vapor.codes").wait() XCTAssertEqual(app.customClient.requests.count, 1) XCTAssertEqual(app.customClient.requests.first?.url.host, "vapor.codes") } } private final class CustomClient: Client { var eventLoop: EventLoop { EmbeddedEventLoop() } var requests: [ClientRequest] init() { self.requests = [] } func send(_ request: ClientRequest) -> EventLoopFuture<ClientResponse> { self.requests.append(request) return self.eventLoop.makeSucceededFuture(ClientResponse()) } func delegating(to eventLoop: EventLoop) -> Client { self } } private extension Application { struct CustomClientKey: StorageKey { typealias Value = CustomClient } var customClient: CustomClient { if let existing = self.storage[CustomClientKey.self] { return existing } else { let new = CustomClient() self.storage[CustomClientKey.self] = new return new } } } private extension Application.Clients.Provider { static var custom: Self { .init { $0.clients.use { $0.customClient } } } }
mit
4baa2c16f19340b5d48210d511973a90
28.240223
97
0.590753
4.543403
false
true
false
false
tlax/looper
looper/View/Camera/Filter/BlenderOverlay/VCameraFilterBlenderOverlayBase.swift
1
1864
import UIKit class VCameraFilterBlenderOverlayBase:UIView { private let kImageMargin:CGFloat = 2 private let kImageAlpha:CGFloat = 0.7 private let kBorderWidth:CGFloat = 1 init(model:MCameraFilterSelectorItem) { super.init(frame:CGRect.zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false layer.borderWidth = kBorderWidth layer.borderColor = UIColor.black.cgColor if let modelRecord:MCameraFilterSelectorItemRecord = model as? MCameraFilterSelectorItemRecord { backgroundColor = UIColor.black let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.scaleAspectFill imageView.clipsToBounds = true imageView.alpha = kImageAlpha imageView.image = modelRecord.record.items.first?.image addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self, margin:kImageMargin) } else if let modelColor:MCameraFilterSelectorItemColor = model as? MCameraFilterSelectorItemColor { backgroundColor = modelColor.color } } required init?(coder:NSCoder) { return nil } //MARK: public func validatePiece(viewPiece:VCameraFilterBlenderOverlayPiece) { let pieceFrame:CGRect = viewPiece.frame if frame.intersects(pieceFrame) { viewPiece.insideBase() } else { viewPiece.outsideBase() } } }
mit
7d3607f1bf777334b951e175fa5687dc
28.587302
104
0.61588
5.806854
false
false
false
false
GarrettAlbright/AdventOfCode
Day 03/main.swift
1
2595
// // main.swift // // // Created by Garrett Albright on 12/5/15. // // import Foundation let input: String var visitedCoords: Dictionary<Int, Dictionary<Int, Int>> = [0: [0: 1]] var x: Int = 0 var y: Int = 0 enum Deliverer: Int { case Santa, RoboSanta } var roboSantasTurn: Bool = true var santaVsRoboSantaVisitedCoords: Dictionary<Int, Dictionary<Int, Int>> = [0: [0: 1]] var santaVsRoboSantaCoords: Dictionary<Deliverer, Dictionary<Character, Int>> = [.Santa: ["x": 0, "y": 0], .RoboSanta: ["x": 0, "y": 0]] do { input = try String(contentsOfFile: "input.txt", encoding: NSASCIIStringEncoding) } catch { print("Coudn't open input file.") exit(1) } for direction: Character in input.characters { roboSantasTurn = !roboSantasTurn let deliverer: Deliverer = roboSantasTurn ? .RoboSanta : .Santa switch direction { case "<": x-- santaVsRoboSantaCoords[deliverer]!["x"] = santaVsRoboSantaCoords[deliverer]!["x"]! - 1 case ">": x++ santaVsRoboSantaCoords[deliverer]!["x"] = santaVsRoboSantaCoords[deliverer]!["x"]! + 1 case "^": y-- santaVsRoboSantaCoords[deliverer]!["y"] = santaVsRoboSantaCoords[deliverer]!["y"]! - 1 case "v": y++ santaVsRoboSantaCoords[deliverer]!["y"] = santaVsRoboSantaCoords[deliverer]!["y"]! + 1 default: print("Unexpected directional character \"\(direction)\"") exit(2) } if visitedCoords.indexForKey(x) == nil { visitedCoords[x] = [:] } if visitedCoords[x]!.indexForKey(y) == nil { visitedCoords[x]![y] = 1 } else { visitedCoords[x]![y] = visitedCoords[x]![y]! + 1 } let delivererX: Int = santaVsRoboSantaCoords[deliverer]!["x"]! let delivererY: Int = santaVsRoboSantaCoords[deliverer]!["y"]! if santaVsRoboSantaVisitedCoords.indexForKey(delivererX) == nil { santaVsRoboSantaVisitedCoords[delivererX] = [:] } if santaVsRoboSantaVisitedCoords[delivererX]!.indexForKey(delivererY) == nil { santaVsRoboSantaVisitedCoords[delivererX]![delivererY] = 1 } else { santaVsRoboSantaVisitedCoords[delivererX]![delivererY] = santaVsRoboSantaVisitedCoords[delivererX]![delivererY]! + 1 } } var houseCount = 0 for (_, yHouses) in visitedCoords { houseCount += yHouses.count } var nextYearHouseCount = 0 for (_, yHouses) in santaVsRoboSantaVisitedCoords { nextYearHouseCount += yHouses.count } print("Santa visited \(houseCount) houses.") print("The next year, Santa and Robo-Santa visited \(nextYearHouseCount) houses.")
bsd-2-clause
16a084105a1d629f6274f2ea0e5bd5d0
27.516484
136
0.654335
4.178744
false
false
false
false
Ashok28/Kingfisher
Sources/General/ImageSource/AVAssetImageDataProvider.swift
6
5129
// // AVAssetImageDataProvider.swift // Kingfisher // // Created by onevcat on 2020/08/09. // // Copyright (c) 2020 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !os(watchOS) import Foundation import AVKit #if canImport(MobileCoreServices) import MobileCoreServices #else import CoreServices #endif /// A data provider to provide thumbnail data from a given AVKit asset. public struct AVAssetImageDataProvider: ImageDataProvider { /// The possible error might be caused by the `AVAssetImageDataProvider`. /// - userCancelled: The data provider process is cancelled. /// - invalidImage: The retrieved image is invalid. public enum AVAssetImageDataProviderError: Error { case userCancelled case invalidImage(_ image: CGImage?) } /// The asset image generator bound to `self`. public let assetImageGenerator: AVAssetImageGenerator /// The time at which the image should be generate in the asset. public let time: CMTime private var internalKey: String { return (assetImageGenerator.asset as? AVURLAsset)?.url.absoluteString ?? UUID().uuidString } /// The cache key used by `self`. public var cacheKey: String { return "\(internalKey)_\(time.seconds)" } /// Creates an asset image data provider. /// - Parameters: /// - assetImageGenerator: The asset image generator controls data providing behaviors. /// - time: At which time in the asset the image should be generated. public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) { self.assetImageGenerator = assetImageGenerator self.time = time } /// Creates an asset image data provider. /// - Parameters: /// - assetURL: The URL of asset for providing image data. /// - time: At which time in the asset the image should be generated. /// /// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls /// the `init(assetImageGenerator:time:)` initializer. /// public init(assetURL: URL, time: CMTime) { let asset = AVAsset(url: assetURL) let generator = AVAssetImageGenerator(asset: asset) self.init(assetImageGenerator: generator, time: time) } /// Creates an asset image data provider. /// /// - Parameters: /// - assetURL: The URL of asset for providing image data. /// - seconds: At which time in seconds in the asset the image should be generated. /// /// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`, /// and calls the `init(assetImageGenerator:time:)` initializer. /// public init(assetURL: URL, seconds: TimeInterval) { let time = CMTime(seconds: seconds, preferredTimescale: 600) self.init(assetURL: assetURL, time: time) } public func data(handler: @escaping (Result<Data, Error>) -> Void) { assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) { (requestedTime, image, imageTime, result, error) in if let error = error { handler(.failure(error)) return } if result == .cancelled { handler(.failure(AVAssetImageDataProviderError.userCancelled)) return } guard let cgImage = image, let data = cgImage.jpegData else { handler(.failure(AVAssetImageDataProviderError.invalidImage(image))) return } handler(.success(data)) } } } extension CGImage { var jpegData: Data? { guard let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) else { return nil } CGImageDestinationAddImage(destination, self, nil) guard CGImageDestinationFinalize(destination) else { return nil } return mutableData as Data } } #endif
mit
ac329523ce7bfe7cb4611119cf518c32
36.437956
117
0.6744
4.861611
false
false
false
false
hanjoes/Smashtag
Smashtag/WebUIViewController.swift
1
1168
// // WebUIViewController.swift // Smashtag // // Created by Hanzhou Shi on 1/17/16. // Copyright © 2016 USF. All rights reserved. // import UIKit class WebUIViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! @IBOutlet weak var goBackButton: UIBarButtonItem! @IBOutlet weak var goForwardButton: UIBarButtonItem! @IBAction func goBack(sender: UIBarButtonItem) { webView.goBack() } @IBAction func goForward(sender: UIBarButtonItem) { webView.goForward() } // MARK: - Live Cycle override func viewDidLoad() { if url != nil { loadPage() } webView.delegate = self } // MARK: - Delegate for UIWebView func webViewDidFinishLoad(webView: UIWebView) { goBackButton.enabled = self.webView.canGoBack goForwardButton.enabled = self.webView.canGoForward } var url: NSURL? { didSet { if url != nil { loadPage() } } } private func loadPage() { webView?.loadRequest(NSURLRequest(URL: url!)) } }
mit
1d69f7c01043f228610c87116c8d7574
21.882353
64
0.594687
4.782787
false
false
false
false
rodrigoff/hackingwithswift
project7/Project7/DetailViewController.swift
1
1163
// // DetailViewController.swift // Project7 // // Created by Rodrigo F. Fernandes on 7/21/17. // Copyright © 2017 Rodrigo F. Fernandes. All rights reserved. // import UIKit import WebKit class DetailViewController: UIViewController { var webView: WKWebView! var detailItem: [String: String]! override func loadView() { webView = WKWebView() view = webView } override func viewDidLoad() { super.viewDidLoad() guard detailItem != nil else { return } if let body = detailItem["body"] { var html = "<html>" html += "<head>" html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" html += "<style> body { font-size: 150%; } </style>" html += "</head>" html += "<body>" html += body html += "</body>" html += "</html>" webView.loadHTMLString(html, baseURL: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
df33ef9a698d16a47e1a658c86877963
24.26087
94
0.549914
4.685484
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/Settings/CliqzAppSettingsOptions.swift
1
25387
// // CliqzAppSettingsOptions.swift // Client // // Created by Mahmoud Adam on 3/4/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import MessageUI import Shared import React //Cliqz: Added to modify the behavior of changing default search engine class CliqzSearchSetting: SearchSetting, SearchEnginePickerDelegate { //Cliqz: override onclick to directly go to default search engine selection override func onClick(_ navigationController: UINavigationController?) { let searchEnginePicker = SearchEnginePicker() searchEnginePicker.title = self.title?.string // Order alphabetically, so that picker is always consistently ordered. // Every engine is a valid choice for the default engine, even the current default engine. searchEnginePicker.engines = profile.searchEngines.orderedEngines.sorted { e, f in e.shortName < f.shortName } searchEnginePicker.delegate = self searchEnginePicker.selectedSearchEngineName = profile.searchEngines.defaultEngine.shortName navigationController?.pushViewController(searchEnginePicker, animated: true) let searchEngineSingal = TelemetryLogEventType.Settings("main", "click", "search_engine", nil, nil) TelemetryLogger.sharedInstance.logEvent(searchEngineSingal) } func searchEnginePicker(_ searchEnginePicker: SearchEnginePicker?, didSelectSearchEngine engine: OpenSearchEngine?) -> Void { if let searchEngine = engine { profile.searchEngines.defaultEngine = searchEngine } } } //Cliqz: Added Settings for legal page class ImprintSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Imprint", tableName: "Cliqz", comment: "Show Cliqz legal page. See https://cliqz.com/legal"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: "https://cliqz.com/legal") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) // log Telemerty signal let imprintSingal = TelemetryLogEventType.Settings("main", "click", "imprint", nil, nil) TelemetryLogger.sharedInstance.logEvent(imprintSingal) } } //Cliqz: Added new settings item for Human Web class HumanWebSetting: Setting { let profile: Profile override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: SettingsPrefs.shared.getHumanWebPref() ? Setting.onStatus : Setting.offStatus) } init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Human Web", tableName: "Cliqz", comment: "[Settings] Human Web") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = HumanWebSettingsTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let humanWebSingal = TelemetryLogEventType.Settings("main", "click", "human_web", nil, nil) TelemetryLogger.sharedInstance.logEvent(humanWebSingal) } } //Cliqz: Added new settings item for Sending crash reports class SendCrashReportsSetting: Setting { let profile: Profile override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: SettingsPrefs.shared.getSendCrashReportsPref() ? Setting.onStatus : Setting.offStatus) } init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Send Crash Reports", tableName: "Cliqz", comment: "[Settings] Send Crash Reports") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = SendCrashReportsSubSettingsController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let humanWebSingal = TelemetryLogEventType.Settings("main", "click", "crash_reports", nil, nil) TelemetryLogger.sharedInstance.logEvent(humanWebSingal) } } class AboutSetting: Setting { override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: "Version \(AppStatus.sharedInstance.distVersion)") } init() { let title = NSLocalizedString("About", tableName: "Cliqz", comment: "[Settings] About") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = AboutSettingsTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) } } class RateUsSetting: Setting { let AppId = "1065837334" init() { super.init(title: NSAttributedString(string: NSLocalizedString("Rate Us", tableName: "Cliqz", comment: "[Settings] Rate Us"), attributes: [NSForegroundColorAttributeName: UIConstants.HighlightBlue])) } override func onClick(_ navigationController: UINavigationController?) { var urlString: String! if #available(iOS 11.0, *) { urlString = "itms-apps://itunes.apple.com/app/id\(AppId)" } else { urlString = "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=\(AppId)&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8" } if let url = URL(string: urlString) { UIApplication.shared.openURL(url) } } } class TestReact: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile let reactTitle = "Test React" super.init(title: NSAttributedString(string: reactTitle, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = UIViewController() viewController.view = Engine.sharedInstance.rootView navigationController?.pushViewController(viewController, animated: true) } } //Cliqz: Added new settings item for Ad Blocker class AdBlockerSetting: Setting { let profile: Profile override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: SettingsPrefs.shared.getAdBlockerPref() ? Setting.onStatus : Setting.offStatus) } init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Block Ads", tableName: "Cliqz", comment: "[Settings] Block Ads") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = AdBlockerSettingsTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let blcokAdsSingal = TelemetryLogEventType.Settings("main", "click", "block_ads", nil, nil) TelemetryLogger.sharedInstance.logEvent(blcokAdsSingal) } } //Cliqz: Added Settings for redirecting to feedback page class SupportSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("FAQ & Support", tableName: "Cliqz", comment: "[Settings] FAQ & Support"),attributes: [NSForegroundColorAttributeName: UIConstants.HighlightBlue]) } override var url: URL? { return URL(string: "https://cliqz.com/support") } override func onClick(_ navigationController: UINavigationController?) { navigationController?.dismiss(animated: true, completion: {}) self.delegate?.settingsOpenURLInNewTab(self.url!) // Cliqz: log telemetry signal let contactSignal = TelemetryLogEventType.Settings("main", "click", "contact", nil, nil) TelemetryLogger.sharedInstance.logEvent(contactSignal) } } //Cliqz: Added Setting for redirecting to report form class ReportWebsiteSetting: Setting { override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("Report Website", tableName: "Cliqz", comment: "[Settings] Report Website"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { if let languageCode = Locale.current.regionCode, languageCode == "de"{ return URL(string: "https://cliqz.com/report-url") } return URL(string: "https://cliqz.com/en/report-url") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) // Cliqz: log telemetry signal let contactSignal = TelemetryLogEventType.Settings("main", "click", "contact", nil, nil) TelemetryLogger.sharedInstance.logEvent(contactSignal) } } //Cliqz: Added Setting for redirecting to MyOffrz url class MyOffrzSetting: Setting { override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var title: NSAttributedString? { //TODO Translations return NSAttributedString(string: NSLocalizedString("About MyOffrz", tableName: "Cliqz", comment: "[Settings] About MyOffrz"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { if let languageCode = Locale.current.regionCode, languageCode == "de"{ return URL(string: "https://cliqz.com/myoffrz") } return URL(string: "https://cliqz.com/en/myoffrz") } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) // Cliqz: log telemetry signal let contactSignal = TelemetryLogEventType.Settings("main", "click", "myoffrz", nil, nil) TelemetryLogger.sharedInstance.logEvent(contactSignal) } } // Cliqz: Custom Bool settings for News Push Notifications class EnablePushNotifications: BoolSetting { @objc override func switchValueChanged(_ control: UISwitch) { super.switchValueChanged(control) if control.isOn { NewsNotificationPermissionHelper.sharedInstance.enableNewsNotifications() } else { NewsNotificationPermissionHelper.sharedInstance.disableNewsNotifications() } } } // Cliqz: setting to reset top sites class RestoreTopSitesSetting: Setting { let profile: Profile weak var settingsViewController: SettingsTableViewController? init(settings: SettingsTableViewController) { self.profile = settings.profile self.settingsViewController = settings let hiddenTopsitesCount = self.profile.history.getHiddenTopSitesCount() var attributes: [String : AnyObject]? if hiddenTopsitesCount > 0 { attributes = [NSForegroundColorAttributeName: UIConstants.HighlightBlue] } else { attributes = [NSForegroundColorAttributeName: UIColor.lightGray] } super.init(title: NSAttributedString(string: NSLocalizedString("Restore Most Visited Websites", tableName: "Cliqz", comment: "[Settings] Restore Most Visited Websites"), attributes: attributes)) } override func onClick(_ navigationController: UINavigationController?) { guard self.profile.history.getHiddenTopSitesCount() > 0 else { return } let alertController = UIAlertController( title: "", message: NSLocalizedString("All most visited websites will be shown again on the startpage.", tableName: "Cliqz", comment: "[Settings] Text of the 'Restore Most Visited Websites' alert"), preferredStyle: UIAlertControllerStyle.actionSheet) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", tableName: "Cliqz", comment: "Cancel button in the 'Show blocked top-sites' alert"), style: .cancel) { (action) in // log telemetry signal let cancelSignal = TelemetryLogEventType.Settings("restore_topsites", "click", "cancel", nil, nil) TelemetryLogger.sharedInstance.logEvent(cancelSignal) }) alertController.addAction( UIAlertAction(title: self.title?.string, style: .destructive) { (action) in // reset top-sites self.profile.history.deleteAllHiddenTopSites() self.settingsViewController?.reloadSettings() // log telemetry signal let confirmSignal = TelemetryLogEventType.Settings("restore_topsites", "click", "confirm", nil, nil) TelemetryLogger.sharedInstance.logEvent(confirmSignal) }) navigationController?.present(alertController, animated: true, completion: nil) // log telemetry signal let restoreTopsitesSignal = TelemetryLogEventType.Settings("main", "click", "restore_topsites", nil, nil) TelemetryLogger.sharedInstance.logEvent(restoreTopsitesSignal) } } // Cliqz: setting to reset subscriptions class ResetSubscriptionsSetting: Setting { let profile: Profile weak var settingsViewController: SettingsTableViewController? init(settings: SettingsTableViewController) { self.profile = settings.profile self.settingsViewController = settings var attributes: [String : AnyObject]? if SubscriptionsHandler.sharedInstance.hasSubscriptions() { attributes = [NSForegroundColorAttributeName: UIConstants.HighlightBlue] } else { attributes = [NSForegroundColorAttributeName: UIColor.lightGray] } super.init(title: NSAttributedString(string: NSLocalizedString("Reset all subscriptions", tableName: "Cliqz", comment: "[Settings] Reset all subscriptions"), attributes: attributes)) } override func onClick(_ navigationController: UINavigationController?) { guard SubscriptionsHandler.sharedInstance.hasSubscriptions() else { return } let alertController = UIAlertController( title: "", message: NSLocalizedString("Would you like to reset all your subscriptions (e.g. to Bundesliga games)?", tableName: "Cliqz", comment: "[Settings] Text of the 'Reset all subscriptions' alert"), preferredStyle: UIAlertControllerStyle.actionSheet) alertController.addAction( UIAlertAction(title: NSLocalizedString("Cancel", tableName: "Cliqz", comment: "Cancel button in the 'Reset all subscriptions' alert"), style: .cancel) { (action) in // log telemetry signal let cancelSignal = TelemetryLogEventType.Settings("reset_subscriptions", "click", "cancel", nil, nil) TelemetryLogger.sharedInstance.logEvent(cancelSignal) }) alertController.addAction( UIAlertAction(title: self.title?.string, style: .destructive) { (action) in SubscriptionsHandler.sharedInstance.resetSubscriptions() self.settingsViewController?.reloadSettings() // log telemetry signal let confirmSignal = TelemetryLogEventType.Settings("reset_subscriptions", "click", "confirm", nil, nil) TelemetryLogger.sharedInstance.logEvent(confirmSignal) }) navigationController?.present(alertController, animated: true, completion: nil) // log telemetry signal let restoreTopsitesSignal = TelemetryLogEventType.Settings("main", "click", "reset_subscriptions", nil, nil) TelemetryLogger.sharedInstance.logEvent(restoreTopsitesSignal) } } // Opens the search settings pane class RegionalSetting: Setting { let profile: Profile override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { let region = SettingsPrefs.shared.getUserRegionPref() let localizedRegionName = RegionalSettingsTableViewController.getLocalizedRegionName(region) return NSAttributedString(string: localizedRegionName) } override var accessibilityIdentifier: String? { return "Search Results for" } init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Search Results for", tableName: "Cliqz" , comment: "[Settings] Search Results for") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override func onClick(_ navigationController: UINavigationController?) { let viewController = RegionalSettingsTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let blcokAdsSingal = TelemetryLogEventType.Settings("main", "click", "search_results_from", nil, nil) TelemetryLogger.sharedInstance.logEvent(blcokAdsSingal) } } //Cliqz: Added new settings item sending local data class ExportLocalDatabaseSetting: Setting, MFMailComposeViewControllerDelegate { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile super.init(title: NSAttributedString(string: "Export Local Database", attributes: [NSForegroundColorAttributeName: UIConstants.HighlightBlue])) } override func onClick(_ navigationController: UINavigationController?) { let localDataBaseFile = try! profile.files.getAndEnsureDirectory() let path = URL(fileURLWithPath: localDataBaseFile) if let data = try? Data(contentsOf: path.appendingPathComponent("browser.db"), options: []) { if MFMailComposeViewController.canSendMail() { let mailComposeViewController = configuredMailComposeViewController(data: data) navigationController?.present(mailComposeViewController, animated: true, completion: nil) } } } func configuredMailComposeViewController(data: Data) -> MFMailComposeViewController { let mailComposerVC = MFMailComposeViewController() mailComposerVC.mailComposeDelegate = self mailComposerVC.setSubject("CLIQZ Local Database") mailComposerVC.addAttachmentData(data, mimeType: "application/sqlite", fileName: "browser.sqlite") return mailComposerVC } // MARK: MFMailComposeViewControllerDelegate Method func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { controller.dismiss(animated: true, completion: nil) } } class LimitMobileDataUsageSetting: Setting { let profile: Profile override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: SettingsPrefs.shared.getLimitMobileDataUsagePref() ? Setting.onStatus : Setting.offStatus) } init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Limit Mobile Data Usage", tableName: "Cliqz", comment: "[Settings] Limit Mobile Data Usage") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = LimitMobileDataUsageTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let limitMobileDataUsageSingal = TelemetryLogEventType.Settings("main", "click", viewController.getViewName(), nil, nil) TelemetryLogger.sharedInstance.logEvent(limitMobileDataUsageSingal) } } class AutoForgetTabSetting: Setting { let profile: Profile override var style: UITableViewCellStyle { return .value1 } override var status: NSAttributedString { return NSAttributedString(string: SettingsPrefs.shared.getAutoForgetTabPref() ? Setting.onStatus : Setting.offStatus) } init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Automatic Forget Tab", tableName: "Cliqz", comment: " [Settings] Automatic Forget Tab") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = AutoForgetTabTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let limitMobileDataUsageSingal = TelemetryLogEventType.Settings("main", "click", viewController.getViewName(), nil, nil) TelemetryLogger.sharedInstance.logEvent(limitMobileDataUsageSingal) } } class CliqzConnectSetting: Setting { let profile: Profile init(settings: SettingsTableViewController) { self.profile = settings.profile let title = NSLocalizedString("Connect", tableName: "Cliqz", comment: "[Settings] Connect") super.init(title: NSAttributedString(string: title, attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor])) } override var accessoryType: UITableViewCellAccessoryType { return .disclosureIndicator } override func onClick(_ navigationController: UINavigationController?) { let viewController = ConnectTableViewController() viewController.title = self.title?.string navigationController?.pushViewController(viewController, animated: true) // log Telemerty signal let connectSingal = TelemetryLogEventType.Settings("main", "click", "connect", nil, nil) TelemetryLogger.sharedInstance.logEvent(connectSingal) } } // Cliqz: Opens the the Eula page in a new tab class EulaSetting: Setting { override var title: NSAttributedString? { return NSAttributedString(string: NSLocalizedString("EULA", tableName: "Cliqz", comment: "[Settings -> About] EULA"), attributes: [NSForegroundColorAttributeName: UIConstants.TableViewRowTextColor]) } override var url: URL? { return URL(string: WebServer.sharedInstance.URLForResource("eula", module: "about")) } override func onClick(_ navigationController: UINavigationController?) { setUpAndPushSettingsContentViewController(navigationController) // Cliqz: log telemetry signal let licenseSignal = TelemetryLogEventType.Settings("main", "click", "eula", nil, nil) TelemetryLogger.sharedInstance.logEvent(licenseSignal) } }
mpl-2.0
cc77085a1e0b6ab10c45caa7ab614b96
41.881757
235
0.708028
5.703437
false
false
false
false
benlangmuir/swift
test/stdlib/Filter.swift
25
2638
//===--- Filter.swift - tests for lazy filtering --------------------------===// // // 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 // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest let FilterTests = TestSuite("Filter") // Check that the generic parameter is called 'Base'. protocol TestProtocol1 {} extension LazyFilterIterator where Base : TestProtocol1 { var _baseIsTestProtocol1: Bool { fatalError("not implemented") } } extension LazyFilterSequence where Base : TestProtocol1 { var _baseIsTestProtocol1: Bool { fatalError("not implemented") } } extension LazyFilterCollection where Base : TestProtocol1 { var _baseIsTestProtocol1: Bool { fatalError("not implemented") } } FilterTests.test("filtering collections") { let f0 = LazyFilterCollection(_base: 0..<30) { $0 % 7 == 0 } expectEqualSequence([0, 7, 14, 21, 28], f0) let f1 = LazyFilterCollection(_base: 1..<30) { $0 % 7 == 0 } expectEqualSequence([7, 14, 21, 28], f1) } FilterTests.test("filtering sequences") { let f0 = (0..<30).makeIterator().lazy.filter { $0 % 7 == 0 } expectEqualSequence([0, 7, 14, 21, 28], f0) let f1 = (1..<30).makeIterator().lazy.filter { $0 % 7 == 0 } expectEqualSequence([7, 14, 21, 28], f1) } FilterTests.test("single-count") { // Check that we're only calling a lazy filter's predicate one time for // each element in a sequence or collection. var count = 0 let mod7AndCount: (Int) -> Bool = { count += 1 return $0 % 7 == 0 } let f0 = (0..<30).makeIterator().lazy.filter(mod7AndCount) _ = Array(f0) expectEqual(30, count) count = 0 let f1 = LazyFilterCollection(_base: 0..<30, mod7AndCount) _ = Array(f1) expectEqual(30, count) } FilterTests.test("chained filter order") { let array = [1] let lazyFilter = array.lazy .filter { _ in false } .filter { _ in expectUnreachable("Executed second filter before first") return true } let lazyResult = Array(lazyFilter) let result = array .filter { _ in false } .filter { _ in expectUnreachable("Executed second filter before first") return true } expectEqual(lazyResult.count, 0) expectEqual(result.count, 0) } runAllTests()
apache-2.0
022a615a486c686ce9fe81cb266e1d6a
25.918367
80
0.643669
3.890855
false
true
false
false
daviejaneway/OrbitFrontend
Sources/PairRule.swift
1
952
// // PairRule.swift // OrbitFrontend // // Created by Davie Janeway on 07/09/2017. // // import Foundation import OrbitCompilerUtils public class PairRule : ParseRule { public let name = "Orb.Core.Grammar.Pair" public func trigger(tokens: [Token]) throws -> Bool { guard tokens.count > 1 else { throw OrbitError.ranOutOfTokens() } let name = tokens[0] let type = tokens[1] return name.type == .Identifier && type.type == .TypeIdentifier } public func parse(context: ParseContext) throws -> AbstractExpression { let nameRule = IdentifierRule() let typeRule = TypeIdentifierRule() let name = try nameRule.parse(context: context) as! IdentifierExpression let type = try typeRule.parse(context: context) as! TypeIdentifierExpression return PairExpression(name: name, type: type, startToken: name.startToken) } }
mit
73af2c0026d74fb0bd357112e5e0a397
27.848485
84
0.642857
4.212389
false
false
false
false
Mobilette/AniMee
AniMee/Classes/Modules/Anime/List/Week/App Logic/Entity/AnimeListWeekItem.swift
1
948
// // AnimeListWeekItem.swift // AniMee // // Created by Romain ASNAR on 9/12/15. // Copyright (c) 2015 Mobilette. All rights reserved. // import Foundation class AnimeListWeekItem: Equatable, CustomStringConvertible { // MARK: - Property var identifier: String? = nil var title: String = "" var imageURLString: String? = nil var releaseDate: NSDate = NSDate() // MARK: - Life cycle init() {} // MARK: - Printable protocol var description: String { return "{ AnimeListWeekItem" + "\n" + "identifier: \(self.identifier)" + "\n" + "title: \(self.title)" + "\n" + "imageURLString: \(self.imageURLString)" + "\n" + "releaseDate: \(self.releaseDate)" + "\n" + "}" + "\n" } } // MARK: - Equatable protocol func ==(lhs: AnimeListWeekItem, rhs: AnimeListWeekItem) -> Bool { return lhs.identifier == rhs.identifier }
mit
69a465bd7cd280e1fd2d09a622a95fcc
21.595238
65
0.579114
4.016949
false
false
false
false
WillH1983/BaseClassesSwift
Pod/Source Files/ServiceLayer/BaseClassesService.swift
1
1433
// // ScrubTechService.swift // Scrub Tech // // Created by William Hindenburg on 11/13/15. // Copyright © 2015 Robot Woods, LLC. All rights reserved. // import UIKit import Alamofire public protocol BaseClassesService: URLConvertible { var serviceURL:String {get} var baseURL:String {get} var rootRequestKeyPath:String? {get} var rootKeyPath:String {get} var requestQueryParameters:Dictionary<String, String>? {get} func asURL() throws -> URL } extension BaseClassesService { public var baseURL:String { return "https://m4cnztuipf.execute-api.us-east-1.amazonaws.com/prod" } public func asURL() throws -> URL { return URL(string: self.URLString)!; } public var URLString:String { var urlString = self.baseURL + self.serviceURL if self.requestQueryParameters != nil { var queryString = "?" for (key, value) in self.requestQueryParameters! { queryString = queryString + key + "=" + value + "&" } urlString = urlString + queryString urlString = String(urlString.characters.dropLast()) } return urlString } public var rootRequestKeyPath:String? { return nil } public var rootKeyPath:String { return "" } public var requestQueryParameters:Dictionary<String, String>? { return nil } }
mit
fdf0785dd3dd2a9d6faba454f3c6e28b
25.518519
76
0.623603
4.379205
false
false
false
false
jeremyabannister/JABSwiftCore
JABSwiftCore/UIFontExtension.swift
1
1221
// // UIFontExtension.swift // JABSwiftCore // // Created by Jeremy Bannister on 5/9/15. // Copyright (c) 2015 Jeremy Bannister. All rights reserved. // import Foundation public extension UIFont { public func sizeOfString (_ string: String, constrainedToWidth width: CGFloat, characterSpacing: CGFloat? = nil, paragraphStyle: NSMutableParagraphStyle? = nil) -> CGSize { var attributes: [NSAttributedStringKey: Any] = [.font: self] if let characterSpacing = characterSpacing { attributes[.kern] = characterSpacing } if let paragraphStyle = paragraphStyle { attributes[.paragraphStyle] = paragraphStyle } return (string as NSString).boundingRect(with: CGSize(width: Double(width), height: Double.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil).size } public static func == (_ lhs: UIFont, rhs: UIFont) -> Bool { return lhs.familyName == rhs.familyName && lhs.fontName == rhs.fontName && lhs.pointSize == rhs.pointSize } }
mit
cccd19f31c3c97ce4833c2552e65f498
42.607143
176
0.622441
5.450893
false
false
false
false
andrelind/swift-catmullrom
CGPoint+Utilities.swift
1
1755
import Foundation extension CGPoint{ func translate(x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPointMake(self.x + x, self.y + y) } func translateX(x: CGFloat) -> CGPoint { return CGPointMake(self.x + x, self.y) } func translateY(y: CGFloat) -> CGPoint { return CGPointMake(self.x, self.y + y) } func invertY() -> CGPoint { return CGPointMake(self.x, -self.y) } func xAxis() -> CGPoint { return CGPointMake(0, self.y) } func yAxis() -> CGPoint { return CGPointMake(self.x, 0) } func addTo(a: CGPoint) -> CGPoint { return CGPointMake(self.x + a.x, self.y + a.y) } func deltaTo(a: CGPoint) -> CGPoint { return CGPointMake(self.x - a.x, self.y - a.y) } func multiplyBy(value:CGFloat) -> CGPoint{ return CGPointMake(self.x * value, self.y * value) } func length() -> CGFloat { return CGFloat(sqrt(CDouble( self.x*self.x + self.y*self.y ))) } func normalize() -> CGPoint { let l = self.length() return CGPointMake(self.x / l, self.y / l) } static func fromString(string: String) -> CGPoint { var s = string.stringByReplacingOccurrencesOfString("{", withString: "") s = s.stringByReplacingOccurrencesOfString("}", withString: "") s = s.stringByReplacingOccurrencesOfString(" ", withString: "") let x = NSString(string: s.componentsSeparatedByString(",").first! as String).doubleValue let y = NSString(string: s.componentsSeparatedByString(",").last! as String).doubleValue return CGPointMake(CGFloat(x), CGFloat(y)) } }
mit
9b179fadaffe17443d33639be3fb4520
27.786885
97
0.57151
4.178571
false
false
false
false
ahoppen/swift
test/SourceKit/CodeComplete/complete_group_overloads.swift
21
2986
struct A {} struct B {} func aaa() {} func aaa(_ x: A) {} func aaa(_ x: B) {} func aaa(_ x: B, y: B) {} func aaa(x x: B, y: B) {} func aab() {} func test001() { #^TOP_LEVEL_0,aa^# } // RUN: %complete-test -group=overloads -tok=TOP_LEVEL_0 %s | %FileCheck -check-prefix=TOP_LEVEL_0 %s // TOP_LEVEL_0-LABEL: aaa: // TOP_LEVEL_0-NEXT: aaa() // TOP_LEVEL_0-NEXT: aaa(x: A) // TOP_LEVEL_0-NEXT: aaa(x: B) // TOP_LEVEL_0-NEXT: aaa(x: B, y: B) // TOP_LEVEL_0-NEXT: aaa(x: B, y: B) // TOP_LEVEL_0-NEXT: #colorLiteral(red: Float, green: Float, blue: Float, alpha: Float) // TOP_LEVEL_0-NEXT: #imageLiteral(resourceName: String) // TOP_LEVEL_0-NEXT: aab() struct Foo { func aaa() {} func aaa(_ x: A) {} func aaa(_ x: B) {} func aaa(_ x: B, y: B) {} func aaa(x x: B, y: B) {} func aab() {} } func test002() { Foo().#^FOO_INSTANCE_0^# } // RUN: %complete-test -group=overloads -tok=FOO_INSTANCE_0 %s | %FileCheck -check-prefix=FOO_INSTANCE_0 %s // FOO_INSTANCE_0-LABEL: aaa: // FOO_INSTANCE_0-NEXT: aaa() // FOO_INSTANCE_0-NEXT: aaa(x: A) // FOO_INSTANCE_0-NEXT: aaa(x: B) // FOO_INSTANCE_0-NEXT: aaa(x: B, y: B) // FOO_INSTANCE_0-NEXT: aaa(x: B, y: B) // FOO_INSTANCE_0-NEXT: aab() extension Foo { static func bbb() {} static func bbb(_ x: A) {} static func bbc() {} } func test003() { Foo.#^FOO_QUAL_0^# } // RUN: %complete-test -group=overloads -tok=FOO_QUAL_0 %s | %FileCheck -check-prefix=FOO_QUAL_0 %s // FOO_QUAL_0-LABEL: bbb: // FOO_QUAL_0-NEXT: bbb() // FOO_QUAL_0-NEXT: bbb(x: A) // FOO_QUAL_0-NEXT: bbc() extension Foo { subscript(x: A) -> A { return A() } subscript(x: B) -> B { return B() } } func test004() { Foo()#^FOO_SUBSCRIPT_0^# } // RUN: %complete-test -group=overloads -tok=FOO_SUBSCRIPT_0 %s | %FileCheck -check-prefix=FOO_SUBSCRIPT_0 %s // FOO_SUBSCRIPT_0-LABEL: [: // FOO_SUBSCRIPT_0-NEXT: [x: A] // FOO_SUBSCRIPT_0-NEXT: [x: B] struct Bar { init() {} init(x: A) {} init(x: B) {} } func test005() { Bar#^BAR_INIT_0^# } // Inline a lonely group // RUN: %complete-test -group=overloads -add-inner-results -no-inner-operators -tok=BAR_INIT_0 %s | %FileCheck -check-prefix=BAR_INIT_0 %s // BAR_INIT_0-LABEL: (: // BAR_INIT_0: () // BAR_INIT_0-NEXT: (x: A) // BAR_INIT_0-NEXT: (x: B) // BAR_INIT_0-NEXT: .foo(self: Bar) // BAR_INIT_0-NEXT: .self extension Bar { func foo() } func test006() { Bar#^BAR_INIT_1^# } // RUN: %complete-test -group=overloads -add-inner-results -no-inner-operators -tok=BAR_INIT_1 %s | %FileCheck -check-prefix=BAR_INIT_1 %s // BAR_INIT_1-LABEL: (: // BAR_INIT_1-NEXT: () // BAR_INIT_1-NEXT: (x: A) // BAR_INIT_1-NEXT: (x: B) // BAR_INIT_1-NEXT: foo(self: Bar) func test007() { #^BAR_INIT_2^# // RUN: %complete-test -add-inits-to-top-level -group=overloads -tok=BAR_INIT_2 %s | %FileCheck -check-prefix=BAR_INIT_2 %s // BAR_INIT_2-LABEL: Bar: // BAR_INIT_2-NEXT: Bar // BAR_INIT_2-NEXT: Bar() // BAR_INIT_2-NEXT: Bar(x: A) // BAR_INIT_2-NEXT: Bar(x: B)
apache-2.0
f4666d800d10750fe3f3ff58a8118054
25.192982
138
0.59779
2.398394
false
true
false
false
firebase/friendlypix-ios
FriendlyPix/AppDelegate.swift
1
11220
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Firebase import FirebaseUI import MaterialComponents import UserNotifications private let kFirebaseTermsOfService = URL(string: "https://firebase.google.com/terms/")! @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { let mdcMessage = MDCSnackbarMessage() let mdcSnackBarManager = MDCSnackbarManager() let mdcAction = MDCSnackbarMessageAction() var window: UIWindow? lazy var database = Database.database() var blockedRef: DatabaseReference! var blockingRef: DatabaseReference! let gcmMessageIDKey = "gcm.message_id" var notificationGranted = false private var blocked = Set<String>() private var blocking = Set<String>() static var euroZone: Bool = { switch Locale.current.regionCode { case "CH", "AT", "IT", "BE", "LV", "BG", "LT", "HR", "LX", "CY", "MT", "CZ", "NL", "DK", "PL", "EE", "PT", "FI", "RO", "FR", "SK", "DE", "SI", "GR", "ES", "HU", "SE", "IE", "GB": return true default: return false } }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self if let uid = Auth.auth().currentUser?.uid { blockedRef = database.reference(withPath: "blocked/\(uid)") blockingRef = database.reference(withPath: "blocking/\(uid)") observeBlocks() } if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { granted, _ in if granted { if let uid = Auth.auth().currentUser?.uid { self.database.reference(withPath: "people/\(uid)/notificationEnabled").setValue(true) } else { self.notificationGranted = true } } }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() let authUI = FUIAuth.defaultAuthUI() authUI?.delegate = self authUI?.tosurl = kFirebaseTermsOfService authUI?.shouldAutoUpgradeAnonymousUsers = true let providers: [FUIAuthProvider] = AppDelegate.euroZone ? [FUIAnonymousAuth()] : [FUIGoogleAuth(), FUIAnonymousAuth()] // ((Auth.auth().currentUser != nil) ? [FUIGoogleAuth()] as [FUIAuthProvider] : [FUIGoogleAuth(), FUIAnonymousAuth()//, FUIFacebookAuth //] as [FUIAuthProvider]) authUI?.providers = providers return true } func showAlert(_ userInfo: [AnyHashable: Any]) { let apsKey = "aps" let gcmMessage = "alert" let gcmLabel = "google.c.a.c_l" if let aps = userInfo[apsKey] as? [String: String], !aps.isEmpty, let message = aps[gcmMessage], let label = userInfo[gcmLabel] as? String { mdcMessage.text = "\(label): \(message)" mdcSnackBarManager.show(mdcMessage) } } func showContent(_ content: UNNotificationContent) { mdcMessage.text = content.body mdcAction.title = content.title mdcMessage.duration = 10_000 mdcAction.handler = { guard let feed = self.window?.rootViewController?.children[0] as? FPFeedViewController else { return } let userId = content.categoryIdentifier.components(separatedBy: "/user/")[1] feed.showProfile(FPUser(dictionary: ["uid": userId])) } mdcMessage.action = mdcAction mdcSnackBarManager.show(mdcMessage) } @available(iOS 9.0, *) func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool { guard let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String else { return false } return self.handleOpenUrl(url, sourceApplication: sourceApplication) } @available(iOS 8.0, *) func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return self.handleOpenUrl(url, sourceApplication: sourceApplication) } func handleOpenUrl(_ url: URL, sourceApplication: String?) -> Bool { return FUIAuth.defaultAuthUI()?.handleOpen(url, sourceApplication: sourceApplication) ?? false } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. showAlert(userInfo) } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // If you are receiving a notification message while your app is in the background, // this callback will not be fired till the user taps on the notification launching the application. showAlert(userInfo) completionHandler(.newData) } func observeBlocks() { blockedRef.observe(.childAdded) { self.blocked.insert($0.key) } blockingRef.observe(.childAdded) { self.blocking.insert($0.key) } blockedRef.observe(.childRemoved) { self.blocked.remove($0.key) } blockingRef.observe(.childRemoved) { self.blocking.remove($0.key) } } func isBlocked(_ snapshot: DataSnapshot) -> Bool { let author = snapshot.childSnapshot(forPath: "author/uid").value as! String if blocked.contains(author) || blocking.contains(author) { return true } return false } func isBlocked(by person: String) -> Bool { return blocked.contains(person) } func isBlocking(_ person: String) -> Bool { return blocking.contains(person) } } extension AppDelegate: FUIAuthDelegate { func authUI(_ authUI: FUIAuth, didSignInWith authDataResult: AuthDataResult?, error: Error?) { switch error { case .some(let error as NSError) where UInt(error.code) == FUIAuthErrorCode.userCancelledSignIn.rawValue: print("User cancelled sign-in") case .some(let error as NSError) where UInt(error.code) == FUIAuthErrorCode.mergeConflict.rawValue: mdcSnackBarManager.show(MDCSnackbarMessage(text: "This identity is already associated with a different user account.")) case .some(let error as NSError) where UInt(error.code) == FUIAuthErrorCode.providerError.rawValue: mdcSnackBarManager.show(MDCSnackbarMessage(text: "There is an error with Google Sign in.")) case .some(let error as NSError) where error.userInfo[NSUnderlyingErrorKey] != nil: mdcSnackBarManager.show(MDCSnackbarMessage(text: "\(error.userInfo[NSUnderlyingErrorKey]!)")) case .some(let error): mdcSnackBarManager.show(MDCSnackbarMessage(text: error.localizedDescription)) case .none: if let user = authDataResult?.user { signed(in: user) } } } func authPickerViewController(forAuthUI authUI: FUIAuth) -> FUIAuthPickerViewController { return FPAuthPickerViewController(nibName: "FPAuthPickerViewController", bundle: Bundle.main, authUI: authUI) } func signOut() { blockedRef.removeAllObservers() blockingRef.removeAllObservers() blocked.removeAll() blocking.removeAll() } func signed(in user: User) { blockedRef = database.reference(withPath: "blocked/\(user.uid)") blockingRef = database.reference(withPath: "blocking/\(user.uid)") observeBlocks() let imageUrl = user.isAnonymous ? "" : user.providerData[0].photoURL?.absoluteString // If the main profile Pic is an expiring facebook profile pic URL we'll update it automatically to use the permanent graph API URL. // if let url = imageUrl, url.contains("lookaside.facebook.com") || url.contains("fbcdn.net") { // let facebookUID = user.providerData.first { (userinfo) -> Bool in // return userinfo.providerID == "facebook.com" // }?.providerID // if let facebook = facebookUID { // imageUrl = "https://graph.facebook.com/\(facebook)/picture?type=large" // } // } let displayName = user.isAnonymous ? "Anonymous" : user.providerData[0].displayName ?? "" var values: [String: Any] = ["profile_picture": imageUrl ?? "", "full_name": displayName] if !user.isAnonymous, let name = user.providerData[0].displayName, !name.isEmpty { values["_search_index"] = ["full_name": name.lowercased(), "reversed_full_name": name.components(separatedBy: " ") .reversed().joined(separator: "")] } if notificationGranted { values["notificationEnabled"] = true notificationGranted = false } database.reference(withPath: "people/\(user.uid)") .updateChildValues(values) } } @available(iOS 10, *) extension AppDelegate: UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { showContent(notification.request.content) completionHandler([]) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { showContent(response.notification.request.content) completionHandler() } } extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { guard let uid = Auth.auth().currentUser?.uid else { return } Database.database().reference(withPath: "/people/\(uid)/notificationTokens/\(fcmToken)").setValue(true) } // Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground. // To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { let data = remoteMessage.appData showAlert(data) } }
apache-2.0
50d1ba5d9e735d5deac5763cee986d75
40.098901
140
0.691622
4.615385
false
false
false
false
adamdahan/MaterialKit
Source/ImageCard.swift
1
1843
// // Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // import UIKit public class ImageCard : MaterialPulseView { public lazy var imageView: UIImageView = UIImageView() public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public required init(frame: CGRect) { super.init(frame: frame) } internal override func initialize() { setupImageView() super.initialize() } internal override func constrainSubviews() { super.constrainSubviews() addConstraints(Layout.constraint("H:|[imageView]|", options: nil, metrics: nil, views: views)) addConstraints(Layout.constraint("V:|[imageView]|", options: nil, metrics: nil, views: views)) } private func setupImageView() { imageView.setTranslatesAutoresizingMaskIntoConstraints(false) imageView.contentMode = .ScaleAspectFill imageView.userInteractionEnabled = false imageView.clipsToBounds = true addSubview(imageView) views["imageView"] = imageView } }
agpl-3.0
f9f198bcc3c0ab13ad8f58d43f3165fc
35.137255
96
0.70917
4.65404
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/0207-swift-parser-parseexprcallsuffix.swift
12
1156
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } class f<p : k, p : k n p.d> : o { } class fclass func i() } i (d() as e).j.i() d protocol i : d { func d a=1 as a=1 } func a<g>() -> (g, g -> g) -> g { var b: ((g, g -> g) -> g)! return b } func f<g : d { return !(a) enum g { func g var _ = g func f<T : BooleanType>(b: T) { } f(true as BooleanType) struct c<d: SequenceType, b where Optional<b> == d.Generator.Element> var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) classwhere A.B == D>(e: A.B) { } } func a() as a).dynamicType.c() func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } protocol a : a { } funcol n { j q } protocol k : k { } class k<f : l, q : l p f.q == q> { } protocol l { j q j o } struct n<r : l> class c { func b((Any, c))(a: (Any, AnyObject)) { b(a) } }
apache-2.0
642a7b01baa6a7fb2218284bcb8ea3a8
16.253731
87
0.527682
2.568889
false
false
false
false
blkbrds/intern09_final_project_tung_bien
MyApp/View/Controls/CustomCells/CommentTableViewCell/CommentTableViewCell.swift
1
1213
// // CommentTableViewCell.swift // MyApp // // Created by asiantech on 7/26/17. // Copyright © 2017 Asian Tech Co., Ltd. All rights reserved. // import UIKit import SDWebImage class CommentTableViewCell: TableCell { // MARK: - Properties @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! var viewModel: CommentCellViewModel? { didSet { updateView() } } // MARK: - LifeCycle override func awakeFromNib() { super.awakeFromNib() avatarImageView.layer.cornerRadius = 25 updateView() } // MARK: - Private private func updateView() { guard let viewModel = viewModel else { return } let urlString = viewModel.avatar let url = URL(string: urlString) avatarImageView.sd_setImage(with: url) usernameLabel.text = viewModel.name contentLabel.text = viewModel.content if let date = viewModel.time.toDate(format: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") { timeLabel.text = date.toString(format: "HH:mm dd/MM/yyyy") } } }
mit
bfa6cb064ce534f6321fde9e01c175f2
25.933333
85
0.635314
4.375451
false
false
false
false
TouchInstinct/LeadKit
TINetworking/Sources/Interceptors/EndpointResponseTokenInterceptor.swift
1
2904
// // Copyright (c) 2022 Touch Instinct // // 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 Alamofire import TIFoundationUtils open class EndpointResponseTokenInterceptor<AE, NE>: DefaultTokenInterceptor<EndpointErrorResult<AE, NE>>, EndpointRequestRetrier { public typealias IsTokenInvalidErrorResultClosure = (EndpointErrorResult<AE, NE>) -> Bool public typealias RepairResult = Result<RetryResult, EndpointErrorResult<AE, NE>> private let isTokenInvalidErrorResultClosure: IsTokenInvalidErrorResultClosure public init(shouldRefreshTokenClosure: @escaping ShouldRefreshTokenClosure, refreshTokenClosure: @escaping RefreshTokenClosure, isTokenInvalidErrorResultClosure: @escaping IsTokenInvalidErrorResultClosure, requestModificationClosure: RequestModificationClosure? = nil) { self.isTokenInvalidErrorResultClosure = isTokenInvalidErrorResultClosure super.init(shouldRefreshTokenClosure: shouldRefreshTokenClosure, refreshTokenClosure: refreshTokenClosure, requestModificationClosure: requestModificationClosure) } // MARK: - EndpointRequestRetrier public func validateAndRepair(errorResults: [EndpointErrorResult<AE, NE>], completion: @escaping (RepairResult) -> Void) -> Cancellable { guard let firstErrorResult = errorResults.first else { completion(.success(.doNotRetry)) return Cancellables.nonCancellable() } return validateAndRepair(validationClosure: { self.isTokenInvalidErrorResultClosure(firstErrorResult) }, completion: completion, defaultCompletionResult: defaultRetryStrategy, recoveredCompletionResult: .retry) } }
apache-2.0
6a6d7260e0bd7d6a792994bc93b73c90
47.4
131
0.722796
5.458647
false
false
false
false
austinzheng/swift
test/Compatibility/protocol_composition.swift
2
2208
// RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s // RUN: %target-swift-frontend -typecheck -primary-file %t/swift4.swift %t/common.swift -verify -swift-version 4 // BEGIN common.swift protocol P1 { static func p1() -> Int } protocol P2 { static var p2: Int { get } } // BEGIN swift3.swift // Warning for mistakenly accepted protocol composition production. func foo(x: P1 & Any & P2.Type?) { // expected-warning @-1 {{protocol-constrained type with postfix '.Type' is ambiguous and will be rejected in future version of Swift}} {{13-13=(}} {{26-26=)}} let _: (P1 & P2).Type? = x let _: (P1 & P2).Type = x! let _: Int = x!.p1() let _: Int? = x?.p2 } // Type expression func bar() -> ((P1 & P2)?).Type { let x = (P1 & P2?).self // expected-warning @-1 {{protocol-constrained type with postfix '?' is ambiguous and will be rejected in future version of Swift}} {{12-12=(}} {{19-19=)}} return x } // Non-ident type at non-last position are rejected anyway. typealias A1 = P1.Type & P2 // expected-error {{non-protocol, non-class type 'P1.Type' cannot be used within a protocol-constrained type}} // BEGIN swift4.swift func foo(x: P1 & Any & P2.Type?) { // expected-error {{non-protocol, non-class type 'P2.Type?' cannot be used within a protocol-constrained type}} let _: (P1 & P2).Type? = x // expected-error {{cannot convert value of type 'P1' to specified type '(P1 & P2).Type?'}} let _: (P1 & P2).Type = x! // expected-error {{cannot force unwrap value of non-optional type 'P1'}} let _: Int = x!.p1() // expected-error {{cannot force unwrap value of non-optional type 'P1'}} let _: Int? = x?.p2 // expected-error {{cannot use optional chaining on non-optional value of type 'P1'}} // expected-error@-1 {{value of type 'P1' has no member 'p2'}} } func bar() -> ((P1 & P2)?).Type { let x = (P1 & P2?).self // expected-error {{non-protocol, non-class type 'P2?' cannot be used within a protocol-constrained type}} return x // expected-error {{cannot convert return expression}} } typealias A1 = P1.Type & P2 // expected-error {{non-protocol, non-class type 'P1.Type' cannot be used within a protocol-constrained type}}
apache-2.0
a38721692cb13b194dea3679994c45df
44.061224
161
0.653986
3.218659
false
false
false
false
ArtSabintsev/MaterialSwitch
MaterialSwitch.swift
1
4508
// // MaterialSwitch.swift // MaterialSwitch // // Created by Arthur Sabintsev on 6/25/15. // Copyright (c) 2015 Arthur Ariel Sabintsev. All rights reserved. // import UIKit public protocol MaterialSwitchDelegate { func switchDidChangeState(#aSwitch: MaterialSwitch, currentState: MaterialSwitchState) } public enum MaterialSwitchState: Int { case Off case On } // Typealiases public typealias MaterialSwitchSize = (x: CGFloat, y: CGFloat, radius: CGFloat) // Class public class MaterialSwitch: UIView { // Public Variables and Constants var state: MaterialSwitchState! var thumbOnColor: UIColor = .blueColor() var thumbOffColor: UIColor = .darkGrayColor() var trackOnColor: UIColor = .cyanColor() var trackOffColor: UIColor = .lightGrayColor() // Private Variables and Constants private let size: MaterialSwitchSize! private var delegate: MaterialSwitchDelegate? private var track: UIView? private var thumb: UIView? private var flashingThumb: UIView? // MARK: Initializers init(size: MaterialSwitchSize) { self.size = size super.init(frame: CGRectMake(size.x, size.y, 1.6*size.radius, size.radius)) } required public init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Setup func setup(#delegate: MaterialSwitchDelegate) { self.delegate = delegate state = .Off track = setupTrack() thumb = setupThumb() setupGesture() flashingThumb = setupThumb() } func setupTrack() -> UIView { let track = UIView(frame: CGRectMake( size.x + 0.1*size.radius, size.y + 0.1*size.radius, 1.6*size.radius, 0.8*size.radius)) track.backgroundColor = trackOffColor track.layer.cornerRadius = CGRectGetHeight(track.frame)/2.0 self.addSubview(track) return track } func setupThumb() -> UIView { let thumb = UIView(frame: CGRectMake( size.x, size.y, size.radius, size.radius)) thumb.backgroundColor = thumbOffColor thumb.layer.cornerRadius = CGRectGetHeight(thumb.frame)/2.0 self.addSubview(thumb) return thumb } func setupGesture() { if let thumb = thumb { self.userInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: "animate") tap.numberOfTapsRequired = 1 self.addGestureRecognizer(tap) } } // MARK: Animations! func animate() { UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseInOut, animations: { () -> Void in let xOffsetForAnimation: CGFloat = (self.state == .Off) ? (self.size.x + 0.8*self.size.radius) : self.size.x self.thumb!.backgroundColor = (self.state == .Off) ? self.thumbOnColor : self.thumbOffColor self.track!.backgroundColor = (self.state == .Off) ? self.trackOnColor : self.trackOffColor self.thumb!.frame = CGRectMake(xOffsetForAnimation, self.size.y, self.size.radius, self.size.radius) if (self.state == .Off) { if self.flashingThumb?.isDescendantOfView(self) == false { self.flashingThumb = self.setupThumb() self.addSubview(self.flashingThumb!) } let xOffsetForAnimation = self.thumb!.backgroundColor self.flashingThumb!.backgroundColor = self.thumb!.backgroundColor self.flashingThumb!.frame = self.thumb!.frame } }) { (finished) -> Void in if (finished) { self.state = (self.state == .Off) ? .On : .Off self.delegate?.switchDidChangeState(aSwitch: self, currentState: self.state) } } UIView.animateWithDuration(0.35, delay: 0.25, options: .CurveEaseOut, animations: { () -> Void in self.flashingThumb!.alpha = 0.0 self.flashingThumb!.transform = CGAffineTransformMakeScale(2.0, 2.0) }) { (finished) -> Void in if (finished) { self.flashingThumb!.removeFromSuperview() } } } }
mit
84aa9bf39f6cb8a69decc7899ef0dd2d
31.431655
120
0.582964
4.755274
false
false
false
false
silence0201/Swift-Study
SwiftLearn/MySwift06_collection.playground/Contents.swift
1
4581
//: Playground - noun: a place where people can play import UIKit /*** * 字典 Dictionary **/ var dict : [String : String] = ["swift": "雨燕", "python": "大蟒", "java": "爪哇岛", "groovy": "绝妙的"] var dictt : Dictionary<String, String> = ["swift": "雨燕", "python": "大蟒", "java": "爪哇岛", "groovy": "绝妙的"] var emptyDict1 : [String:Int] = [:] var emptyDict2 : Dictionary<Int, String> = [:] var emptyDict3 = [String: String]() var emptyDict4 = Dictionary<Int, Int>() print(dict["swift"] ?? "nil") //返回的是可选型的数据, 因为你无法知道"swift"键是否存在. dict["C++"] //nil 返回可选型的nil, 没有找到 if let value = dict["swift"] { print("swift is " + value) } dict.count dict.isEmpty emptyDict1.isEmpty Array(dict.keys) Array(dict.values) //遍历字典的所有键, 值 for (key, value) in dict{ print("\(key) : \(value)") } let dict1 = [1: "A", 2:"B", 3:"C"] let dict2 = [1: "A", 3:"C", 2:"B"] dict1 == dict2 //true 说明swift中字典和数组的比较是<值>的比较. 注字典是无序的, 且key不能重复. /*** * 字典的 增 删 改 **/ var user = ["name": "bobobo", "password":"liuyubo", "occupation":"programmer"] //修改 user["occupation"] = "freeancer" user.updateValue("imooc1", forKey: "password") //forKey标识要修改的键. "imooc"为最终要修改的值. let oldPassword = user.updateValue("imooc1", forKey: "password") //返回 String?可选型. if let oldPassword = oldPassword, let newPassword = user["password"] , oldPassword == newPassword{ print("注意: 修改后的密码和之前一样, 可能导致安全问题!") } user["email"] = "[email protected]" user user.updateValue("imooc.com", forKey: "website") user user["website"] = nil //var email = user.removeValueForKey("email") if let email = user.removeValue(forKey: "email"){ //swift3 print("电子邮箱 \(email) 被删除了") } user //: Playground - noun: a place where people can play import UIKit /*** 集合 Set 声明与赋值 **/ var skillsOfA: Set<String> = ["swift", "OC", "OC"] var emptySet1: Set<Int> = [] var emptySet2 = Set<Double>() var vowels = Set(["A", "E", "I", "O", "U", "U"]) //将字符串数组转换成集合Set var skillsOfB: Set = ["HTML", "CSS", "Javascript"] //将字符串数组转换成集合Set skillsOfA.count let set: Set<Int> = [2,2,2,2] set.count skillsOfB.isEmpty emptySet1.isEmpty let e = skillsOfA.first skillsOfA.contains("swift") //true for skill in skillsOfB{ print(skill) } let setA: Set = [1, 2, 3] let setB: Set = [3, 2, 1, 1, 2, 3, 1, 1, 1, 1] setA == setB //true 这说明集合是无序的, 比较的是值. /*** 集合的操作 **/ var seta: Set<String> = ["swift", "OC"] var setb: Set<String> = ["HTML", "CSS", "Javascript"] var setc: Set<String> = [] setc.insert("swift") setc.insert("HTML") setc.insert("CSS") setc.insert("CSS") let remCss = setc.remove("CSS") //String? let remJavaScript = setc.remove("Javascript") //nil if let skill = setc.remove("HTML"){ print("HTML is removed.") } //Set集合没有修改一个值的操作, 通常我们直接增加即可. setc.insert("CSS") setc.insert("Javascript") setc.insert("HTML") //并集 seta.union(setc) //并集 //seta.unionInPlace(setc) //并集, 且赋值setc到seta //交集 //seta.intersect(setc) //swift2 seta.intersection(setc) //swift3 //差集 seta.subtract(setc) //seta独有的, 而setc没有的. setc.subtract(seta) //亦或 exclusiveOr, exclusiveOrInPlace //seta.exclusiveOr(setc) //去除并集剩下的所有 //swift2 seta.symmetricDifference(setc) //返回交集的补集 //swift3 seta.union(["java", "android"]) //集合与数组一起操作求并集. var setd: Set = ["swift"] //setd.isSubsetOf(seta) //setd是否是seta的子集. //swift2 setd.isSubset(of: seta) //swift3 //setd.isStrictSubsetOf(seta) //setd是否是seta的真子集. //swift2 setd.isStrictSubset(of: seta) //swift3 //seta.isSupersetOf(setd) //seta是否是setd的超集. //swift2 seta.isSuperset(of: setd) //swift3 //seta.isStrictSupersetOf(setd) //seta是否是setd的真超集. //swift2 seta.isStrictSuperset(of: setd) //swift3 //seta.isDisjointWith(setb) //两个集合是否是相离的. seta与setb没有相同的一项技能. //swift2 seta.isDisjoint(with: setb) //swift3 //seta.isDisjointWith(setc) //swift2 seta.isDisjoint(with: setc) //swift3 /*** 选择合适的数据结构 **/ //数组: 有序 //集合: 无序, 唯一性, 提供集合操作, 快速查找. //字典: 键-值数据对 //for-in 和更多
mit
371c5a4961b373bab100b1a4a1a1414a
16.515837
104
0.655386
2.693807
false
false
false
false
abelsanchezali/ViewBuilder
Source/Model/Core/PathFromBundle.swift
1
1938
// // PathFromBundle.swift // ViewBuilder // // Created by Abel Sanchez on 6/25/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import Foundation open class PathFromBundle: Object, TextDeserializer { public static func deserialize(text: String?, service: TextDeserializerServiceProtocol) -> Any? { guard let value = text else { return nil } // Resolve path:<path> identifier:<identifier> if let params = service.parseKeyValueSequence(from: value, params: ["path", "identifier"]) { guard let path = params[0] as? String, let identifier = params[1] as? String else { return nil } return resolvePathFromBundle(resourcePath: path, bundle: Foundation.Bundle(identifier: identifier)) } // Only one parameter will handled as path if let chunks = service.parseValueSequence(from: value), chunks.count == 1, let path = chunks[0] as? String { return resolvePathFromBundle(resourcePath: path) } return nil } static func resolvePathFromBundle(resourcePath: String, bundle: Foundation.Bundle? = Foundation.Bundle.main) -> String? { guard let url = URL(string: resourcePath) else { return nil } let normalizedPath = url.path guard !normalizedPath.isEmpty else { return nil } let targetBundle = bundle ?? Foundation.Bundle.main let fileName = url.lastPathComponent guard !fileName.isEmpty else { return nil } let directory = normalizedPath.substring(to: normalizedPath.index(normalizedPath.endIndex, offsetBy: -fileName.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/\\")) let result = targetBundle.path(forResource: fileName, ofType: nil, inDirectory: directory) return result } }
mit
88d14811c7555ab4b29f9ccaca542efe
36.980392
184
0.632421
4.818408
false
false
false
false
jianweihehe/JWDouYuZB
JWDouYuZB/JWDouYuZB/Classes/Home/View/AmuseMenuCell.swift
1
1615
// // AmuseMenuCell.swift // JWDouYuZB // // Created by [email protected] on 2017/1/16. // Copyright © 2017年 简伟. All rights reserved. // import UIKit private let GameViewCellID = "GameViewCellID" class AmuseMenuCell: UICollectionViewCell { @IBOutlet var collectionView: UICollectionView! var groups:[AnchorGroup]? { didSet{ self.collectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() autoresizingMask = UIViewAutoresizing() collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: GameViewCellID) } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout let itemWidth = collectionView.bounds.width / 4 let itemHeight = collectionView.bounds.height / 2 layout.itemSize = CGSize(width: itemWidth, height: itemHeight) } } extension AmuseMenuCell: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GameViewCellID, for: indexPath) as! CollectionGameCell cell.game = groups![indexPath.item] cell.clipsToBounds = true return cell } }
mit
3c9e1a9e8eaa39d59066151d2fe9e598
28.777778
129
0.687189
5.377926
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/FeedProvider/Twitter/TwitterHashtag.swift
1
536
// // TwitterHashtag.swift // Account // // Created by Maurice Parker on 4/18/20. // Copyright © 2020 Ranchero Software, LLC. All rights reserved. // import Foundation struct TwitterHashtag: Codable, TwitterEntity { let text: String? let indices: [Int]? enum CodingKeys: String, CodingKey { case text = "text" case indices = "indices" } func renderAsHTML() -> String { var html = String() if let text = text { html += "<a href=\"https://twitter.com/search?q=%23\(text)\">#\(text)</a>" } return html } }
mit
cb0c021c111c644601584a3cd6d90c3b
18.107143
77
0.64486
3.16568
false
false
false
false
jonasman/TeslaSwift
Sources/Extensions/Streaming/TeslaStreaming.swift
1
8165
// // TeslaStreaming.swift // TeslaSwift // // Created by Joao Nunes on 23/04/2017. // Copyright © 2017 Joao Nunes. All rights reserved. // import Foundation import Starscream #if COCOAPODS #else // SPM import TeslaSwift #endif enum TeslaStreamingError: Error { case streamingMissingVehicleTokenOrEmail case streamingMissingOAuthToken } enum TeslaStreamAuthenticationType { case bearer(String, String) // email, vehicleToken case oAuth(String) // oAuthToken } struct TeslaStreamAuthentication { let type: TeslaStreamAuthenticationType let vehicleId: String public init(type: TeslaStreamAuthenticationType, vehicleId: String) { self.type = type self.vehicleId = vehicleId } } /* * Streaming class takes care of the different types of data streaming from Tesla servers * */ public class TeslaStreaming { var debuggingEnabled: Bool { teslaSwift.debuggingEnabled } private var httpStreaming: WebSocket private var teslaSwift: TeslaSwift public init(teslaSwift: TeslaSwift) { httpStreaming = WebSocket(request: URLRequest(url: URL(string: "wss://streaming.vn.teslamotors.com/streaming/")!)) self.teslaSwift = teslaSwift } /** Streams vehicle data - parameter vehicle: the vehicle that will receive the command - parameter reloadsVehicle: if you have a cached vehicle, the token might be expired, this forces a vehicle token reload - parameter dataReceived: callback to receive the websocket data */ public func openStream(vehicle: Vehicle, reloadsVehicle: Bool = true) async throws -> AsyncThrowingStream<TeslaStreamingEvent, Error> { if reloadsVehicle { return AsyncThrowingStream { continuation in Task { do { let freshVehicle = try await reloadVehicle(vehicle: vehicle) self.startStream(vehicle: freshVehicle, dataReceived: { data in continuation.yield(data) if data == .disconnected { continuation.finish() } }) } catch let error { continuation.finish(throwing: error) } } } } else { return AsyncThrowingStream { continuation in startStream(vehicle: vehicle, dataReceived: { data in continuation.yield(data) if data == .disconnected { continuation.finish() } }) } } } /** Stops the stream */ public func closeStream() { httpStreaming.disconnect() logDebug("Stream closed", debuggingEnabled: self.debuggingEnabled) } private func reloadVehicle(vehicle: Vehicle) async throws -> Vehicle { let vehicles = try await teslaSwift.getVehicles() for freshVehicle in vehicles where freshVehicle.vehicleID == vehicle.vehicleID { return freshVehicle } throw TeslaError.failedToReloadVehicle } private func startStream(vehicle: Vehicle, dataReceived: @escaping (TeslaStreamingEvent) -> Void) { guard let accessToken = teslaSwift.token?.accessToken else { dataReceived(TeslaStreamingEvent.error(TeslaStreamingError.streamingMissingOAuthToken)) return } let type: TeslaStreamAuthenticationType = .oAuth(accessToken) let authentication = TeslaStreamAuthentication(type: type, vehicleId: "\(vehicle.vehicleID!)") openStream(authentication: authentication, dataReceived: dataReceived) } private func openStream(authentication: TeslaStreamAuthentication, dataReceived: @escaping (TeslaStreamingEvent) -> Void) { let url = httpStreaming.request.url?.absoluteString logDebug("Opening Stream to: \(url ?? "")", debuggingEnabled: debuggingEnabled) httpStreaming.onEvent = { [weak self] event in guard let self = self else { return } switch event { case let .connected(headers): logDebug("Stream open headers: \(headers)", debuggingEnabled: self.debuggingEnabled) if let authMessage = StreamAuthentication(type: authentication.type, vehicleId: authentication.vehicleId), let string = try? teslaJSONEncoder.encode(authMessage) { self.httpStreaming.write(data: string) dataReceived(TeslaStreamingEvent.open) } else { dataReceived(TeslaStreamingEvent.error(NSError(domain: "TeslaStreamingError", code: 0, userInfo: ["errorDescription": "Failed to parse authentication data"]))) self.closeStream() } case let .binary(data): logDebug("Stream data: \(String(data: data, encoding: .utf8) ?? "")", debuggingEnabled: self.debuggingEnabled) guard let message = try? teslaJSONDecoder.decode(StreamMessage.self, from: data) else { return } let type = message.messageType switch type { case "control:hello": logDebug("Stream got hello", debuggingEnabled: self.debuggingEnabled) case "data:update": if let values = message.value { let event = StreamEvent(values: values) logDebug("Stream got data: \(values)", debuggingEnabled: self.debuggingEnabled) dataReceived(TeslaStreamingEvent.event(event)) } case "data:error": logDebug("Stream got data error: \(message.value ?? ""), \(message.errorType ?? "")", debuggingEnabled: self.debuggingEnabled) dataReceived(TeslaStreamingEvent.error(NSError(domain: "TeslaStreamingError", code: 0, userInfo: [message.value ?? "error": message.errorType ?? ""]))) default: break } case let .disconnected(error, code): logDebug("Stream disconnected \(code):\(error)", debuggingEnabled: self.debuggingEnabled) dataReceived(TeslaStreamingEvent.error(NSError(domain: "TeslaStreamingError", code: Int(code), userInfo: ["error": error]))) case let .pong(data): logDebug("Stream Pong", debuggingEnabled: self.debuggingEnabled) self.httpStreaming.write(pong: data ?? Data()) case let .text(text): logDebug("Stream Text: \(text)", debuggingEnabled: self.debuggingEnabled) case let .ping(ping): logDebug("Stream ping: \(String(describing: ping))", debuggingEnabled: self.debuggingEnabled) case let .error(error): DispatchQueue.main.async { logDebug("Stream error:\(String(describing: error))", debuggingEnabled: self.debuggingEnabled) dataReceived(TeslaStreamingEvent.error(NSError(domain: "TeslaStreamingError", code: 0, userInfo: ["error": error ?? ""]))) } case let .viabilityChanged(viability): logDebug("Stream viabilityChanged: \(viability)", debuggingEnabled: self.debuggingEnabled) case let .reconnectSuggested(reconnect): logDebug("Stream reconnectSuggested: \(reconnect)", debuggingEnabled: self.debuggingEnabled) case .cancelled: logDebug("Stream cancelled", debuggingEnabled: self.debuggingEnabled) } } httpStreaming.connect() } } #if COCOAPODS #else // SPM func logDebug(_ format: String, debuggingEnabled: Bool) { if debuggingEnabled { print(format) } } #endif
mit
a8858a6505f45d4dd6e4637f6b75c58e
41.520833
183
0.591867
5.66551
false
false
false
false
apple/swift-nio-http2
Sources/NIOHTTP2/HTTP2UserEvents.swift
1
5050
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore /// A ``StreamClosedEvent`` is fired whenever a stream is closed. /// /// This event is fired whether the stream is closed normally, or via `RST_STREAM`, /// or via `GOAWAY`. Normal closure is indicated by having ``reason`` be `nil`. In the /// case of closure by `GOAWAY` the ``reason`` is always ``HTTP2ErrorCode/refusedStream``, /// indicating that the remote peer has not processed this stream. In the case of /// `RST_STREAM`, the ``reason`` contains the error code sent by the peer in the `RST_STREAM` frame. public struct StreamClosedEvent: Sendable { /// The stream ID of the stream that is closed. public let streamID: HTTP2StreamID /// The reason for the stream closure. `nil` if the stream was closed without /// error. Otherwise, ``HTTP2ErrorCode`` indicating why the stream was closed. public let reason: HTTP2ErrorCode? public init(streamID: HTTP2StreamID, reason: HTTP2ErrorCode?) { self.streamID = streamID self.reason = reason } } extension StreamClosedEvent: Hashable { } /// A ``NIOHTTP2WindowUpdatedEvent`` is fired whenever a flow control window is changed. /// This includes changes on the connection flow control window, which is signalled by /// this event having ``streamID`` set to ``HTTP2StreamID/rootStream``. public struct NIOHTTP2WindowUpdatedEvent { /// The stream ID of the window that has been changed. May be ``HTTP2StreamID/rootStream``, in which /// case the connection window has changed. public let streamID: HTTP2StreamID /// The new inbound window size for this stream, if any. May be nil if this stream is half-closed. public var inboundWindowSize: Int? { get { return self._inboundWindowSize.map { Int($0) } } set { self._inboundWindowSize = newValue.map { Int32($0) } } } /// The new outbound window size for this stream, if any. May be nil if this stream is half-closed. public var outboundWindowSize: Int? { get { return self._outboundWindowSize.map { Int($0) } } set { self._outboundWindowSize = newValue.map { Int32($0) } } } private var _inboundWindowSize: Int32? private var _outboundWindowSize: Int32? public init(streamID: HTTP2StreamID, inboundWindowSize: Int?, outboundWindowSize: Int?) { // We use Int here instead of Int32. Nonetheless, the value must fit in the Int32 range. precondition(inboundWindowSize == nil || inboundWindowSize! <= Int(HTTP2FlowControlWindow.maxSize)) precondition(outboundWindowSize == nil || outboundWindowSize! <= Int(HTTP2FlowControlWindow.maxSize)) precondition(inboundWindowSize == nil || inboundWindowSize! >= Int(Int32.min)) precondition(outboundWindowSize == nil || outboundWindowSize! >= Int(Int32.min)) self.streamID = streamID self._inboundWindowSize = inboundWindowSize.map { Int32($0) } self._outboundWindowSize = outboundWindowSize.map { Int32($0) } } } extension NIOHTTP2WindowUpdatedEvent: Hashable { } /// A ``NIOHTTP2StreamCreatedEvent`` is fired whenever a HTTP/2 stream is created. public struct NIOHTTP2StreamCreatedEvent { /// The ``HTTP2StreamID`` of the created stream. public let streamID: HTTP2StreamID /// The initial local stream window size. May be nil if this stream may never have data sent on it. public let localInitialWindowSize: UInt32? /// The initial remote stream window size. May be nil if this stream may never have data received on it. public let remoteInitialWidowSize: UInt32? public init(streamID: HTTP2StreamID, localInitialWindowSize: UInt32?, remoteInitialWindowSize: UInt32?) { self.streamID = streamID self.localInitialWindowSize = localInitialWindowSize self.remoteInitialWidowSize = remoteInitialWindowSize } } extension NIOHTTP2StreamCreatedEvent: Hashable { } /// A ``NIOHTTP2BulkStreamWindowChangeEvent`` is fired whenever all of the remote flow control windows for a given stream have been changed. /// /// This occurs when an `ACK` to a `SETTINGS` frame is received that changes the value of `SETTINGS_INITIAL_WINDOW_SIZE`. This is only fired /// when the local peer has changed its settings. public struct NIOHTTP2BulkStreamWindowChangeEvent { /// The change in the remote stream window sizes. public let delta: Int public init(delta: Int) { self.delta = delta } } extension NIOHTTP2BulkStreamWindowChangeEvent: Hashable { }
apache-2.0
977f679c81d06c4e35e3486d7c9243fa
40.393443
140
0.684554
4.741784
false
false
false
false
spronin/hse-swift-course
HSEProject/Airline.swift
1
1125
import Foundation import CoreData @objc(Airline) class Airline: NSManagedObject { @NSManaged var code: String @NSManaged var name: String @NSManaged var flights: NSSet class var entity: NSEntityDescription { return NSEntityDescription.entityForName("Airline", inManagedObjectContext: CoreDataHelper.instance.context)! } convenience init() { self.init(entity: Airline.entity, insertIntoManagedObjectContext: CoreDataHelper.instance.context) //nil если не храним } convenience init(code: String, name: String) { self.init() self.code = code self.name = name } class func allAirlines() -> [Airline] { let request = NSFetchRequest(entityName: "Airline") //сортировка по возрастанию по полю name request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)] var results = CoreDataHelper.instance.context.executeFetchRequest(request, error: nil) return results as! [Airline] } }
mit
97b5df060b49cd3bb400ffd0513e6e83
27.526316
97
0.647601
4.860987
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Chat Items/Composable/Binder.swift
1
2168
// MARK: - Protocols public protocol BinderProtocol { typealias Key = AnyBindingKey typealias Subviews = IndexedSubviews<Key> typealias ViewModels = [Key: Any] func bind(subviews: Subviews, viewModels: ViewModels) throws } public protocol BinderRegistryProtocol { mutating func register<Binding: ViewModelBinding, Key: BindingKeyProtocol>( binding: Binding, for key: Key ) where Binding.View == Key.View, Binding.ViewModel == Key.ViewModel } // MARK: - Implementation public struct Binder: BinderProtocol, BinderRegistryProtocol { // MARK: - Type declarations public enum Error: Swift.Error { case keysMismatch case noView(key: String) case noViewModel(key: String) } // MARK: - Private properties private var bindings: [AnyBindingKey: AnyViewModelBinding] = [:] // MARK: - Instantiation public init() {} // MARK: - BinderRegistryProtocol public mutating func register<Binding: ViewModelBinding, Key: BindingKeyProtocol>(binding: Binding, for key: Key) where Binding.View == Key.View, Binding.ViewModel == Key.ViewModel { self.bindings[.init(key)] = AnyViewModelBinding(binding) } // MARK: - BinderProtocol public func bind(subviews: Subviews, viewModels: ViewModels) throws { try self.checkKeys(subviews: subviews, viewModels: viewModels) for (key, binding) in self.bindings { guard let view = subviews.subviews[key] else { throw Error.noView(key: key.description) } guard let viewModel = viewModels[key] else { throw Error.noViewModel(key: key.description) } try binding.bind(view: view, to: viewModel) } } // MARK: - Private private func checkKeys(subviews: Subviews, viewModels: ViewModels) throws { let bindingKeys = Set(bindings.keys) let subviewsKeys = Set(subviews.subviews.keys) let viewModelsKeys = Set(viewModels.keys) guard bindingKeys == subviewsKeys && subviewsKeys == viewModelsKeys else { throw Error.keysMismatch } } }
mit
62a0af70ab7a5f09bc1cead6890c64ee
28.69863
117
0.65452
4.545073
false
false
false
false
lorentey/GlueKit
Sources/Sink.swift
1
3546
// // Sink.swift // GlueKit // // Created by Károly Lőrentey on 2016-10-22. // Copyright © 2015–2017 Károly Lőrentey. // public protocol SinkType: Hashable { associatedtype Value func receive(_ value: Value) var anySink: AnySink<Value> { get } } extension SinkType { public var anySink: AnySink<Value> { return AnySink(SinkBox<Self>(self)) } } extension SinkType where Self: AnyObject { public func unowned() -> AnySink<Value> { return UnownedSink(self).anySink } public var hashValue: Int { return ObjectIdentifier(self).hashValue } public static func ==(a: Self, b: Self) -> Bool { return a === b } } public struct AnySink<Value>: SinkType { // TODO: Replace this with a generalized protocol existential when Swift starts supporting those. // (We always need to allocate a box for the sink, while an existential may have magical inline storage for // tiny sinks -- say, less than three words.) private let box: _AbstractSink<Value> fileprivate init(_ box: _AbstractSink<Value>) { self.box = box } public func receive(_ value: Value) { box.receive(value) } public var anySink: AnySink<Value> { return self } public var hashValue: Int { return box.hashValue } public static func ==(left: AnySink, right: AnySink) -> Bool { return left.box == right.box } public func opened<Sink: SinkType>(as type: Sink.Type = Sink.self) -> Sink? where Sink.Value == Value { if let sink = self as? Sink { return sink } if let sink = box as? Sink { return sink } if let box = self.box as? SinkBox<Sink> { return box.contents } return nil } } fileprivate class _AbstractSink<Value>: SinkType { // TODO: Eliminate this when Swift starts supporting generalized protocol existentials. func receive(_ value: Value) { abstract() } var hashValue: Int { abstract() } func isEqual(to other: _AbstractSink<Value>) -> Bool { abstract() } public static func ==(left: _AbstractSink<Value>, right: _AbstractSink<Value>) -> Bool { return left.isEqual(to: right) } public final var anySink: AnySink<Value> { return AnySink(self) } } fileprivate class SinkBox<Wrapped: SinkType>: _AbstractSink<Wrapped.Value> { // TODO: Eliminate this when Swift starts supporting generalized protocol existentials. typealias Value = Wrapped.Value fileprivate let contents: Wrapped init(_ contents: Wrapped) { self.contents = contents } override func receive(_ value: Value) { contents.receive(value) } override var hashValue: Int { return contents.hashValue } override func isEqual(to other: _AbstractSink<Wrapped.Value>) -> Bool { guard let other = other as? SinkBox<Wrapped> else { return false } return self.contents == other.contents } } fileprivate class UnownedSink<Wrapped: SinkType & AnyObject>: _AbstractSink<Wrapped.Value> { typealias Value = Wrapped.Value unowned let wrapped: Wrapped init(_ wrapped: Wrapped) { self.wrapped = wrapped } override func receive(_ value: Value) { wrapped.receive(value) } override var hashValue: Int { return wrapped.hashValue } override func isEqual(to other: _AbstractSink<Wrapped.Value>) -> Bool { guard let other = other as? UnownedSink<Wrapped> else { return false } return self.wrapped == other.wrapped } }
mit
38bbcb200b6602be99201e2c797b2835
26.434109
112
0.649901
4.326406
false
false
false
false
whong7/swift-knowledge
思维导图/4-3:网易新闻/Pods/Kingfisher/Sources/ImageDownloader.swift
70
23194
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2017 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(macOS) import AppKit #else import UIKit #endif /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((_ image: Image?, _ error: NSError?, _ url: URL?, _ originalData: Data?) -> ()) /// Download task. public struct RetrieveImageDownloadTask { let internalTask: URLSessionDataTask /// Downloader by which this task is intialized. public private(set) weak var ownerDownloader: ImageDownloader? /** Cancel this download task. It will trigger the completion handler with an NSURLErrorCancelled error. */ public func cancel() { ownerDownloader?.cancelDownloadingTask(self) } /// The original request URL of this download task. public var url: URL? { return internalTask.originalRequest?.url } /// The relative priority of this download task. /// It represents the `priority` property of the internal `NSURLSessionTask` of this download task. /// The value for it is between 0.0~1.0. Default priority is value of 0.5. /// See documentation on `priority` of `NSURLSessionTask` for more about it. public var priority: Float { get { return internalTask.priority } set { internalTask.priority = newValue } } } ///The code of errors which `ImageDownloader` might encountered. public enum KingfisherError: Int { /// badData: The downloaded data is not an image or the data is corrupted. case badData = 10000 /// notModified: The remote server responsed a 304 code. No image data downloaded. case notModified = 10001 /// The HTTP status code in response is not valid. If an invalid /// code error received, you could check the value under `KingfisherErrorStatusCodeKey` /// in `userInfo` to see the code. case invalidStatusCode = 10002 /// notCached: The image rquested is not in cache but .onlyFromCache is activated. case notCached = 10003 /// The URL is invalid. case invalidURL = 20000 /// The downloading task is cancelled before started. case downloadCancelledBeforeStarting = 30000 } /// Key will be used in the `userInfo` of `.invalidStatusCode` public let KingfisherErrorStatusCodeKey = "statusCode" /// Protocol of `ImageDownloader`. public protocol ImageDownloaderDelegate: class { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. - parameter downloader: The `ImageDownloader` object finishes the downloading. - parameter image: Downloaded image. - parameter url: URL of the original request URL. - parameter response: The response object of the downloading process. */ func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) /** Check if a received HTTP status code is valid or not. By default, a status code between 200 to 400 (excluded) is considered as valid. If an invalid code is received, the downloader will raise an .invalidStatusCode error. It has a `userInfo` which includes this statusCode and localizedString error message. - parameter code: The received HTTP status code. - parameter downloader: The `ImageDownloader` object asking for validate status code. - returns: Whether this HTTP status code is valid or not. - Note: If the default 200 to 400 valid code does not suit your need, you can implement this method to change that behavior. */ func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool } extension ImageDownloaderDelegate { public func imageDownloader(_ downloader: ImageDownloader, didDownload image: Image, for url: URL, with response: URLResponse?) {} public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { return (200..<400).contains(code) } } /// Protocol indicates that an authentication challenge could be handled. public protocol AuthenticationChallengeResponsable: class { /** Called when an session level authentication challenge is received. This method provide a chance to handle and response to the authentication challenge before downloading could start. - parameter downloader: The downloader which receives this challenge. - parameter challenge: An object that contains the request for authentication. - parameter completionHandler: A handler that your delegate method must call. - Note: This method is a forward from `URLSession(:didReceiveChallenge:completionHandler:)`. Please refer to the document of it in `NSURLSessionDelegate`. */ func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) } extension AuthenticationChallengeResponsable { func downloader(_ downloader: ImageDownloader, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential, credential) return } } completionHandler(.performDefaultHandling, nil) } } /// `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. open class ImageDownloader { class ImageFetchLoad { var contents = [(callback: CallbackPair, options: KingfisherOptionsInfo)]() var responseData = NSMutableData() var downloadTaskCount = 0 var downloadTask: RetrieveImageDownloadTask? } // MARK: - Public property /// The duration before the download is timeout. Default is 15 seconds. open var downloadTimeout: TimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. /// You can use this set to specify the self-signed site. It only will be used if you don't specify the `authenticationChallengeResponder`. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implemention of `authenticationChallengeResponder` will be used instead. open var trustedHosts: Set<String>? /// Use this to set supply a configuration for the downloader. By default, NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. /// You could change the configuration before a downloaing task starts. A configuration without persistent storage for caches is requsted for downloader working correctly. open var sessionConfiguration = URLSessionConfiguration.ephemeral { didSet { session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: OperationQueue.main) } } /// Whether the download requests should use pipeling or not. Default is false. open var requestsUsePipeling = false fileprivate let sessionHandler: ImageDownloaderSessionHandler fileprivate var session: URLSession? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. open weak var delegate: ImageDownloaderDelegate? /// A responder for authentication challenge. /// Downloader will forward the received authentication challenge for the downloading session to this responder. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable? // MARK: - Internal property let barrierQueue: DispatchQueue let processQueue: DispatchQueue typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) var fetchLoads = [URL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public static let `default` = ImageDownloader(name: "default") /** Init a downloader with name. - parameter name: The name for the downloader. It should not be empty. - returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Barrier.\(name)", attributes: .concurrent) processQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process.\(name)", attributes: .concurrent) sessionHandler = ImageDownloaderSessionHandler() // Provide a default implement for challenge responder. authenticationChallengeResponder = sessionHandler session = URLSession(configuration: sessionConfiguration, delegate: sessionHandler, delegateQueue: .main) } func fetchLoad(for url: URL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? barrierQueue.sync { fetchLoad = fetchLoads[url] } return fetchLoad } /** Download an image with a URL and option. - parameter url: Target URL. - parameter options: The options could control download behavior. See `KingfisherOptionsInfo`. - parameter progressBlock: Called when the download progress updated. - parameter completionHandler: Called when the download progress finishes. - returns: A downloading task. You could call `cancel` on it to stop the downloading process. */ @discardableResult open func downloadImage(with url: URL, options: KingfisherOptionsInfo? = nil, progressBlock: ImageDownloaderProgressBlock? = nil, completionHandler: ImageDownloaderCompletionHandler? = nil) -> RetrieveImageDownloadTask? { return downloadImage(with: url, retrieveImageTask: nil, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } } // MARK: - Download method extension ImageDownloader { func downloadImage(with url: URL, retrieveImageTask: RetrieveImageTask?, options: KingfisherOptionsInfo?, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) -> RetrieveImageDownloadTask? { if let retrieveImageTask = retrieveImageTask, retrieveImageTask.cancelledBeforeDownloadStarting { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: timeout) request.httpShouldUsePipelining = requestsUsePipeling if let modifier = options?.modifier { guard let r = modifier.modified(for: request) else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.downloadCancelledBeforeStarting.rawValue, userInfo: nil), nil, nil) return nil } request = r } // There is a possiblility that request modifier changed the url to `nil` or empty. guard let url = request.url, !url.absoluteString.isEmpty else { completionHandler?(nil, NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidURL.rawValue, userInfo: nil), nil, nil) return nil } var downloadTask: RetrieveImageDownloadTask? setup(progressBlock: progressBlock, with: completionHandler, for: url, options: options) {(session, fetchLoad) -> Void in if fetchLoad.downloadTask == nil { let dataTask = session.dataTask(with: request) fetchLoad.downloadTask = RetrieveImageDownloadTask(internalTask: dataTask, ownerDownloader: self) dataTask.priority = options?.downloadPriority ?? URLSessionTask.defaultPriority dataTask.resume() // Hold self while the task is executing. self.sessionHandler.downloadHolder = self } fetchLoad.downloadTaskCount += 1 downloadTask = fetchLoad.downloadTask retrieveImageTask?.downloadTask = downloadTask } return downloadTask } // A single key may have multiple callbacks. Only download once. func setup(progressBlock: ImageDownloaderProgressBlock?, with completionHandler: ImageDownloaderCompletionHandler?, for url: URL, options: KingfisherOptionsInfo?, started: ((URLSession, ImageFetchLoad) -> Void)) { barrierQueue.sync(flags: .barrier) { let loadObjectForURL = fetchLoads[url] ?? ImageFetchLoad() let callbackPair = (progressBlock: progressBlock, completionHandler: completionHandler) loadObjectForURL.contents.append((callbackPair, options ?? KingfisherEmptyOptionsInfo)) fetchLoads[url] = loadObjectForURL if let session = session { started(session, loadObjectForURL) } } } func cancelDownloadingTask(_ task: RetrieveImageDownloadTask) { barrierQueue.sync { if let URL = task.internalTask.originalRequest?.url, let imageFetchLoad = self.fetchLoads[URL] { imageFetchLoad.downloadTaskCount -= 1 if imageFetchLoad.downloadTaskCount == 0 { task.internalTask.cancel() } } } } func clean(for url: URL) { barrierQueue.sync(flags: .barrier) { fetchLoads.removeValue(forKey: url) return } } } // MARK: - NSURLSessionDataDelegate /// Delegate class for `NSURLSessionTaskDelegate`. /// The session object will hold its delegate until it gets invalidated. /// If we use `ImageDownloader` as the session delegate, it will not be released. /// So we need an additional handler to break the retain cycle. // See https://github.com/onevcat/Kingfisher/issues/235 class ImageDownloaderSessionHandler: NSObject, URLSessionDataDelegate, AuthenticationChallengeResponsable { // The holder will keep downloader not released while a data task is being executed. // It will be set when the task started, and reset when the task finished. var downloadHolder: ImageDownloader? func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard let downloader = downloadHolder else { completionHandler(.cancel) return } if let statusCode = (response as? HTTPURLResponse)?.statusCode, let url = dataTask.originalRequest?.url, !(downloader.delegate ?? downloader).isValidStatusCode(statusCode, for: downloader) { let error = NSError(domain: KingfisherErrorDomain, code: KingfisherError.invalidStatusCode.rawValue, userInfo: [KingfisherErrorStatusCodeKey: statusCode, NSLocalizedDescriptionKey: HTTPURLResponse.localizedString(forStatusCode: statusCode)]) callCompletionHandlerFailure(error: error, url: url) } completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { guard let downloader = downloadHolder else { return } if let url = dataTask.originalRequest?.url, let fetchLoad = downloader.fetchLoad(for: url) { fetchLoad.responseData.append(data) if let expectedLength = dataTask.response?.expectedContentLength { for content in fetchLoad.contents { DispatchQueue.main.async { content.callback.progressBlock?(Int64(fetchLoad.responseData.length), expectedLength) } } } } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let url = task.originalRequest?.url else { return } guard error == nil else { callCompletionHandlerFailure(error: error!, url: url) return } processImage(for: task, url: url) } /** This method is exposed since the compiler requests. Do not call it. */ func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard let downloader = downloadHolder else { return } downloader.authenticationChallengeResponder?.downloader(downloader, didReceive: challenge, completionHandler: completionHandler) } private func cleanFetchLoad(for url: URL) { guard let downloader = downloadHolder else { return } downloader.clean(for: url) if downloader.fetchLoads.isEmpty { downloadHolder = nil } } private func callCompletionHandlerFailure(error: Error, url: URL) { guard let downloader = downloadHolder, let fetchLoad = downloader.fetchLoad(for: url) else { return } // We need to clean the fetch load first, before actually calling completion handler. cleanFetchLoad(for: url) for content in fetchLoad.contents { content.options.callbackDispatchQueue.safeAsync { content.callback.completionHandler?(nil, error as NSError, url, nil) } } } private func processImage(for task: URLSessionTask, url: URL) { guard let downloader = downloadHolder else { return } // We are on main queue when receiving this. downloader.processQueue.async { guard let fetchLoad = downloader.fetchLoad(for: url) else { return } self.cleanFetchLoad(for: url) let data = fetchLoad.responseData as Data // Cache the processed images. So we do not need to re-process the image if using the same processor. // Key is the identifier of processor. var imageCache: [String: Image] = [:] for content in fetchLoad.contents { let options = content.options let completionHandler = content.callback.completionHandler let callbackQueue = options.callbackDispatchQueue let processor = options.processor var image = imageCache[processor.identifier] if image == nil { image = processor.process(item: .data(data), options: options) // Add the processed image to cache. // If `image` is nil, nothing will happen (since the key is not existing before). imageCache[processor.identifier] = image } if let image = image { downloader.delegate?.imageDownloader(downloader, didDownload: image, for: url, with: task.response) if options.backgroundDecode { let decodedImage = image.kf.decoded(scale: options.scaleFactor) callbackQueue.safeAsync { completionHandler?(decodedImage, nil, url, data) } } else { callbackQueue.safeAsync { completionHandler?(image, nil, url, data) } } } else { if let res = task.response as? HTTPURLResponse , res.statusCode == 304 { let notModified = NSError(domain: KingfisherErrorDomain, code: KingfisherError.notModified.rawValue, userInfo: nil) completionHandler?(nil, notModified, url, nil) continue } let badData = NSError(domain: KingfisherErrorDomain, code: KingfisherError.badData.rawValue, userInfo: nil) callbackQueue.safeAsync { completionHandler?(nil, badData, url, nil) } } } } } } // Placeholder. For retrieving extension methods of ImageDownloaderDelegate extension ImageDownloader: ImageDownloaderDelegate {}
mit
5c11725ca8dda16e51d67e43a4ef174e
42.597744
217
0.655471
5.715623
false
false
false
false
happyeverydayzhh/WWDC
WWDC/PreferencesWindowController.swift
2
5199
// // PreferencesWindowController.swift // WWDC // // Created by Guilherme Rambo on 01/05/15. // Copyright (c) 2015 Guilherme Rambo. All rights reserved. // import Cocoa class PreferencesWindowController: NSWindowController { let prefs = Preferences.SharedPreferences() convenience init() { self.init(windowNibName: "PreferencesWindowController") } @IBOutlet weak var downloadProgressIndicator: NSProgressIndicator! override func windowDidLoad() { super.windowDidLoad() populateFontsPopup() downloadsFolderLabel.stringValue = prefs.localVideoStoragePath automaticRefreshEnabledCheckbox.state = prefs.automaticRefreshEnabled ? NSOnState : NSOffState if let familyName = prefs.transcriptFont.familyName { fontPopUp.selectItemWithTitle(familyName) } let size = "\(Int(prefs.transcriptFont.pointSize))" sizePopUp.selectItemWithTitle(size) textColorWell.color = prefs.transcriptTextColor bgColorWell.color = prefs.transcriptBgColor } // MARK: Downloads folder @IBOutlet weak var downloadsFolderLabel: NSTextField! @IBAction func changeDownloadsFolder(sender: NSButton) { let panel = NSOpenPanel() panel.directoryURL = NSURL(fileURLWithPath: Preferences.SharedPreferences().localVideoStoragePath) panel.canChooseDirectories = true panel.canChooseFiles = false panel.canCreateDirectories = true panel.prompt = "Choose" panel.beginSheetModalForWindow(window!) { result in if result > 0 { if let path = panel.URL?.path { Preferences.SharedPreferences().localVideoStoragePath = path self.downloadsFolderLabel.stringValue = path } } } } @IBAction func downloadAllSessions(sender: AnyObject) { let completionHandler: DataStore.fetchSessionsCompletionHandler = { success, sessions in dispatch_async(dispatch_get_main_queue()) { let sessions2015 = sessions.filter{(session) in return session.year == 2015 && !VideoStore.SharedStore().hasVideo(session.hd_url!) } print("Videos fetched, start downloading") DownloadVideosBatch.SharedDownloader().sessions = sessions2015 DownloadVideosBatch.SharedDownloader().startDownloading() } } DataStore.SharedStore.fetchSessions(completionHandler, disableCache: true) if let appDelegate = NSApplication.sharedApplication().delegate as? AppDelegate { appDelegate.showDownloadsWindow(appDelegate) } } @IBAction func revealInFinder(sender: NSButton) { let path = Preferences.SharedPreferences().localVideoStoragePath let root = (path as NSString).stringByDeletingLastPathComponent let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(path) { do { try fileManager.createDirectoryAtPath(path, withIntermediateDirectories: false, attributes: nil) } catch _ { } } NSWorkspace.sharedWorkspace().selectFile(path, inFileViewerRootedAtPath: root) } // MARK: Session refresh @IBOutlet weak var automaticRefreshEnabledCheckbox: NSButton! @IBAction func automaticRefreshCheckboxAction(sender: NSButton) { prefs.automaticRefreshEnabled = (sender.state == NSOnState) } // MARK: Transcript appearance @IBOutlet weak var fontPopUp: NSPopUpButton! @IBOutlet weak var sizePopUp: NSPopUpButton! @IBOutlet weak var textColorWell: NSColorWell! @IBOutlet weak var bgColorWell: NSColorWell! @IBAction func fontPopUpAction(sender: NSPopUpButton) { if let newFont = NSFont(name: fontPopUp.selectedItem!.title, size: prefs.transcriptFont.pointSize) { prefs.transcriptFont = newFont } } @IBAction func sizePopUpAction(sender: NSPopUpButton) { let size = NSString(string: sizePopUp.selectedItem!.title).doubleValue prefs.transcriptFont = NSFont(name: prefs.transcriptFont.fontName, size: CGFloat(size))! } @IBAction func textColorWellAction(sender: NSColorWell) { prefs.transcriptTextColor = textColorWell.color } @IBAction func bgColorWellAction(sender: NSColorWell) { prefs.transcriptBgColor = bgColorWell.color } func populateFontsPopup() { fontPopUp.addItemsWithTitles(NSFontManager.sharedFontManager().availableFontFamilies) } private func hideProgressIndicator() { self.downloadProgressIndicator.hidden = true downloadProgressIndicator.stopAnimation(nil) } private func showProgressIndicator() { self.downloadProgressIndicator.hidden = false downloadProgressIndicator.startAnimation(nil) } }
bsd-2-clause
fd80fe35cb82ad2d3686f619d379bb17
32.541935
112
0.648971
5.848144
false
false
false
false
dfreniche/SpriteKit-Playground
Spritekit-playgorund.playground/Pages/Basic Physics.xcplaygroundpage/Sources/SceneConfig.swift
1
1135
import SpriteKit import PlaygroundSupport // Create your view public func setupView() -> SKView { let view = SKView(frame: CGRect(x: 0, y: 0, width: 1024, height: 768)) view.showsFPS = true // Show the view in the Playground PlaygroundPage.current.liveView = view return view } public class Scene: SKScene { let myPlane = SKSpriteNode(imageNamed: "Spaceship") override init(size: CGSize) { super.init(size: size) self.scaleMode = .aspectFit // define the scaleMode for this scene self.backgroundColor = SKColor.lightGray myPlane.position = CGPoint(x: self.size.width / 2, y: self.size.height) myPlane.physicsBody = SKPhysicsBody(circleOfRadius: myPlane.size.width / 2) myPlane.physicsBody?.affectedByGravity = false self.addChild(myPlane) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public func setupScene() -> Scene { let scene = Scene(size: CGSize(width: 1024, height: 768)) return scene }
mit
3f895ca4f55432cf98ae84e967c925b1
26.02381
83
0.639648
4.468504
false
false
false
false
Fluci/CPU-Spy
CPU Spy/lib/Util/FSStringASCII.swift
1
352
// // FSStringASCII.swift // CPU Spy // // Created by Felice Serena on 04.02.16. // Copyright © 2016 Serena. All rights reserved. // import Foundation public enum ASCII: CChar { case Null = 0 case NewLine = 10 case Space = 32 case Comma = 44 case Slash = 47 case UpperA = 65 case UpperZ = 90 case Backslash = 92 }
mit
af49ebdd438687024136cfb447c57d77
16.6
49
0.623932
3.407767
false
false
false
false
vector-im/vector-ios
Riot/Modules/Integrations/WidgetPermission/WidgetPermissionViewController.swift
1
7966
// File created from ScreenTemplate // $ createScreen.sh Modal/Show ServiceTermsModalScreen /* Copyright 2019 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 final class WidgetPermissionViewController: UIViewController { // MARK: - Constants private enum Constants { static let continueButtonCornerRadius: CGFloat = 8.0 } private enum Sizing { static var viewController: WidgetPermissionViewController? static var widthConstraint: NSLayoutConstraint? } // MARK: - Properties // MARK: Outlets @IBOutlet private weak var scrollView: UIScrollView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var closeButton: UIButton! @IBOutlet private weak var creatorInfoTitleLabel: UILabel! @IBOutlet private weak var creatorAvatarImageView: MXKImageView! @IBOutlet private weak var creatorDisplayNameLabel: UILabel! @IBOutlet private weak var creatorUserIDLabel: UILabel! @IBOutlet private weak var informationLabel: UILabel! @IBOutlet private weak var continueButton: UIButton! // MARK: Private private var viewModel: WidgetPermissionViewModel! { didSet { self.updateViews() } } private var theme: Theme! // MARK: Public @objc var didTapCloseButton: (() -> Void)? @objc var didTapContinueButton: (() -> Void)? // MARK: - Setup @objc class func instantiate(with viewModel: WidgetPermissionViewModel) -> WidgetPermissionViewController { let viewController = StoryboardScene.WidgetPermissionViewController.initialScene.instantiate() viewController.viewModel = viewModel viewController.theme = ThemeService.shared().theme return viewController } // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setupViews() self.updateViews() self.registerThemeServiceDidChangeThemeNotification() self.update(theme: self.theme) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.scrollView.flashScrollIndicators() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.creatorAvatarImageView.layer.cornerRadius = self.creatorAvatarImageView.frame.size.width/2 self.continueButton.layer.cornerRadius = Constants.continueButtonCornerRadius self.closeButton.layer.cornerRadius = self.closeButton.frame.size.width/2 } override var preferredStatusBarStyle: UIStatusBarStyle { return self.theme.statusBarStyle } // MARK: - Private private func update(theme: Theme) { self.theme = theme self.view.backgroundColor = theme.headerBackgroundColor self.titleLabel.textColor = theme.textPrimaryColor self.closeButton.vc_setBackgroundColor(theme.headerTextSecondaryColor, for: .normal) self.creatorInfoTitleLabel.textColor = theme.textSecondaryColor self.creatorDisplayNameLabel.textColor = theme.textSecondaryColor self.creatorUserIDLabel.textColor = theme.textSecondaryColor self.informationLabel.textColor = theme.textSecondaryColor self.continueButton.vc_setBackgroundColor(theme.tintColor, for: .normal) } private func registerThemeServiceDidChangeThemeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil) } @objc private func themeDidChange() { self.update(theme: ThemeService.shared().theme) } private func setupViews() { self.closeButton.layer.masksToBounds = true self.setupCreatorAvatarImageView() self.titleLabel.text = VectorL10n.roomWidgetPermissionTitle self.creatorInfoTitleLabel.text = VectorL10n.roomWidgetPermissionCreatorInfoTitle self.informationLabel.text = "" self.setupContinueButton() } private func updateViews() { if let avatarImageView = self.creatorAvatarImageView { let defaultavatarImage = AvatarGenerator.generateAvatar(forMatrixItem: self.viewModel.creatorUserId, withDisplayName: self.viewModel.creatorDisplayName) avatarImageView.setImageURI(self.viewModel.creatorAvatarUrl, withType: nil, andImageOrientation: .up, previewImage: defaultavatarImage, mediaManager: self.viewModel.mediaManager) } if let creatorDisplayNameLabel = self.creatorDisplayNameLabel { if let creatorDisplayName = self.viewModel.creatorDisplayName { creatorDisplayNameLabel.text = creatorDisplayName } else { creatorDisplayNameLabel.isHidden = true } } if let creatorUserIDLabel = self.creatorUserIDLabel { creatorUserIDLabel.text = self.viewModel.creatorUserId } if let informationLabel = self.informationLabel { informationLabel.text = self.viewModel.permissionsInformationText } } private func setupCreatorAvatarImageView() { self.creatorAvatarImageView.defaultBackgroundColor = UIColor.clear self.creatorAvatarImageView.enableInMemoryCache = true self.creatorAvatarImageView.clipsToBounds = true } private func setupContinueButton() { self.continueButton.layer.masksToBounds = true self.continueButton.setTitle(VectorL10n.continue, for: .normal) } // MARK: - Actions @IBAction private func closeButtonAction(_ sender: Any) { self.didTapCloseButton?() } @IBAction private func continueButtonAction(_ sender: Any) { self.didTapContinueButton?() } } // MARK: - SlidingModalPresentable extension WidgetPermissionViewController: SlidingModalPresentable { func allowsDismissOnBackgroundTap() -> Bool { return false } func layoutHeightFittingWidth(_ width: CGFloat) -> CGFloat { let sizingViewContoller: WidgetPermissionViewController if let viewController = WidgetPermissionViewController.Sizing.viewController { viewController.viewModel = self.viewModel sizingViewContoller = viewController } else { sizingViewContoller = WidgetPermissionViewController.instantiate(with: self.viewModel) WidgetPermissionViewController.Sizing.viewController = sizingViewContoller } let sizingViewContollerView: UIView = sizingViewContoller.view if let widthConstraint = WidgetPermissionViewController.Sizing.widthConstraint { widthConstraint.constant = width } else { let widthConstraint = sizingViewContollerView.widthAnchor.constraint(equalToConstant: width) widthConstraint.isActive = true WidgetPermissionViewController.Sizing.widthConstraint = widthConstraint } sizingViewContollerView.layoutIfNeeded() return sizingViewContoller.scrollView.contentSize.height } }
apache-2.0
b82106aecd5d038519da42a19de4ff0f
34.092511
190
0.685162
5.962575
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/weibo/Classes/Home/View/QRCode/QRCodeViewController.swift
1
6313
// // QRCodeViewController.swift // weibo // // Created by mada on 15/9/28. // Copyright © 2015年 MD. All rights reserved. // import UIKit import AVFoundation class QRCodeViewController: UIViewController, UITabBarDelegate { @IBOutlet weak var customTabBar: UITabBar! @IBOutlet weak var scanlineTopCons: NSLayoutConstraint! @IBOutlet weak var containerHeightCons: NSLayoutConstraint! @IBOutlet weak var scanlineView: UIImageView! @IBOutlet weak var containerView: UIView! override func viewDidLoad() { super.viewDidLoad() customTabBar.selectedItem = customTabBar.items![0] customTabBar.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) startAnimation() // 超出边框的裁剪掉 containerView.clipsToBounds = true setupQRScan() } // MARK: - 开启二维码扫描 private func setupQRScan() { // 1.判断是否可以输入设备 if !session.canAddInput(inputDevice) { return } // 2.判断是否可以输出设备 if !session.canAddOutput(output) { return } // 3.添加输入输出设备到会话中 session.addInput(inputDevice) session.addOutput(output) // 4.设置输出解析数据类型 output.metadataObjectTypes = output.availableMetadataObjectTypes // 5.添加输出代理,监听解析得到结果 output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) // 6.添加预览图层 view.layer.insertSublayer(previewLayer, atIndex: 0) // 7.利用会话开始扫描 session.startRunning() } // MARK: - 二维码扫描动画 private func startAnimation() { scanlineTopCons.constant = -containerHeightCons.constant view.layoutIfNeeded() UIView.animateWithDuration(1.5) { () -> Void in // 执行无数次 UIView.setAnimationRepeatCount(MAXFLOAT) self.scanlineTopCons.constant = self.containerHeightCons.constant self.view.layoutIfNeeded() } } // MARK: - 二维码扫描界面相关点击事件的监听 @IBAction func closeQRView(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } // tabBar的代理方法 func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { containerHeightCons.constant = (item.tag == 1) ? 125 : 200 // 停止动画 scanlineView.layer.removeAllAnimations() // 再开始动画 startAnimation() } // MARK: - 懒加载 private lazy var inputDevice: AVCaptureDeviceInput? = { let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do { let input = try AVCaptureDeviceInput(device: device) return input }catch { return nil } }() private lazy var output: AVCaptureMetadataOutput = { let output = AVCaptureMetadataOutput() // 设置兴趣点(即扫描范围,默认是全屏扫描) // 注意:坐标是以横屏时的左上角为原点 let frame = self.containerView.frame let size = self.view.frame.size // 默认(0,0,1,1) // 由于是按照横屏来计算的, 所以需要将x变为y, y变为x, 将宽变为高, 高变为宽 output.rectOfInterest = CGRect(x: frame.origin.y / size.height, y: frame.origin.x / size.width, width: frame.size.height / size.height, height: frame.size.width / size.width) return output }() private lazy var session: AVCaptureSession = { let session = AVCaptureSession() session.sessionPreset = "AVCaptureSessionPreset1920x1080" return session }() // 创建预览图层 private lazy var previewLayer: AVCaptureVideoPreviewLayer = { let preLayer = AVCaptureVideoPreviewLayer(session: self.session) preLayer.frame = UIScreen.mainScreen().bounds return preLayer }() // 创建一个二维码描边图层 private lazy var drawLayer: CALayer = { let layer = CALayer() layer.frame = UIScreen.mainScreen().bounds return layer }() } extension QRCodeViewController : AVCaptureMetadataOutputObjectsDelegate { func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { JSJLog(metadataObjects.last?.intValue) for obj in metadataObjects { // 将扫描到的二维码坐标转换为我们能够识别的坐标 let codeObject = previewLayer.transformedMetadataObjectForMetadataObject(obj as! AVMetadataObject) // 根据转换好的坐标给二维码描边 drawConner(codeObject as! AVMetadataMachineReadableCodeObject) } } private func drawConner(codeObject: AVMetadataMachineReadableCodeObject) { // 移除以前的描边 clearCorner() let layer = CAShapeLayer() layer.fillColor = UIColor.clearColor().CGColor layer.strokeColor = UIColor.blueColor().CGColor layer.lineWidth = 2.0 /* 绘图路径*/ let path = UIBezierPath() var point = CGPointZero var index = 0 let dictArray = codeObject.corners // 取出第0个,将字典中的x,y转换成CGPoint CGPointMakeWithDictionaryRepresentation((dictArray[index++] as! CFDictionaryRef), &point) path.moveToPoint(point) while index < dictArray.count { CGPointMakeWithDictionaryRepresentation((dictArray[index++] as! CFDictionaryRef), &point) path.addLineToPoint(point) } // 关闭路径 path.closePath() layer.path = path.CGPath drawLayer.addSublayer(layer) } private func clearCorner() { if drawLayer.sublayers == nil || drawLayer.sublayers?.count == 0 { return } for subLayer in drawLayer.sublayers! { subLayer.removeFromSuperlayer() } } }
mit
a085805ccfa8ce7d58158010c10c2a28
30.659341
182
0.628254
4.874788
false
false
false
false
coodly/laughing-adventure
Source/UI/FullScreenTableCreate.swift
1
1873
/* * Copyright 2015 Coodly LLC * * 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 public protocol FullScreenTableCreate: UITableViewDelegate, UITableViewDataSource { var tableView: UITableView! { get set } var tableTop: NSLayoutConstraint? { get set } func checkTableView(_ style: UITableViewStyle) } public extension FullScreenTableCreate where Self: UIViewController { func checkTableView(_ style: UITableViewStyle = .plain) { if tableView != nil { return } //not loaded from xib tableView = UITableView(frame: view.bounds, style: style) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) let views: [String: AnyObject] = ["table": tableView] tableView.translatesAutoresizingMaskIntoConstraints = false let top = NSLayoutConstraint.constraints(withVisualFormat: "V:|[table]", options: [], metrics: nil, views: views).first! tableTop = top let bottom = NSLayoutConstraint.constraints(withVisualFormat: "V:[table]|", options: [], metrics: nil, views: views).first! let horizontal = NSLayoutConstraint.constraints(withVisualFormat: "H:|[table]|", options: [], metrics: nil, views: views) view.addConstraints([top, bottom] + horizontal) } }
apache-2.0
ed3b90f59479ea708c54c852308a2824
38.851064
131
0.689802
4.839793
false
false
false
false
hoangdang1449/Spendy
Spendy/Helper.swift
1
5496
// // Helper.swift // Spendy // // Created by Dave Vo on 9/16/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit class Helper: NSObject { static let sharedInstance = Helper() func customizeBarButton(viewController: UIViewController, button: UIButton, imageName: String, isLeft: Bool) { let avatar = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 22)) avatar.image = UIImage(named: imageName) button.setImage(avatar.image, forState: .Normal) button.frame = CGRectMake(0, 0, 22, 22) let item: UIBarButtonItem = UIBarButtonItem() item.customView = button // item.customView?.layer.cornerRadius = 11 // item.customView?.layer.masksToBounds = true if isLeft { viewController.navigationItem.leftBarButtonItem = item } else { viewController.navigationItem.rightBarButtonItem = item } } func setSeparatorFullWidth(cell: UITableViewCell) { // Set full width for the separator cell.layoutMargins = UIEdgeInsetsZero cell.preservesSuperviewLayoutMargins = false cell.separatorInset = UIEdgeInsetsZero } func getCellAtGesture(gestureRecognizer: UIGestureRecognizer, tableView: UITableView) -> UITableViewCell? { let location = gestureRecognizer.locationInView(tableView) let indexPath = tableView.indexPathForRowAtPoint(location) if let indexPath = indexPath { return tableView.cellForRowAtIndexPath(indexPath)! } else { return nil } } func getWeek(weekOfYear: Int) -> (NSDate?, NSDate?) { var beginningOfWeek: NSDate? var endOfWeek: NSDate? let cal = NSCalendar.currentCalendar() let components = NSDateComponents() components.weekOfYear = weekOfYear if let date = cal.dateByAddingComponents(components, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) { var weekDuration = NSTimeInterval() if cal.rangeOfUnit(NSCalendarUnit.NSWeekOfYearCalendarUnit, startDate: &beginningOfWeek, interval: &weekDuration, forDate: date) { endOfWeek = beginningOfWeek?.dateByAddingTimeInterval(weekDuration) } beginningOfWeek = cal.dateByAddingUnit(NSCalendarUnit.NSDayCalendarUnit, value: 1, toDate: beginningOfWeek!, options: NSCalendarOptions(rawValue: 0)) } return (beginningOfWeek!, endOfWeek!) } func showActionSheet(viewController: UIViewController, imagePicker: UIImagePickerController) { let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let takePhotoAction = UIAlertAction(title: "Take a Photo", style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("Take a Photo", terminator: "\n") imagePicker.allowsEditing = false imagePicker.sourceType = UIImagePickerControllerSourceType.Camera imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo imagePicker.modalPresentationStyle = .FullScreen viewController.presentViewController(imagePicker, animated: true, completion: nil) }) let photoLibraryAction = UIAlertAction(title: "Photo from Library", style: .Default, handler: { (alert: UIAlertAction!) -> Void in print("Photo from Library", terminator: "\n") imagePicker.allowsEditing = true imagePicker.sourceType = .PhotoLibrary viewController.presentViewController(imagePicker, animated: true, completion: nil) }) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: { (alert: UIAlertAction!) -> Void in print("Cancelled", terminator: "\n") }) optionMenu.addAction(takePhotoAction) optionMenu.addAction(photoLibraryAction) optionMenu.addAction(cancelAction) viewController.presentViewController(optionMenu, animated: true, completion: nil) } } extension String { subscript (r: Range<Int>) -> String { get { let startIndex = self.startIndex.advancedBy(r.startIndex) let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } func replace(target: String, withString: String) -> String { return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil) } } extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(netHex:Int) { self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff) } } enum ViewMode: Int { case Weekly = 0, Monthly, Yearly, Custom }
mit
d9a7f1ba341387da7f93fbc3738fe522
36.643836
161
0.631368
5.199622
false
false
false
false
Takanu/Pelican
Sources/Pelican/API/Types/Inline/InputMessageContent/InputMessageContent_Text.swift
1
1124
// // InputMessageText.swift // Pelican // // Created by Takanu Kyriako on 19/12/2017. // import Foundation /** Represents the content of a text message to be sent as the result of an inline query. */ public struct InputMessageContent_Text: InputMessageContent_Any { // The type of the input content, used for Codable. public static var type: InputMessageContentType = .text /// Text of the message to be sent. 1-4096 characters. public var text: String /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. public var parseMode: String? /// Disables link previews for links in the sent message. public var disableWebPreview: Bool? public init(text: String, parseMode: String?, disableWebPreview: Bool?) { self.text = text self.parseMode = parseMode self.disableWebPreview = disableWebPreview } /// Coding keys to map values when Encoding and Decoding. enum CodingKeys: String, CodingKey { case text = "message_text" case parseMode = "parse_mode" case disableWebPreview = "disable_web_page_preview" } }
mit
d35686368019ddd84ff3d81da490cc63
27.1
130
0.732206
3.836177
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay/NSStringEncodings.swift
1
7724
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: one day this will be bridged from CoreFoundation and we // should drop it here. <rdar://problem/14497260> (need support // for CF bridging) public var kCFStringEncodingASCII: CFStringEncoding { return 0x0600 } extension String { public struct Encoding : RawRepresentable { public var rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let ascii = Encoding(rawValue: 1) public static let nextstep = Encoding(rawValue: 2) public static let japaneseEUC = Encoding(rawValue: 3) public static let utf8 = Encoding(rawValue: 4) public static let isoLatin1 = Encoding(rawValue: 5) public static let symbol = Encoding(rawValue: 6) public static let nonLossyASCII = Encoding(rawValue: 7) public static let shiftJIS = Encoding(rawValue: 8) public static let isoLatin2 = Encoding(rawValue: 9) public static let unicode = Encoding(rawValue: 10) public static let windowsCP1251 = Encoding(rawValue: 11) public static let windowsCP1252 = Encoding(rawValue: 12) public static let windowsCP1253 = Encoding(rawValue: 13) public static let windowsCP1254 = Encoding(rawValue: 14) public static let windowsCP1250 = Encoding(rawValue: 15) public static let iso2022JP = Encoding(rawValue: 21) public static let macOSRoman = Encoding(rawValue: 30) public static let utf16 = Encoding.unicode public static let utf16BigEndian = Encoding(rawValue: 0x90000100) public static let utf16LittleEndian = Encoding(rawValue: 0x94000100) public static let utf32 = Encoding(rawValue: 0x8c000100) public static let utf32BigEndian = Encoding(rawValue: 0x98000100) public static let utf32LittleEndian = Encoding(rawValue: 0x9c000100) } public typealias EncodingConversionOptions = NSString.EncodingConversionOptions public typealias EnumerationOptions = NSString.EnumerationOptions public typealias CompareOptions = NSString.CompareOptions } extension String.Encoding : Hashable { public var hashValue: Int { // Note: This is effectively the same hashValue definition that // RawRepresentable provides on its own. We only need to keep this to // ensure ABI compatibility with 5.0. return rawValue.hashValue } @_alwaysEmitIntoClient // Introduced in 5.1 public func hash(into hasher: inout Hasher) { // Note: `hash(only:)` is only defined here because we also define // `hashValue`. // // In 5.0, `hash(into:)` was resolved to RawRepresentable's functionally // equivalent definition; we added this definition in 5.1 to make it // clear this `hash(into:)` isn't synthesized by the compiler. // (Otherwise someone may be tempted to define it, possibly breaking the // hash encoding and thus the ABI. RawRepresentable's definition is // inlinable.) hasher.combine(rawValue) } public static func ==(lhs: String.Encoding, rhs: String.Encoding) -> Bool { // Note: This is effectively the same == definition that // RawRepresentable provides on its own. We only need to keep this to // ensure ABI compatibility with 5.0. return lhs.rawValue == rhs.rawValue } } extension String.Encoding : CustomStringConvertible { public var description: String { return String.localizedName(of: self) } } @available(*, unavailable, renamed: "String.Encoding") public typealias NSStringEncoding = UInt @available(*, unavailable, renamed: "String.Encoding.ascii") public var NSASCIIStringEncoding: String.Encoding { return String.Encoding.ascii } @available(*, unavailable, renamed: "String.Encoding.nextstep") public var NSNEXTSTEPStringEncoding: String.Encoding { return String.Encoding.nextstep } @available(*, unavailable, renamed: "String.Encoding.japaneseEUC") public var NSJapaneseEUCStringEncoding: String.Encoding { return String.Encoding.japaneseEUC } @available(*, unavailable, renamed: "String.Encoding.utf8") public var NSUTF8StringEncoding: String.Encoding { return String.Encoding.utf8 } @available(*, unavailable, renamed: "String.Encoding.isoLatin1") public var NSISOLatin1StringEncoding: String.Encoding { return String.Encoding.isoLatin1 } @available(*, unavailable, renamed: "String.Encoding.symbol") public var NSSymbolStringEncoding: String.Encoding { return String.Encoding.symbol } @available(*, unavailable, renamed: "String.Encoding.nonLossyASCII") public var NSNonLossyASCIIStringEncoding: String.Encoding { return String.Encoding.nonLossyASCII } @available(*, unavailable, renamed: "String.Encoding.shiftJIS") public var NSShiftJISStringEncoding: String.Encoding { return String.Encoding.shiftJIS } @available(*, unavailable, renamed: "String.Encoding.isoLatin2") public var NSISOLatin2StringEncoding: String.Encoding { return String.Encoding.isoLatin2 } @available(*, unavailable, renamed: "String.Encoding.unicode") public var NSUnicodeStringEncoding: String.Encoding { return String.Encoding.unicode } @available(*, unavailable, renamed: "String.Encoding.windowsCP1251") public var NSWindowsCP1251StringEncoding: String.Encoding { return String.Encoding.windowsCP1251 } @available(*, unavailable, renamed: "String.Encoding.windowsCP1252") public var NSWindowsCP1252StringEncoding: String.Encoding { return String.Encoding.windowsCP1252 } @available(*, unavailable, renamed: "String.Encoding.windowsCP1253") public var NSWindowsCP1253StringEncoding: String.Encoding { return String.Encoding.windowsCP1253 } @available(*, unavailable, renamed: "String.Encoding.windowsCP1254") public var NSWindowsCP1254StringEncoding: String.Encoding { return String.Encoding.windowsCP1254 } @available(*, unavailable, renamed: "String.Encoding.windowsCP1250") public var NSWindowsCP1250StringEncoding: String.Encoding { return String.Encoding.windowsCP1250 } @available(*, unavailable, renamed: "String.Encoding.iso2022JP") public var NSISO2022JPStringEncoding: String.Encoding { return String.Encoding.iso2022JP } @available(*, unavailable, renamed: "String.Encoding.macOSRoman") public var NSMacOSRomanStringEncoding: String.Encoding { return String.Encoding.macOSRoman } @available(*, unavailable, renamed: "String.Encoding.utf16") public var NSUTF16StringEncoding: String.Encoding { return String.Encoding.utf16 } @available(*, unavailable, renamed: "String.Encoding.utf16BigEndian") public var NSUTF16BigEndianStringEncoding: String.Encoding { return String.Encoding.utf16BigEndian } @available(*, unavailable, renamed: "String.Encoding.utf16LittleEndian") public var NSUTF16LittleEndianStringEncoding: String.Encoding { return String.Encoding.utf16LittleEndian } @available(*, unavailable, renamed: "String.Encoding.utf32") public var NSUTF32StringEncoding: String.Encoding { return String.Encoding.utf32 } @available(*, unavailable, renamed: "String.Encoding.utf32BigEndian") public var NSUTF32BigEndianStringEncoding: String.Encoding { return String.Encoding.utf32BigEndian } @available(*, unavailable, renamed: "String.Encoding.utf32LittleEndian") public var NSUTF32LittleEndianStringEncoding: String.Encoding { return String.Encoding.utf32LittleEndian }
apache-2.0
f81334ec0d9c14805d56d88384be39ce
41.20765
81
0.74767
4.519602
false
false
false
false
xedin/swift
benchmark/single-source/Breadcrumbs.swift
20
17014
//===--- Breadcrumbs.swift ------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // Tests the performance of String's memoized UTF-8 to UTF-16 index conversion // breadcrumbs. These are used to speed up range- and positional access through // conventional NSString APIs. public let Breadcrumbs: [BenchmarkInfo] = [ UTF16ToIdx(workload: longASCIIWorkload, count: 5_000).info, UTF16ToIdx(workload: longMixedWorkload, count: 5_000).info, IdxToUTF16(workload: longASCIIWorkload, count: 5_000).info, IdxToUTF16(workload: longMixedWorkload, count: 5_000).info, UTF16ToIdxRange(workload: longASCIIWorkload, count: 1_000).info, UTF16ToIdxRange(workload: longMixedWorkload, count: 1_000).info, IdxToUTF16Range(workload: longASCIIWorkload, count: 1_000).info, IdxToUTF16Range(workload: longMixedWorkload, count: 1_000).info, CopyUTF16CodeUnits(workload: asciiWorkload, count: 500).info, CopyUTF16CodeUnits(workload: mixedWorkload, count: 500).info, MutatedUTF16ToIdx(workload: asciiWorkload, count: 50).info, MutatedUTF16ToIdx(workload: mixedWorkload, count: 50).info, MutatedIdxToUTF16(workload: asciiWorkload, count: 50).info, MutatedIdxToUTF16(workload: mixedWorkload, count: 50).info, ] extension String { func forceNativeCopy() -> String { var result = String() result.reserveCapacity(64) result.append(self) return result } } extension Collection { /// Returns a randomly ordered array of random non-overlapping index ranges /// that cover this collection entirely. /// /// Note: some of the returned ranges may be empty. func randomIndexRanges<R: RandomNumberGenerator>( count: Int, using generator: inout R ) -> [Range<Index>] { // Load indices into a buffer to prevent quadratic performance with // forward-only collections. FIXME: Eliminate this if Self conforms to RAC. let indices = Array(self.indices) var cuts: [Index] = (0 ..< count - 1).map { _ in indices.randomElement(using: &generator)! } cuts.append(self.startIndex) cuts.append(self.endIndex) cuts.sort() let ranges = (0 ..< count).map { cuts[$0] ..< cuts[$0 + 1] } return ranges.shuffled(using: &generator) } } struct Workload { let name: String let string: String } class BenchmarkBase { let name: String let workload: Workload var inputString: String = "" init(name: String, workload: Workload) { self.name = name self.workload = workload } var label: String { return "\(name).\(workload.name)" } func setUp() { self.inputString = workload.string.forceNativeCopy() } func tearDown() { self.inputString = "" } func run(iterations: Int) { fatalError("unimplemented abstract method") } var info: BenchmarkInfo { return BenchmarkInfo( name: self.label, runFunction: self.run(iterations:), tags: [.validation, .api, .String], setUpFunction: self.setUp, tearDownFunction: self.tearDown) } } //============================================================================== // Workloads //============================================================================== let asciiBase = #""" * Debugger support. Swift has a `-g` command line switch that turns on debug info for the compiled output. Using the standard lldb debugger this will allow single-stepping through Swift programs, printing backtraces, and navigating through stack frames; all in sync with the corresponding Swift source code. An unmodified lldb cannot inspect any variables. Example session: ``` $ echo 'println("Hello World")' >hello.swift $ swift hello.swift -c -g -o hello.o $ ld hello.o "-dynamic" "-arch" "x86_64" "-macosx_version_min" "10.9.0" \ -framework Foundation lib/swift/libswift_stdlib_core.dylib \ lib/swift/libswift_stdlib_posix.dylib -lSystem -o hello $ lldb hello Current executable set to 'hello' (x86_64). (lldb) b top_level_code Breakpoint 1: where = hello`top_level_code + 26 at hello.swift:1, addre... (lldb) r Process 38592 launched: 'hello' (x86_64) Process 38592 stopped * thread #1: tid = 0x1599fb, 0x0000000100000f2a hello`top_level_code + ... frame #0: 0x0000000100000f2a hello`top_level_code + 26 at hello.shi... -> 1 println("Hello World") (lldb) bt * thread #1: tid = 0x1599fb, 0x0000000100000f2a hello`top_level_code + ... frame #0: 0x0000000100000f2a hello`top_level_code + 26 at hello.shi... frame #1: 0x0000000100000f5c hello`main + 28 frame #2: 0x00007fff918605fd libdyld.dylib`start + 1 frame #3: 0x00007fff918605fd libdyld.dylib`start + 1 ``` Also try `s`, `n`, `up`, `down`. * `nil` can now be used without explicit casting. Previously, `nil` had type `NSObject`, so one would have to write (e.g.) `nil as! NSArray` to create a `nil` `NSArray`. Now, `nil` picks up the type of its context. * `POSIX.EnvironmentVariables` and `swift.CommandLineArguments` global variables were merged into a `swift.Process` variable. Now you can access command line arguments with `Process.arguments`. In order to access environment variables add `import POSIX` and use `Process.environmentVariables`. func _toUTF16Offsets(_ indices: Range<Index>) -> Range<Int> { let lowerbound = _toUTF16Offset(indices.lowerBound) let length = self.utf16.distance( from: indices.lowerBound, to: indices.upperBound) return Range( uncheckedBounds: (lower: lowerbound, upper: lowerbound + length)) } 0 swift 0x00000001036b5f58 llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 40 1 swift 0x00000001036b50f8 llvm::sys::RunSignalHandlers() + 248 2 swift 0x00000001036b6572 SignalHandler(int) + 258 3 libsystem_platform.dylib 0x00007fff64010b5d _sigtramp + 29 4 libsystem_platform.dylib 0x0000000100000000 _sigtramp + 2617177280 5 libswiftCore.dylib 0x0000000107b5d135 $sSh8_VariantV7element2atxSh5IndexVyx_G_tF + 613 6 libswiftCore.dylib 0x0000000107c51449 $sShyxSh5IndexVyx_Gcig + 9 7 libswiftCore.dylib 0x00000001059d60be $sShyxSh5IndexVyx_Gcig + 4258811006 8 swift 0x000000010078801d llvm::MCJIT::runFunction(llvm::Function*, llvm::ArrayRef<llvm::GenericValue>) + 381 9 swift 0x000000010078b0a4 llvm::ExecutionEngine::runFunctionAsMain(llvm::Function*, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, char const* const*) + 1268 10 swift 0x00000001000e048c REPLEnvironment::executeSwiftSource(llvm::StringRef, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&) + 1532 11 swift 0x00000001000dbbd3 swift::runREPL(swift::CompilerInstance&, std::__1::vector<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, std::__1::allocator<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > > > const&, bool) + 1443 12 swift 0x00000001000b5341 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*, swift::UnifiedStatsReporter*) + 2865 13 swift 0x00000001000b38f4 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 3028 14 swift 0x000000010006ca44 main + 660 15 libdyld.dylib 0x00007fff63e293f1 start + 1 16 libdyld.dylib 0x0000000000000008 start + 2619173912 Illegal instruction: 4 """# let asciiWorkload = Workload( name: "ASCII", string: asciiBase) let longASCIIWorkload = Workload( name: "longASCII", string: String(repeating: asciiBase, count: 100)) let mixedBase = """ siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig 👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿 siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig 👍👩‍👩‍👧‍👧👨‍👨‍👦‍👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿the quick brown fox👍🏿👍🏾👍🏽👍🏼👍🏻🇲🇽🇨🇦🇺🇸👨‍👨‍👦‍👦👩‍👩‍👧‍👧👍 siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig 今回のアップデートでSwiftに大幅な改良が施され、安定していてしかも直感的に使うことができるAppleプラットフォーム向けプログラミング言語になりました。 Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭 Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。 siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig 이번 업데이트에서는 강력하면서도 직관적인 Apple 플랫폼용 프로그래밍 언어인 Swift를 완벽히 개선하였습니다. Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭 в чащах юга жил-был цитрус? да, но фальшивый экземпляр siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig \u{201c}Hello\u{2010}world\u{2026}\u{201d} \u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d} Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭 """ let mixedWorkload = Workload( name: "Mixed", string: mixedBase) let longMixedWorkload = Workload( name: "longMixed", string: String(repeating: mixedBase, count: 100)) //============================================================================== // Benchmarks //============================================================================== /// Convert `count` random UTF-16 offsets into String indices. class UTF16ToIdx: BenchmarkBase { let count: Int var inputOffsets: [Int] = [] init(workload: Workload, count: Int) { self.count = count super.init(name: "Breadcrumbs.UTF16ToIdx", workload: workload) } override func setUp() { super.setUp() var rng = SplitMix64(seed: 42) let range = 0 ..< inputString.utf16.count inputOffsets = Array(range.shuffled(using: &rng).prefix(count)) } override func tearDown() { super.tearDown() inputOffsets = [] } @inline(never) override func run(iterations: Int) { for _ in 0 ..< iterations { for offset in inputOffsets { blackHole(inputString._toUTF16Index(offset)) } } } } /// Convert `count` random String indices into UTF-16 offsets. class IdxToUTF16: BenchmarkBase { let count: Int var inputIndices: [String.Index] = [] init(workload: Workload, count: Int) { self.count = count super.init(name: "Breadcrumbs.IdxToUTF16", workload: workload) } override func setUp() { super.setUp() var rng = SplitMix64(seed: 42) inputIndices = Array(inputString.indices.shuffled(using: &rng).prefix(count)) } override func tearDown() { super.tearDown() inputIndices = [] } @inline(never) override func run(iterations: Int) { for _ in 0 ..< iterations { for index in inputIndices { blackHole(inputString._toUTF16Offset(index)) } } } } /// Split a string into `count` random slices and convert their UTF-16 offsets /// into String index ranges. class UTF16ToIdxRange: BenchmarkBase { let count: Int var inputOffsets: [Range<Int>] = [] init(workload: Workload, count: Int) { self.count = count super.init(name: "Breadcrumbs.UTF16ToIdxRange", workload: workload) } override func setUp() { super.setUp() var rng = SplitMix64(seed: 42) inputOffsets = ( 0 ..< inputString.utf16.count ).randomIndexRanges(count: count, using: &rng) } override func tearDown() { super.tearDown() inputOffsets = [] } @inline(never) override func run(iterations: Int) { for _ in 0 ..< iterations { for range in inputOffsets { blackHole(inputString._toUTF16Indices(range)) } } } } /// Split a string into `count` random slices and convert their index ranges /// into into UTF-16 offset pairs. class IdxToUTF16Range: BenchmarkBase { let count: Int var inputIndices: [Range<String.Index>] = [] init(workload: Workload, count: Int) { self.count = count super.init(name: "Breadcrumbs.IdxToUTF16Range", workload: workload) } override func setUp() { super.setUp() var rng = SplitMix64(seed: 42) inputIndices = self.inputString.randomIndexRanges(count: count, using: &rng) } override func tearDown() { super.tearDown() inputIndices = [] } @inline(never) override func run(iterations: Int) { for _ in 0 ..< iterations { for range in inputIndices { blackHole(inputString._toUTF16Offsets(range)) } } } } class CopyUTF16CodeUnits: BenchmarkBase { let count: Int var inputIndices: [Range<Int>] = [] var outputBuffer: [UInt16] = [] init(workload: Workload, count: Int) { self.count = count super.init(name: "Breadcrumbs.CopyUTF16CodeUnits", workload: workload) } override func setUp() { super.setUp() var rng = SplitMix64(seed: 42) inputIndices = ( 0 ..< inputString.utf16.count ).randomIndexRanges(count: count, using: &rng) outputBuffer = Array(repeating: 0, count: inputString.utf16.count) } override func tearDown() { super.tearDown() inputIndices = [] } @inline(never) override func run(iterations: Int) { outputBuffer.withUnsafeMutableBufferPointer { buffer in for _ in 0 ..< iterations { for range in inputIndices { inputString._copyUTF16CodeUnits( into: UnsafeMutableBufferPointer(rebasing: buffer[range]), range: range) } } } } } /// This is like `UTF16ToIdx` but appends to the string after every index /// conversion. In effect, this tests breadcrumb creation performance. class MutatedUTF16ToIdx: BenchmarkBase { let count: Int var inputOffsets: [Int] = [] init(workload: Workload, count: Int) { self.count = count super.init( name: "Breadcrumbs.MutatedUTF16ToIdx", workload: workload) } override func setUp() { super.setUp() var generator = SplitMix64(seed: 42) let range = 0 ..< inputString.utf16.count inputOffsets = Array(range.shuffled(using: &generator).prefix(count)) } override func tearDown() { super.tearDown() inputOffsets = [] } @inline(never) override func run(iterations: Int) { var flag = true for _ in 0 ..< iterations { var string = inputString for offset in inputOffsets { blackHole(string._toUTF16Index(offset)) if flag { string.append(" ") } else { string.removeLast() } flag.toggle() } } } } /// This is like `IdxToUTF16` but appends to the string after every index /// conversion. In effect, this tests breadcrumb creation performance. class MutatedIdxToUTF16: BenchmarkBase { let count: Int var inputIndices: [String.Index] = [] init(workload: Workload, count: Int) { self.count = count super.init( name: "Breadcrumbs.MutatedIdxToUTF16", workload: workload) } override func setUp() { super.setUp() var rng = SplitMix64(seed: 42) inputIndices = Array(inputString.indices.shuffled(using: &rng).prefix(count)) } override func tearDown() { super.tearDown() inputIndices = [] } @inline(never) override func run(iterations: Int) { var flag = true for _ in 0 ..< iterations { var string = inputString for index in inputIndices { blackHole(string._toUTF16Offset(index)) if flag { string.append(" ") flag = false } else { string.removeLast() flag = true } } } } }
apache-2.0
391d2041311f1a095ba3590eaff46e1d
33.093555
357
0.653028
3.847724
false
false
false
false
tranhieutt/BrightFutures
BrightFutures/Future.swift
1
5182
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // 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 Result /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T>(@autoclosure(escaping) task: () -> T) -> Future<T, NoError> { return future(context: Queue.global.context, task: task) } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T>(task: () -> T) -> Future<T, NoError> { return future(context: Queue.global.context, task: task) } /// Executes the given task on the given context and wraps the result of the task in a Future public func future<T>(context c: ExecutionContext, task: () -> T) -> Future<T, NoError> { return future(context: c) { () -> Result<T, NoError> in return Result(value: task()) } } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T, E>(@autoclosure(escaping) task: () -> Result<T, E>) -> Future<T, E> { return future(context: Queue.global.context, task: task) } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T, E>(task: () -> Result<T, E>) -> Future<T, E> { return future(context: Queue.global.context, task: task) } /// Executes the given task on the given context and wraps the result of the task in a Future public func future<T, E>(context c: ExecutionContext, task: () -> Result<T, E>) -> Future<T, E> { let future = Future<T, E>(); c { let result = task() try! future.complete(result) } return future } /// A Future represents the outcome of an asynchronous operation /// The outcome will be represented as an instance of the `Result` enum and will be stored /// in the `result` property. As long as the operation is not yet completed, `result` will be nil. /// Interested parties can be informed of the completion by using one of the available callback /// registration methods (e.g. onComplete, onSuccess & onFailure) or by immediately composing/chaining /// subsequent actions (e.g. map, flatMap, recover, andThen, etc.). /// /// For more info, see the project README.md public final class Future<T, E: ErrorType>: Async<Result<T, E>> { public typealias CompletionCallback = (result: Result<T,E>) -> Void public typealias SuccessCallback = T -> Void public typealias FailureCallback = E -> Void public required init() { super.init() } public required init(result: Future.Value) { super.init(result: result) } public init(value: T, delay: NSTimeInterval) { super.init(result: Result<T, E>(value: value), delay: delay) } public required init<A: AsyncType where A.Value == Value>(other: A) { super.init(other: other) } public convenience init(value: T) { self.init(result: Result(value: value)) } public convenience init(error: E) { self.init(result: Result(error: error)) } public required init(@noescape resolver: (result: Value throws -> Void) -> Void) { super.init(resolver: resolver) } } /// Short-hand for `lhs.recover(rhs())` /// `rhs` is executed according to the default threading model (see README.md) public func ?? <T, E>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> T) -> Future<T, NoError> { return lhs.recover(context: DefaultThreadingModel(), task: { _ in return rhs() }) } /// Short-hand for `lhs.recoverWith(rhs())` /// `rhs` is executed according to the default threading model (see README.md) public func ?? <T, E, E1>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> Future<T, E1>) -> Future<T, E1> { return lhs.recoverWith(context: DefaultThreadingModel(), task: { _ in return rhs() }) } /// Can be used as the value type of a `Future` or `Result` to indicate it can never be a success. /// This is guaranteed by the type system, because `NoValue` has no possible values and thus cannot be created. public enum NoValue { }
mit
e54c778a218c9c264aa9ed1f44ec063a
39.80315
112
0.682748
3.952708
false
false
false
false
payjp/payjp-ios
Sources/Views/CardFormTableStyledView.swift
1
6593
// // CardFormTableStyledView.swift // PAYJP // // Created by Li-Hsuan Chen on 2019/07/17. // Copyright © 2019 PAY, Inc. All rights reserved. // import UIKit /// CardFormView without label. /// It's suitable for UITableView design. @IBDesignable @objcMembers @objc(PAYCardFormTableStyledView) public class CardFormTableStyledView: CardFormView, CardFormProperties { // MARK: CardFormView /// Card holder input field enabled. @IBInspectable var isHolderRequired: Bool = false { didSet { holderContainer.isHidden = !isHolderRequired holderSeparator.isHidden = !isHolderRequired viewModel.update(isCardHolderEnabled: isHolderRequired) notifyIsValidChanged() } } @IBOutlet weak var brandLogoImage: UIImageView! @IBOutlet weak var cvcIconImage: UIImageView! @IBOutlet weak var holderContainer: UIStackView! @IBOutlet weak var ocrButton: UIButton! @IBOutlet weak var cardNumberTextField: FormTextField! @IBOutlet weak var expirationTextField: FormTextField! @IBOutlet weak var cvcTextField: FormTextField! @IBOutlet weak var cardHolderTextField: FormTextField! @IBOutlet weak var cardNumberErrorLabel: UILabel! @IBOutlet weak var expirationErrorLabel: UILabel! @IBOutlet weak var cvcErrorLabel: UILabel! @IBOutlet weak var cardHolderErrorLabel: UILabel! var inputTextColor: UIColor = Style.Color.blue var inputTintColor: UIColor = Style.Color.blue var inputTextErrorColorEnabled: Bool = false var cardNumberSeparator: String = "-" // MARK: Private @IBOutlet private weak var expirationSeparator: UIView! @IBOutlet private weak var cvcSeparator: UIView! @IBOutlet private weak var holderSeparator: UIView! @IBOutlet private weak var expirationSeparatorConstraint: NSLayoutConstraint! @IBOutlet private weak var cvcSeparatorConstraint: NSLayoutConstraint! @IBOutlet private weak var holderSeparatorConstraint: NSLayoutConstraint! /// Camera scan action /// /// - Parameter sender: sender @IBAction func onTapOcrButton(_ sender: Any) { viewModel.requestOcr() } private var contentView: UIView! // MARK: Lifecycle override public init(frame: CGRect) { super.init(frame: frame) initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { let nib = UINib(nibName: "CardFormTableStyledView", bundle: .payjpBundle) let view = nib.instantiate(withOwner: self, options: nil).first as? UIView if let view = view { contentView = view view.frame = bounds view.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(view) } backgroundColor = Style.Color.groupedBackground // set images brandLogoImage.image = "icon_card".image cvcIconImage.image = "icon_card_cvc_3".image ocrButton.setImage("icon_camera".image, for: .normal) ocrButton.imageView?.contentMode = .scaleAspectFit ocrButton.contentHorizontalAlignment = .fill ocrButton.contentVerticalAlignment = .fill ocrButton.isHidden = !CardIOProxy.isCardIOAvailable() // separatorのheightを 0.5 で指定すると太さが統一ではなくなってしまうためscaleを使って対応 // cf. https://stackoverflow.com/a/21553495 let height = 1.0 / UIScreen.main.scale expirationSeparatorConstraint.constant = height cvcSeparatorConstraint.constant = height holderSeparatorConstraint.constant = height expirationSeparator.backgroundColor = Style.Color.separator cvcSeparator.backgroundColor = Style.Color.separator holderSeparator.backgroundColor = Style.Color.separator setupInputFields() apply(style: .defaultStyle) cardFormProperties = self } override public var intrinsicContentSize: CGSize { return contentView.intrinsicContentSize } // MARK: Private private func setupInputFields() { cardHolderTextField.keyboardType = .alphabet // placeholder cardNumberTextField.attributedPlaceholder = NSAttributedString( string: "payjp_card_form_number_placeholder".localized, attributes: [NSAttributedString.Key.foregroundColor: Style.Color.placeholderText]) expirationTextField.attributedPlaceholder = NSAttributedString( string: "payjp_card_form_expiration_placeholder".localized, attributes: [NSAttributedString.Key.foregroundColor: Style.Color.placeholderText]) cvcTextField.attributedPlaceholder = NSAttributedString( string: "payjp_card_form_cvc_placeholder".localized, attributes: [NSAttributedString.Key.foregroundColor: Style.Color.placeholderText]) cardHolderTextField.attributedPlaceholder = NSAttributedString( string: "payjp_card_form_holder_name_placeholder".localized, attributes: [NSAttributedString.Key.foregroundColor: Style.Color.placeholderText]) [cardNumberTextField, expirationTextField, cvcTextField, cardHolderTextField].forEach { textField in guard let textField = textField else { return } textField.delegate = self textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) } } } extension CardFormTableStyledView: CardFormStylable { public func apply(style: FormStyle) { let inputTextColor = style.inputTextColor let errorTextColor = style.errorTextColor let tintColor = style.tintColor self.inputTintColor = tintColor // input text cardNumberTextField.textColor = inputTextColor expirationTextField.textColor = inputTextColor cvcTextField.textColor = inputTextColor cardHolderTextField.textColor = inputTextColor // error text cardNumberErrorLabel.textColor = errorTextColor expirationErrorLabel.textColor = errorTextColor cvcErrorLabel.textColor = errorTextColor cardHolderErrorLabel.textColor = errorTextColor // tint cardNumberTextField.tintColor = tintColor expirationTextField.tintColor = tintColor cvcTextField.tintColor = tintColor cardHolderTextField.tintColor = tintColor } public func setCardHolderRequired(_ required: Bool) { isHolderRequired = required } }
mit
a1e1a1985d7b875bc59105924d659ca1
35.892655
108
0.70245
5.392238
false
false
false
false
just-a-computer/carton
src/desktop/mac/CartonUrlProtocol.swift
1
1821
import Foundation class CartonUrlProtocol : NSURLProtocol { var connection: NSURLConnection! override class func canInitWithRequest(request: NSURLRequest) -> Bool { NSLog("%@", request.URL!) if (request.URL!.scheme == "carton") { return true } return false } override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest { var canonUrl = "carton://" + request.URL!.path! if (request.URL!.fragment != nil) { canonUrl += "#" + request.URL!.fragment! } return NSURLRequest(URL: NSURL(string: canonUrl)!) } override func startLoading() { var cartonUrl = self.request.URL!.absoluteString cartonUrl = cartonUrl.substringFromIndex(cartonUrl.startIndex.advancedBy(9)) let fileUrl = NSURL(string: "file://" + NSBundle.mainBundle().resourcePath! + "/carton/" + cartonUrl)! connection = NSURLConnection(request: NSURLRequest(URL: fileUrl), delegate: self) } override func stopLoading() { connection.cancel() connection = nil } func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) { self.client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: NSURLCacheStoragePolicy.AllowedInMemoryOnly) } func connection(connection: NSURLConnection, didReceiveData data: NSData) { self.client!.URLProtocol(self, didLoadData: data) } func connectionDidFinishLoading(connection: NSURLConnection) { self.client!.URLProtocolDidFinishLoading(self) } func connection(connection: NSURLConnection, didFailWithError error: NSError) { self.client!.URLProtocol(self, didFailWithError: error) } }
mit
2d8b12f6d6d892cf9f436cde8d1ff221
35.42
133
0.66447
5.144068
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden_old/HTWDresden/MPListTVC.swift
1
2170
// // MPListTVC.swift // HTWDresden // // Created by Benjamin Herzog on 27.08.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit class MPListTVC: UITableViewController { var mensen: [String]! var mensaDic = [String:UIImage]() var mensaMeta: [[String:String]]! override func viewDidLoad() { super.viewDidLoad() if mensen == nil || mensen.count == 0 { mensen = ["Keine Mensen verfügbar. Bitte hier tippen."] } let mensaMetaData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("mensen", ofType: "json")!)! mensaMeta = NSJSONSerialization.JSONObjectWithData(mensaMetaData, options: .MutableContainers, error: nil) as! [[String:String]] for mensa in mensen { mensaDic[mensa] = UIImage(named: mensaImageNameForMensa(mensa))?.resizeToBoundingSquare(boundingSquareSideLength: 90) } } func mensaImageNameForMensa(mensa: String) -> String { for temp in mensaMeta { if temp["name"] == mensa { return temp["bild"]! } } return "noavailablemensaimage.jpg" } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mensen?.count ?? 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MPListCell cell.mensaName = mensen[indexPath.row] cell.mensaBild = mensaDic[cell.mensaName] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { CURR_MENSA = mensen[indexPath.row] if device() == .Pad { presentingViewController?.viewWillAppear(true) } presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } }
gpl-2.0
50b1d81a7fb02f2592a8a5f3a711692f
30.897059
136
0.652374
4.767033
false
false
false
false
tomlokhorst/Promissum
Sources/Promissum/AsyncExtensions.swift
1
2653
// // AsyncExtensions.swift // Promissum // // Created by Tom Lokhorst on 2021-03-06. // import Foundation @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension Promise { /// Async property that returns the value of the promise when it is resolved, or throws when the promise is rejected. public var asyncValue: Value { get async throws { #if canImport(_Concurrency) try await withUnsafeThrowingContinuation { continuation in self.finallyResult { result in continuation.resume(with: result) } } #else fatalError() #endif } } /// Async property that returns the result of a promise, when it is resolved or rejected. public var asyncResult: Result<Value, Error> { get async { #if canImport(_Concurrency) await withUnsafeContinuation { continuation in self.finallyResult { result in continuation.resume(returning: result) } } #else fatalError() #endif } } } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension Promise where Error == Swift.Error { /// Initialize a Promise using an async closure that can throw an error. /// Used to transform an async function into a promise. /// /// Example: /// ``` /// Promise { /// try await myAsyncFunction() /// } /// ``` public convenience init(block: @escaping () async throws -> Value) { let source = PromiseSource<Value, Error>() self.init(source: source) #if canImport(_Concurrency) Task { do { let value = try await block() source.resolve(value) } catch { source.reject(error) } } #else fatalError() #endif } } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) extension Promise where Error == Never { /// Async property that returns the value of the promise when it is resolved. public var asyncValue: Value { get async { #if canImport(_Concurrency) await withUnsafeContinuation { continuation in self.finallyResult { result in continuation.resume(with: result) } } #else fatalError() #endif } } /// Initialize a Promise using an async closure. /// Used to transform an async function into a promise. /// /// Example: /// ``` /// Promise { /// await myAsyncFunction() /// } /// ``` public convenience init(block: @escaping () async -> Value) { let source = PromiseSource<Value, Never>() self.init(source: source) #if canImport(_Concurrency) Task { let value = await block() source.resolve(value) } #else fatalError() #endif } }
mit
47e5fee5259a6d3ab31b514898a689c5
21.87069
119
0.629099
4.081538
false
false
false
false
danialzahid94/template-project-ios
TemplateProject/Utilities/Spring/Spring.swift
1
23436
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @objc public protocol Springable { var autostart: Bool { get set } var autohide: Bool { get set } var animation: String { get set } var force: CGFloat { get set } var delay: CGFloat { get set } var duration: CGFloat { get set } var damping: CGFloat { get set } var velocity: CGFloat { get set } var repeatCount: Float { get set } var x: CGFloat { get set } var y: CGFloat { get set } var scaleX: CGFloat { get set } var scaleY: CGFloat { get set } var rotate: CGFloat { get set } var opacity: CGFloat { get set } var animateFrom: Bool { get set } var curve: String { get set } // UIView var layer : CALayer { get } var transform : CGAffineTransform { get set } var alpha : CGFloat { get set } func animate() func animateNext(completion: () -> ()) func animateTo() func animateToNext(completion: () -> ()) } public class Spring : NSObject { private unowned var view : Springable private var shouldAnimateAfterActive = false private var shouldAnimateInLayoutSubviews = true init(_ view: Springable) { self.view = view super.init() commonInit() } func commonInit() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActiveNotification:", name: UIApplicationDidBecomeActiveNotification, object: nil) } func didBecomeActiveNotification(notification: NSNotification) { if shouldAnimateAfterActive { alpha = 0 animate() shouldAnimateAfterActive = false } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) } private var autostart: Bool { set { self.view.autostart = newValue } get { return self.view.autostart }} private var autohide: Bool { set { self.view.autohide = newValue } get { return self.view.autohide }} private var animation: String { set { self.view.animation = newValue } get { return self.view.animation }} private var force: CGFloat { set { self.view.force = newValue } get { return self.view.force }} private var delay: CGFloat { set { self.view.delay = newValue } get { return self.view.delay }} private var duration: CGFloat { set { self.view.duration = newValue } get { return self.view.duration }} private var damping: CGFloat { set { self.view.damping = newValue } get { return self.view.damping }} private var velocity: CGFloat { set { self.view.velocity = newValue } get { return self.view.velocity }} private var repeatCount: Float { set { self.view.repeatCount = newValue } get { return self.view.repeatCount }} private var x: CGFloat { set { self.view.x = newValue } get { return self.view.x }} private var y: CGFloat { set { self.view.y = newValue } get { return self.view.y }} private var scaleX: CGFloat { set { self.view.scaleX = newValue } get { return self.view.scaleX }} private var scaleY: CGFloat { set { self.view.scaleY = newValue } get { return self.view.scaleY }} private var rotate: CGFloat { set { self.view.rotate = newValue } get { return self.view.rotate }} private var opacity: CGFloat { set { self.view.opacity = newValue } get { return self.view.opacity }} private var animateFrom: Bool { set { self.view.animateFrom = newValue } get { return self.view.animateFrom }} private var curve: String { set { self.view.curve = newValue } get { return self.view.curve }} // UIView private var layer : CALayer { return view.layer } private var transform : CGAffineTransform { get { return view.transform } set { view.transform = newValue }} private var alpha: CGFloat { get { return view.alpha } set { view.alpha = newValue } } public enum AnimationPreset: String { case SlideLeft = "slideLeft" case SlideRight = "slideRight" case SlideDown = "slideDown" case SlideUp = "slideUp" case SqueezeLeft = "squeezeLeft" case SqueezeRight = "squeezeRight" case SqueezeDown = "squeezeDown" case SqueezeUp = "squeezeUp" case FadeIn = "fadeIn" case FadeOut = "fadeOut" case FadeOutIn = "fadeOutIn" case FadeInLeft = "fadeInLeft" case FadeInRight = "fadeInRight" case FadeInDown = "fadeInDown" case FadeInUp = "fadeInUp" case ZoomIn = "zoomIn" case ZoomOut = "zoomOut" case Fall = "fall" case Shake = "shake" case Pop = "pop" case FlipX = "flipX" case FlipY = "flipY" case Morph = "morph" case Squeeze = "squeeze" case Flash = "flash" case Wobble = "wobble" case Swing = "swing" } public enum AnimationCurve: String { case EaseIn = "easeIn" case EaseOut = "easeOut" case EaseInOut = "easeInOut" case Linear = "linear" case Spring = "spring" case EaseInSine = "easeInSine" case EaseOutSine = "easeOutSine" case EaseInOutSine = "easeInOutSine" case EaseInQuad = "easeInQuad" case EaseOutQuad = "easeOutQuad" case EaseInOutQuad = "easeInOutQuad" case EaseInCubic = "easeInCubic" case EaseOutCubic = "easeOutCubic" case EaseInOutCubic = "easeInOutCubic" case EaseInQuart = "easeInQuart" case EaseOutQuart = "easeOutQuart" case EaseInOutQuart = "easeInOutQuart" case EaseInQuint = "easeInQuint" case EaseOutQuint = "easeOutQuint" case EaseInOutQuint = "easeInOutQuint" case EaseInExpo = "easeInExpo" case EaseOutExpo = "easeOutExpo" case EaseInOutExpo = "easeInOutExpo" case EaseInCirc = "easeInCirc" case EaseOutCirc = "easeOutCirc" case EaseInOutCirc = "easeInOutCirc" case EaseInBack = "easeInBack" case EaseOutBack = "easeOutBack" case EaseInOutBack = "easeInOutBack" } func animatePreset() { alpha = 0.99 if let animation = AnimationPreset(rawValue: animation) { switch animation { case .SlideLeft: x = 300*force case .SlideRight: x = -300*force case .SlideDown: y = -300*force case .SlideUp: y = 300*force case .SqueezeLeft: x = 300 scaleX = 3*force case .SqueezeRight: x = -300 scaleX = 3*force case .SqueezeDown: y = -300 scaleY = 3*force case .SqueezeUp: y = 300 scaleY = 3*force case .FadeIn: opacity = 0 case .FadeOut: animateFrom = false opacity = 0 case .FadeOutIn: let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.autoreverses = true layer.addAnimation(animation, forKey: "fade") case .FadeInLeft: opacity = 0 x = 300*force case .FadeInRight: x = -300*force opacity = 0 case .FadeInDown: y = -300*force opacity = 0 case .FadeInUp: y = 300*force opacity = 0 case .ZoomIn: opacity = 0 scaleX = 2*force scaleY = 2*force case .ZoomOut: animateFrom = false opacity = 0 scaleX = 2*force scaleY = 2*force case .Fall: animateFrom = false rotate = 15 * CGFloat(M_PI/180) y = 600*force case .Shake: let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 30*force, -30*force, 30*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.additive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "shake") case .Pop: let animation = CAKeyframeAnimation() animation.keyPath = "transform.scale" animation.values = [0, 0.2*force, -0.2*force, 0.2*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.additive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "pop") case .FlipX: rotate = 0 scaleX = 1 scaleY = 1 var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(CATransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(CATransform3D: CATransform3DConcat(perspective, CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve) layer.addAnimation(animation, forKey: "3d") case .FlipY: var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(CATransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(CATransform3D: CATransform3DConcat(perspective,CATransform3DMakeRotation(CGFloat(M_PI), 1, 0, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve) layer.addAnimation(animation, forKey: "3d") case .Morph: let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.3*force, 0.7, 1.3*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.7, 1.3*force, 0.7, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphY, forKey: "morphY") case .Squeeze: let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.5*force, 0.5, 1.5*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.5, 1, 0.5, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphY, forKey: "morphY") case .Flash: let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.duration = CFTimeInterval(duration) animation.repeatCount = repeatCount * 2.0 animation.autoreverses = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "flash") case .Wobble: let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.additive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "wobble") let x = CAKeyframeAnimation() x.keyPath = "position.x" x.values = [0, 30*force, -30*force, 30*force, 0] x.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] x.timingFunction = getTimingFunction(curve) x.duration = CFTimeInterval(duration) x.additive = true x.repeatCount = repeatCount x.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(x, forKey: "x") case .Swing: let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.additive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "swing") } } } func getTimingFunction(curve: String) -> CAMediaTimingFunction { if let curve = AnimationCurve(rawValue: curve) { switch curve { case .EaseIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case .EaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case .EaseInOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) case .Linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case .Spring: return CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1) case .EaseInSine: return CAMediaTimingFunction(controlPoints: 0.47, 0, 0.745, 0.715) case .EaseOutSine: return CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1) case .EaseInOutSine: return CAMediaTimingFunction(controlPoints: 0.445, 0.05, 0.55, 0.95) case .EaseInQuad: return CAMediaTimingFunction(controlPoints: 0.55, 0.085, 0.68, 0.53) case .EaseOutQuad: return CAMediaTimingFunction(controlPoints: 0.25, 0.46, 0.45, 0.94) case .EaseInOutQuad: return CAMediaTimingFunction(controlPoints: 0.455, 0.03, 0.515, 0.955) case .EaseInCubic: return CAMediaTimingFunction(controlPoints: 0.55, 0.055, 0.675, 0.19) case .EaseOutCubic: return CAMediaTimingFunction(controlPoints: 0.215, 0.61, 0.355, 1) case .EaseInOutCubic: return CAMediaTimingFunction(controlPoints: 0.645, 0.045, 0.355, 1) case .EaseInQuart: return CAMediaTimingFunction(controlPoints: 0.895, 0.03, 0.685, 0.22) case .EaseOutQuart: return CAMediaTimingFunction(controlPoints: 0.165, 0.84, 0.44, 1) case .EaseInOutQuart: return CAMediaTimingFunction(controlPoints: 0.77, 0, 0.175, 1) case .EaseInQuint: return CAMediaTimingFunction(controlPoints: 0.755, 0.05, 0.855, 0.06) case .EaseOutQuint: return CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1) case .EaseInOutQuint: return CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1) case .EaseInExpo: return CAMediaTimingFunction(controlPoints: 0.95, 0.05, 0.795, 0.035) case .EaseOutExpo: return CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1) case .EaseInOutExpo: return CAMediaTimingFunction(controlPoints: 1, 0, 0, 1) case .EaseInCirc: return CAMediaTimingFunction(controlPoints: 0.6, 0.04, 0.98, 0.335) case .EaseOutCirc: return CAMediaTimingFunction(controlPoints: 0.075, 0.82, 0.165, 1) case .EaseInOutCirc: return CAMediaTimingFunction(controlPoints: 0.785, 0.135, 0.15, 0.86) case .EaseInBack: return CAMediaTimingFunction(controlPoints: 0.6, -0.28, 0.735, 0.045) case .EaseOutBack: return CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.275) case .EaseInOutBack: return CAMediaTimingFunction(controlPoints: 0.68, -0.55, 0.265, 1.55) } } return CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) } func getAnimationOptions(curve: String) -> UIViewAnimationOptions { if let curve = AnimationCurve(rawValue: curve) { switch curve { case .EaseIn: return UIViewAnimationOptions.CurveEaseIn case .EaseOut: return UIViewAnimationOptions.CurveEaseOut case .EaseInOut: return UIViewAnimationOptions.CurveEaseInOut default: break } } return UIViewAnimationOptions.CurveLinear } public func animate() { animateFrom = true animatePreset() setView {} } public func animateNext(completion: () -> ()) { animateFrom = true animatePreset() setView { completion() } } public func animateTo() { animateFrom = false animatePreset() setView {} } public func animateToNext(completion: () -> ()) { animateFrom = false animatePreset() setView { completion() } } public func customAwakeFromNib() { if autohide { alpha = 0 } } public func customLayoutSubviews() { if shouldAnimateInLayoutSubviews { shouldAnimateInLayoutSubviews = false if autostart { if UIApplication.sharedApplication().applicationState != .Active { shouldAnimateAfterActive = true return } alpha = 0 animate() } } } func setView(completion: () -> ()) { if animateFrom { let translate = CGAffineTransformMakeTranslation(self.x, self.y) let scale = CGAffineTransformMakeScale(self.scaleX, self.scaleY) let rotate = CGAffineTransformMakeRotation(self.rotate) let translateAndScale = CGAffineTransformConcat(translate, scale) self.transform = CGAffineTransformConcat(rotate, translateAndScale) self.alpha = self.opacity } UIView.animateWithDuration( NSTimeInterval(duration), delay: NSTimeInterval(delay), usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: getAnimationOptions(curve).union(UIViewAnimationOptions.AllowUserInteraction), animations: { [weak self] in if let _self = self { if _self.animateFrom { _self.transform = CGAffineTransformIdentity _self.alpha = 1 } else { let translate = CGAffineTransformMakeTranslation(_self.x, _self.y) let scale = CGAffineTransformMakeScale(_self.scaleX, _self.scaleY) let rotate = CGAffineTransformMakeRotation(_self.rotate) let translateAndScale = CGAffineTransformConcat(translate, scale) _self.transform = CGAffineTransformConcat(rotate, translateAndScale) _self.alpha = _self.opacity } } }, completion: { [weak self] finished in completion() self?.resetAll() }) } func reset() { x = 0 y = 0 opacity = 1 } func resetAll() { x = 0 y = 0 animation = "" opacity = 1 scaleX = 1 scaleY = 1 rotate = 0 damping = 0.7 velocity = 0.7 repeatCount = 1 delay = 0 duration = 0.7 } }
mit
eae4b35d9feed9652614fd295682717b
43.220755
165
0.587771
4.876404
false
false
false
false
ReactorKit/ReactorKit
Tests/ReactorKitTests/ReactorSchedulerTests.swift
1
4282
// // ReactorSchedulerTests.swift // ReactorKitTests // // Created by Suyeol Jeon on 2019/10/17. // import XCTest import ReactorKit import RxSwift final class ReactorSchedulerTests: XCTestCase { func testStateStreamIsCreatedOnce() { final class SimpleReactor: Reactor { typealias Action = Never typealias Mutation = Never typealias State = Int let initialState: State = 0 func transform(action: Observable<Action>) -> Observable<Action> { sleep(5) return action } } let reactor = SimpleReactor() var states: [Observable<SimpleReactor.State>] = [] let lock = NSLock() for _ in 0..<100 { DispatchQueue.global().async { let state = reactor.state lock.lock() states.append(state) lock.unlock() } } XCTWaiter().wait(for: [XCTestExpectation()], timeout: 10) XCTAssertGreaterThan(states.count, 0) for state in states { XCTAssertTrue(state === states.first) } } func testDefaultScheduler() { final class SimpleReactor: Reactor { typealias Action = Void typealias Mutation = Void struct State { var reductionThreads: [Thread] = [] } let initialState = State() func reduce(state: State, mutation: Mutation) -> State { var newState = state let currentThread = Thread.current newState.reductionThreads.append(currentThread) return newState } } let reactor = SimpleReactor() let disposeBag = DisposeBag() var observationThreads: [Thread] = [] var isExecuted = false DispatchQueue.global().async { let currentThread = Thread.current reactor.state .subscribe(onNext: { _ in let currentThread = Thread.current observationThreads.append(currentThread) }) .disposed(by: disposeBag) for _ in 0..<100 { reactor.action.onNext(Void()) } XCTWaiter().wait(for: [XCTestExpectation()], timeout: 1) let reductionThreads = reactor.currentState.reductionThreads XCTAssertEqual(reductionThreads.count, 100) for thread in reductionThreads { XCTAssertEqual(thread, currentThread) } XCTAssertEqual(observationThreads.count, 101) // +1 for initial state // states are observed on the main thread. for thread in observationThreads { XCTAssertTrue(thread.isMainThread) } isExecuted = true } XCTWaiter().wait(for: [XCTestExpectation()], timeout: 1.5) XCTAssertTrue(isExecuted) } func testCustomScheduler() { final class SimpleReactor: Reactor { typealias Action = Void typealias Mutation = Void struct State { var reductionThreads: [Thread] = [] } let initialState = State() let scheduler: ImmediateSchedulerType = SerialDispatchQueueScheduler(qos: .default) func reduce(state: State, mutation: Mutation) -> State { var newState = state let currentThread = Thread.current newState.reductionThreads.append(currentThread) return newState } } let reactor = SimpleReactor() let disposeBag = DisposeBag() var observationThreads: [Thread] = [] var isExecuted = false DispatchQueue.global().async { let currentThread = Thread.current reactor.state .subscribe(onNext: { _ in let currentThread = Thread.current observationThreads.append(currentThread) }) .disposed(by: disposeBag) for _ in 0..<100 { reactor.action.onNext(Void()) } XCTWaiter().wait(for: [XCTestExpectation()], timeout: 1) let reductionThreads = reactor.currentState.reductionThreads XCTAssertEqual(reductionThreads.count, 100) for thread in reductionThreads { XCTAssertEqual(thread, currentThread) } XCTAssertEqual(observationThreads.count, 101) // +1 for initial state // states are observed on the specified thread. for thread in observationThreads { XCTAssertNotEqual(thread, currentThread) } isExecuted = true } XCTWaiter().wait(for: [XCTestExpectation()], timeout: 1.5) XCTAssertTrue(isExecuted) } }
mit
976c6b5e6cbcf614b5ce67cd35274971
23.751445
89
0.63802
5.01993
false
true
false
false
alessiobrozzi/firefox-ios
Storage/SQL/BrowserDB.swift
1
18600
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import XCGLogger import Deferred import Shared import Deferred public let NotificationDatabaseWasRecreated = Notification.Name("NotificationDatabaseWasRecreated") private let log = Logger.syncLogger public typealias Args = [Any?] protocol Changeable { func run(_ sql: String, withArgs args: Args?) -> Success func run(_ commands: [String]) -> Success func run(_ commands: [(sql: String, args: Args?)]) -> Success } protocol Queryable { func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> } public enum DatabaseOpResult { case success case failure case closed } // Version 1 - Basic history table. // Version 2 - Added a visits table, refactored the history table to be a GenericTable. // Version 3 - Added a favicons table. // Version 4 - Added a readinglist table. // Version 5 - Added the clients and the tabs tables. // Version 6 - Visit timestamps are now microseconds. // Version 7 - Eliminate most tables. See BrowserTable instead. open class BrowserDB { fileprivate let db: SwiftData // XXX: Increasing this should blow away old history, since we currently don't support any upgrades. fileprivate let Version: Int = 7 fileprivate let files: FileAccessor fileprivate let filename: String fileprivate let secretKey: String? fileprivate let schemaTable: SchemaTable fileprivate var initialized = [String]() // SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can // appear in a query string. open static let MaxVariableNumber = 999 public init(filename: String, secretKey: String? = nil, files: FileAccessor) { log.debug("Initializing BrowserDB: \(filename).") self.files = files self.filename = filename self.schemaTable = SchemaTable() self.secretKey = secretKey let file = URL(fileURLWithPath: (try! files.getAndEnsureDirectory())).appendingPathComponent(filename).path self.db = SwiftData(filename: file, key: secretKey, prevKey: nil) if AppConstants.BuildChannel == .developer && secretKey != nil { log.debug("Creating db: \(file) with secret = \(secretKey)") } // Create or update will also delete and create the database if our key was incorrect. switch self.createOrUpdate(self.schemaTable) { case .failure: log.error("Failed to create/update the scheme table. Aborting.") fatalError() case .closed: log.info("Database not created as the SQLiteConnection is closed.") case .success: log.debug("db: \(file) has been created") } } // Creates a table and writes its table info into the table-table database. fileprivate func createTable(_ conn: SQLiteDBConnection, table: SectionCreator) -> TableResult { log.debug("Try create \(table.name) version \(table.version)") if !table.create(conn) { // If creating failed, we'll bail without storing the table info log.debug("Creation failed.") return .failed } var err: NSError? = nil guard let result = schemaTable.insert(conn, item: table, err: &err) else { return .failed } return result > -1 ? .created : .failed } // Updates a table and writes its table into the table-table database. // Exposed internally for testing. func updateTable(_ conn: SQLiteDBConnection, table: SectionUpdater) -> TableResult { log.debug("Trying update \(table.name) version \(table.version)") var from = 0 // Try to find the stored version of the table let cursor = schemaTable.query(conn, options: QueryOptions(filter: table.name)) if cursor.count > 0 { if let info = cursor[0] as? TableInfoWrapper { from = info.version } } // If the versions match, no need to update if from == table.version { return .exists } if !table.updateTable(conn, from: from) { // If the update failed, we'll bail without writing the change to the table-table. log.debug("Updating failed.") return .failed } var err: NSError? = nil // Yes, we UPDATE OR INSERT… because we might be transferring ownership of a database table // to a different Table. It'll trigger exists, and thus take the update path, but we won't // necessarily have an existing schema entry -- i.e., we'll be updating from 0. let insertResult = schemaTable.insert(conn, item: table, err: &err) ?? 0 let updateResult = schemaTable.update(conn, item: table, err: &err) if updateResult > 0 || insertResult > 0 { return .updated } return .failed } // Utility for table classes. They should call this when they're initialized to force // creation of the table in the database. func createOrUpdate(_ tables: Table...) -> DatabaseOpResult { guard !db.closed else { log.info("Database is closed - skipping schema create/updates") return .closed } var success = true let doCreate = { (table: Table, connection: SQLiteDBConnection) -> Void in switch self.createTable(connection, table: table) { case .created: success = true return case .exists: log.debug("Table already exists.") success = true return default: success = false } } if let _ = self.db.transaction({ connection -> Bool in let thread = Thread.current.description // If the table doesn't exist, we'll create it. for table in tables { log.debug("Create or update \(table.name) version \(table.version) on \(thread).") if !table.exists(connection) { log.debug("Doesn't exist. Creating table \(table.name).") doCreate(table, connection) } else { // Otherwise, we'll update it switch self.updateTable(connection, table: table) { case .updated: log.debug("Updated table \(table.name).") success = true break case .exists: log.debug("Table \(table.name) already exists.") success = true break default: log.error("Update failed for \(table.name). Dropping and recreating.") let _ = table.drop(connection) var err: NSError? = nil let _ = self.schemaTable.delete(connection, item: table, err: &err) doCreate(table, connection) } } if !success { log.warning("Failed to configure multiple tables. Aborting.") return false } } return success }) { // Err getting a transaction success = false } // If we failed, move the file and try again. This will probably break things that are already // attached and expecting a working DB, but at least we should be able to restart. var notify: Notification? = nil if !success { log.debug("Couldn't create or update \(tables.map { $0.name }).") log.debug("Attempting to move \(self.filename) to another location.") // Make sure that we don't still have open the files that we want to move! // Note that we use sqlite3_close_v2, which might actually _not_ close the // database file yet. For this reason we move the -shm and -wal files, too. db.forceClose() // Note that a backup file might already exist! We append a counter to avoid this. var bakCounter = 0 var bak: String repeat { bakCounter += 1 bak = "\(self.filename).bak.\(bakCounter)" } while self.files.exists(bak) do { try self.files.move(self.filename, toRelativePath: bak) let shm = self.filename + "-shm" let wal = self.filename + "-wal" log.debug("Moving \(shm) and \(wal)…") if self.files.exists(shm) { log.debug("\(shm) exists.") try self.files.move(shm, toRelativePath: bak + "-shm") } if self.files.exists(wal) { log.debug("\(wal) exists.") try self.files.move(wal, toRelativePath: bak + "-wal") } success = true // Notify the world that we moved the database. This allows us to // reset sync and start over in the case of corruption. notify = Notification(name: NotificationDatabaseWasRecreated, object: self.filename) } catch _ { success = false } assert(success) // Do this after the relevant tables have been created. defer { if let notify = notify { NotificationCenter.default.post(notify) } } self.reopenIfClosed() if let _ = db.transaction({ connection -> Bool in for table in tables { doCreate(table, connection) if !success { return false } } return success }) { success = false } } return success ? .success : .failure } typealias IntCallback = (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Int func withConnection<T>(flags: SwiftData.Flags, err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) -> T { var res: T! err = db.withConnection(flags) { connection in // An error may occur if the internet connection is dropped. var err: NSError? = nil res = callback(connection, &err) return err } return res } func withConnection<T>(_ err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) -> T { /* * Opening a WAL-using database with a hot journal cannot complete in read-only mode. * The supported mechanism for a read-only query against a WAL-using SQLite database is to use PRAGMA query_only, * but this isn't all that useful for us, because we have a mixed read/write workload. */ return withConnection(flags: SwiftData.Flags.readWriteCreate, err: &err, callback: callback) } func transaction(_ err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Bool) -> NSError? { return self.transaction(synchronous: true, err: &err, callback: callback) } func transaction(synchronous: Bool=true, err: inout NSError?, callback: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> Bool) -> NSError? { return db.transaction(synchronous: synchronous) { connection in var err: NSError? = nil return callback(connection, &err) } } } extension BrowserDB { func vacuum() { log.debug("Vacuuming a BrowserDB.") let _ = db.withConnection(SwiftData.Flags.readWriteCreate, synchronous: true) { connection in return connection.vacuum() } } func checkpoint() { log.debug("Checkpointing a BrowserDB.") let _ = db.transaction(synchronous: true) { connection in connection.checkpoint() return true } } } extension BrowserDB { public class func varlist(_ count: Int) -> String { return "(" + Array(repeating: "?", count: count).joined(separator: ", ") + ")" } enum InsertOperation: String { case Insert = "INSERT" case Replace = "REPLACE" case InsertOrIgnore = "INSERT OR IGNORE" case InsertOrReplace = "INSERT OR REPLACE" case InsertOrRollback = "INSERT OR ROLLBACK" case InsertOrAbort = "INSERT OR ABORT" case InsertOrFail = "INSERT OR FAIL" } /** * Insert multiple sets of values into the given table. * * Assumptions: * 1. The table exists and contains the provided columns. * 2. Every item in `values` is the same length. * 3. That length is the same as the length of `columns`. * 4. Every value in each element of `values` is non-nil. * * If there are too many items to insert, multiple individual queries will run * in sequence. * * A failure anywhere in the sequence will cause immediate return of failure, but * will not roll back — use a transaction if you need one. */ func bulkInsert(_ table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success { // Note that there's a limit to how many ?s can be in a single query! // So here we execute 999 / (columns * rows) insertions per query. // Note that we can't use variables for the column names, so those don't affect the count. if values.isEmpty { log.debug("No values to insert.") return succeed() } let variablesPerRow = columns.count // Sanity check. assert(values[0].count == variablesPerRow) let cols = columns.joined(separator: ", ") let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES " let varString = BrowserDB.varlist(variablesPerRow) let insertChunk: ([Args]) -> Success = { vals -> Success in let valuesString = Array(repeating: varString, count: vals.count).joined(separator: ", ") let args: Args = vals.flatMap { $0 } return self.run(queryStart + valuesString, withArgs: args) } let rowCount = values.count if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber { return insertChunk(values) } log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!") let rowsPerInsert = (999 / variablesPerRow) let chunks = chunk(values, by: rowsPerInsert) log.debug("Inserting in \(chunks.count) chunks.") // There's no real reason why we can't pass the ArraySlice here, except that I don't // want to keep fighting Swift. return walk(chunks, f: { insertChunk(Array($0)) }) } func runWithConnection<T>(_ block: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) -> Deferred<Maybe<T>> { return DeferredDBOperation(db: self.db, block: block).start() } func write(_ sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> { return self.runWithConnection() { (connection, err) -> Int in err = connection.executeChange(sql, withArgs: args) if err == nil { let modified = connection.numberOfRowsModified log.debug("Modified rows: \(modified).") return modified } return 0 } } public func forceClose() { db.forceClose() } public func reopenIfClosed() { db.reopenIfClosed() } } extension BrowserDB: Changeable { func run(_ sql: String, withArgs args: Args? = nil) -> Success { return run([(sql, args)]) } func run(_ commands: [String]) -> Success { return self.run(commands.map { (sql: $0, args: nil) }) } /** * Runs an array of SQL commands. Note: These will all run in order in a transaction and will block * the caller's thread until they've finished. If any of them fail the operation will abort (no more * commands will be run) and the transaction will roll back, returning a DatabaseError. */ func run(_ commands: [(sql: String, args: Args?)]) -> Success { if commands.isEmpty { return succeed() } var err: NSError? = nil let errorResult = self.transaction(&err) { (conn, err) -> Bool in for (sql, args) in commands { err = conn.executeChange(sql, withArgs: args) if let err = err { log.warning("SQL operation failed: \(err.localizedDescription)") return false } } return true } if let err = err ?? errorResult { return deferMaybe(DatabaseError(err: err)) } return succeed() } } extension BrowserDB: Queryable { func runQuery<T>(_ sql: String, args: Args?, factory: @escaping (SDRow) -> T) -> Deferred<Maybe<Cursor<T>>> { return runWithConnection { (connection, _) -> Cursor<T> in return connection.executeQuery(sql, factory: factory, withArgs: args) } } func queryReturnsResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> { return self.runQuery(sql, args: args, factory: { _ in true }) >>== { deferMaybe($0[0] ?? false) } } func queryReturnsNoResults(_ sql: String, args: Args? = nil) -> Deferred<Maybe<Bool>> { return self.runQuery(sql, args: nil, factory: { _ in false }) >>== { deferMaybe($0[0] ?? true) } } } extension SQLiteDBConnection { func tablesExist(_ names: [String]) -> Bool { let count = names.count let inClause = BrowserDB.varlist(names.count) let tablesSQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN \(inClause)" let res = self.executeQuery(tablesSQL, factory: StringFactory, withArgs: names) log.debug("\(res.count) tables exist. Expected \(count)") return res.count > 0 } }
mpl-2.0
5418074a34c0c6d56a9f72d5729327b3
37.496894
166
0.582123
4.764028
false
false
false
false