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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
evgenyneu/Auk | Demo/ViewController.swift | 1 | 5998 | import UIKit
import Auk
import moa
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
var imageDescriptions = [String]()
@IBOutlet weak var imageDescriptionLabel: UILabel!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var leftButton: UIButton!
@IBOutlet weak var rightButton: UIButton!
@IBOutlet weak var autoScrollButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
scrollView.auk.settings.placeholderImage = UIImage(named: "great_auk_placeholder.png")
scrollView.auk.settings.errorImage = UIImage(named: "error_image.png")
// Preload the next and previous images
scrollView.auk.settings.preloadRemoteImagesAround = 1
// Turn on the image logger. The download log will be visible in the Xcode console
Moa.logger = MoaConsoleLogger
showInitialImage()
showCurrentImageDescription()
}
// Show the first image when the app starts
private func showInitialImage() {
if let image = UIImage(named: DemoConstants.initialImage.fileName) {
scrollView.auk.show(image: image,
accessibilityLabel: DemoConstants.initialImage.description)
imageDescriptions.append(DemoConstants.initialImage.description)
}
}
// Show local images
@IBAction func onShowLocalTapped(_ sender: AnyObject) {
scrollView.auk.stopAutoScroll()
for localImage in DemoConstants.localImages {
if let image = UIImage(named: localImage.fileName) {
scrollView.auk.show(image: image, accessibilityLabel: localImage.description)
imageDescriptions.append(localImage.description)
}
}
showCurrentImageDescription()
}
// Show remote images
@IBAction func onShowRemoteTapped(_ sender: AnyObject) {
scrollView.auk.stopAutoScroll()
for remoteImage in DemoConstants.remoteImages {
let url = "\(DemoConstants.remoteImageBaseUrl)\(remoteImage.fileName)"
scrollView.auk.show(url: url, accessibilityLabel: remoteImage.description)
imageDescriptions.append(remoteImage.description)
}
showCurrentImageDescription()
}
// Scroll to the next image
@IBAction func onShowRightButtonTapped(_ sender: AnyObject) {
scrollView.auk.stopAutoScroll()
if RightToLeft.isRightToLeft(view) {
scrollView.auk.scrollToPreviousPage()
} else {
scrollView.auk.scrollToNextPage()
}
}
// Scroll to the previous image
@IBAction func onShowLeftButtonTapped(_ sender: AnyObject) {
scrollView.auk.stopAutoScroll()
if RightToLeft.isRightToLeft(view) {
scrollView.auk.scrollToNextPage()
} else {
scrollView.auk.scrollToPreviousPage()
}
}
// Remove all images
@IBAction func onDeleteButtonTapped(_ sender: AnyObject) {
scrollView.auk.stopAutoScroll()
scrollView.auk.removeAll()
imageDescriptions = []
showCurrentImageDescription()
}
@IBAction func onDeleteCurrentButtonTapped(_ sender: AnyObject) {
guard let indexToRemove = scrollView.auk.currentPageIndex else { return }
scrollView.auk.stopAutoScroll()
scrollView.auk.removeCurrentPage(animated: true)
if imageDescriptions.count >= scrollView.auk.numberOfPages {
imageDescriptions.remove(at: indexToRemove)
}
showCurrentImageDescription()
}
@IBAction func onAutoscrollTapped(_ sender: AnyObject) {
scrollView.auk.startAutoScroll(delaySeconds: 2)
}
@IBAction func onScrollViewTapped(_ sender: AnyObject) {
imageDescriptionLabel.text = "Tapped image #\(scrollView.auk.currentPageIndex ?? 42)"
}
// MARK: - Handle orientation change
/// Animate scroll view on orientation change
override func viewWillTransition(to size: CGSize,
with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard let pageIndex = scrollView.auk.currentPageIndex else { return }
let newScrollViewWidth = size.width // Assuming scroll view occupies 100% of the screen width
coordinator.animate(alongsideTransition: { [weak self] _ in
self?.scrollView.auk.scrollToPage(atIndex: pageIndex, pageWidth: newScrollViewWidth, animated: false)
}, completion: nil)
}
/// Animate scroll view on orientation change
/// Support iOS 7 and older
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation,
duration: TimeInterval) {
super.willRotate(to: toInterfaceOrientation, duration: duration)
var screenWidth = UIScreen.main.bounds.height
if toInterfaceOrientation.isPortrait {
screenWidth = UIScreen.main.bounds.width
}
guard let pageIndex = scrollView.auk.currentPageIndex else { return }
scrollView.auk.scrollToPage(atIndex: pageIndex, pageWidth: screenWidth, animated: false)
}
// MARK: - Image description
private func showCurrentImageDescription() {
if let description = currentImageDescription {
imageDescriptionLabel.text = description
} else {
imageDescriptionLabel.text = nil
}
}
private func changeCurrentImageDescription(_ description: String) {
guard let currentPageIndex = scrollView.auk.currentPageIndex else { return }
if currentPageIndex >= imageDescriptions.count {
return
}
imageDescriptions[currentPageIndex] = description
showCurrentImageDescription()
}
private var currentImageDescription: String? {
guard let currentPageIndex = scrollView.auk.currentPageIndex else { return nil }
if currentPageIndex >= imageDescriptions.count {
return nil
}
return imageDescriptions[currentPageIndex]
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
showCurrentImageDescription()
}
}
| mit | 13b9d65b5ac1b6de2f93449666a87325 | 30.73545 | 107 | 0.708236 | 4.957025 | false | false | false | false |
WeltN24/Carlos | Tests/CarlosTests/BatchTests.swift | 1 | 9356 | import Foundation
import Nimble
import Quick
import Carlos
import Combine
final class BatchAllCacheTests: QuickSpec {
override func spec() {
describe("allBatch") {
let requestsCount = 5
var internalCache: CacheLevelFake<Int, String>!
var cache: BatchAllCache<[Int], CacheLevelFake<Int, String>>!
var cancellable: AnyCancellable?
beforeEach {
internalCache = CacheLevelFake<Int, String>()
cache = internalCache.allBatch()
}
afterEach {
cancellable?.cancel()
cancellable = nil
}
context("when calling clear") {
beforeEach {
cache.clear()
}
it("should call clear on the internal cache") {
expect(internalCache.numberOfTimesCalledClear).toEventually(equal(1))
}
}
context("when calling onMemoryWarning") {
beforeEach {
cache.onMemoryWarning()
}
it("should call onMemoryWarning on the internal cache") {
expect(internalCache.numberOfTimesCalledOnMemoryWarning).toEventually(equal(1))
}
}
context("when calling set") {
var succeeded: Bool!
var failed: Error?
let keys = [1, 2, 3]
let values = ["", "", ""]
beforeEach {
cancellable = cache.set(values, forKey: keys)
.sink(receiveCompletion: { completion in
if case let .failure(error) = completion {
failed = error
}
}, receiveValue: { _ in succeeded = true })
}
it("should call set on the internal cache") {
expect(internalCache.numberOfTimesCalledSet).toEventually(equal(values.count))
}
context("when one of the set calls fails") {
let error = TestError.anotherError
beforeEach {
internalCache.setPublishers[0]?.send()
internalCache.setPublishers[1]?.send(completion: .failure(error))
}
it("should fail the whole future") {
expect(failed as? TestError).toEventually(equal(error))
}
}
context("when all the set calls succeed") {
beforeEach {
internalCache.setPublishers[1]?.send()
internalCache.setPublishers[2]?.send()
internalCache.setPublishers[3]?.send()
}
it("should succeed the whole future") {
expect(succeeded).toEventually(beTrue())
}
}
}
context("when calling get") {
var result: [String]?
var errors: [Error]!
beforeEach {
errors = []
result = nil
cancellable = cache.get(Array(0..<requestsCount))
.sink(receiveCompletion: { completion in
if case let .failure(error) = completion {
errors.append(error)
}
}, receiveValue: {
result = $0
})
}
it("should dispatch all of the requests to the underlying cache") {
expect(internalCache.numberOfTimesCalledGet).toEventually(equal(requestsCount))
}
context("when one of the requests fails") {
beforeEach {
internalCache.getPublishers[0]?.send(completion: .failure(TestError.simpleError))
}
it("should fail the resulting future") {
expect(errors).toEventuallyNot(beEmpty())
}
it("should pass the right error") {
expect(errors.first as? TestError).toEventually(equal(TestError.simpleError))
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
}
context("when one of the requests succeeds") {
beforeEach {
internalCache.getPublishers[0]?.send("Test")
}
it("should not call the failure closure") {
expect(errors).toEventually(beEmpty())
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
}
context("when all of the requests succeed") {
beforeEach {
internalCache.getPublishers.forEach { key, value in
value.send("\(key)")
}
}
it("should not call the failure closure") {
expect(errors).toEventually(beEmpty())
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should pass all the values") {
expect(result?.count).toEventually(equal(internalCache.getPublishers.count))
}
it("should pass the individual results in the right order") {
expect(result?.sorted()).toEventually(equal(internalCache.getPublishers.enumerated().map { iteration, _ in
"\(iteration)"
}))
}
}
}
}
}
}
final class BatchTests: QuickSpec {
override func spec() {
let requestsCount = 5
var cache: CacheLevelFake<Int, String>!
var cancellable: AnyCancellable?
beforeEach {
cache = CacheLevelFake<Int, String>()
}
afterEach {
cancellable?.cancel()
}
describe("batchGetSome") {
var result: [String]!
var errors: [Error]!
beforeEach {
errors = []
result = nil
cancellable = cache.batchGetSome(Array(0..<requestsCount))
.sink(receiveCompletion: { completion in
if case let .failure(error) = completion {
errors.append(error)
}
}, receiveValue: { result = $0 })
}
it("should dispatch all of the requests to the underlying cache") {
expect(cache.numberOfTimesCalledGet).toEventually(equal(requestsCount))
}
context("when one of the requests fails") {
let failedIndex = 2
beforeEach {
cache.getPublishers[failedIndex]?.send(completion: .failure(TestError.simpleError))
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should not call the failure closure") {
expect(errors).toEventually(beEmpty())
}
context("when all the other requests succeed") {
beforeEach {
cache.getPublishers.forEach { key, value in
value.send("\(key)")
}
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should pass the right number of results") {
expect(result.count).toEventually(equal(cache.getPublishers.count - 1))
}
it("should only pass the succeeded requests") {
var expectedResult = cache.getPublishers.enumerated().map { iteration, _ in
"\(iteration)"
}
_ = expectedResult.remove(at: failedIndex)
expect(result.sorted()).toEventually(equal(expectedResult))
}
it("should not call the failure closure") {
expect(errors).toEventually(beEmpty())
}
}
}
context("when all the other requests complete") {
beforeEach {
cache.getPublishers.forEach { key, value in
value.send("\(key)")
}
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should pass the right number of results") {
expect(result.count).toEventually(equal(cache.getPublishers.count))
}
it("should only pass the succeeded requests") {
expect(result.sorted()).toEventually(equal(cache.getPublishers.enumerated().map { iteration, _ in
"\(iteration)"
}))
}
it("should not call the failure closure") {
expect(errors).toEventually(beEmpty())
}
}
context("when one of the requests fails") {
let failedIndex = 3
beforeEach {
cache.getPublishers[failedIndex]?.send(completion: .failure(TestError.simpleError))
}
it("should not call the success closure") {
expect(result).toEventually(beNil())
}
it("should not call the error closure") {
expect(errors).toEventually(beEmpty())
}
context("when all the other requests complete") {
beforeEach {
cache.getPublishers.forEach { key, value in
value.send("\(key)")
}
}
it("should call the success closure") {
expect(result).toEventuallyNot(beNil())
}
it("should pass the right number of results") {
expect(result.count).toEventually(equal(cache.getPublishers.count - 1))
}
it("should only pass the succeeded requests") {
var expectedResult = cache.getPublishers.enumerated().map { iteration, _ in
"\(iteration)"
}
_ = expectedResult.remove(at: failedIndex)
expect(result.sorted()).toEventually(equal(expectedResult))
}
it("should not call the failure closure") {
expect(errors).toEventually(beEmpty())
}
}
}
}
}
}
| mit | 2462d9ff33381a1c01ca931b5d8191ae | 27.351515 | 118 | 0.556114 | 5.000534 | false | false | false | false |
proversity-org/edx-app-ios | Source/SpinnerButton.swift | 1 | 2084 | //
// SpinnerButton.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 16/09/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
class SpinnerButton: UIButton {
private let SpinnerViewTrailingMargin : CGFloat = 10
private let VerticalContentMargin : CGFloat = 5
private let SpinnerHorizontalMargin : CGFloat = 10
private var SpinnerViewWidthWithMargins : CGFloat {
return spinnerView.intrinsicContentSize.width + 2 * SpinnerHorizontalMargin
}
private let spinnerView = SpinnerView(size: .Large, color: .White)
override func layoutSubviews() {
super.layoutSubviews()
layoutSpinnerView()
}
private func layoutSpinnerView() {
self.addSubview(spinnerView)
self.titleLabel?.adjustsFontSizeToFitWidth = true
spinnerView.snp.remakeConstraints { make in
make.centerY.equalTo(self)
make.width.equalTo(spinnerView.intrinsicContentSize.width)
if let label = titleLabel {
make.leading.equalTo(label.snp.trailing).offset(SpinnerHorizontalMargin).priority(.low)
}
make.trailing.equalTo(self.snp.trailing).offset(-SpinnerHorizontalMargin).priority(.high)
}
self.setNeedsUpdateConstraints()
if !showProgress { spinnerView.isHidden = true }
}
override var intrinsicContentSize: CGSize {
let width = self.titleLabel?.intrinsicContentSize.width ?? 0 + SpinnerViewTrailingMargin + self.spinnerView.intrinsicContentSize.width
let height = max(super.intrinsicContentSize.height, spinnerView.intrinsicContentSize.height + 2 * VerticalContentMargin)
return CGSize(width: width, height: height)
}
var showProgress : Bool = false {
didSet {
if showProgress {
spinnerView.isHidden = false
spinnerView.startAnimating()
}
else {
spinnerView.isHidden = true
spinnerView.stopAnimating()
}
}
}
}
| apache-2.0 | e5907c120d602b8e89a0663c2fb9a984 | 32.612903 | 142 | 0.647793 | 5.236181 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressTest/StatsTestCase.swift | 1 | 910 | import XCTest
import CoreData
@testable import WordPress
// A thin wrapper round XCTestCase for Stats test to avoid repeating boilerplate.
class StatsTestCase: CoreDataTestCase {
@discardableResult func createStatsRecord(in context: NSManagedObjectContext,
type: StatsRecordType,
period: StatsRecordPeriodType = .notApplicable,
date: Date) -> StatsRecord {
let newRecord = StatsRecord(context: context)
newRecord.type = type.rawValue
newRecord.date = Calendar.autoupdatingCurrent.startOfDay(for: date) as NSDate
newRecord.period = period.rawValue
newRecord.blog = defaultBlog
return newRecord
}
lazy var defaultBlog: Blog = {
return ModelTestHelper.insertDotComBlog(context: mainContext)
}()
}
| gpl-2.0 | b5a13c4acf79ff0b738d911d8a72ea7b | 34 | 93 | 0.624176 | 5.870968 | false | true | false | false |
sstanic/VirtualTourist | VirtualTourist/VirtualTourist/WSClientConstants.swift | 1 | 2783 | //
// WSClientConstants.swift
// VirtualTourist
//
// Created by Sascha Stanic on 09.06.16.
// Copyright © 2016 Sascha Stanic. All rights reserved.
//
import Foundation
extension WSClient {
//# MARK: Authentication
struct AuthConstants {
// URL
static let ApiScheme = "https"
static let ApiHost = "api.flickr.com"
static let ApiPath = "/services/rest/"
}
// MARK: Flickr Parameter Keys
struct FlickrParameterKeys {
static let Method = "method"
static let APIKey = "api_key"
static let GalleryID = "gallery_id"
static let Extras = "extras"
static let Format = "format"
static let NoJSONCallback = "nojsoncallback"
static let SafeSearch = "safe_search"
static let Text = "text"
static let BoundingBox = "bbox"
static let Latitude = "lat"
static let Longitude = "lon"
static let Page = "page"
static let PerPage = "per_page"
}
// MARK: Flickr Parameter Values
struct FlickrParameterValues {
static let SearchMethod = "flickr.photos.search"
static let APIKey = "4120b4b57e0c20e206965d809d8d59e4"
static let ResponseFormat = "json"
static let DisableJSONCallback = "1" /* 1 means "yes" */
static let GalleryPhotosMethod = "flickr.galleries.getPhotos"
static let GalleryID = "5704-72157622566655097"
static let MediumURL = "url_m"
static let UseSafeSearch = "1"
static let PerPage = 24
}
// MARK: Flickr Response Keys
struct FlickrResponseKeys {
static let Status = "stat"
static let Photos = "photos"
static let Photo = "photo"
static let Title = "title"
static let MediumURL = "url_m"
static let Pages = "pages"
static let PerPage = "perpage"
static let Total = "total"
}
// MARK: Flickr Response Values
struct FlickrResponseValues {
static let OKStatus = "ok"
}
//# MARK: Data Access
struct DataConstants {
static let Timeout = 10
}
//#MARK: Error Messages
struct ErrorMessage {
static let NetworkTimeout = "Network timeout. Please check your network connection."
static let GeneralHttpRequestError = "Http request error. Error message: "
static let StatusCodeFailure = "Your request returned a status code other than 2xx."
static let NoDataFoundInRequest = "No data was returned by the request."
static let JsonParseError = "Could not parse the data as JSON. Data: "
static let HttpDataTaskFailed = "Http data task failed. Cannot convert result data."
}
} | mit | 3f383464860f4794e4eb0c196f4c8c1d | 29.922222 | 92 | 0.611431 | 4.479871 | false | false | false | false |
melsomino/unified-ios | Unified/Library/Ui/Layout/LayoutView.swift | 1 | 1380 | //
// Created by Власов М.Ю. on 01.06.16.
// Copyright (c) 2016 Tensor. All rights reserved.
//
import Foundation
import UIKit
public class LayoutView<View: UIView>: LayoutViewItem {
let size: CGSize
let _fixedSize: Bool
var view: View!
var createView: ((CGRect) -> View)?
public override var boundView: UIView? {
return view
}
public init(size: CGSize, fixedSize: Bool, _ createView: ((CGRect) -> View)? = nil) {
self.size = size
self._fixedSize = fixedSize
self.createView = createView
}
public convenience init(size: CGSize, _ createView: ((CGRect) -> View)? = nil) {
self.init(size: size, fixedSize: true, createView)
}
// MARK: - LayoutItem
public override func createViews(inSuperview superview: UIView) {
if createView != nil {
view = createView!(CGRectMake(0, 0, size.width, size.height))
superview.addSubview(view!)
}
}
public override var fixedSize: Bool {
return _fixedSize
}
public override func measureMaxSize(bounds: CGSize) -> CGSize {
return visible ? size : CGSizeZero
}
public override func measureSize(bounds: CGSize) -> CGSize {
return visible ? size : CGSizeZero
}
public override func layout(bounds: CGRect) -> CGRect {
if fixedSize {
self.frame = CGRectMake(bounds.origin.x, bounds.origin.y, size.width, size.height)
}
else {
self.frame = bounds
}
return frame
}
}
| mit | fbe1f5e1c6b89e737faf3fc64634af36 | 18.884058 | 86 | 0.68586 | 3.404467 | false | false | false | false |
omondigeno/ActionablePushMessages | PushedActionableMessages/ResponseHandler.swift | 1 | 3068 | //
// ResponseHandler.swift
// PushedActionableMessages
//
// Created by Samuel Geno on 10/04/2016.
// Copyright © 2016 Geno. All rights reserved.
//
import Foundation
import Alamofire
import UIKit
class ResponseHandler: ResponseHandlerDelegate {
var background: Bool
weak var viewController: UIViewController?
init(background: Bool, viewController: UIViewController?){
self.background = background
self.viewController = viewController
}
func handleResponse(response: Response<AnyObject, NSError>){
if(response.response?.statusCode == HTTPStatusCode.OK.rawValue){
if let jsonObj = response.result.value {
let json = JSON(jsonObj)
print(json)
if let responseStatus = json["status_code"].asInt where responseStatus == 1 {
handleResponse(json)
}else{
handleAPIerror(json)
}
}
}else{
handleHTTPerror(response.response)
}
}
func handleResponse(response: JSON) {
showMessageHideProgress(getResponseMessage(response))
}
func handleAPIerror(response: JSON) {
showMessageHideProgress(getResponseMessage(response))
}
func getResponseMessage(response: JSON) -> String? {
var msg: String?
if let responseMesage = response["status_message"].asString {
return responseMesage;
}else{
return Utils.getString("network_error_internal_error")
}
}
func showMessageHideProgress(message: String?){
if !background && viewController != nil{
Common.hideProgress(viewController!)
if message != nil{
Common.showMessage(message!, viewController: viewController!)
}
}
print(message)
}
func handleHTTPerror(response: NSHTTPURLResponse?){
var msg: String = ""
switch response?.statusCode {
case .Some(HTTPStatusCode.BadRequest.rawValue):
msg = Utils.getString("network_error_bad_request")
case .Some(HTTPStatusCode.Unauthorized.rawValue), .Some(HTTPStatusCode.Forbidden.rawValue):
msg = Utils.getString("network_error_unauthorized")
case .Some(HTTPStatusCode.NotFound.rawValue), .Some(HTTPStatusCode.Gone.rawValue):
msg = Utils.getString("network_error_not_found")
case .Some(HTTPStatusCode.RequestTimeout.rawValue), .Some(HTTPStatusCode.GatewayTimeout.rawValue):
msg = Utils.getString("network_error_time_out")
case .Some(HTTPStatusCode.InternalServerError.rawValue):
msg = Utils.getString("network_error_internal_error")
case .Some(HTTPStatusCode.ServiceUnavailable.rawValue):
msg = Utils.getString("network_error_unavailable")
default:
msg = Utils.getString("network_error_msg")
}
showMessageHideProgress(msg)
}
} | apache-2.0 | 2f793c63f5a8ab53f0bd695e028ffe4f | 33.47191 | 106 | 0.617216 | 5.069421 | false | false | false | false |
Shopify/unity-buy-sdk | PluginDependencies/iOSPlugin/UnityBuySDKPluginTests/Models.swift | 1 | 9629 | //
// Models.swift
// UnityBuySDK
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import PassKit
@testable import UnityBuySDKPlugin
struct Models {
static let emailAddress = "[email protected]"
static let firstName = "first name"
static let lastName = "last name"
static let phone = "123-456-7890"
static let address1 = "80 Spadina Ave"
static let address2 = "420 Wellington"
static let edgeAddress1 = "420\\nWellington"
static let edgeAddress2 = "80\\nSpadina\\nAve"
static let city = "Toronto"
static let country = "Canada"
static let province = "ON"
static let zip = "M5V 2J4"
static let merchantId = "com.merchant.id"
static let countryCode = "US"
static let currencyCode = "USD"
static let supportedPaymentNetworks: [PKPaymentNetwork] = [.amex, .visa, .masterCard]
// ----------------------------------
// MARK: - PersonNameComponents -
//
static func createPersonName() -> PersonNameComponents {
var personName = PersonNameComponents()
personName.givenName = firstName
personName.familyName = lastName
return personName
}
// ----------------------------------
// MARK: - CNPostalAddress -
//
static func createPartialPostalAddress() -> CNPostalAddress {
let postalAddress = CNMutablePostalAddress()
postalAddress.city = city
postalAddress.country = country
postalAddress.postalCode = zip
postalAddress.state = province
return postalAddress
}
static func createPostalAddress() -> CNPostalAddress {
let postalAddress = CNMutablePostalAddress()
postalAddress.street = address1
postalAddress.postalCode = zip
postalAddress.country = country
postalAddress.state = province
postalAddress.city = city
return postalAddress
}
static func createMultiplePostalAddresses() -> CNPostalAddress {
let postalAddress = createPostalAddress() as! CNMutablePostalAddress
postalAddress.street = address1 + "\n" + address2
return postalAddress
}
static func createMultiplePostalAddressesEdgeCase() -> CNPostalAddress {
let postalAddress = createPostalAddress() as! CNMutablePostalAddress
postalAddress.street = edgeAddress1 + "\n" + edgeAddress2
return postalAddress
}
// ----------------------------------
// MARK: - PassKit -
//
static func createContact(with postalAddress: CNPostalAddress) -> PKContact {
let contact = PKContact()
contact.name = createPersonName()
contact.emailAddress = emailAddress
contact.phoneNumber = CNPhoneNumber(stringValue: phone)
contact.postalAddress = postalAddress
return contact
}
static func createPaymentMethod() -> PKPaymentMethod {
return MockPaymentMethod(displayName: "AMEX", network: .amex, type: .credit)
}
static func createShippingMethod() -> PKShippingMethod {
let shippingMethod = PKShippingMethod(label: "Free Shipping", amount: 0)
shippingMethod.identifier = "unique_id"
shippingMethod.detail = "10-15 Days"
return shippingMethod
}
static func createPaymentToken() -> PKPaymentToken {
return MockPaymentToken(paymentMethod: Models.createPaymentMethod() as! MockPaymentMethod)
}
static func createSimulatorPaymentToken() -> PKPaymentToken {
return MockPaymentToken(paymentMethod: Models.createPaymentMethod() as! MockPaymentMethod, forSimulator: true)
}
static func createPayment() -> PKPayment {
return MockPayment(
token: createPaymentToken() as! MockPaymentToken,
billingContact: createContact(with: createPostalAddress()),
shippingContact: createContact(with: createPostalAddress()),
shippingMethod: createShippingMethod())
}
static func createSummaryItem() -> PKPaymentSummaryItem {
return PKPaymentSummaryItem(label: "SubTotal", amount: NSDecimalNumber(value: 1.00))
}
static func createSummaryItems() -> [PKPaymentSummaryItem] {
var summaryItems = [PKPaymentSummaryItem]()
summaryItems.append(PKPaymentSummaryItem(label: "SubTotal", amount: NSDecimalNumber(value: 1.00)))
summaryItems.append(PKPaymentSummaryItem(label: "Tax", amount: NSDecimalNumber(value: 1.00)))
summaryItems.append(PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(value: 1.00)))
summaryItems.append(PKPaymentSummaryItem(label: "Total", amount: NSDecimalNumber(value: 3.00)))
return summaryItems
}
static func createShippingMethods() -> [PKShippingMethod] {
var shippingMethods = [PKShippingMethod]()
shippingMethods.append(
PKShippingMethod(
label: "Free",
amount: NSDecimalNumber(value: 0.0),
identifier: "Free",
detail: "10-15 Days"))
shippingMethods.append(
PKShippingMethod(
label: "Standard",
amount: NSDecimalNumber(value: 5.0),
identifier: "Standard",
detail: "10-15 Days"))
shippingMethods.append(
PKShippingMethod(
label: "Express",
amount: NSDecimalNumber(value: 10.0),
identifier: "Express",
detail: "10-15 Days"))
return shippingMethods
}
static func createPaymentSession(requiringShippingAddressFields: Bool, usingNonDefault controllerType: PKPaymentAuthorizationController.Type?) -> PaymentSession {
if let controllerType = controllerType {
return PaymentSession(
merchantId: merchantId,
countryCode: countryCode,
currencyCode: currencyCode,
requiringShippingAddressFields: requiringShippingAddressFields,
supportedNetworks: supportedPaymentNetworks,
summaryItems: createSummaryItems(),
shippingMethods: createShippingMethods(),
controllerType: controllerType)!
} else {
return PaymentSession(
merchantId: merchantId,
countryCode: countryCode,
currencyCode: currencyCode,
requiringShippingAddressFields: requiringShippingAddressFields,
supportedNetworks: supportedPaymentNetworks,
summaryItems: createSummaryItems(),
shippingMethods: createShippingMethods())!
}
}
static func createSerializedPaymentNetworksString() -> String {
let jsonData = try! JSONSerialization.data(withJSONObject: supportedPaymentNetworks)
let stringRepresentation = String(data: jsonData, encoding: .utf8)!
return stringRepresentation
}
}
// ----------------------------------
// MARK: - JSON models -
//
extension Models {
enum SummaryItemField: String {
case amount = "Amount"
case label = "Label"
case type = "Type"
}
enum ShippingMethodField: String {
case detail = "Detail"
case identifier = "Identifier"
}
static func createSummaryItemJson(amount: String, label: String, type: PKPaymentSummaryItemType? = nil) -> JSON {
var json = JSON.init()
json[SummaryItemField.amount.rawValue] = amount
json[SummaryItemField.label.rawValue] = label
if let type = type {
json[SummaryItemField.type.rawValue] = type.rawStringValue
}
return json
}
static func createShippingMethodJson(amount: String, label: String, identifier: String, detail: String, type: PKPaymentSummaryItemType? = nil) -> JSON {
var json = createSummaryItemJson(amount: amount, label: label, type: type)
json[ShippingMethodField.detail.rawValue] = detail
json[ShippingMethodField.identifier.rawValue] = identifier
if let type = type {
json[SummaryItemField.type.rawValue] = type.rawStringValue
}
return json
}
}
| mit | a95a7a9847351f5882123961af5939dc | 37.983806 | 166 | 0.632153 | 5.273275 | false | false | false | false |
hongdong/Gank | Pods/Action/Sources/Action/Action.swift | 1 | 4372 | import Foundation
import RxSwift
import RxCocoa
/// Typealias for compatibility with UIButton's rx.action property.
public typealias CocoaAction = Action<Void, Void>
/// Possible errors from invoking execute()
public enum ActionError: Error {
case notEnabled
case underlyingError(Error)
}
/**
Represents a value that accepts a workFactory which takes some Observable<Input> as its input
and produces an Observable<Element> as its output.
When this excuted via execute() or inputs subject, it passes its parameter to this closure and subscribes to the work.
*/
public final class Action<Input, Element> {
public typealias WorkFactory = (Input) -> Observable<Element>
public let _enabledIf: Observable<Bool>
public let workFactory: WorkFactory
/// Inputs that triggers execution of action.
/// This subject also includes inputs as aguments of execute().
/// All inputs are always appear in this subject even if the action is not enabled.
/// Thus, inputs count equals elements count + errors count.
public let inputs = PublishSubject<Input>()
/// Errors aggrevated from invocations of execute().
/// Delivered on whatever scheduler they were sent from.
public let errors: Observable<ActionError>
/// Whether or not we're currently executing.
/// Delivered on whatever scheduler they were sent from.
public let elements: Observable<Element>
/// Whether or not we're currently executing.
public let executing: Observable<Bool>
/// Observables returned by the workFactory.
/// Useful for sending results back from work being completed
/// e.g. response from a network call.
public let executionObservables: Observable<Observable<Element>>
/// Whether or not we're enabled. Note that this is a *computed* sequence
/// property based on enabledIf initializer and if we're currently executing.
/// Always observed on MainScheduler.
public let enabled: Observable<Bool>
private let disposeBag = DisposeBag()
public init(
enabledIf: Observable<Bool> = Observable.just(true),
workFactory: @escaping WorkFactory) {
self._enabledIf = enabledIf
self.workFactory = workFactory
let enabledSubject = BehaviorSubject<Bool>(value: false)
enabled = enabledSubject.asObservable()
let errorsSubject = PublishSubject<ActionError>()
errors = errorsSubject.asObservable()
executionObservables = inputs
.withLatestFrom(enabled) { $0 }
.flatMap { input, enabled -> Observable<Observable<Element>> in
if enabled {
return Observable.of(workFactory(input)
.do(onError: { errorsSubject.onNext(.underlyingError($0)) })
.shareReplay(1))
} else {
errorsSubject.onNext(.notEnabled)
return Observable.empty()
}
}
.share()
elements = executionObservables
.flatMap { $0.catchError { _ in Observable.empty() } }
executing = executionObservables.flatMap {
execution -> Observable<Bool> in
let execution = execution
.flatMap { _ in Observable<Bool>.empty() }
.catchError { _ in Observable.empty()}
return Observable.concat([Observable.just(true),
execution,
Observable.just(false)])
}
.startWith(false)
.shareReplay(1)
Observable
.combineLatest(executing, enabledIf) { !$0 && $1 }
.bindTo(enabledSubject)
.addDisposableTo(disposeBag)
}
@discardableResult
public func execute(_ value: Input) -> Observable<Element> {
defer {
inputs.onNext(value)
}
let subject = ReplaySubject<Element>.createUnbounded()
let work = executionObservables
.map { $0.catchError { throw ActionError.underlyingError($0) } }
let error = errors
.map { Observable<Element>.error($0) }
work.amb(error)
.take(1)
.flatMap { $0 }
.subscribe(subject)
.addDisposableTo(disposeBag)
return subject.asObservable()
}
}
| mit | f0abbc29772a670b108ea95a1a44b77f | 33.698413 | 118 | 0.625572 | 5.119438 | false | false | false | false |
wesleysadler/UniversalStoryboard | UniversalStoryboard/BirdsViewController.swift | 1 | 2292 | //
// BirdsViewController.swift
// UniversalStoryboard
//
// Created by Wesley Sadler on 1/6/15.
// Copyright (c) 2015 Digital Sadler. All rights reserved.
//
import UIKit
class BirdsViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects: [String]!
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row]
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("BirdsCell", forIndexPath: indexPath) as! UITableViewCell
let object = objects[indexPath.row] as String
cell.textLabel!.text = object
return cell
}
}
| mit | 64f2b2489dd6b04030d40ce5eb0ab2cd | 31.742857 | 136 | 0.658377 | 5.64532 | false | false | false | false |
tad-iizuka/swift-sdk | Source/TextToSpeechV1/Models/SynthesisVoice.swift | 3 | 2182 | /**
* Copyright IBM Corporation 2016
*
* 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
/** A voice to be used for synthesis. */
public enum SynthesisVoice: String {
/// German with a female voice (`de-DE_BirgitVoice`).
case de_Birgit = "de-DE_BirgitVoice"
/// German with a male voice (`de-DE_DieterVoice`).
case de_Dieter = "de-DE_DieterVoice"
/// English (British dialect) with a female voice (`en-GB_KateVoice`).
case gb_Kate = "en-GB_KateVoice"
/// English (US dialect) with a female voice (`en-US_AllisonVoice`).
case us_Allison = "en-US_AllisonVoice"
/// English (US dialect) with a female voice (`en-US_LisaVoice`).
case us_Lisa = "en-US_LisaVoice"
/// English (US dialect) with a male voice (`en-US_MichaelVoice`).
case us_Michael = "en-US_MichaelVoice"
/// Spanish (Castillian dialect) with a male voice (`es-ES_EnriqueVoice`).
case es_Enrique = "es-ES_EnriqueVoice"
/// Spanish (Castillian dialect) with a female voice (`es-ES_LauraVoice`).
case es_Laura = "es-ES_LauraVoice"
/// Spanish (North-American dialect) with a female voice (`es-US_SofiaVoice`).
case us_Sofia = "es-US_SofiaVoice"
/// French with a female voice (`fr-FR_ReneeVoice`).
case fr_Renee = "fr-FR_ReneeVoice"
/// Italian with a female voice (`it-IT_FrancescaVoice`).
case it_Francesca = "it-IT_FrancescaVoice"
/// Japanese with a female voice (`ja-JP_EmiVoice`).
case jp_Emi = "ja-JP_EmiVoice"
/// Brazilian Portuguese with a female voice (`pt-BR_IsabelaVoice`).
case br_Isabela = "pt-BR_IsabelaVoice"
}
| apache-2.0 | c39d635a69df654ed221a58bcf85aa37 | 35.366667 | 82 | 0.664528 | 3.468998 | false | false | false | false |
Chris-Perkins/Lifting-Buddy | Lifting Buddy/WorkoutSessionSummaryTableViewCell.swift | 1 | 19245 | //
// WorkoutSummaryTableViewCell.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 11/22/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
import UIKit
import Realm
import RealmSwift
class WorkoutSessionSummaryTableViewCell: UITableViewCell {
// MARK: View properties
public static var dateRecorded = Date.init(timeIntervalSince1970: 0)
// The height for the progressionMethod views
private static let heightPerProgressionMethod: CGFloat = 30
private let cellTitleLabel: UILabel
private let cellGraphButton: PrettyButton
private var progressionMethodSummaryViews: [ProgressionMethodSummaryView]
private var exercise: Exercise?
// MARK: View inits
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
cellTitleLabel = UILabel()
cellGraphButton = PrettyButton()
progressionMethodSummaryViews = [ProgressionMethodSummaryView]()
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
addSubview(cellTitleLabel)
addSubview(cellGraphButton)
cellGraphButton.addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside)
createAndActivateCellTitleLabelConstraints()
createAndActivateCellGraphButtonConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View overrides
override func layoutSubviews() {
super.layoutSubviews()
// Self
backgroundColor = .primaryBlackWhiteColor
// Cell Title Label
cellTitleLabel.setDefaultProperties()
cellTitleLabel.textAlignment = .left
// Graph Button
cellGraphButton.setDefaultProperties()
cellGraphButton.setTitle(NSLocalizedString("Button.View", comment: ""), for: .normal)
// PGM Views
for (index, view) in progressionMethodSummaryViews.enumerated() {
// We check using bit-level comparison here. This provides a nice alternating
// background color, making the view much more readable
view.backgroundColor = UIColor.oppositeBlackWhiteColor.withAlphaComponent(index&1 == 0 ? 0.1 : 0.2)
}
}
// MARK: View functions
public static func heightForExercise(exercise: Exercise) -> CGFloat {
return UITableViewCell.defaultHeight +
CGFloat(exercise.getProgressionMethods().count) *
WorkoutSessionSummaryTableViewCell.heightPerProgressionMethod
}
// Called by tableview to set the exercise
public func setExercise(exercise: Exercise, withDateRecorded: Date) {
self.exercise = exercise
deleteProgressionMethodSummaryViews()
cellTitleLabel.text = exercise.getName()
createProgressionMethodSummaryViews(data: getDataForSummaryViews(forExercise: exercise,
withDateRecorded: withDateRecorded))
}
// Gets the progression method, new value, and old value for data based on an exercise.
private func getDataForSummaryViews(forExercise: Exercise,
withDateRecorded: Date) -> [(ProgressionMethod, Float?, Float?)] {
// The data we'll be returning
var returnData = [(ProgressionMethod, Float?, Float?)]()
// A shorter name for easier calls
let exerciseHistory = forExercise.getExerciseHistory()
/*
Get the history after the session began.
We use this data to get the maximum from the workout for display
*/
let historyAfterSessionBegin = List<ExerciseHistoryEntry>()
for exerciseEntry in exerciseHistory.reversed() {
/*
If we found something that was not done after the workout began,
it must not be a part of this workout!
We break whenever an entry was not in the history
Bugs can occur here if the user decides that they want to
move the calendar time up then back to the current date.
I'm not worried about that possibility for now.
*/
if exerciseEntry.date!.seconds(from: withDateRecorded) >= 0 {
historyAfterSessionBegin.append(exerciseEntry)
} else {
break
}
}
// Get the maximum for the progression methods after the session began.
let maxForHistoryAfterSessionBegin = ProgressionMethod.getMaxValueForProgressionMethods(fromHistory: historyAfterSessionBegin)
// Just used to map everything out while we iterate.
// Data will be sent to the cells
var pgmToNewOldValues = Dictionary<ProgressionMethod, (Float?, Float?)>()
// Initialize every progression method to have a new value, old value deal.
for pgm in forExercise.getProgressionMethods() {
pgmToNewOldValues[pgm] = (maxForHistoryAfterSessionBegin[pgm] /* new value */,
pgm.getMaxValue()/* old value */)
}
for pgm in forExercise.getProgressionMethods() {
returnData.append((pgm, pgmToNewOldValues[pgm]?.0, pgmToNewOldValues[pgm]?.1))
}
return returnData
}
// Creates the progression method data views
private func createProgressionMethodSummaryViews(data: [(ProgressionMethod, // Progression method
Float?, // New data
Float?) // Old data
]) {
var prevView: UIView = cellTitleLabel
for dataPiece in data {
let view = ProgressionMethodSummaryView(progressionMethod: dataPiece.0,
newValue: dataPiece.1,
oldValue: dataPiece.2,
frame: .zero)
addSubview(view)
progressionMethodSummaryViews.append(view)
// Then, give it constraints.
// Cling to left, right of view. place below prevView ; height of default
view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewBelowViewConstraint(view: view,
belowView: prevView).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: view,
withCopyView: self,
attribute: .left).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: view,
withCopyView: self,
attribute: .right).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: view,
height: WorkoutSessionSummaryTableViewCell.heightPerProgressionMethod
).isActive = true
prevView = view
}
}
// Deletes progression methods views
private func deleteProgressionMethodSummaryViews() {
for view in progressionMethodSummaryViews {
view.removeFromSuperview()
}
progressionMethodSummaryViews.removeAll()
}
// MARK: Event functions
@objc func buttonPress(sender: PrettyButton) {
guard let exercise = exercise else {
fatalError("Exercise wants to be viewed, but was nil")
}
(viewContainingController() as? ExerciseDisplayer)?.displayExercise(exercise)
}
// MARK: Constraint functions
private func createAndActivateCellTitleLabelConstraints() {
cellTitleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitleLabel,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellTitleLabel,
withCopyView: self,
attribute: .left,
plusConstant: 10).isActive = true
NSLayoutConstraint(item: cellGraphButton,
attribute: .left,
relatedBy: .equal,
toItem: cellTitleLabel,
attribute: .right,
multiplier: 1,
constant: 10).isActive = true
NSLayoutConstraint.createHeightConstraintForView(view: cellTitleLabel,
height: UITableViewCell.defaultHeight).isActive = true
}
private func createAndActivateCellGraphButtonConstraints() {
cellGraphButton.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellGraphButton,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellGraphButton,
withCopyView: self,
attribute: .right).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellGraphButton,
withCopyView: cellTitleLabel,
attribute: .height).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: cellGraphButton,
withCopyView: self,
attribute: .width,
multiplier: 1 - WorkoutSessionSummaryView.newDataLabelWidthOfView - WorkoutSessionSummaryView.pgmLabelWidthOfView
).isActive = true
}
}
// MARK: ProgressionMethodSummaryView class
class ProgressionMethodSummaryView: UIView {
// MARK: View properties
// The progression method associated with this summary
private let progressionMethod: ProgressionMethod
// The value just added to the workout
private let newValue: Float?
// The old value associated with the workout
private let oldValue: Float?
// The title label associated with this progressionMethod
private let titleLabel: UILabel
// The label that says how much we did in this label
private let newValueLabel: UILabel
// Summary results controller
private let differenceLabel: UILabel
// MARK: View inits
init(progressionMethod: ProgressionMethod, newValue: Float?, oldValue: Float?, frame: CGRect) {
self.progressionMethod = progressionMethod
self.newValue = newValue
self.oldValue = oldValue
titleLabel = UILabel()
newValueLabel = UILabel()
differenceLabel = UILabel()
super.init(frame: frame)
addSubview(titleLabel)
addSubview(newValueLabel)
addSubview(differenceLabel)
createAndActivateTitleLabelConstraints()
createAndActivateNewValueLabelConstraints()
createAndActivateDifferenceLabelConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View functions
override func layoutSubviews() {
super.layoutSubviews()
// Title label
titleLabel.setDefaultProperties()
titleLabel.font = UIFont.systemFont(ofSize: 18.0)
titleLabel.textAlignment = .left
titleLabel.text = progressionMethod.getName()
// NewValue & Difference label
differenceLabel.textAlignment = .center
newValueLabel.textAlignment = .center
if let newValue = newValue {
newValueLabel.textColor = .niceBlue
newValueLabel.text = progressionMethod.getDisplayValue(forValue: newValue)
newValueLabel.backgroundColor = UIColor.niceLightBlue.withAlphaComponent(0.2)
if let oldValue = oldValue {
// Green text color if new > old. Red if less. Blue for equal
if newValue > oldValue {
differenceLabel.textColor = .niceGreen
differenceLabel.backgroundColor = UIColor.niceGreen.withAlphaComponent(0.2)
} else if newValue < oldValue {
differenceLabel.textColor = .niceRed
differenceLabel.backgroundColor = UIColor.niceRed.withAlphaComponent(0.2)
} else {
differenceLabel.textColor = .niceBlue
differenceLabel.backgroundColor = UIColor.niceBlue.withAlphaComponent(0.2)
}
// Add a "+" char to symbolize that we gained some weight
differenceLabel.text = (newValue >= oldValue ? "+" : "") +
progressionMethod.getDisplayValue(forValue: newValue - oldValue)
} else {
differenceLabel.textColor = .niceGreen
differenceLabel.backgroundColor = UIColor.niceGreen.withAlphaComponent(0.2)
differenceLabel.text = progressionMethod.getDisplayValue(forValue: newValue)
}
} else {
differenceLabel.textColor = .niceRed
differenceLabel.backgroundColor = UIColor.niceRed.withAlphaComponent(0.2)
differenceLabel.text = NSLocalizedString("SessionView.Label.Skipped", comment: "")
}
}
// MARK: Constraint functions
// Cling to left, top, bottom of view ; Width of related multiplier
private func createAndActivateTitleLabelConstraints() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel,
withCopyView: self,
attribute: .left,
plusConstant: 10).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel,
withCopyView: self,
attribute: .bottom).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: titleLabel,
withCopyView: self,
attribute: .width,
multiplier: WorkoutSessionSummaryView.pgmLabelWidthOfView,
plusConstant: -10 * (1/WorkoutSessionSummaryView.pgmLabelWidthOfView)).isActive = true
}
// Cling to top, bottom ; cling to right of titlelabel ; width of related multiplier
private func createAndActivateNewValueLabelConstraints() {
newValueLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: newValueLabel,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: newValueLabel,
withCopyView: self,
attribute: .bottom).isActive = true
NSLayoutConstraint(item: titleLabel,
attribute: .right,
relatedBy: .equal,
toItem: newValueLabel,
attribute: .left,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: newValueLabel,
withCopyView: self,
attribute: .width,
multiplier: WorkoutSessionSummaryView.newDataLabelWidthOfView).isActive = true
}
// Cling to right, top, bottom of view ; cling to right of newresultlabel
private func createAndActivateDifferenceLabelConstraints() {
differenceLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.createViewAttributeCopyConstraint(view: differenceLabel,
withCopyView: self,
attribute: .right).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: differenceLabel,
withCopyView: self,
attribute: .top).isActive = true
NSLayoutConstraint.createViewAttributeCopyConstraint(view: differenceLabel,
withCopyView: self,
attribute: .bottom).isActive = true
NSLayoutConstraint(item: newValueLabel,
attribute: .right,
relatedBy: .equal,
toItem: differenceLabel,
attribute: .left,
multiplier: 1,
constant: 0).isActive = true
}
}
| mit | e6c5f08597577df81d80df8973166631 | 46.051345 | 174 | 0.544845 | 6.863053 | false | false | false | false |
apple/swift-format | Sources/SwiftFormatRules/RuleNameCache+Generated.swift | 1 | 3620 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file is automatically generated with generate-pipeline. Do Not Edit!
/// By default, the `Rule.ruleName` should be the name of the implementing rule type.
public let ruleNameCache: [ObjectIdentifier: String] = [
ObjectIdentifier(AllPublicDeclarationsHaveDocumentation.self): "AllPublicDeclarationsHaveDocumentation",
ObjectIdentifier(AlwaysUseLowerCamelCase.self): "AlwaysUseLowerCamelCase",
ObjectIdentifier(AmbiguousTrailingClosureOverload.self): "AmbiguousTrailingClosureOverload",
ObjectIdentifier(BeginDocumentationCommentWithOneLineSummary.self): "BeginDocumentationCommentWithOneLineSummary",
ObjectIdentifier(DoNotUseSemicolons.self): "DoNotUseSemicolons",
ObjectIdentifier(DontRepeatTypeInStaticProperties.self): "DontRepeatTypeInStaticProperties",
ObjectIdentifier(FileScopedDeclarationPrivacy.self): "FileScopedDeclarationPrivacy",
ObjectIdentifier(FullyIndirectEnum.self): "FullyIndirectEnum",
ObjectIdentifier(GroupNumericLiterals.self): "GroupNumericLiterals",
ObjectIdentifier(IdentifiersMustBeASCII.self): "IdentifiersMustBeASCII",
ObjectIdentifier(NeverForceUnwrap.self): "NeverForceUnwrap",
ObjectIdentifier(NeverUseForceTry.self): "NeverUseForceTry",
ObjectIdentifier(NeverUseImplicitlyUnwrappedOptionals.self): "NeverUseImplicitlyUnwrappedOptionals",
ObjectIdentifier(NoAccessLevelOnExtensionDeclaration.self): "NoAccessLevelOnExtensionDeclaration",
ObjectIdentifier(NoAssignmentInExpressions.self): "NoAssignmentInExpressions",
ObjectIdentifier(NoBlockComments.self): "NoBlockComments",
ObjectIdentifier(NoCasesWithOnlyFallthrough.self): "NoCasesWithOnlyFallthrough",
ObjectIdentifier(NoEmptyTrailingClosureParentheses.self): "NoEmptyTrailingClosureParentheses",
ObjectIdentifier(NoLabelsInCasePatterns.self): "NoLabelsInCasePatterns",
ObjectIdentifier(NoLeadingUnderscores.self): "NoLeadingUnderscores",
ObjectIdentifier(NoParensAroundConditions.self): "NoParensAroundConditions",
ObjectIdentifier(NoVoidReturnOnFunctionSignature.self): "NoVoidReturnOnFunctionSignature",
ObjectIdentifier(OneCasePerLine.self): "OneCasePerLine",
ObjectIdentifier(OneVariableDeclarationPerLine.self): "OneVariableDeclarationPerLine",
ObjectIdentifier(OnlyOneTrailingClosureArgument.self): "OnlyOneTrailingClosureArgument",
ObjectIdentifier(OrderedImports.self): "OrderedImports",
ObjectIdentifier(ReturnVoidInsteadOfEmptyTuple.self): "ReturnVoidInsteadOfEmptyTuple",
ObjectIdentifier(UseEarlyExits.self): "UseEarlyExits",
ObjectIdentifier(UseLetInEveryBoundCaseVariable.self): "UseLetInEveryBoundCaseVariable",
ObjectIdentifier(UseShorthandTypeNames.self): "UseShorthandTypeNames",
ObjectIdentifier(UseSingleLinePropertyGetter.self): "UseSingleLinePropertyGetter",
ObjectIdentifier(UseSynthesizedInitializer.self): "UseSynthesizedInitializer",
ObjectIdentifier(UseTripleSlashForDocumentationComments.self): "UseTripleSlashForDocumentationComments",
ObjectIdentifier(UseWhereClausesInForLoops.self): "UseWhereClausesInForLoops",
ObjectIdentifier(ValidateDocumentationComments.self): "ValidateDocumentationComments",
]
| apache-2.0 | 05bb5cb3acb261e6da6af66ba860dbfa | 68.615385 | 116 | 0.808564 | 5.164051 | false | false | false | false |
aleffert/dials | Desktop/Source/ControlController.swift | 1 | 4418 | //
// ControlController.swift
// Dials-Desktop
//
// Created by Akiva Leffert on 3/19/15.
//
//
import Foundation
import AppKit
protocol ControlControllerDelegate : class {
func controlController(_ controller : ControlController, changedControlInfo info : DLSControlInfo, toValue value : NSCoding?)
func controlController(_ controller : ControlController, shouldSaveControlInfo info : DLSControlInfo, withValue value : NSCoding?)
}
class ControlController : NSObject, EditorControllerDelegate {
@IBOutlet var bodyView : NSView?
@IBOutlet var containerView : NSView?
@IBOutlet var revertButton : NSButton?
@IBOutlet var saveButton : NSButton?
@IBOutlet var openButton : NSButton?
fileprivate var currentValue : NSCoding?
fileprivate var updated : Bool = false
fileprivate var mouseInView : Bool = false
fileprivate let contentController : EditorController
let controlInfo : DLSControlInfo
weak var delegate : ControlControllerDelegate?
init(controlInfo : DLSControlInfo, contentController : EditorController, delegate : ControlControllerDelegate) {
contentController.configuration = EditorInfo(editor : controlInfo.editor, name : controlInfo.label, label : controlInfo.label, value : controlInfo.value)
self.controlInfo = controlInfo
self.delegate = delegate
self.contentController = contentController
currentValue = controlInfo.value
super.init()
contentController.delegate = self
Bundle.main.loadNibNamed("ControlCellView", owner: self, topLevelObjects: nil)
bodyView?.translatesAutoresizingMaskIntoConstraints = false
let area = NSTrackingArea(rect: NSZeroRect, options: [.activeInActiveApp, .mouseEnteredAndExited, .inVisibleRect], owner: self, userInfo: nil)
let currentBody = bodyView
self.dls_performAction {
currentBody?.removeTrackingArea(area)
}
bodyView?.addTrackingArea(area)
containerView?.addSubview(contentController.view)
contentController.view.addConstraintsMatchingSuperviewBounds()
validateButtons(animated : false)
}
func validateButtons(animated : Bool) {
NSAnimationContext.runAnimationGroup({ ctx in
ctx.allowsImplicitAnimation = true
self.revertButton?.isEnabled = self.updated
self.saveButton?.isEnabled = self.controlInfo.canSave && self.updated && self.controlInfo.file != nil
self.revertButton?.isHidden = !self.mouseInView
self.saveButton?.isHidden = !self.mouseInView
self.openButton?.isHidden = !self.mouseInView
}, completionHandler: nil)
}
func editorController(_ controller: EditorController, changedToValue value: NSCoding?) {
currentValue = value
updated = true
delegate?.controlController(self, changedControlInfo:controlInfo, toValue: value)
validateButtons(animated: true)
}
var view : NSView {
return bodyView!
}
func mouseEntered(_ theEvent: NSEvent) {
mouseInView = true
validateButtons(animated: true)
}
func mouseExited(_ theEvent: NSEvent) {
mouseInView = false
validateButtons(animated: true)
}
@IBAction func openFilePressed(_ sender : AnyObject) {
if let file = controlInfo.file {
Process.launchedProcess(launchPath: "/usr/bin/xed", arguments: ["--line", controlInfo.line.description, file])
}
}
@IBAction func revertPressed(_ sender : AnyObject) {
contentController.configuration = contentController.configuration
delegate?.controlController(self, changedControlInfo: controlInfo, toValue: contentController.configuration!.value)
updated = false
validateButtons(animated: true)
}
@IBAction func saveFilePressed(_ sender : AnyObject) {
delegate?.controlController(self, shouldSaveControlInfo : controlInfo, withValue: currentValue)
controlInfo.value = currentValue
updated = false
validateButtons(animated: true)
}
}
func < (left : ControlController, right : ControlController) -> Bool {
return left.controlInfo.label < right.controlInfo.label
}
func == (left : ControlController, right : ControlController) -> Bool {
return left.controlInfo.uuid == right.controlInfo.uuid
}
| mit | 4a00998dcb3d368831ee128636035ce5 | 38.097345 | 161 | 0.696695 | 5.00907 | false | false | false | false |
TobacoMosaicVirus/MemorialDay | MemorialDay/MemorialDay/Classes/Home/Controller/VRSHomeTabBarController.swift | 1 | 916 | //
// VRSHomeTabBarController.swift
// MemorialDay
//
// Created by apple on 16/4/29.
// Copyright © 2016年 virus. All rights reserved.
//
import UIKit
class VRSHomeTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setUI()
}
func setUI(){
let homeListVC = VRSDayListViewController()
let sb = UIStoryboard(name: "VRSMeStoryboard", bundle: nil)
let meVC = sb.instantiateInitialViewController()
let homeVC = VRSNavHomeController(rootViewController: homeListVC)
let aboutVC = VRSNavHomeController(rootViewController: meVC!)
homeVC.tabBarItem = UITabBarItem(title: "纪念日", image: nil, selectedImage: nil)
aboutVC.tabBarItem = UITabBarItem(title: "我", image: nil, selectedImage: nil)
self.viewControllers = [homeVC,aboutVC];
}
}
| apache-2.0 | 93049ca67e107f633a405308507e96ba | 26.424242 | 86 | 0.650829 | 4.371981 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/file formats/XGFsys.swift | 1 | 33990 | //
// XGFsys.swift
// XG Tool
//
// Created by StarsMmd on 01/06/2015.
// Copyright (c) 2015 StarsMmd. All rights reserved.
//
import Foundation
let kFSYSGroupIDOffset = 0x08
let kNumberOfEntriesOffset = 0x0C
let kFSYSFileSizeOffset = 0x20
let kFSYSDetailsPointersListOffset = 0x40
let kFirstFileNamePointerOffset = 0x44
let kFirstFileOffset = 0x48
let kFirstFileDetailsPointerOffset = 0x60
let kFirstFileNameOffset = 0x70
let kSizeOfArchiveEntry = game == .Colosseum ? 0x50 : 0x70
let kFileIdentifierOffset = 0x00 // 3rd byte is the file format, 1st half is an arbitrary identifier
let kFileFormatOffset = 0x02
let kFileStartPointerOffset = 0x04
let kUncompressedSizeOffset = 0x08
let kCompressedSizeOffset = 0x14
let kFileDetailsFullFilenameOffset = 0x1C // includes file extension. Not always used.
let kFileFormatIndexOffset = 0x20 // half of value in byte 3
let kFileDetailsFilenameOffset = 0x24
let kLZSSUncompressedSizeOffset = 0x04
let kLZSSCompressedSizeOffset = 0x08
let kLZSSUnkownOffset = 0x0C // PBR only, unused in Colo/XD
let kSizeOfLZSSHeader = 0x10
let kLZSSbytes: UInt32 = 0x4C5A5353
let kTCODbytes: UInt32 = 0x54434F44
let kFSYSbytes: UInt32 = 0x46535953
let kUSbytes = 0x5553
let kJPbytes = 0x4A50
final class XGFsys {
var file: XGFiles!
var data: XGMutableData!
private(set) var filenames: [String]!
var files: [XGFiles] {
return filenames.map { XGFiles.nameAndFolder($0, file.folder) }
}
var fileDetailsOffsets: [Int] {
let firstPointerOffset = data.get4BytesAtOffset(kFSYSDetailsPointersListOffset)
return (0 ..< numberOfEntries).map { (index) -> Int in
let offset = firstPointerOffset + (index * 4)
return data.get4BytesAtOffset(offset)
}
}
init(file: XGFiles) {
self.file = file
self.data = file.data
setupFilenames()
}
init(data: XGMutableData) {
self.data = data
self.file = data.file
setupFilenames()
}
private func setupFilenames() {
var names = usesFileExtensions ? rawFullFileNames : rawFileNames
for i in 0 ..< names.count {
let name = names[i]
if name == "(null)" {
// In non JP versions of PBR it is common for filenames to be scrubbed
// and replaced with (null)
// This names those files the same as the fsys file with an index appended
// just to differentiate between the filenames
var addendum = "\(i)"
while addendum.length < 4 {
addendum = "0" + addendum
}
addendum = " " + addendum
names[i] = fileName.removeFileExtensions() + addendum
} else {
// some files are named things like "common_rel" instead of "common.rel"
// this checks to see if the end of the filename is a file extension preceded by _
// and if so will replace the _ with .
let underscoreReplaced = name.replacingOccurrences(of: "_", with: ".")
let replacedExtension = XGFiles.nameAndFolder(underscoreReplaced, .Documents).fileExtension
if let filetype = XGFileTypes.fileTypeForExtension(replacedExtension) {
let dotExtension = filetype.fileExtension
let underscoreExtension = dotExtension.replacingOccurrences(of: ".", with: "_")
names[i] = name.replacingOccurrences(of: underscoreExtension, with: dotExtension)
}
}
// Each file has an identifier which has a byte indicating the file type.
// If the name doesn't already have a file extension then add the extension for its type.
var updatedName = names[i]
if updatedName.fileExtensions == "" {
updatedName = updatedName + fileTypeForFile(index: i).fileExtension
names[i] = updatedName
}
if updatedName.fileExtensions.lowercased() != updatedName.fileExtensions {
updatedName = updatedName.replacingOccurrences(of: updatedName.fileExtensions, with: updatedName.fileExtensions.lowercased())
names[i] = updatedName
}
if game == .PBR {
let updatedName = names[i]
if updatedName.contains("mes_common"), updatedName.fileExtensions == ".bin" {
if let data = extractDataForFileWithIndex(index: i), data.length > 4 {
if data.getWordAtOffset(0) == 0x4D455347 { // MESG magic bytes
names[i] = updatedName.replacingOccurrences(of: ".bin", with: XGFileTypes.msg.fileExtension)
}
}
}
}
}
// If any files have duplicate names, append an index number
let hasDuplicates = Array(Set(names)).count != names.count
if names.count > 0, hasDuplicates {
for mainIndex in 0 ..< names.count - 1 {
let currentFilename = names[mainIndex]
for subIndex in (mainIndex + 1) ..< names.count {
let comparisonFilename = names[subIndex]
if comparisonFilename == currentFilename {
names[subIndex] = currentFilename.removeFileExtensions() + " (\(subIndex))" + currentFilename.fileExtensions
}
}
}
}
filenames = names
}
var description: String {
var s = "\(self.fileName) - contains \(self.numberOfEntries) files\n"
for i in 0 ..< self.numberOfEntries {
let offset = String(format: "0x%x", self.startOffsetForFile(i))
let filename = i < filenames.count ? filenames[i] : "-"
s += "\(i):\t\(offset)\t\t\(filename)\n"
}
return s
}
var fileName: String {
return file.fileName
}
var groupID: Int {
return data.get4BytesAtOffset(kFSYSGroupIDOffset)
}
func setGroupID(_ id: Int) {
data.replace4BytesAtOffset(kFSYSGroupIDOffset, withBytes: id)
}
// some fsys files have 2 filenames per entry with the second containing the file extension
var usesFileExtensions: Bool {
return data.getByteAtOffset(0x13) == 0x1
}
var numberOfEntries: Int {
return data.get4BytesAtOffset(kNumberOfEntriesOffset)
}
func setNumberOfEntries(_ newEntries: Int) {
data.replaceWordAtOffset(kNumberOfEntriesOffset, withBytes: UInt32(newEntries))
}
func setFilesize(_ newSize: Int) {
data.replaceWordAtOffset(kFSYSFileSizeOffset, withBytes: UInt32(newSize))
}
func getStringAtOffset(_ offset: Int) -> String {
var currentOffset = offset
var currentChar = 0x1
var string = ""
while currentChar != 0x0 {
currentChar = data.getByteAtOffset(currentOffset)
if currentChar != 0x0 {
let char = UInt32(currentChar)
var unicode = "_"
unicode = String(describing: UnicodeScalar(char)!)
string = string + unicode
}
currentOffset += 1
}
return string
}
func fileNameForFileWithIndex(index: Int) -> String? {
guard filenames != nil else { return nil }
return index < filenames.count ? filenames[index] : nil
}
func fileNameForFileWithIdentifier(_ identifier: Int) -> String? {
guard let index = indexForIdentifier(identifier: identifier) else { return nil }
return fileNameForFileWithIndex(index: index)
}
func fileTypeForFileWithIndex(index: Int) -> XGFileTypes? {
return index < files.count ? files[index].fileType : nil
}
var firstFileNameOffset: Int {
return Int(data.getWordAtOffset(kFirstFileNamePointerOffset))
}
func setFirstFilenameOffset(_ newOffset: Int) {
data.replaceWordAtOffset(kFirstFileNamePointerOffset, withBytes: UInt32(newOffset))
}
private var rawFileNames: [String] {
return (0 ..< numberOfEntries).map { (index) -> String in
let offset = data.get4BytesAtOffset(startOffsetForFileDetails(index) + kFileDetailsFilenameOffset)
return getStringAtOffset(offset)
}
}
private var rawFullFileNames: [String] {
guard usesFileExtensions else { return [] }
return (0 ..< numberOfEntries).map { (index) -> String in
let offset = data.get4BytesAtOffset(startOffsetForFileDetails(index) + kFileDetailsFullFilenameOffset)
return getStringAtOffset(offset)
}
}
var identifiers: [Int] {
return (0 ..< numberOfEntries).map {identifierForFile(index: $0)}
}
func indexForIdentifier(identifier: Int) -> Int? {
// .rdat models use the last byte as the animation index so we ignore it here
// just to compare the file identifier itself
return identifiers.firstIndex(where: { ($0 & 0xFFFFFF00) == (identifier & 0xFFFFFF00)})
}
func indexForFileType(type: XGFileTypes) -> Int? {
return files.firstIndex(where: {$0.fileType == type})
}
var firstEntryDetailOffset: Int {
return data.get4BytesAtOffset(kFirstFileDetailsPointerOffset)
}
func setFirstEntryDetailOffset(_ newOffset: Int) {
data.replaceWordAtOffset(kFirstFileDetailsPointerOffset, withBytes: UInt32(newOffset))
}
var dataEnd: Int {
return data.length - 0x4
}
func startOffsetForFileDetails(_ index: Int) -> Int {
return data.get4BytesAtOffset(kFirstFileDetailsPointerOffset + (index * 4))
}
func startOffsetForFile(_ index: Int) -> Int {
let start = startOffsetForFileDetails(index) + kFileStartPointerOffset
return data.get4BytesAtOffset(start)
}
func setStartOffsetForFile(index: Int, newStart: Int) {
let start = startOffsetForFileDetails(index) + kFileStartPointerOffset
data.replaceWordAtOffset(start, withBytes: UInt32(newStart))
}
func sizeForFile(index: Int) -> Int {
let start = startOffsetForFileDetails(index) + kCompressedSizeOffset
return data.get4BytesAtOffset(start)
}
func setSizeForFile(index: Int, newSize: Int) {
let start = startOffsetForFileDetails(index) + kCompressedSizeOffset
data.replaceWordAtOffset(start, withBytes: UInt32(newSize))
}
func uncompressedSizeForFile(index: Int) -> Int {
let start = startOffsetForFileDetails(index) + kUncompressedSizeOffset
return data.get4BytesAtOffset(start)
}
func setUncompressedSizeForFile(index: Int, newSize: Int) {
let start = startOffsetForFileDetails(index) + kUncompressedSizeOffset
data.replaceWordAtOffset(start, withBytes: UInt32(newSize))
}
func identifierForFile(index: Int) -> Int {
let start = startOffsetForFileDetails(index) + kFileIdentifierOffset
return data.get4BytesAtOffset(start)
}
func setIdentifier(_ identifier: Int, fileType: XGFileTypes, forFileWithIndex index: Int) {
let start = startOffsetForFileDetails(index) + kFileIdentifierOffset
data.replace2BytesAtOffset(start, withBytes: identifier)
data.replaceByteAtOffset(start + 2, withByte: fileType.rawValue)
}
private func fileTypeForFile(index: Int) -> XGFileTypes {
if index >= numberOfEntries || index < 0 {
return .unknown
}
return XGFileTypes(rawValue: (identifierForFile(index: index) & 0xFF00) >> 8) ?? .unknown
}
func fileWithIndex(_ index: Int) -> XGFiles? {
guard index < numberOfEntries else { return nil }
return files[index]
}
func dataForFileWithName(name: String) -> XGMutableData? {
let index = self.indexForFile(filename: name)
if index == nil {
printg("file doesn't exist: ", name)
return nil
}
return dataForFileWithIndex(index: index!)
}
func decompressedDataForFileWithName(name: String) -> XGMutableData? {
let index = self.indexForFile(filename: name)
if index == nil {
printg("file doesn't exist: ", name)
return nil
}
return decompressedDataForFileWithIndex(index: index!)
}
func decompressedDataForFileWithFiletype(type: XGFileTypes) -> XGMutableData? {
if let index = indexForFileType(type: type) {
if index < 0 || index > self.numberOfEntries {
if XGSettings.current.verbose {
printg(self.fileName + " - file type: " + type.fileExtension + " doesn't exists.")
}
return nil
}
return decompressedDataForFileWithIndex(index: index)
}
return nil
}
func dataForFileWithFiletype(type: XGFileTypes) -> XGMutableData? {
if let index = indexForFileType(type: type) {
if index < 0 || index > self.numberOfEntries {
if XGSettings.current.verbose {
printg(self.fileName + " - file type: " + type.fileExtension + " doesn't exists.")
}
return nil
}
return dataForFileWithIndex(index: index)
}
return nil
}
func decompressedDataForFilesWithFiletype(type: XGFileTypes) -> [XGMutableData] {
var filesData = [XGMutableData]()
for index in 0 ..< self.numberOfEntries {
if fileTypeForFile(index: index) == type {
if let file = decompressedDataForFileWithIndex(index: index) {
filesData.append(file)
}
}
}
return filesData
}
func dataForFileWithIndex(index: Int) -> XGMutableData? {
guard index < numberOfEntries else { return nil }
let start = startOffsetForFile(index)
let length = sizeForFile(index: index)
var filename = fileNameForFileWithIndex(index: index) ?? "none.bin" // Used when file is required while loading fsys
if isFileCompressed(index: index) {
filename = filename + XGFileTypes.lzss.fileExtension
}
let fileData = data.getCharStreamFromOffset(start, length: length)
return XGMutableData(byteStream: fileData, file: .nameAndFolder(filename, .Documents))
}
func decompressedDataForFileWithIndex(index: Int) -> XGMutableData? {
guard index < numberOfEntries else { return nil }
let fileData = dataForFileWithIndex(index: index)!
//let decompressedSize = fileData.getWordAtOffset(kLZSSUncompressedSizeOffset)
fileData.deleteBytes(start: 0, count: kSizeOfLZSSHeader)
let decompressedData = XGLZSS.decode(data: fileData)
let filename = fileNameForFileWithIndex(index: index) ?? "none.bin"
decompressedData.file = .nameAndFolder(filename, .Documents)
return decompressedData
}
func isFileCompressed(index: Int) -> Bool {
return data.getWordAtOffset(startOffsetForFile(index)) == kLZSSbytes
}
func getUnknownLZSSForFileWithIndex(_ index: Int) -> UInt32 {
return data.getWordAtOffset(startOffsetForFile(index) + kLZSSUnkownOffset)
}
/// checks if the file is compressed or not and returns the appropriate data
func extractDataForFileWithIndex(index: Int) -> XGMutableData? {
guard index < numberOfEntries else {
return nil
}
return isFileCompressed(index: index) ? decompressedDataForFileWithIndex(index: index) : dataForFileWithIndex(index: index)
}
/// checks if the file is compressed or not and returns the appropriate data
func extractDataForFile(_ file: XGFiles) -> XGMutableData? {
guard let index = indexForFile(file) else { return nil }
let data = extractDataForFileWithIndex(index: index)
data?.file = file
return data
}
func extractDataForFile(filename: String) -> XGMutableData? {
guard let index = indexForFile(filename: filename) else { return nil }
let data = extractDataForFileWithIndex(index: index)
return data
}
func indexForFile(_ file: XGFiles) -> Int? {
return indexForFile(filename: file.fileName)
}
func indexForFile(filename: String) -> Int? {
return filenames.firstIndex(of: filename)
}
func replaceFileWithName(name: String, withFile newFile: XGFiles, save: Bool = true) {
guard newFile.exists else {
printg("file doesn't exist:", newFile.path)
return
}
guard let index = indexForFile(filename: name) else {
printg("file with name '", name ,"' doesn't exist in ", file.path)
return
}
if isFileCompressed(index: index) && (newFile.fileType != .lzss) {
shiftAndReplaceFileWithIndex(index, withFile: newFile.compress(), save: save)
} else {
shiftAndReplaceFileWithIndex(index, withFile: newFile, save: save)
}
}
func replaceFile(file: XGFiles, save: Bool = true) {
replaceFileWithName(name: file.fileName, withFile: file, save: save)
}
func shiftAndReplaceFileWithIndex(_ index: Int, withFile newFile: XGFiles, save: Bool) {
guard index < self.numberOfEntries else {
printg("skipping fsys import: \(newFile.fileName) to \(self.fileName)\nindex doesn't exist:", index)
return
}
guard let newFileData = newFile.data, newFileData.length > 3 else {
printg("skipping fsys import: \(newFile.fileName) to \(self.fileName)\nInsufficient data.")
return
}
shiftAndReplaceFileWithIndex(index, withData: newFileData, save: save)
}
func shiftAndReplaceFileWithIndex(_ index: Int, withData newData: XGMutableData, save: Bool) {
var newFileData = newData
if isFileCompressed(index: index) && (newFileData.getWordAtOffset(0) != kLZSSbytes) {
newFileData = XGLZSS.encode(data: newFileData)
}
var fileEnd = startOffsetForFile(index) + newFileData.length
let nextStart = index < self.numberOfEntries - 1 ? startOffsetForFile(index + 1) : dataEnd
let shift = fileEnd > nextStart
if shift {
for i in 0 ..< self.numberOfEntries {
self.shiftUpFileWithIndex(index: i)
}
let end = dataEnd
let lastIndex = self.numberOfEntries - 1
var lastFileEnd = self.startOffsetForFile(lastIndex) + self.sizeForFile(index: lastIndex)
while lastFileEnd % 16 != 0 {
lastFileEnd += 1
}
let excess = end - lastFileEnd - 0xc
if excess > 0x100 {
self.data.deleteBytes(start: lastFileEnd, count: (excess - 0x100))
self.setFilesize(self.data.length)
}
fileEnd = startOffsetForFile(index) + newFileData.length
var expansionRequired = 0
let newNextStart = index < self.numberOfEntries - 1 ? startOffsetForFile(index + 1) : dataEnd
if fileEnd > newNextStart {
// add a little extra free space so future size increases can be accounted for if they are small.
expansionRequired = fileEnd - newNextStart + 0x80
while expansionRequired % 16 != 0 {
expansionRequired += 1
}
}
if expansionRequired > 0 {
if index < numberOfEntries - 1 {
for i in index + 1 ..< numberOfEntries {
setStartOffsetForFile(index: i, newStart: startOffsetForFile(i) + expansionRequired)
}
}
data.insertRepeatedByte(byte: 0, count: expansionRequired, atOffset: newNextStart)
setFilesize(data.length)
}
}
replaceFileWithIndex(index, withData: newFileData, saveWhenDone: save)
}
func replaceFileWithIndex(_ index: Int, withFile newFile: XGFiles, saveWhenDone: Bool) {
guard newFile.exists, let data = newFile.data else {
printg("file doesn't exist: ", newFile.path)
return
}
replaceFileWithIndex(index, withData: data, saveWhenDone: saveWhenDone)
}
func replaceFileWithIndex(_ index: Int, withData newData: XGMutableData, saveWhenDone: Bool, allowExpansion: Bool = false) {
guard index < self.numberOfEntries else {
printg("skipping fsys import: \(data.file.fileName) to \(self.file.path)\nindex doesn't exist:", index)
return
}
var unknownLZSSBytes: UInt32?
if game == .PBR, isFileCompressed(index: index) {
unknownLZSSBytes = getUnknownLZSSForFileWithIndex(index)
}
let fileStart = startOffsetForFile(index)
let fileEnd = fileStart + newData.length
let nextStart = index < self.numberOfEntries - 1 ? startOffsetForFile(index + 1) : dataEnd
if allowExpansion {
var expansionRequired = 0
if fileEnd > nextStart {
expansionRequired = fileEnd - nextStart
while expansionRequired % 16 != 0 {
expansionRequired += 1
}
}
if expansionRequired > 0 {
if index < numberOfEntries - 1 {
for i in index + 1 ..< numberOfEntries {
setStartOffsetForFile(index: i, newStart: startOffsetForFile(i) + expansionRequired)
}
}
data.insertRepeatedByte(byte: 0, count: expansionRequired, atOffset: nextStart)
setFilesize(data.length)
}
} else {
if index < self.numberOfEntries - 1, fileEnd > startOffsetForFile(index + 1) {
printg(file.fileName)
printg("file too large to replace: ", newData.file.path)
return
}
if fileEnd > self.dataEnd {
printg(file.fileName)
printg("file too large to replace: ", newData.file.path)
return
}
}
eraseDataForFile(index: index)
let fileSize = UInt32(newData.length)
let detailsStart = startOffsetForFileDetails(index)
data.replaceWordAtOffset(detailsStart + kCompressedSizeOffset, withBytes: fileSize)
let lzssCheck = newData.getWordAtOffset(0) == kLZSSbytes
if lzssCheck {
if let unknown = unknownLZSSBytes {
newData.replaceWordAtOffset(kLZSSUnkownOffset, withBytes: unknown)
}
data.replaceWordAtOffset(detailsStart + kUncompressedSizeOffset, withBytes: newData.getWordAtOffset(kLZSSUncompressedSizeOffset))
} else {
data.replaceWordAtOffset(detailsStart + kUncompressedSizeOffset, withBytes: fileSize)
}
data.replaceBytesFromOffset(fileStart, withByteStream: newData.byteStream)
if saveWhenDone {
save()
}
}
func eraseDataForFile(index: Int) {
let start = startOffsetForFile(index)
let size = sizeForFile(index: index)
eraseData(start: start, length: size)
}
func eraseData(start: Int, length: Int) {
data.nullBytes(start: start, length: length)
}
func deleteFile(index: Int) {
eraseDataForFile(index: index)
setSizeForFile(index: index, newSize: 4)
data.replaceBytesFromOffset(startOffsetForFile(index), withByteStream: [0xDE, 0x1E, 0x7E, 0xD0])
}
func increaseDataLength(by bytes: Int) {
var expansionRequired = bytes + 0x14
while (expansionRequired % 16) != 0 { // byte alignment is required by the iso
expansionRequired += 1
}
self.data.appendBytes(.init(repeating: 0, count: expansionRequired))
self.setFilesize(self.data.length)
self.data.replaceWordAtOffset(dataEnd, withBytes: kFSYSbytes)
}
func addFile(_ file: XGFiles, fileType: XGFileTypes, compress: Bool, shortID: Int) {
guard file.exists, let data = file.data else { return }
self.addFile(data, fileType: fileType, compress: compress, shortID: shortID)
}
func addFile(_ fileData: XGMutableData, fileType: XGFileTypes, compress: Bool, shortID: Int) {
// doesn't considered fsys with alternate filename data. might change things, might not.
let file = fileData.file
let filename = file.fileName.removeFileExtensions()
var bytesAdded = 0
let names = rawFileNames
let fullnames = rawFullFileNames
let fileDetailsPointerOffset = kFirstFileDetailsPointerOffset + (4 * numberOfEntries)
if numberOfEntries % 4 == 0 {
data.insertRepeatedByte(byte: 0, count: 16, atOffset: fileDetailsPointerOffset)
bytesAdded += 16
}
let filenamesShift = bytesAdded
let fullfilenamesShift = filenamesShift + filename.count + 1
setFirstFilenameOffset(firstFileNameOffset + bytesAdded)
let allnames = usesFileExtensions ? names + fullnames : names
var filenamesSize = 0
for file in allnames {
filenamesSize += file.count + 1
}
var padding = 16 - (filenamesSize % 16)
padding = padding == 16 ? 0 : padding
var extraNameBytes = usesFileExtensions ? file.fileName.count + filename.count + 2 : filename.count + 1
if extraNameBytes <= padding {
extraNameBytes = 0
} else {
extraNameBytes -= padding
}
while (filenamesSize + padding + extraNameBytes) % 16 != 0 {
extraNameBytes += 1
}
bytesAdded += extraNameBytes
data.insertRepeatedByte(byte: 0, count: extraNameBytes, atOffset: firstFileNameOffset)
var currentOffset = firstFileNameOffset
for name in names + [filename] {
data.replaceBytesFromOffset(currentOffset, withByteStream: name.unicodeRepresentation)
currentOffset += name.unicodeRepresentation.count
}
let filenameStart = currentOffset - filename.unicodeRepresentation.count
if usesFileExtensions {
for name in fullnames + [file.fileName] {
data.replaceBytesFromOffset(currentOffset, withByteStream: name.unicodeRepresentation)
currentOffset += name.unicodeRepresentation.count
}
}
let fullFilenameStart = usesFileExtensions ? currentOffset - file.fileName.unicodeRepresentation.count : 0
while currentOffset % 16 != 0 {
data.replaceByteAtOffset(currentOffset, withByte: 0)
currentOffset += 1
}
let entryShift = bytesAdded
for i in 0 ..< numberOfEntries {
let detailsPointer = kFirstFileDetailsPointerOffset + (4 * i)
let newPointer = data.getWordAtOffset(detailsPointer) + UInt32(entryShift)
data.replaceWordAtOffset(detailsPointer, withBytes: newPointer)
}
let entryStart = firstEntryDetailOffset + (kSizeOfArchiveEntry * numberOfEntries)
data.insertRepeatedByte(byte: 0, count: kSizeOfArchiveEntry, atOffset: entryStart)
bytesAdded += kSizeOfArchiveEntry
let fileStartShift = bytesAdded
let newFirstFileOffset = data.getWordAtOffset(kFirstFileOffset) + UInt32(fileStartShift)
data.replaceWordAtOffset(kFirstFileOffset, withBytes: newFirstFileOffset)
var fileStart = startOffsetForFile(numberOfEntries - 1) + sizeForFile(index: numberOfEntries - 1) + bytesAdded
while (fileStart % 16) != 0 {
fileStart += 1
}
for i in 0 ..< numberOfEntries {
let dets = firstEntryDetailOffset + (i * kSizeOfArchiveEntry)
let fileStart = data.getWordAtOffset(dets + kFileStartPointerOffset) + UInt32(fileStartShift)
let nameStart = data.getWordAtOffset(dets + kFileDetailsFilenameOffset) + UInt32(filenamesShift)
data.replaceWordAtOffset(dets + kFileStartPointerOffset, withBytes: fileStart)
data.replaceWordAtOffset(dets + kFileDetailsFilenameOffset, withBytes: nameStart)
if usesFileExtensions {
let fullnameStart = data.getWordAtOffset(dets + kFileDetailsFullFilenameOffset) + UInt32(fullfilenamesShift)
data.replaceWordAtOffset(dets + kFileDetailsFullFilenameOffset, withBytes: fullnameStart)
}
}
let data = compress ? XGLZSS.encode(data: fileData) : fileData
var newFileSize = data.length
while newFileSize % 16 != 0 {
self.data.insertByte(byte: 0, atOffset: fileStart)
newFileSize += 1
}
self.data.insertData(data: data, atOffset: fileStart)
self.data.replaceWordAtOffset(fileDetailsPointerOffset, withBytes: UInt32(entryStart))
self.data.replaceWordAtOffset(kFSYSFileSizeOffset, withBytes: UInt32(self.data.length))
self.data.replaceWordAtOffset(kNumberOfEntriesOffset, withBytes: UInt32(numberOfEntries + 1))
let isCompressed = data.getWordAtOffset(0) == kLZSSbytes
let uncompressedSize = isCompressed ? data.getWordAtOffset(kLZSSUncompressedSizeOffset) : UInt32(data.length)
let compressedSize = isCompressed ? data.getWordAtOffset(kLZSSCompressedSizeOffset) : UInt32(data.length)
self.data.replaceWordAtOffset(entryStart + kUncompressedSizeOffset, withBytes: uncompressedSize)
self.data.replaceWordAtOffset(entryStart + kCompressedSizeOffset, withBytes: compressedSize)
self.data.replace2BytesAtOffset(entryStart + kFileIdentifierOffset, withBytes: shortID)
self.data.replaceByteAtOffset(entryStart + kFileFormatOffset, withByte: fileType.identifier)
self.data.replaceWordAtOffset(entryStart + kFileStartPointerOffset, withBytes: UInt32(fileStart))
self.data.replaceWordAtOffset(entryStart + 0xc, withBytes: 0x80000000)
self.data.replaceWordAtOffset(entryStart + kFileFormatIndexOffset, withBytes: UInt32(fileType.index))
self.data.replaceWordAtOffset(entryStart + kFileDetailsFilenameOffset, withBytes: UInt32(filenameStart))
if usesFileExtensions {
self.data.replaceWordAtOffset(entryStart + kFileDetailsFullFilenameOffset, withBytes: UInt32(fullFilenameStart))
}
self.data.replaceWordAtOffset(0x1c, withBytes: self.data.getWordAtOffset(0x48))
}
private func shiftUpFileWithIndex(index: Int) {
// used to push a file closer to the file above it and create more space for other files
guard index < self.numberOfEntries else { return }
var previousEnd = 0x0
if index == 0 {
previousEnd = self.startOffsetForFileDetails(self.numberOfEntries - 1) + kSizeOfArchiveEntry
} else {
previousEnd = self.startOffsetForFile(index - 1) + sizeForFile(index: index - 1)
}
while (previousEnd % 16) != 0 {
previousEnd += 1
}
self.moveFile(index: index, toOffset: previousEnd)
}
private func shiftDownFileWithIndex(index: Int) {
// used to push a file closer to the file above it and create more space for other files
guard index < self.numberOfEntries else { return }
let size = sizeForFile(index: index)
var nextStart = 0x0
if index == self.numberOfEntries - 1 {
nextStart = self.dataEnd
} else {
nextStart = startOffsetForFile(index + 1)
}
var start = nextStart - size
while (start % 16) != 0 {
start -= 1
}
self.moveFile(index: index, toOffset: start)
}
private func shiftDownFileWithIndex(index: Int, byOffset by: Int) {
// used to push a file closer to the file above it and create more space for other files
if !(index < self.numberOfEntries && index > 0) { return }
guard by % 16 == 0 else {
printg("Attempted to shift \(fileName), file '\(index)' by \(by) bytes but the offset must be a multiple of 16.")
return
}
let start = startOffsetForFile(index) + by
let size = sizeForFile(index: index)
let nextStart = index == self.numberOfEntries - 1 ? self.dataEnd : startOffsetForFile(index + 1)
if start + 0x10 + size < nextStart {
self.moveFile(index: index, toOffset: start)
}
}
func moveFile(index: Int, toOffset startOffset: Int) {
let bytes = self.dataForFileWithIndex(index: index)!.byteStream
self.eraseData(start: startOffsetForFile(index), length: sizeForFile(index: index))
self.setStartOffsetForFile(index: index, newStart: startOffset)
data.replaceBytesFromOffset(startOffset, withByteStream: bytes)
}
func save() {
data.save()
}
func extractFilesToFolder(folder: XGFolders, extract: Bool = true, decode: Bool, overwrite: Bool = false) {
if extract {
for i in 0 ..< self.numberOfEntries {
if XGSettings.current.verbose, let filename = fileNameForFileWithIndex(index: i) {
printg("extracting file: \(filename) from \(self.file.path)")
}
if let fileData = extractDataForFileWithIndex(index: i) {
fileData.file = .nameAndFolder(fileData.file.fileName, folder)
if !fileData.file.exists || overwrite {
fileData.save()
}
}
}
}
// decode certain file types
if decode {
for file in folder.files where filenames.contains(file.fileName) {
if XGSettings.current.verbose {
printg("decoding file: \(file.fileName)")
}
if file.fileType == .pkx {
let datFile = XGFiles.nameAndFolder(file.fileName + XGFileTypes.dat.fileExtension, file.folder)
if !datFile.exists || overwrite, let pkxData = file.data {
let dat = XGUtility.exportDatFromPKX(pkx: pkxData)
dat.file = datFile
dat.save()
}
}
#if !GAME_PBR
if file.fileType == .wzx {
if let wzxData = file.data {
let wzx = WZXModel(data: wzxData)
for modelData in wzx.models {
if !modelData.file.exists {
modelData.save()
}
}
}
}
#endif
if file.fileType == .msg, !XGFiles.nameAndFolder(file.fileName.removeFileExtensions() + XGFileTypes.scd.fileExtension, folder).exists || game == .Colosseum {
let msgFile = XGFiles.nameAndFolder(file.fileName + XGFileTypes.json.fileExtension, file.folder)
if !msgFile.exists || overwrite {
let msg = XGStringTable(file: file, startOffset: 0, fileSize: file.fileSize)
msg.writeJSON(to: msgFile)
}
}
#if !GAME_PBR
let fileContainsScript = (file.fileType == .scd || file == .common_rel)
#else
let fileContainsScript = file.fileType == .scd
#endif
if fileContainsScript, (game != .Colosseum || XGSettings.current.enableExperimentalFeatures) { // TODO allow colosseum scripts once less buggy
let xdsFile = XGFiles.nameAndFolder(file.fileName + XGFileTypes.xds.fileExtension, folder)
if !xdsFile.exists || overwrite {
let scriptText = file.scriptData.getXDSScript()
XGUtility.saveString(scriptText, toFile: xdsFile)
}
}
#if !GAME_PBR
if file == .common_rel || file == .tableres2 || file == .dol {
let msgFile = XGFiles.nameAndFolder(file.fileName + XGFileTypes.json.fileExtension, file.folder)
if !msgFile.exists {
let table = file.stringTable
table.writeJSON(to: msgFile)
}
if file == .common_rel && game == .Colosseum && region != .JP && XGSettings.current.enableExperimentalFeatures {
let msgFile2 = XGFiles.nameAndFolder("common2.json", file.folder)
if !msgFile2.exists {
let table = XGStringTable.common_rel2()
table.writeJSON(to: msgFile2)
}
let msgFile3 = XGFiles.nameAndFolder("common3.json", file.folder)
if !msgFile3.exists {
let table = XGStringTable.common_rel3()
table.writeJSON(to: msgFile3)
}
}
if file == .dol && game == .XD && region != .JP && XGSettings.current.enableExperimentalFeatures {
let msgFile2 = XGFiles.nameAndFolder("Start2.json", file.folder)
if !msgFile2.exists {
let table = XGStringTable.dol2()
table.writeJSON(to: msgFile2)
}
let msgFile3 = XGFiles.nameAndFolder("Start3.json", file.folder)
if !msgFile3.exists {
let table = XGStringTable.dol3()
table.writeJSON(to: msgFile3)
}
}
}
#endif
if file.fileType == .thh {
let thpFile = XGFiles.nameAndFolder(file.fileName.removeFileExtensions() + XGFileTypes.thp.fileExtension, folder)
if (!thpFile.exists || overwrite), let thpData = folder.files.first(where: { $0.fileType == .thd && $0.fileName.removeFileExtensions() == file.fileName.removeFileExtensions() })?.data {
if let thpHeader = file.data {
let thp = XGTHP(header: thpHeader, body: thpData)
thp.thpData.save()
}
}
}
}
for file in folder.files {
#if !GAME_PBR
// skip pkx textures since the .dat inside should already have been exported and the textures will be dumped from that
if file.fileType == .pkx { continue }
#endif
for texture in file.textures {
if !texture.file.exists || overwrite {
texture.save()
}
let pngFile = XGFiles.nameAndFolder(texture.file.fileName + XGFileTypes.png.fileExtension, file.folder)
if !pngFile.exists || overwrite {
texture.writePNGData(toFile: pngFile)
}
}
}
}
}
}
extension XGFsys: XGEnumerable {
var enumerableName: String {
return file.path
}
var enumerableValue: String? {
return nil
}
static var className: String {
return "Fsys"
}
static var allValues: [XGFsys] {
return XGISO.current.allFileNames
.filter{$0.fileExtensions == XGFileTypes.fsys.fileExtension}
.map{XGFiles.fsys($0.removeFileExtensions())}
.filter{$0.exists}
.map{$0.fsysData}
}
}
| gpl-2.0 | 85496bf72f404548648680e84001927b | 31.682692 | 190 | 0.714651 | 3.518634 | false | false | false | false |
zhenghuadong11/firstGitHub | 旅游app_useSwift/旅游app_useSwift/Source/Constraint.swift | 36 | 21321 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to expose API's for a Constraint
*/
public class Constraint {
public func install() -> [LayoutConstraint] { fatalError("Must be implemented by Concrete subclass.") }
public func uninstall() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func activate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func deactivate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGPoint) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: CGSize) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateOffset(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updateInsets(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriority(priority: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityRequired() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
internal var makerFile: String = "Unknown"
internal var makerLine: UInt = 0
}
/**
Used internally to implement a ConcreteConstraint
*/
internal class ConcreteConstraint: Constraint {
internal override func updateOffset(amount: Float) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: Double) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: CGFloat) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: Int) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: UInt) -> Void {
self.updateOffset(Float(amount))
}
internal override func updateOffset(amount: CGPoint) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: CGSize) -> Void {
self.constant = amount
}
internal override func updateOffset(amount: EdgeInsets) -> Void {
self.constant = amount
}
internal override func updateInsets(amount: EdgeInsets) -> Void {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
}
internal override func updatePriority(priority: Float) -> Void {
self.priority = priority
}
internal override func updatePriority(priority: Double) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: CGFloat) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: UInt) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriority(priority: Int) -> Void {
self.updatePriority(Float(priority))
}
internal override func updatePriorityRequired() -> Void {
self.updatePriority(Float(1000.0))
}
internal override func updatePriorityHigh() -> Void {
self.updatePriority(Float(750.0))
}
internal override func updatePriorityMedium() -> Void {
#if os(iOS) || os(tvOS)
self.updatePriority(Float(500.0))
#else
self.updatePriority(Float(501.0))
#endif
}
internal override func updatePriorityLow() -> Void {
self.updatePriority(Float(250.0))
}
internal override func install() -> [LayoutConstraint] {
return self.installOnView(updateExisting: false, file: self.makerFile, line: self.makerLine)
}
internal override func uninstall() -> Void {
self.uninstallFromView()
}
internal override func activate() -> Void {
guard self.installInfo != nil else {
self.install()
return
}
#if SNAPKIT_DEPLOYMENT_LEGACY
guard #available(iOS 8.0, OSX 10.10, *) else {
self.install()
return
}
#endif
let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
if layoutConstraints.count > 0 {
NSLayoutConstraint.activateConstraints(layoutConstraints)
}
}
internal override func deactivate() -> Void {
guard self.installInfo != nil else {
return
}
#if SNAPKIT_DEPLOYMENT_LEGACY
guard #available(iOS 8.0, OSX 10.10, *) else {
return
}
#endif
let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
if layoutConstraints.count > 0 {
NSLayoutConstraint.deactivateConstraints(layoutConstraints)
}
}
private let fromItem: ConstraintItem
private let toItem: ConstraintItem
private let relation: ConstraintRelation
private let multiplier: Float
private var constant: Any {
didSet {
if let installInfo = self.installInfo {
for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
let attribute = (layoutConstraint.secondAttribute == .NotAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
layoutConstraint.constant = attribute.snp_constantForValue(self.constant)
}
}
}
}
private var priority: Float {
didSet {
if let installInfo = self.installInfo {
for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
layoutConstraint.priority = self.priority
}
}
}
}
private let label: String?
private var installInfo: ConcreteConstraintInstallInfo? = nil
internal init(fromItem: ConstraintItem, toItem: ConstraintItem, relation: ConstraintRelation, constant: Any, multiplier: Float, priority: Float, label: String? = nil) {
self.fromItem = fromItem
self.toItem = toItem
self.relation = relation
self.constant = constant
self.multiplier = multiplier
self.priority = priority
self.label = label
}
internal func installOnView(updateExisting updateExisting: Bool = false, file: String? = nil, line: UInt? = nil) -> [LayoutConstraint] {
var installOnView: View? = nil
if self.toItem.view != nil {
installOnView = closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view)
if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "No common superview between views (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
} else {
if self.fromItem.attributes.isSubsetOf(ConstraintAttributes.Width.union(.Height)) {
installOnView = self.fromItem.view
} else {
installOnView = self.fromItem.view?.superview
if installOnView == nil {
NSException(name: "Cannot Install Constraint", reason: "Missing superview (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
}
}
if let installedOnView = self.installInfo?.view {
if installedOnView != installOnView {
NSException(name: "Cannot Install Constraint", reason: "Already installed on different view. (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
return []
}
return self.installInfo?.layoutConstraints.allObjects as? [LayoutConstraint] ?? []
}
var newLayoutConstraints = [LayoutConstraint]()
let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
let layoutToAttributes = self.toItem.attributes.layoutAttributes
// get layout from
let layoutFrom: View? = self.fromItem.view
// get layout relation
let layoutRelation: NSLayoutRelation = self.relation.layoutRelation
for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
// get layout constant
let layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
// get layout to
#if os(iOS) || os(tvOS)
var layoutTo: AnyObject? = self.toItem.view ?? self.toItem.layoutSupport
#else
var layoutTo: AnyObject? = self.toItem.view
#endif
if layoutTo == nil && layoutToAttribute != .Width && layoutToAttribute != .Height {
layoutTo = installOnView
}
// create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom!,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: CGFloat(self.multiplier),
constant: layoutConstant)
layoutConstraint.identifier = self.label
// set priority
layoutConstraint.priority = self.priority
// set constraint
layoutConstraint.snp_constraint = self
newLayoutConstraints.append(layoutConstraint)
}
// special logic for updating
if updateExisting {
// get existing constraints for this view
let existingLayoutConstraints = layoutFrom!.snp_installedLayoutConstraints.reverse()
// array that will contain only new layout constraints to keep
var newLayoutConstraintsToKeep = [LayoutConstraint]()
// begin looping
for layoutConstraint in newLayoutConstraints {
// layout constraint that should be updated
var updateLayoutConstraint: LayoutConstraint? = nil
// loop through existing and check for match
for existingLayoutConstraint in existingLayoutConstraints {
if existingLayoutConstraint == layoutConstraint {
updateLayoutConstraint = existingLayoutConstraint
break
}
}
// if we have existing one lets just update the constant
if updateLayoutConstraint != nil {
updateLayoutConstraint!.constant = layoutConstraint.constant
}
// otherwise add this layout constraint to new keep list
else {
newLayoutConstraintsToKeep.append(layoutConstraint)
}
}
// set constraints to only new ones
newLayoutConstraints = newLayoutConstraintsToKeep
}
// add constraints
#if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
if #available(iOS 8.0, *) {
NSLayoutConstraint.activateConstraints(newLayoutConstraints)
} else {
installOnView!.addConstraints(newLayoutConstraints)
}
#else
NSLayoutConstraint.activateConstraints(newLayoutConstraints)
#endif
// set install info
self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable())
// store which layout constraints are installed for this constraint
for layoutConstraint in newLayoutConstraints {
self.installInfo!.layoutConstraints.addObject(layoutConstraint)
}
// store the layout constraints against the layout from view
layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints
// return the new constraints
return newLayoutConstraints
}
internal func uninstallFromView() {
if let installInfo = self.installInfo,
let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] {
if installedLayoutConstraints.count > 0 {
// remove the constraints from the UIView's storage
#if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
if #available(iOS 8.0, *) {
NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
} else if let installedOnView = installInfo.view {
installedOnView.removeConstraints(installedLayoutConstraints)
}
#else
NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
#endif
// remove the constraints from the from item view
if let fromView = self.fromItem.view {
fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter {
return !installedLayoutConstraints.contains($0)
}
}
}
}
self.installInfo = nil
}
}
private struct ConcreteConstraintInstallInfo {
weak var view: View? = nil
let layoutConstraints: NSHashTable
}
private extension NSLayoutAttribute {
private func snp_constantForValue(value: Any?) -> CGFloat {
// Float
if let float = value as? Float {
return CGFloat(float)
}
// Double
else if let double = value as? Double {
return CGFloat(double)
}
// UInt
else if let int = value as? Int {
return CGFloat(int)
}
// Int
else if let uint = value as? UInt {
return CGFloat(uint)
}
// CGFloat
else if let float = value as? CGFloat {
return float
}
// CGSize
else if let size = value as? CGSize {
if self == .Width {
return size.width
} else if self == .Height {
return size.height
}
}
// CGPoint
else if let point = value as? CGPoint {
#if os(iOS) || os(tvOS)
switch self {
case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x
case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return point.y
case .Right, .RightMargin: return point.x
case .Bottom, .BottomMargin: return point.y
case .Leading, .LeadingMargin: return point.x
case .Trailing, .TrailingMargin: return point.x
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
}
#else
switch self {
case .Left, .CenterX: return point.x
case .Top, .CenterY, .Baseline: return point.y
case .Right: return point.x
case .Bottom: return point.y
case .Leading: return point.x
case .Trailing: return point.x
case .Width, .Height, .NotAnAttribute: return CGFloat(0)
case .FirstBaseline: return point.y
}
#endif
}
// EdgeInsets
else if let insets = value as? EdgeInsets {
#if os(iOS) || os(tvOS)
switch self {
case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left
case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return insets.top
case .Right, .RightMargin: return insets.right
case .Bottom, .BottomMargin: return insets.bottom
case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
case .Width: return -insets.left + insets.right
case .Height: return -insets.top + insets.bottom
case .NotAnAttribute: return CGFloat(0)
}
#else
switch self {
case .Left, .CenterX: return insets.left
case .Top, .CenterY, .Baseline: return insets.top
case .Right: return insets.right
case .Bottom: return insets.bottom
case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
case .Width: return -insets.left + insets.right
case .Height: return -insets.top + insets.bottom
case .NotAnAttribute: return CGFloat(0)
case .FirstBaseline: return insets.bottom
}
#endif
}
return CGFloat(0);
}
}
private func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
var views = Set<View>()
var fromView = fromView
var toView = toView
repeat {
if let view = toView {
if views.contains(view) {
return view
}
views.insert(view)
toView = view.superview
}
if let view = fromView {
if views.contains(view) {
return view
}
views.insert(view)
fromView = view.superview
}
} while (fromView != nil || toView != nil)
return nil
}
private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool {
return (left.fromItem == right.fromItem &&
left.toItem == right.toItem &&
left.relation == right.relation &&
left.multiplier == right.multiplier &&
left.priority == right.priority)
}
| apache-2.0 | 3f78f7bfb1c90c590d275396967a3912 | 41.303571 | 172 | 0.606022 | 5.397722 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/NSNumberFormatter+WMFExtras.swift | 2 | 3409 | import Foundation
let thousandsFormatter = { () -> NumberFormatter in
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 1
formatter.roundingMode = .halfUp
return formatter
}()
let threeSignificantDigitWholeNumberFormatterGlobal = { () -> NumberFormatter in
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 0
formatter.usesSignificantDigits = true
formatter.maximumSignificantDigits = 3
formatter.roundingMode = .halfUp
return formatter
}()
extension NumberFormatter {
public class var threeSignificantDigitWholeNumberFormatter: NumberFormatter {
get {
return threeSignificantDigitWholeNumberFormatterGlobal
}
}
public class func localizedThousandsStringFromNumber(_ number: NSNumber) -> String {
let doubleValue = number.doubleValue
let absDoubleValue = abs(doubleValue)
var adjustedDoubleValue: Double = doubleValue
var formatString: String = "%1$@"
if absDoubleValue > 1000000000 {
adjustedDoubleValue = doubleValue/1000000000.0
formatString = WMFLocalizedString("number-billions", value:"%1$@B", comment:"%1$@B - %1$@ is replaced with a number represented in billions. In English 'B' is commonly used after a number to indicate that number is in 'billions'. So the 'B' should be changed to a character or short string indicating billions. For example 5,100,000,000 would become 5.1B. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.")
} else if absDoubleValue > 1000000 {
adjustedDoubleValue = doubleValue/1000000.0
formatString = WMFLocalizedString("number-millions", value:"%1$@M", comment:"%1$@M - %1$@ is replaced with a number represented in millions. In English 'M' is commonly used after a number to indicate that number is in 'millions'. So the 'M' should be changed to a character or short string indicating millions. For example 500,000,000 would become 500M. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown.")
} else if absDoubleValue > 1000 {
adjustedDoubleValue = doubleValue/1000.0
formatString = WMFLocalizedString("number-thousands", value:"%1$@K", comment:"%1$@K - %1$@ is replaced with a number represented in thousands. In English the letter 'K' is commonly used after a number to indicate that number is in 'thousands'. So the letter 'K' should be changed to a character or short string indicating thousands. For example 500,000 would become 500K. If there is no simple translation for this in the target language, make the translation %1$@ with no other characters and the full number will be shown. {{Identical|%1$@k}}")
}
if formatString == "%1$@" { //check for opt-out translations
adjustedDoubleValue = doubleValue
}
if let numberString = thousandsFormatter.string(from: NSNumber(value:adjustedDoubleValue)) {
return String.localizedStringWithFormat(formatString, numberString)
} else {
return ""
}
}
}
| mit | 7b7764e129d720eeeee63b4baa3e33b3 | 56.779661 | 558 | 0.701672 | 5.095665 | false | false | false | false |
toco1001/Sources | Sources/UIView+Extension.swift | 1 | 1138 | //
// UIView+Extension.swift
// Sources
//
// Created by toco on 25/02/17.
// Copyright © 2017 tocozakura. All rights reserved.
//
import UIKit
enum FadeType: TimeInterval {
case
Normal = 0.2,
Slow = 1.0
}
extension UIView {
/** For typical purpose, use "public func fadeIn(type: FadeType = .Normal, completed: (() -> ())? = nil)" instead of this */
func fadeIn(duration: TimeInterval = FadeType.Slow.rawValue, completed: (() -> ())? = nil) {
alpha = 0
isHidden = false
UIView.animate(withDuration: duration, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.alpha = CGFloat(1.0)
}){ finished in
completed?()
}
}
/** For typical purpose, use "public func fadeOut(type: FadeType = .Normal, completed: (() -> ())? = nil)" instead of this */
func fadeOut(duration: TimeInterval = FadeType.Slow.rawValue, completed: (() -> ())? = nil) {
UIView.animate(withDuration: duration
, animations: {
self.alpha = 0
}) { [weak self] finished in
self?.isHidden = true
self?.alpha = 1
completed?()
}
}
}
| mit | 094024f8efc9a6fe1cb0672e30b179ab | 25.44186 | 127 | 0.608619 | 3.867347 | false | false | false | false |
el-hoshino/NotAutoLayout | Playground.playground/Contents.swift | 1 | 2287 | //: Playground - noun: a place where people can play
import PlaygroundSupport
import NotAutoLayout
let controller = IPhoneXScreenController()
controller.rotate(to: .portrait)
PlaygroundPage.current.liveView = controller.view
let appView = LayoutInfoStoredView()
appView.backgroundColor = .white
controller.view.addSubview(appView)
controller.view.nal.layout(appView) { $0
.stickOnParent()
}
let padding: NotAutoLayout.Float = 10
let summaryView = ProfileSummaryView()
let contentsView = ContentsView()
let replyView = ReplyView()
summaryView.avatar = #imageLiteral(resourceName: "avatar.png")
summaryView.mainTitle = "星野恵瑠@今日も1日フレンズ㌠"
summaryView.subTitle = "@lovee"
contentsView.contents = """
Hello, NotAutoLayout!
The new NotAutoLayout 3.0 now has even better syntax which is:
- Easy to write (thanks to method-chain structures)
- Easy to read (thanks to more natural English-like statements)
- Capable with dynamic view sizes (with commands like `fitSize()`)
- Even better closure support to help you set various kinds of layouts with various kinds of properties!
- And one more thing: an experienmental sequencial layout engine!
"""
contentsView.timeStamp = Date()
appView.nal.setupSubview(summaryView) { $0
.setDefaultLayout { $0
.setLeft(by: { $0.layoutMarginsGuide.left })
.setRight(by: { $0.layoutMarginsGuide.right })
.setTop(by: { $0.layoutMarginsGuide.top })
.setHeight(to: 50)
}
.addToParent()
}
appView.nal.setupSubview(contentsView) { $0
.setDefaultLayout({ $0
.setLeft(by: { $0.layoutMarginsGuide.left })
.setRight(by: { $0.layoutMarginsGuide.right })
.pinTop(to: summaryView, with: { $0.bottom + padding })
.fitHeight()
})
.setDefaultOrder(to: 1)
.addToParent()
}
appView.nal.setupSubview(replyView) { $0
.setDefaultLayout({ $0
.setBottomLeft(by: { $0.layoutMarginsGuide.bottomLeft })
.setRight(by: { $0.layoutMarginsGuide.right })
.setHeight(to: 30)
})
.addToParent()
}
let imageViews = (0 ..< 3).map { (_) -> UIImageView in
let image = #imageLiteral(resourceName: "avatar.png")
let view = UIImageView(image: image)
appView.addSubview(view)
return view
}
appView.nal.layout(imageViews) { $0
.setMiddle(by: { $0.vertical(at: 0.7) })
.fitSize()
.setHorizontalInsetsEqualingToMargin()
}
| apache-2.0 | 3a475339e7833a968f34d790499c3db7 | 28.723684 | 105 | 0.736609 | 3.29781 | false | false | false | false |
sauravexodus/RxFacebook | Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/UIScrollView+RxTests.swift | 2 | 8581 | //
// UIScrollView+RxTests.swift
// Tests
//
// Created by Suyeol Jeon on 6/8/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
#if os(iOS)
import RxSwift
import RxCocoa
import UIKit
import XCTest
import RxTest
final class UIScrollViewTests : RxTest {}
extension UIScrollViewTests {
func testScrollEnabled_False() {
let scrollView = UIScrollView()
scrollView.isScrollEnabled = true
Observable.just(false).bind(to: scrollView.rx.isScrollEnabled).dispose()
XCTAssertTrue(scrollView.isScrollEnabled == false)
}
func testScrollEnabled_True() {
let scrollView = UIScrollView(frame: CGRect.zero)
scrollView.isScrollEnabled = false
Observable.just(true).bind(to: scrollView.rx.isScrollEnabled).dispose()
XCTAssertTrue(scrollView.isScrollEnabled == true)
}
func testScrollView_DelegateEventCompletesOnDealloc() {
let createView: () -> UIScrollView = { UIScrollView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) }
ensurePropertyDeallocated(createView, CGPoint(x: 1, y: 1)) { (view: UIScrollView) in view.rx.contentOffset }
}
func testScrollViewDidScroll() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
var didScroll = false
_ = scrollView.rx.didScroll.subscribe(onNext: {
didScroll = true
}, onCompleted: {
completed = true
})
XCTAssertFalse(didScroll)
scrollView.delegate!.scrollViewDidScroll!(scrollView)
XCTAssertTrue(didScroll)
}
XCTAssertTrue(completed)
}
func testScrollViewWillBeginDecelerating() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
var willBeginDecelerating = false
_ = scrollView.rx.willBeginDecelerating.subscribe(onNext: {
willBeginDecelerating = true
}, onCompleted: {
completed = true
})
XCTAssertFalse(willBeginDecelerating)
scrollView.delegate!.scrollViewWillBeginDecelerating!(scrollView)
XCTAssertTrue(willBeginDecelerating)
}
XCTAssertTrue(completed)
}
func testScrollViewDidEndDecelerating() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
var didEndDecelerating = false
_ = scrollView.rx.didEndDecelerating.subscribe(onNext: {
didEndDecelerating = true
}, onCompleted: {
completed = true
})
XCTAssertFalse(didEndDecelerating)
scrollView.delegate!.scrollViewDidEndDecelerating!(scrollView)
XCTAssertTrue(didEndDecelerating)
}
XCTAssertTrue(completed)
}
func testScrollViewWillBeginDragging() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
var willBeginDragging = false
_ = scrollView.rx.willBeginDragging.subscribe(onNext: {
willBeginDragging = true
}, onCompleted: {
completed = true
})
XCTAssertFalse(willBeginDragging)
scrollView.delegate!.scrollViewWillBeginDragging!(scrollView)
XCTAssertTrue(willBeginDragging)
}
XCTAssertTrue(completed)
}
func testScrollViewDidEndDragging() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
var results: [Bool] = []
_ = scrollView.rx.didEndDragging.subscribe(onNext: {
results.append($0)
}, onCompleted: {
completed = true
})
XCTAssertTrue(results.isEmpty)
scrollView.delegate!.scrollViewDidEndDragging!(scrollView, willDecelerate: false)
scrollView.delegate!.scrollViewDidEndDragging!(scrollView, willDecelerate: true)
XCTAssertEqual(results, [false, true])
}
XCTAssertTrue(completed)
}
func testScrollViewContentOffset() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
scrollView.contentOffset = .zero
var contentOffset = CGPoint(x: -1, y: -1)
_ = scrollView.rx.contentOffset.subscribe(onNext: { value in
contentOffset = value
}, onCompleted: {
completed = true
})
XCTAssertEqual(contentOffset, .zero)
scrollView.contentOffset = CGPoint(x: 2, y: 2)
scrollView.delegate!.scrollViewDidScroll!(scrollView)
XCTAssertEqual(contentOffset, CGPoint(x: 2, y: 2))
}
XCTAssertTrue(completed)
}
func testScrollViewDidZoom() {
let scrollView = UIScrollView()
var didZoom = false
let subscription = scrollView.rx.didZoom.subscribe(onNext: {
didZoom = true
})
XCTAssertFalse(didZoom)
scrollView.delegate!.scrollViewDidZoom!(scrollView)
XCTAssertTrue(didZoom)
subscription.dispose()
}
func testScrollToTop() {
let scrollView = UIScrollView()
var didScrollToTop = false
let subscription = scrollView.rx.didScrollToTop.subscribe(onNext: {
didScrollToTop = true
})
XCTAssertFalse(didScrollToTop)
scrollView.delegate!.scrollViewDidScrollToTop!(scrollView)
XCTAssertTrue(didScrollToTop)
subscription.dispose()
}
func testDidEndScrollingAnimation() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
var didEndScrollingAnimation = false
_ = scrollView.rx.didEndScrollingAnimation.subscribe(onNext: {
didEndScrollingAnimation = true
}, onCompleted: {
completed = true
})
XCTAssertFalse(didEndScrollingAnimation)
scrollView.delegate!.scrollViewDidEndScrollingAnimation!(scrollView)
XCTAssertTrue(didEndScrollingAnimation)
}
XCTAssertTrue(completed)
}
func testScrollViewWillBeginZooming() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
let zoomView = UIView()
var results: [UIView?] = []
_ = scrollView.rx.willBeginZooming.subscribe(onNext: { value in
results.append(value)
}, onCompleted: {
completed = true
})
XCTAssertTrue(results.isEmpty)
scrollView.delegate!.scrollViewWillBeginZooming!(scrollView, with: zoomView)
scrollView.delegate!.scrollViewWillBeginZooming!(scrollView, with: nil)
XCTAssertEqual(results[0], zoomView)
XCTAssertNil(results[1])
}
XCTAssertTrue(completed)
}
func testScrollViewDidEndZooming() {
var completed = false
autoreleasepool {
let scrollView = UIScrollView()
let zoomView = UIView()
var viewResults: [UIView?] = []
var scaleResults: [CGFloat] = []
_ = scrollView.rx.didEndZooming.subscribe(onNext: { (view, scale) in
viewResults.append(view)
scaleResults.append(scale)
}, onCompleted: {
completed = true
})
XCTAssertTrue(viewResults.isEmpty)
XCTAssertTrue(scaleResults.isEmpty)
scrollView.delegate!.scrollViewDidEndZooming!(scrollView, with: zoomView, atScale: 0)
scrollView.delegate!.scrollViewDidEndZooming!(scrollView, with: nil, atScale: 2)
XCTAssertEqual(viewResults[0], zoomView)
XCTAssertNil(viewResults[1])
XCTAssertEqual(scaleResults, [0, 2])
}
XCTAssertTrue(completed)
}
}
@objc final class MockScrollViewDelegate
: NSObject
, UIScrollViewDelegate {}
extension UIScrollViewTests {
func testSetDelegateUsesWeakReference() {
let scrollView = UIScrollView()
var delegateDeallocated = false
autoreleasepool {
let delegate = MockScrollViewDelegate()
_ = scrollView.rx.setDelegate(delegate)
_ = delegate.rx.deallocated.subscribe(onNext: { _ in
delegateDeallocated = true
})
XCTAssert(delegateDeallocated == false)
}
XCTAssert(delegateDeallocated == true)
}
}
#endif
| mit | b8dbb372cc8e7eb95f45e790db5e16a9 | 25.728972 | 116 | 0.610956 | 5.571429 | false | true | false | false |
maxim-pervushin/Overlap | Overlap/App/Editors/OverlapEditor.swift | 1 | 1673 | //
// Created by Maxim Pervushin on 29/04/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import Foundation
class OverlapEditor {
// MARK: public
var id: String? {
didSet {
updated?()
}
}
var updated: (Void -> Void)? = nil {
didSet {
connectHandlers()
updated?()
}
}
var overlap: Overlap? {
set {
id = newValue?.id
originalId = newValue?.id
interval1Editor.interval = newValue?.interval1
interval2Editor.interval = newValue?.interval2
}
get {
if let interval1 = interval1Editor.interval, interval2 = interval2Editor.interval {
if let id = id {
return Overlap(id: id, interval1: interval1, interval2: interval2)
} else {
return Overlap(interval1: interval1, interval2: interval2)
}
} else {
return nil
}
}
}
var hasChanges: Bool {
return originalId != id || interval1Editor.hasChanges || interval2Editor.hasChanges
}
private (set) var interval1Editor = IntervalEditor() {
didSet {
connectHandlers()
}
}
private (set) var interval2Editor = IntervalEditor() {
didSet {
connectHandlers()
}
}
// MARK: private
private var originalId: String? = nil {
didSet {
updated?()
}
}
private func connectHandlers() {
interval1Editor.updated = updated
interval2Editor.updated = updated
}
}
| mit | af1ad3f48d5ffc77285ab00aca0ad3ad | 21.917808 | 95 | 0.521817 | 4.766382 | false | false | false | false |
ifeherva/HSTracker | HSTracker/UIs/Preferences/TrackersPreferences.swift | 2 | 6273 | //
// TrackersPreferences.swift
// HSTracker
//
// Created by Benjamin Michotte on 29/02/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import MASPreferences
class TrackersPreferences: NSViewController {
@IBOutlet weak var highlightCardsInHand: NSButton!
@IBOutlet weak var highlightLastDrawn: NSButton!
@IBOutlet weak var removeCards: NSButton!
@IBOutlet weak var showPlayerGet: NSButton!
@IBOutlet weak var highlightDiscarded: NSButton!
@IBOutlet weak var opacity: NSSlider!
@IBOutlet weak var cardSize: NSComboBox!
@IBOutlet weak var showTimer: NSButton!
@IBOutlet weak var autoPositionTrackers: NSButton!
@IBOutlet weak var showSecretHelper: NSButton!
@IBOutlet weak var showRarityColors: NSButton!
@IBOutlet weak var showFloatingCard: NSButton!
@IBOutlet weak var showTopdeckChance: NSButton!
@IBOutlet weak var theme: NSComboBox!
@IBOutlet weak var allowFullscreen: NSButton!
@IBOutlet weak var hideAllWhenNotInGame: NSButton!
@IBOutlet weak var hideAllWhenGameInBackground: NSButton!
@IBOutlet weak var disableTrackingInSpectatorMode: NSButton!
@IBOutlet weak var floatingCardStyle: NSComboBox!
let themes = ["classic", "frost", "dark", "minimal"]
override func viewDidLoad() {
super.viewDidLoad()
highlightCardsInHand.state = Settings.highlightCardsInHand ? .on : .off
highlightLastDrawn.state = Settings.highlightLastDrawn ? .on : .off
removeCards.state = Settings.removeCardsFromDeck ? .on : .off
highlightDiscarded.state = Settings.highlightDiscarded ? .on : .off
opacity.doubleValue = Settings.trackerOpacity
var index: Int
switch Settings.cardSize {
case .tiny: index = 0
case .small: index = 1
case .medium: index = 2
case .big: index = 3
case .huge: index = 4
}
cardSize.selectItem(at: index)
showTimer.state = Settings.showTimer ? .on : .off
autoPositionTrackers.state = Settings.autoPositionTrackers ? .on : .off
showSecretHelper.state = Settings.showSecretHelper ? .on : .off
showRarityColors.state = Settings.showRarityColors ? .on : .off
showFloatingCard.state = Settings.showFloatingCard ? .on : .off
showTopdeckChance.state = Settings.showTopdeckchance ? .on : .off
floatingCardStyle.isEnabled = Settings.showFloatingCard
switch Settings.floatingCardStyle {
case .text: index = 0
case .image: index = 1
}
floatingCardStyle.selectItem(at: index)
theme.selectItem(at: themes.index(of: Settings.theme) ?? 0)
allowFullscreen.state = Settings.canJoinFullscreen ? .on : .off
hideAllWhenNotInGame.state = Settings.hideAllTrackersWhenNotInGame ? .on : .off
hideAllWhenGameInBackground.state = Settings.hideAllWhenGameInBackground
? .on : .off
disableTrackingInSpectatorMode.state = Settings.dontTrackWhileSpectating ? .on : .off
}
@IBAction func sliderChange(_ sender: AnyObject) {
Settings.trackerOpacity = opacity.doubleValue
}
@IBAction func comboboxChange(_ sender: NSComboBox) {
if sender == cardSize {
if let value = cardSize.objectValueOfSelectedItem as? String {
let size: CardSize
switch value {
case NSLocalizedString("Tiny", comment: ""): size = .tiny
case NSLocalizedString("Small", comment: ""): size = .small
case NSLocalizedString("Big", comment: ""): size = .big
case NSLocalizedString("Huge", comment: ""): size = .huge
default: size = .medium
}
Settings.cardSize = size
}
} else if sender == theme {
Settings.theme = themes[theme.indexOfSelectedItem]
}
}
@IBAction func checkboxClicked(_ sender: NSButton) {
if sender == highlightCardsInHand {
Settings.highlightCardsInHand = highlightCardsInHand.state == .on
} else if sender == highlightLastDrawn {
Settings.highlightLastDrawn = highlightLastDrawn.state == .on
} else if sender == removeCards {
Settings.removeCardsFromDeck = removeCards.state == .on
} else if sender == highlightDiscarded {
Settings.highlightDiscarded = highlightDiscarded.state == .on
} else if sender == autoPositionTrackers {
Settings.autoPositionTrackers = autoPositionTrackers.state == .on
if Settings.autoPositionTrackers {
Settings.windowsLocked = true
}
} else if sender == showSecretHelper {
Settings.showSecretHelper = showSecretHelper.state == .on
} else if sender == showRarityColors {
Settings.showRarityColors = showRarityColors.state == .on
} else if sender == showTimer {
Settings.showTimer = showTimer.state == .on
} else if sender == showFloatingCard {
Settings.showFloatingCard = showFloatingCard.state == .on
showTopdeckChance.isEnabled = Settings.showFloatingCard
} else if sender == showTopdeckChance {
Settings.showTopdeckchance = showTopdeckChance.state == .on
} else if sender == allowFullscreen {
Settings.canJoinFullscreen = allowFullscreen.state == .on
} else if sender == hideAllWhenNotInGame {
Settings.hideAllTrackersWhenNotInGame = hideAllWhenNotInGame.state == .on
} else if sender == hideAllWhenGameInBackground {
Settings.hideAllWhenGameInBackground = hideAllWhenGameInBackground.state == .on
} else if sender == disableTrackingInSpectatorMode {
Settings.dontTrackWhileSpectating = disableTrackingInSpectatorMode.state == .on
}
}
}
// MARK: - MASPreferencesViewController
extension TrackersPreferences: MASPreferencesViewController {
var viewIdentifier: String {
return "trackers"
}
var toolbarItemImage: NSImage? {
return NSImage(named: NSImage.Name.advanced)
}
var toolbarItemLabel: String? {
return NSLocalizedString("Trackers", comment: "")
}
}
| mit | 948616034c076f26b7ddd25cc30337bc | 41.666667 | 93 | 0.661033 | 4.751515 | false | false | false | false |
kzin/swift-testing | swift-testing/swift-testing Tests/UserTests.swift | 1 | 2079 | //
// UserTests.swift
// swift-testing
//
// Created by Rodrigo Cavalcante on 03/03/17.
// Copyright © 2017 Rodrigo Cavalcante. All rights reserved.
//
import Nimble
import Quick
@testable import swift_testing
extension User {
static func validJson() -> JsonObject {
return [
"username": "username",
"email": "[email protected]",
"age": 26,
"access": [
"profile": true,
"timeline": true,
"friends": true,
"dashboard": true
]
]
}
}
class UserTests: QuickSpec {
override func spec() {
describe("User") {
var user: User!
var validJson: JsonObject!
beforeEach {
validJson = User.validJson()
}
it("should parse all properties") {
user = User(json: validJson)
expect(user.username) == "username"
expect(user.email) == "[email protected]"
expect(user.age) == 26
expect(user.access.profile) == true
expect(user.access.timeline) == true
expect(user.access.friends) == true
expect(user.access.dashboard) == true
}
it("should not parse for missing username") {
validJson.removeValue(forKey: "username")
user = User(json: validJson)
expect(user).to(beNil())
}
it("should not parse for missing email") {
validJson.removeValue(forKey: "email")
user = User(json: validJson)
expect(user).to(beNil())
}
it("should not parse for missing age") {
validJson.removeValue(forKey: "age")
user = User(json: validJson)
expect(user).to(beNil())
}
}
}
}
| mit | 53c57cc8e4f95ea4d5de97abf9581ba1 | 26.342105 | 61 | 0.450914 | 5.007229 | false | true | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Display information/Sketch on the map/SketchViewController.swift | 1 | 4982 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class SketchViewController: UIViewController {
@IBOutlet var mapView: AGSMapView! {
didSet {
// Add the sketch editor to the map view.
mapView.sketchEditor = sketchEditor
// Start a default sketch editor with the polyline creation mode.
sketchEditor.start(with: nil, creationMode: .polyline)
// Set the map.
mapView.map = AGSMap(basemapStyle: .arcGISLightGrayBase)
// Set the viewpoint.
mapView.setViewpoint(AGSViewpoint(targetExtent: AGSEnvelope(xMin: -10049589.670344, yMin: 3480099.843772, xMax: -10010071.251113, yMax: 3512023.489701, spatialReference: .webMercator())))
}
}
@IBOutlet var addBarButtonItem: UIBarButtonItem!
@IBOutlet var undoBarButtonItem: UIBarButtonItem!
@IBOutlet var redoBarButtonItem: UIBarButtonItem!
@IBOutlet var clearBarButtonItem: UIBarButtonItem!
@IBOutlet var statusLabel: UILabel!
/// The sketch editor to use on the map.
let sketchEditor = AGSSketchEditor()
/// An observer for the toolbar items.
var barItemObserver: NSObjectProtocol!
/// Key value pairs containing the creation modes and their titles.
let creationModes: KeyValuePairs = [
"Arrow": AGSSketchCreationMode.arrow,
"Ellipse": .ellipse,
"FreehandPolygon": .freehandPolygon,
"FreehandPolyline": .freehandPolyline,
"Multipoint": .multipoint,
"Point": .point,
"Polygon": .polygon,
"Polyline": .polyline,
"Rectangle": .rectangle,
"Triangle": .triangle
]
// MARK: - Actions
@IBAction func addGeometryButtonTapped(_ sender: UIBarButtonItem) {
// Create an alert controller for the action sheets.
let alertController = UIAlertController(title: "Select a creation mode", message: nil, preferredStyle: .actionSheet)
// Create an action for each creation mode and add it to the alert controller.
creationModes.forEach { name, mode in
let action = UIAlertAction(title: name, style: .default) { [weak self] _ in
self?.statusLabel.text = "\(name) selected."
self?.sketchEditor.start(with: nil, creationMode: mode)
}
alertController.addAction(action)
}
// Add "cancel" item.
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(cancelAction)
// Present the action sheets when the add button is tapped.
alertController.popoverPresentationController?.barButtonItem = addBarButtonItem
present(alertController, animated: true)
}
@IBAction func undo() {
// Check if there are actions to undo.
guard sketchEditor.undoManager.canUndo else { return }
sketchEditor.undoManager.undo()
}
@IBAction func redo() {
// Check if there are actions to redo.
guard sketchEditor.undoManager.canRedo else { return }
sketchEditor.undoManager.redo()
}
@IBAction func clear() {
self.sketchEditor.clearGeometry()
}
// MARK: - Views
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Add an observer to udate UI when needed.
barItemObserver = NotificationCenter.default.addObserver(forName: .AGSSketchEditorGeometryDidChange, object: sketchEditor, queue: nil, using: { [unowned self] _ in
// Enable/disable UI elements appropriately.
undoBarButtonItem.isEnabled = sketchEditor.undoManager.canUndo
redoBarButtonItem.isEnabled = sketchEditor.undoManager.canRedo
clearBarButtonItem.isEnabled = sketchEditor.geometry.map { !$0.isEmpty } ?? false
})
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if let observer = barItemObserver {
// Remove the observer.
NotificationCenter.default.removeObserver(observer)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["SketchViewController"]
}
}
| apache-2.0 | ff094e0f569de23a851a8aa720c6ad11 | 39.836066 | 199 | 0.659775 | 4.846304 | false | false | false | false |
steelwheels/KiwiControls | Source/Controls/KCTextEditCore.swift | 1 | 6067 | /**
* @file KCTextEditCore.swift
* @brief Define KCTextEditCore class
* @par Copyright
* Copyright (C) 2018-2021 Steel Wheels Project
*/
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
import CoconutData
#if os(iOS)
public protocol NSTextFieldDelegate {
}
#endif
open class KCTextEditCore : KCCoreView, NSTextFieldDelegate
{
public typealias CallbackFunction = (_ str: String) -> Void
#if os(OSX)
@IBOutlet weak var mTextEdit: NSTextField!
#else
@IBOutlet weak var mTextEdit: UITextField!
#endif
private var mIsBold: Bool = false
private var mDecimalPlaces: Int = 0
private var mMinWidth: Int = 40
private var mCurrentValue: CNValue = CNValue.null
public var callbackFunction: CallbackFunction? = nil
public func setup(frame frm: CGRect){
super.setup(isSingleView: true, coreView: mTextEdit)
KCView.setAutolayoutMode(views: [self, mTextEdit])
#if os(OSX)
if let cell = mTextEdit.cell {
cell.wraps = true
cell.isScrollable = false
}
#endif
#if os(OSX)
mTextEdit.delegate = self
mTextEdit.lineBreakMode = .byWordWrapping
#else
mTextEdit.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
#endif
/* Initialize */
self.isEnabled = true
self.isEditable = false
setFormat(isNumber: false, isBold: mIsBold, isEditable: self.isEditable, decimalPlaces: mDecimalPlaces)
mCurrentValue = .stringValue("")
}
public var isBold: Bool {
get { return mIsBold }
set(newval) { mIsBold = newval }
}
public var decimalPlaces: Int {
get { return mDecimalPlaces }
set(newval){ mDecimalPlaces = newval }
}
public var isEditable: Bool {
get {
#if os(OSX)
return mTextEdit.isEditable
#else
return false
#endif
}
set(newval) {
#if os(OSX)
mTextEdit.isEditable = newval
#endif
}
}
public var isEnabled: Bool {
get { return mTextEdit.isEnabled }
set(newval){ mTextEdit.isEnabled = newval }
}
#if os(OSX)
public var preferredTextFieldWidth: CGFloat {
get { return mTextEdit.preferredMaxLayoutWidth }
set(newwidth) { mTextEdit.preferredMaxLayoutWidth = newwidth }
}
#endif
public var font: CNFont? {
get {
return mTextEdit.font
}
set(font){
mTextEdit.font = font
}
}
public var alignment: NSTextAlignment {
get {
#if os(OSX)
return mTextEdit.alignment
#else
return mTextEdit.textAlignment
#endif
}
set(align){
#if os(OSX)
mTextEdit.alignment = align
#else
mTextEdit.textAlignment = align
#endif
}
}
public var text: String {
get {
#if os(OSX)
return mTextEdit.stringValue
#else
if let t = mTextEdit.text {
return t
} else {
return ""
}
#endif
}
set(newval) {
setFormat(isNumber: false, isBold: mIsBold, isEditable: self.isEditable, decimalPlaces: mDecimalPlaces)
setString(string: newval)
mCurrentValue = .stringValue(newval)
}
}
public var number: NSNumber? {
get {
if let val = Double(self.text) {
return NSNumber(value: val)
} else {
return nil
}
}
set(newval){
if let num = newval {
setFormat(isNumber: true, isBold: mIsBold, isEditable: self.isEditable, decimalPlaces: mDecimalPlaces)
setNumber(number: num, decimalPlaces: self.decimalPlaces)
mCurrentValue = .numberValue(num)
}
}
}
#if os(OSX)
open override var intrinsicContentSize: CGSize {
get {
let curnum = mTextEdit.stringValue.count
let newnum = max(curnum, mMinWidth)
let fitsize = mTextEdit.fittingSize
let newwidth: CGFloat
let fontsize = self.fontSize(font: mTextEdit.font)
newwidth = fontsize.width * CGFloat(newnum)
mTextEdit.preferredMaxLayoutWidth = newwidth
return CGSize(width: newwidth, height: fitsize.height)
}
}
#else
open override var intrinsicContentSize: CGSize {
get { return mTextEdit.intrinsicContentSize }
}
#endif
#if os(OSX)
public override var acceptsFirstResponder: Bool { get {
return mTextEdit.acceptsFirstResponder
}}
#endif
public override func becomeFirstResponder() -> Bool {
return mTextEdit.becomeFirstResponder()
}
private func setString(string str: String) {
#if os(OSX)
if self.isEditable {
mTextEdit.placeholderString = str
} else {
mTextEdit.stringValue = str
}
#else
mTextEdit.text = str
#endif
mTextEdit.invalidateIntrinsicContentSize()
}
private func setNumber(number num: NSNumber, decimalPlaces dplaces: Int?) {
let newstr: String
if let dp = dplaces {
if 0 <= dp {
newstr = String(format: "%.*lf", dp, num.doubleValue)
} else {
newstr = "\(num.intValue)"
}
} else {
newstr = "\(num.intValue)"
}
setString(string: newstr)
}
private func setFormat(isNumber num: Bool, isBold bld: Bool, isEditable edt: Bool, decimalPlaces dplace: Int) {
/* Set font */
let font: CNFont
if num {
font = CNFont.monospacedSystemFont(ofSize: CNFont.systemFontSize, weight: .regular)
} else if bld {
font = CNFont.boldSystemFont(ofSize: CNFont.systemFontSize)
} else {
font = CNFont.systemFont(ofSize: CNFont.systemFontSize)
}
mTextEdit.font = font
/* Set attributes */
#if os(OSX)
mTextEdit.isEditable = edt
mTextEdit.usesSingleLineMode = true
if num {
/* For number */
let numform = NumberFormatter()
numform.numberStyle = .decimal
numform.maximumFractionDigits = dplace
numform.minimumFractionDigits = dplace
mTextEdit.formatter = numform
} else {
/* for text */
mTextEdit.formatter = nil
}
#endif
/* Set bezel */
#if os(OSX)
mTextEdit.isBezeled = edt
#else
mTextEdit.borderStyle = edt ? .bezel : .none
#endif
}
#if os(OSX)
public func controlTextDidEndEditing(_ obj: Notification) {
notifyTextDidEndEditing()
}
public func controlTextDidChange(_ obj: Notification) {
notifyTextDidEndEditing()
}
#else
@objc public func textFieldDidChange(_ textEdit: KCTextEdit) {
notifyTextDidEndEditing()
}
#endif
private func notifyTextDidEndEditing() {
if let cbfunc = self.callbackFunction {
cbfunc(self.text)
}
}
}
| lgpl-2.1 | 8ced176e7f7b7274f884b1ae2dfaf35c | 20.902527 | 112 | 0.68749 | 3.211752 | false | false | false | false |
qingtianbuyu/Mono | Moon/Classes/Explore/Model/MNExploreEntityList.swift | 1 | 670 | //
// MNExploreEntityList.swift
// Moon
//
// Created by YKing on 16/5/23.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNExploreEntityList {
var start: Int = 1
var entity_list: [MNExploreEntity]?
func loadExploreEntityList(_ start:String) {
let path = Bundle.main.path(forResource: "05-30-0853.plist", ofType: nil)
let teaDict = NSDictionary(contentsOfFile: path!) as! [String: AnyObject]
// let tea = teaDict["tea"] as! [String: AnyObject]
// let tea = teaDict["morning_tea"] as! [String: AnyObject]
let teaArray = MNTea(dict: teaDict)
entity_list = teaArray.entity_list
}
}
| mit | b1fef4cb5a9efd1e0155ffe0efad4369 | 22 | 79 | 0.652174 | 3.269608 | false | false | false | false |
APUtils/APExtensions | APExtensions/Classes/Storyboard/UISearchView+Storyboard.swift | 1 | 1411 | //
// UISearchView+Storyboard.swift
// APExtensions
//
// Created by Anton Plebanovich on 8.02.22.
// Copyright © 2022 Anton Plebanovich. All rights reserved.
//
import UIKit
private var defaultFontAssociationKey = 0
extension UISearchBar {
private var defaultFont: UIFont? {
get {
return objc_getAssociatedObject(self, &defaultFontAssociationKey) as? UIFont
}
set {
objc_setAssociatedObject(self, &defaultFontAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Scale title font for screen
@available(iOS 13.0, *)
@IBInspectable var fitScreenSize: Bool {
get {
return defaultFont != nil
}
set {
if newValue {
defaultFont = searchTextField.font
searchTextField.font = searchTextField.font?.screenFitFont
} else {
// Restore
if let defaultFont = defaultFont {
searchTextField.font = defaultFont
self.defaultFont = nil
}
}
}
}
/// Makes font scalable depending on device content size category
@available(iOS 13.0, *)
@IBInspectable
var scalable: Bool {
@available(*, unavailable)
get { return false }
set { searchTextField.scalable = newValue }
}
}
| mit | 765bd1599b4e21018d7ac0deab148427 | 26.115385 | 116 | 0.575177 | 5.164835 | false | false | false | false |
lpniuniu/bookmark | bookmark/bookmark/BookListViewController/BookListTableView.swift | 1 | 7614 | //
// BookListTableView.swift
// bookmark
//
// Created by FanFamily on 16/12/14.
// Copyright © 2016年 niuniu. All rights reserved.
//
import UIKit
import SnapKit
import Bulb
import SWTableViewCell
import RealmSwift
import Crashlytics
// what she say
class BookListDidSelectSignal: BulbBoolSignal {
override class func description() -> String {
return "BookList is selected";
}
}
class BookListDidDeselectSignal: BulbBoolSignal {
override class func description() -> String {
return "BookList is not selected";
}
}
class BookListTableView: UITableView, UITableViewDelegate, UITableViewDataSource, SWTableViewCellDelegate {
let cellIdentifier:String = "book_list_cellIdentifier"
var selectIndexPath:IndexPath? = nil
override init(frame:CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
delegate = self
dataSource = self
separatorStyle = .none
register(BookCell.self, forCellReuseIdentifier: cellIdentifier)
showsVerticalScrollIndicator = false
weak var weakSelf = self
Bulb.bulbGlobal().register(BookSavedSignal.signalDefault()) { (data:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in
weakSelf?.isHidden = false
weakSelf?.reloadData()
if weakSelf?.selectIndexPath != nil {
weakSelf?.selectRow(at: weakSelf?.selectIndexPath, animated: true, scrollPosition: .none)
}
if let book = data as? BookData {
Answers.logCustomEvent(withName: "addbook", customAttributes: ["name" : book.name])
}
return true
}
Bulb.bulbGlobal().register(BookChangePageValue.signalDefault()) { (book:Any?, identifier2Signal:[String : BulbSignal]?) -> Bool in
weakSelf?.reloadData()
if weakSelf?.selectIndexPath != nil {
weakSelf?.selectRow(at: weakSelf?.selectIndexPath, animated: true, scrollPosition: .none)
}
return true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let realm = try! Realm()
return realm.objects(BookData.self).filter("done == false").count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:BookCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! BookCell
cell.configureFlatCell(with: UIColor.white, selectedColor: UIColor.greenSea(), roundingCorners:.allCorners)
cell.cornerRadius = 5.0
cell.separatorHeight = 20.0
cell.backgroundColor = backgroundColor
cell.rightUtilityButtons = rightButton() as NSArray as? [Any]
cell.delegate = self
let realm = try! Realm()
if let imageUrl = realm.objects(BookData.self).filter("done == false")[indexPath.row].photoUrl {
let url = URL(string: imageUrl)
if (url?.scheme == "http" || url?.scheme == "https") {
cell.bookImageView.kf.setImage(with: url)
} else {
let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let photoPath = doc?.appendingPathComponent("photos")
cell.bookImageView.image = UIImage(contentsOfFile: (photoPath?.appendingPathComponent((url?.path)!).path)!)
}
}
cell.nameLabel.text = realm.objects(BookData.self).filter("done == false")[indexPath.row].name
cell.pageLabel.text = "\(realm.objects(BookData.self).filter("done == false")[indexPath.row].pageCurrent)/\(realm.objects(BookData.self).filter("done == false")[indexPath.row].pageTotal)"
return cell
}
func swipeableTableViewCell(_ cell: SWTableViewCell!, didTriggerRightUtilityButtonWith index: Int) {
if index == 0 {
let realm = try! Realm()
let bookData = realm.objects(BookData.self).filter("done == false")[(indexPath(for: cell)?.row)!]
try! realm.write({
bookData.done = true
bookData.doneDate = Date()
})
deleteRows(at:[indexPath(for: cell)!], with: .fade)
Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data:nil)
// 加入日历
let now = Date()
let result = realm.objects(BookReadDateData.self).filter("date == %@", now.zeroOfDate)
guard result.count == 0 else {
return
}
let readDate = BookReadDateData()
readDate.date = now.zeroOfDate
try! realm.write({
realm.add(readDate)
})
} else if index == 1 {
let deleteConfirmAlert = UIAlertController(title: "即将删除这本书,是否确认", message: "", preferredStyle: .alert)
deleteConfirmAlert.view.tintColor = UIColor.greenSea()
let confirmAction = UIAlertAction(title: "确认", style: .default, handler: { (action:UIAlertAction) in
let realm = try! Realm()
let object = realm.objects(BookData.self)[(self.indexPath(for: cell)?.row)!]
let doc = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let photoPath = doc?.appendingPathComponent("photos")
try! FileManager.default.removeItem(at: (photoPath?.appendingPathComponent(object.photoUrl!))!)
try! realm.write({
realm.delete(object)
})
self.deleteRows(at:[self.indexPath(for: cell)!], with: .fade)
Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data:nil)
})
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: { (action:UIAlertAction) in
})
deleteConfirmAlert.addAction(confirmAction)
deleteConfirmAlert.addAction(cancelAction)
UIApplication.shared.keyWindow?.rootViewController?.present(deleteConfirmAlert, animated: true, completion: {
})
}
}
func rightButton() -> NSMutableArray {
let buttons:NSMutableArray = []
buttons.sw_addUtilityButton(with: UIColor.turquoise(), title: "阅完")
buttons.sw_addUtilityButton(with: UIColor.red, title: "删除")
return buttons
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectIndexPath = indexPath
let realm = try! Realm()
Bulb.bulbGlobal().fire(BookListDidSelectSignal.signalDefault(), data: realm.objects(BookData.self).filter("done == false")[indexPath.row])
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
selectIndexPath = nil
let realm = try! Realm()
Bulb.bulbGlobal().fire(BookListDidDeselectSignal.signalDefault(), data: realm.objects(BookData.self).filter("done == false")[indexPath.row])
}
}
| mit | 7fceba932715dd7a6e8be0b6b8eae449 | 41.016667 | 195 | 0.614306 | 4.783681 | false | false | false | false |
XavierDK/Coordinator | Demo/AppDelegate.swift | 1 | 1244 | //
// AppDelegate.swift
// Demo
//
// Created by Xavier De Koninck on 27/07/2017.
// Copyright © 2017 PagesJaunes. All rights reserved.
//
import UIKit
import NeoCoordinator
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var appCoordinator: Coordinator!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
/// Create a window manually
window = UIWindow()
/// Init your main navigation controller
let navigationController = UINavigationController()
window?.rootViewController = navigationController
/// Create your main coordinator for your app
// if UIDevice.current.userInterfaceIdiom == .phone {
appCoordinator = AppCoordinator(navigationController: navigationController, parentCoordinator: nil, context: Context(value: ()))
// }
// else {
// appCoordinator = AppCoordinator_iPad(navigationController: navigationController, parentCoordinator: nil, context: Context(value: ()))
// }
/// And start it
try! appCoordinator.start(withCallback: nil)
window?.makeKeyAndVisible()
return true
}
}
| mit | 1dd5f3e4b4087f6ce9b6fb2ef0b8eeb3 | 27.906977 | 142 | 0.712792 | 5.222689 | false | false | false | false |
boyXiong/XWSwiftRefreshT | XWSwiftRefreshT/Footer/XWRefreshAutoFooter.swift | 2 | 5169 | //
// XWRefreshAutoFooter.swift
// XWSwiftRefresh
//
// Created by Xiong Wei on 15/10/6.
// Copyright © 2015年 Xiong Wei. All rights reserved.
// 新浪微博: @爱吃香干炒肉
import UIKit
/** footerView 什么样式都没有的 */
public class XWRefreshAutoFooter: XWRefreshFooter {
//MARK: 公共接口
/** 是否自动刷新(默认为YES) */
public var automaticallyRefresh:Bool = true
/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */
// @available(*, deprecated=1.0, message="Use -automaticallyChangeAlpha instead.")
var appearencePercentTriggerAutoRefresh:CGFloat = 1.0 {
willSet{
self.triggerAutomaticallyRefreshPercent = newValue
}
}
/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */
public var triggerAutomaticallyRefreshPercent:CGFloat = 1.0
//MARK: 重写
//初始化
override public func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if let _ = newSuperview {
if self.hidden == false {
self.scrollView.xw_insertBottom += self.xw_height
}
//设置位置
self.xw_y = self.scrollView.xw_contentH
}else { // 被移除了两种结果,一种是手动移除,一种是父控件消除
//TODO:防止 是 空的
if let realScrollView = self.scrollView {
if self.hidden == false {
realScrollView.xw_insertBottom -= self.xw_height
}
}
}
}
//MARK: 实现父类的接口
override func scrollViewContentSizeDidChange(change: Dictionary<String, AnyObject>?) {
super.scrollViewContentSizeDidChange(change)
//设置位置
self.xw_y = self.scrollView.xw_contentH
}
override func scrollViewContentOffsetDidChange(change: Dictionary<String, AnyObject>?) {
super.scrollViewContentOffsetDidChange(change)
if self.state != XWRefreshState.Idle || !self.automaticallyRefresh || self.xw_y == 0 { return }
if self.scrollView.xw_insertTop + self.scrollView.xw_contentH > self.scrollView.xw_height {
// 内容超过一个屏幕
//TODO: 计算公式,判断是不是在拖在到了底部
if self.scrollView.contentSize.height - self.scrollView.contentOffset.y + self.scrollView.contentInset.bottom + self.xw_height * self.triggerAutomaticallyRefreshPercent - self.xw_height <= self.scrollView.xw_height {
self.beginRefreshing()
}
}
}
override func scrollViewPanStateDidChange(change: Dictionary<String, AnyObject>?) {
super.scrollViewPanStateDidChange(change)
if self.state != XWRefreshState.Idle { return }
//2.1.1 抬起
if self.scrollView.panGestureRecognizer.state == UIGestureRecognizerState.Ended {
// 向上拖拽
func draggingUp(){
//如果是向 上拖拽 刷新
if self.scrollView.contentOffset.y > -self.scrollView.contentInset.top {
beginRefreshing()
}
}
//2.2.1.1 不够一个屏幕的滚动 top + content.height 就是内容显示的高度
if self.scrollView.contentInset.top +
self.scrollView.contentSize.height < self.scrollView.xw_height {
draggingUp()
//2.1.1.2 超出一个屏幕 也就是scrollView的
}else {
//拖拽到了底部
if self.scrollView.contentSize.height - self.scrollView.contentOffset.y + self.scrollView.contentInset.top + self.scrollView.contentInset.bottom == self.scrollView.xw_height {
draggingUp()
}
}
}
}
override var state:XWRefreshState {
didSet{
if state == oldValue { return }
if state == XWRefreshState.Refreshing {
xwDelay(0.5, task: { () -> Void in
self.executeRefreshingCallback()
})
}
}
}
override public var hidden:Bool{
didSet{
//如果之前没有隐藏的现在隐藏了,那么要设置状态和去掉底部区域
if !oldValue && hidden {
self.state = XWRefreshState.Idle
self.scrollView.xw_insertBottom -= self.xw_height
//如果之前是隐藏的,现在没有隐藏了,那么要增加底部区域
}else if oldValue && !hidden {
self.scrollView.xw_insertBottom += self.xw_height
// 设置位置
self.xw_y = self.scrollView.xw_contentH
}
}
}
}
| mit | 06eece579cbfb1ecd0655264aca7c507 | 30.410959 | 228 | 0.555386 | 4.509341 | false | false | false | false |
box/box-ios-sdk | Sources/Sessions/CCGAuth/CCGAuthSession.swift | 1 | 5758 | //
// CCGAuthSession.swift
// BoxSDK
//
// Created by Artur Jankowski on 8/03/2022.
// Copyright © 2022 Box. All rights reserved.
//
import Foundation
/// An authorization session using Client Credentials Grant
public class CCGAuthSession: SessionProtocol, ExpiredTokenHandling {
var authModule: CCGAuthModule
var configuration: BoxSDKConfiguration
var tokenStore: TokenStore
var tokenInfo: TokenInfo?
let authDispatcher = AuthModuleDispatcher()
init(
authModule: CCGAuthModule,
configuration: BoxSDKConfiguration,
tokenInfo: TokenInfo?,
tokenStore: TokenStore
) {
self.authModule = authModule
self.configuration = configuration
self.tokenInfo = tokenInfo
self.tokenStore = tokenStore
}
/// Revokes token
///
/// - Parameter completion: Returns empty result in case of success and an error otherwise.
public func revokeTokens(completion: @escaping Callback<Void>) {
guard let accessToken = tokenInfo?.accessToken else {
completion(.success(()))
return
}
authModule.revokeToken(token: accessToken) { [weak self] result in
guard let self = self else {
return
}
switch result {
case .success:
self.tokenStore.clear { _ in }
self.tokenInfo = nil
completion(.success(()))
case let .failure(error):
completion(.failure(error))
}
}
}
/// Retrieves valid access token
///
/// - Parameter completion: AccessTokenClosure returning either valid access token string or an error.
public func getAccessToken(completion: @escaping AccessTokenClosure) {
// Check if the cached token info is valid, if so just return that access token
if let unwrappedTokenInfo = tokenInfo {
if isValidToken() {
completion(.success(unwrappedTokenInfo.accessToken))
return
}
}
authDispatcher.start { [weak self] done in
guard let self = self else {
completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to get Access Token - CCGAuthSession deallocated"))))
done()
return
}
if let unwrappedTokenInfo = self.tokenInfo {
if self.isValidToken() {
completion(.success(unwrappedTokenInfo.accessToken))
done()
return
}
}
self.authModule.getCCGToken { result in
switch result {
case let .success(tokenInfo):
if tokenInfo.expiresIn < self.configuration.tokenRefreshThreshold {
completion(.failure(BoxAPIAuthError(message: .expiredToken)))
done()
return
}
self.tokenInfo = tokenInfo
self.tokenStore.write(tokenInfo: tokenInfo, completion: { storeResult in
switch storeResult {
case .success:
completion(.success(tokenInfo.accessToken))
case let .failure(error):
completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error)))
}
done()
})
case let .failure(error):
completion(.failure(BoxAPIAuthError(message: .ccgAuthError, error: error)))
done()
}
}
}
}
/// Handles token expiration.
///
/// - Parameter completion: Returns either empty result representing success or error.
public func handleExpiredToken(completion: @escaping Callback<Void>) {
tokenStore.clear { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(BoxAPIAuthError(message: .tokenStoreFailure, error: error)))
}
}
}
/// Downscope the token.
///
/// - Parameters:
/// - scope: Scope or scopes that you want to apply to the resulting token.
/// - resource: Full url path to the file that the token should be generated for, eg: https://api.box.com/2.0/files/{file_id}
/// - sharedLink: Shared link to get a token for.
/// - completion: Returns the success or an error.
public func downscopeToken(
scope: Set<TokenScope>,
resource: String? = nil,
sharedLink: String? = nil,
completion: @escaping TokenInfoClosure
) {
getAccessToken { [weak self] result in
guard let self = self else {
completion(.failure(BoxAPIAuthError(message: .instanceDeallocated("Unable to downscope Token - CCGAuthSession deallocated"))))
return
}
switch result {
case let .success(accessToken):
self.authModule.downscopeToken(parentToken: accessToken, scope: scope, resource: resource, sharedLink: sharedLink, completion: completion)
case let .failure(error):
completion(.failure(error))
}
}
}
}
// MARK: - Private Helpers
private extension CCGAuthSession {
func isValidToken() -> Bool {
if let unwrappedTokenInfo = tokenInfo, unwrappedTokenInfo.expiresAt.timeIntervalSinceNow > configuration.tokenRefreshThreshold {
return true
}
return false
}
}
| apache-2.0 | 5de2e92ffa00db418dfdb6e75dff1ca7 | 34.103659 | 154 | 0.568178 | 5.472433 | false | false | false | false |
nguyenantinhbk77/practice-swift | Networking/Handling Timeouts/Handling Timeouts/ViewController.swift | 2 | 1421 | //
// ViewController.swift
// Handling Timeouts
//
// Created by Domenico Solazzo on 16/05/15.
// License MIT
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/* We have a 15 second timeout for our connection */
let timeout = 15
/* You can choose your own URL here */
let urlAsString = "http://www.apple.com"
let url = NSURL(string: urlAsString)
/* Set the timeout on our request here */
let urlRequest = NSURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: queue) {[weak self]
(response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
/* Now we may have access to the data, but check if an error came back
first or not */
if data.length > 0 && error == nil{
let html = NSString(data: data, encoding: NSUTF8StringEncoding)
println("html = \(html)")
} else if data.length == 0 && error == nil{
println("Nothing was downloaded")
} else if error != nil{
println("Error happened = \(error)")
}
}
}
}
| mit | 1bde7de285b3b0069e731b5a4d58f4da | 30.577778 | 86 | 0.562984 | 4.985965 | false | false | false | false |
rene-dohan/CS-IOS | Renetik/Renetik/Classes/Core/Extensions/Foundation/Dictionary+CSExtension.swift | 1 | 940 | //
// Created by Rene Dohan on 1/24/20.
//
import Foundation
public extension Dictionary {
var isSet: Bool { !isEmpty }
var isNotEmpty: Bool { !isEmpty }
@discardableResult
public mutating func add(_ other: Dictionary) -> Dictionary {
for (k, v) in other { self[k] = v }
return self
}
@discardableResult
public mutating func add(key: Key, value: Value) -> Value {
self[key] = value
return value
}
@discardableResult
public mutating func remove(key: Key) -> Value? {
removeValue(forKey: key)
}
public func toJsonString(formatted: Bool = false) -> String? {
var options: JSONSerialization.WritingOptions = formatted ? [.prettyPrinted] : []
if let theJSONData = try? JSONSerialization.data(withJSONObject: self, options: options) {
return String(data: theJSONData, encoding: .ascii)
}
return nil
}
} | mit | 668b86a6332ed176925ba046b2389d57 | 24.432432 | 98 | 0.621277 | 4.372093 | false | false | false | false |
madson/AppleWatchExamples | WatchApp Extension/GeoipInterfaceController.swift | 1 | 3186 | //
// HaddadInterfaceController.swift
// Examples
//
// Created by Madson Cardoso on 9/28/15.
// Copyright © 2015 Madson. All rights reserved.
//
import WatchKit
import Foundation
import WatchConnectivity
typealias TipoBloco = (NSData?, NSURLResponse?, NSError?) -> (Void)
typealias TipoReply = ([String : AnyObject]) -> (Void)
typealias TipoError = (NSError) -> (Void)
class GeoipInterfaceController: WKInterfaceController, WCSessionDelegate {
@IBOutlet var labelGeoip: WKInterfaceLabel!
@IBOutlet var labelCidade: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
if WCSession.isSupported() {
let sessao = WCSession.defaultSession()
sessao.delegate = self
sessao.activateSession()
}
}
override func willActivate() {
self.getGeoip()
self.getCidade()
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
func getGeoip() {
// Obtendo o ip no watch
self.labelGeoip.setText("Carregando ip...")
let url = NSURL(string: "http://www.telize.com/geoip")
let request = NSURLRequest(URL: url!)
let bloco: TipoBloco = {
(data, response, error) in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
print("json recebido no watch: \(json)")
guard
let ip = json["city"] as? String
else {
print("guard falhou")
return
}
WKInterfaceDevice.currentDevice().playHaptic(.Success)
self.labelGeoip.setText(ip)
}
catch {
print("Aconteceu algum erro na requisição")
}
}
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: bloco)
task.resume()
} // end getGeoip()
func getCidade() {
self.labelCidade.setText("Carregando cidade...")
let blocoReply: TipoReply = {
(response) in
print("dicionario recebido do iphone: \(response)")
guard
let cidade = response["cidade"] as? String
else {
print("guard falhou")
return
}
WKInterfaceDevice.currentDevice().playHaptic(.Success)
self.labelCidade.setText(cidade)
}
let blocoError: TipoError = {
(error) in
print("Aconteceu algum erro na comunicação: \(error)")
}
var dicionario = [String : AnyObject]()
dicionario["solicitacao"] = "cidade"
WCSession.defaultSession().sendMessage(dicionario, replyHandler: blocoReply, errorHandler: blocoError)
}
}
| mit | b089ef6b5814218dbc0dc3f118360e4f | 27.657658 | 122 | 0.536624 | 4.901387 | false | false | false | false |
benlangmuir/swift | test/Distributed/Inputs/EchoActor.swift | 7 | 697 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Distributed
distributed actor Echo /* in the mirror */{
typealias ActorSystem = LocalTestingDistributedActorSystem
distributed func echo(_ input: String) -> String {
return "echo: \(input)"
}
}
| apache-2.0 | 3db8cccecf503f5d2cfaa0cde84c6ecd | 29.304348 | 80 | 0.556671 | 5.162963 | false | false | false | false |
Snail93/iOSDemos | SnailSwiftDemos/SnailSwiftDemos/SmallPoints/ViewControllers/CalendarViewController.swift | 2 | 8466 | //
// CalendarViewController.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2017/7/20.
// Copyright © 2017年 Snail. All rights reserved.
//
import UIKit
class CalendarViewController: CustomViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
@IBOutlet weak var aCollectionView: UICollectionView!
@IBOutlet weak var flowLayout: UICollectionViewFlowLayout!
let sizeWidth = (Width - 11) / 7
var data : [IMonth] = [IMonth]()
var didSelectedDate = ""
var didSelectedBlock : GlobalAnyBlock!
override func viewDidLoad() {
super.viewDidLoad()
initData()
// Do any additional setup after loading the view.
aCollectionView.register(UINib(nibName: "CalendarCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CalendarCollectionViewCell")
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
aCollectionView.showsHorizontalScrollIndicator = false
aCollectionView.register(UINib(nibName: "CalendarCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader.self, withReuseIdentifier: "CalendarCollectionReusableView")
}
func test(date : Date) -> IMonth {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let stringToDate = dateFormatter.string(from: date)
let strArr = stringToDate.components(separatedBy: ["-"])
let iMonth = IMonth()
iMonth.year = strArr[0].toInt()
iMonth.month = strArr[1].toInt()
iMonth.day = strArr[2].toInt()
switch iMonth.month {
case 1:
iMonth.itemCount = 31
break
case 2:
iMonth.itemCount = 28
break
case 3:
iMonth.itemCount = 31
break
case 4:
iMonth.itemCount = 30
break
case 5:
iMonth.itemCount = 31
break
case 6:
iMonth.itemCount = 30
break
case 7:
iMonth.itemCount = 31
break
case 8:
iMonth.itemCount = 31
break
case 9:
iMonth.itemCount = 30
break
case 10:
iMonth.itemCount = 31
break
case 11:
iMonth.itemCount = 30
break
case 12:
iMonth.itemCount = 31
break
default:
print("error")
}
if ((iMonth.year / 400 == 0) || (iMonth.year / 4 == 0 && iMonth.year / 100 != 0)) {
iMonth.itemCount = 29
}
let dateString = "\(iMonth.year)-\(iMonth.month)-\(01)"
let dateFirstIMonth = dateString.covertToDate()
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "EEEE"
let str = dateFormatter1.string(from: dateFirstIMonth)
switch str {
case "星期日":
iMonth.firstDayOfWeek = 0 //7为一个进制 7的话就是0
break
case "星期一":
iMonth.firstDayOfWeek = 1
break
case "星期二":
iMonth.firstDayOfWeek = 2
break
case "星期三":
iMonth.firstDayOfWeek = 3
break
case "星期四":
iMonth.firstDayOfWeek = 4
break
case "星期五":
iMonth.firstDayOfWeek = 5
break
case "星期六":
iMonth.firstDayOfWeek = 6
break
default:
print("error")
}
for i in 0 ..< (iMonth.itemCount + iMonth.firstDayOfWeek) {
let day = IDay()
if i > iMonth.firstDayOfWeek - 1 {
day.day = i - iMonth.firstDayOfWeek + 1
}
if iMonth.month == 8 {
//TODO: - 测试数据
if i > 2 && i < 10 {
day.isShow = true
if i == 4 || i == 5 {
day.ticketCount = 10
}
}
}
iMonth.days.append(day)
}
return iMonth
}
func test2(iMonth : IMonth) -> IMonth{
var iMonthTemp = IMonth()
var dateString = ""
if iMonth.month == 12 {
dateString = "\(iMonth.year + 1)-\(01)-\(01)"
}else {
dateString = "\(iMonth.year)-\(iMonth.month + 1)-\(01)"
}
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd"
let date = dateFormatter1.date(from: dateString)
iMonthTemp = test(date: date!)
return iMonthTemp
}
//MARK: - 初始化数据
func initData() {
let date = Date()
let iMonth = test(date: date)
data.append(iMonth)
let iMonth1 = test2(iMonth: iMonth)
data.append(iMonth1)
let iMonth2 = test2(iMonth: iMonth1)
data.append(iMonth2)
}
//MARK: - 得到服务器数据后再对数据进行处理
func getInternetData() {
}
override func back() {
self.dismiss(animated: true, completion: nil)
}
//MARK: - UICollectionView methods
func numberOfSections(in collectionView: UICollectionView) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let iMonth = data[section]
return iMonth.itemCount + iMonth.firstDayOfWeek
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalendarCollectionViewCell", for: indexPath) as! CalendarCollectionViewCell
let iMonth = data[indexPath.section]
let iDay = iMonth.days[indexPath.row]
if iDay.day > 0 {
if iDay.day == iMonth.day {
cell.infoLabel.text = "今天"
}else {
cell.infoLabel.text = "\(iDay.day)"
}
if iDay.isShow {
if iDay.ticketCount > 0 {
cell.infoDetailLabel.text = "有票"
}else {
cell.infoDetailLabel.text = "无票"
}
}else {
cell.infoDetailLabel.text = ""
}
cell.infoLabel.textColor = iDay.isShow ? UIColor.black : UIColor.gray
cell.lineLabel.isHidden = false
}else {
cell.infoLabel.text = ""
cell.infoDetailLabel.text = ""
cell.lineLabel.isHidden = true
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let iMonth = data[indexPath.section]
let iDay = iMonth.days[indexPath.row]
self.didSelectedBlock?(iMonth,iDay)
self.dismiss(animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "CalendarCollectionReusableView", for: indexPath) as! CalendarCollectionReusableView
let iMonth = data[indexPath.section]
view.infoLabel.text = "\(iMonth.year)-\(iMonth.month)"
return view
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//TODO:Cell的大小
return CGSize(width: sizeWidth, height: sizeWidth)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: 414, height: 30)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 5db094ab13ebe1b15cd30b8937615c08 | 31.181467 | 221 | 0.561488 | 4.970185 | false | false | false | false |
quangpc/HQPagerViewController | HQPagerViewController/Sources/HQPagerViewController.swift | 1 | 6871 | //
// HQPagerViewController.swift
// HQPagerViewController
//
// Created by robert pham on 11/10/16.
// Copyright © 2016 quangpc. All rights reserved.
//
import UIKit
public protocol HQPagerViewControllerDataSource {
func menuViewItemOf(inPager pagerViewController: HQPagerViewController)-> HQPagerMenuViewItemProvider
}
open class HQPagerViewController: UIViewController {
@IBOutlet public weak var menuView: HQPagerMenuView!
@IBOutlet public weak var containerView: UIView!
public var pageViewController: UIPageViewController!
public var viewControllers: [UIViewController]? {
didSet {
setupViewControllers()
}
}
public var nextIndex: Int = 0
public var selectedIndex: Int = 0
override open func viewDidLoad() {
super.viewDidLoad()
setupPageViewController()
setupMenuView()
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Public functions
public func setSelectedIndex(index: Int, animated: Bool) {
menuView.setSelectedIndex(index: index, animated: animated)
selectViewController(atIndex: index, animated: animated)
}
private func setupMenuView() {
menuView.selectedIndex = selectedIndex
menuView.dataSource = self
menuView.delegate = self
}
private func setupPageViewController() {
pageViewController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
pageViewController.view.frame = containerView.bounds
pageViewController.dataSource = self
pageViewController.delegate = self
addChildViewController(pageViewController)
containerView.addSubview(pageViewController.view)
pageViewController.didMove(toParentViewController: self)
// add constrains
pageViewController.view.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
pageViewController.view.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
pageViewController.view.topAnchor.constraint(equalTo: containerView.topAnchor).isActive = true
pageViewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor).isActive = true
self.view.layoutIfNeeded()
}
fileprivate func indexOfViewController(viewController: UIViewController)-> Int? {
if let viewControllers = viewControllers {
for i in 0..<viewControllers.count {
let vc = viewControllers[i]
if vc == viewController {
return i
}
}
}
return nil
}
fileprivate func setupViewControllers() {
if let viewControllers = viewControllers {
menuView.reloadData()
let viewController = viewControllers[selectedIndex]
pageViewController.setViewControllers([viewController], direction: .forward, animated: false, completion: nil)
viewControllers.forEach { if !($0 is HQPagerViewControllerDataSource) { fatalError("Every child view controller must conform to HQPagerViewControllerDataSource") }}
}
}
fileprivate func selectViewController(atIndex index: Int, animated: Bool) {
if let viewControllers = viewControllers {
let oldIndex = selectedIndex
selectedIndex = index
let direction: UIPageViewControllerNavigationDirection = (oldIndex < selectedIndex) ? .forward : .reverse
if index >= 0 && index < viewControllers.count {
let viewController = viewControllers[index]
pageViewController.setViewControllers([viewController], direction: direction, animated: animated, completion: nil)
}
}
}
}
extension HQPagerViewController: HQPagerMenuViewDataSource {
public func numberOfItems(inPagerMenu menuView: HQPagerMenuView) -> Int {
if let viewControllers = viewControllers {
return viewControllers.count
}
return 0
}
public func pagerMenuView(_ menuView: HQPagerMenuView, itemAt index: Int) -> HQPagerMenuViewItemProvider? {
if let viewControllers = viewControllers {
if let viewController = viewControllers[index] as? HQPagerViewControllerDataSource {
return viewController.menuViewItemOf(inPager: self)
}
}
return nil
}
}
extension HQPagerViewController: HQPagerMenuViewDelegate {
public func menuView(_ menuView: HQPagerMenuView, didChangeToIndex index: Int) {
selectViewController(atIndex: index, animated: true)
}
}
extension HQPagerViewController: UIPageViewControllerDataSource {
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let index = indexOfViewController(viewController: viewController) {
if index > 0 {
return viewControllers?[index-1]
}
}
return nil
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let index = indexOfViewController(viewController: viewController) {
if let viewControllers = viewControllers, index < viewControllers.count-1 {
return viewControllers[index+1]
}
}
return nil
}
}
extension HQPagerViewController: UIPageViewControllerDelegate {
public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
if let vc = pendingViewControllers.first, let index = indexOfViewController(viewController: vc) {
self.nextIndex = index
}
}
public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
if let vc = previousViewControllers.first, let previousIndex = indexOfViewController(viewController: vc) {
if self.nextIndex != previousIndex {
if let currentVc = pageViewController.viewControllers?.first {
if let index = indexOfViewController(viewController: currentVc) {
self.selectedIndex = index
menuView.setSelectedIndex(index: index, animated: true)
}
}
}
}
}
self.nextIndex = self.selectedIndex
}
}
| mit | 90857ef6d7e3a2787f165c4be14de4f8 | 39.892857 | 197 | 0.675109 | 5.881849 | false | false | false | false |
zeroc-ice/ice-demos | swift/IceStorm/clock/Sources/Subscriber/main.swift | 1 | 5463 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Foundation
import Ice
import IceStorm
// Automatically flush stdout
setbuf(__stdoutp, nil)
func usage() {
print("Usage: [--batch] [--datagram|--twoway|--ordered|--oneway] [--retryCount count] [--id id] [topic]")
}
class ClockI: Clock {
func tick(time date: String, current _: Ice.Current) throws {
print(date)
}
}
enum Option: String {
case none = ""
case datagram = "--datagram"
case twoway = "--twoway"
case ordered = "--ordered"
case oneway = "--oneway"
}
func run() -> Int32 {
do {
var args = [String](CommandLine.arguments.dropFirst())
signal(SIGTERM, SIG_IGN)
signal(SIGINT, SIG_IGN)
let communicator = try Ice.initialize(args: &args, configFile: "config.sub")
defer {
communicator.destroy()
}
let sigintSource = DispatchSource.makeSignalSource(signal: SIGINT,
queue: DispatchQueue.global())
let sigtermSource = DispatchSource.makeSignalSource(signal: SIGTERM,
queue: DispatchQueue.global())
sigintSource.setEventHandler { communicator.shutdown() }
sigtermSource.setEventHandler { communicator.shutdown() }
sigintSource.resume()
sigtermSource.resume()
args = try communicator.getProperties().parseCommandLineOptions(prefix: "Clock", options: args)
var topicName = "time"
var option: Option = .none
var batch = false
var id: String?
var retryCount: String?
for var i in 0 ..< args.count {
let oldoption = option
if let o = Option(rawValue: args[i]) {
option = o
} else if args[i] == "--batch" {
batch = true
} else if args[i] == "--id" {
i += 1
if i >= args.count {
usage()
return 1
}
id = args[i]
} else if args[i] == "--retryCount" {
i += 1
if i >= args.count {
usage()
return 1
}
retryCount = args[i]
} else if args[i].starts(with: "--") {
usage()
return 1
} else {
topicName = args[i]
i += 1
break
}
if oldoption != option, oldoption != .none {
usage()
return 1
}
}
if retryCount != nil {
if option == .none {
option = .twoway
} else if option != .twoway, option != .ordered {
usage()
return 1
}
}
guard let base = try communicator.propertyToProxy("TopicManager.Proxy"),
let manager = try checkedCast(prx: base, type: IceStorm.TopicManagerPrx.self) else {
print("invalid proxy")
return 1
}
//
// Retrieve the topic.
//
let topic: IceStorm.TopicPrx!
do {
topic = try manager.retrieve(topicName)
} catch is IceStorm.NoSuchTopic {
do {
topic = try manager.create(topicName)
} catch is IceStorm.TopicExists {
print("temporary error. try again.")
return 1
}
}
let adapter = try communicator.createObjectAdapter("Clock.Subscriber")
//
// Add a servant for the Ice object. If --id is used the
// identity comes from the command line, otherwise a UUID is
// used.
//
// id is not directly altered since it is used below to
// detect whether subscribeAndGetPublisher can raise
// AlreadySubscribed.
//
let subId = Ice.Identity(name: id ?? UUID().uuidString, category: "")
var subscriber = try adapter.add(servant: ClockDisp(ClockI()), id: subId)
//
// Activate the object adapter before subscribing.
//
try adapter.activate()
var qos: [String: String] = [:]
if let retryCount = retryCount {
qos["retryCount"] = retryCount
}
//
// Set up the proxy.
//
switch option {
case .datagram:
subscriber = batch ? subscriber.ice_batchDatagram() : subscriber.ice_datagram()
case .ordered:
// Do nothing to the subscriber proxy. Its already twoway.
qos["reliability"] = "ordered"
case .oneway,
.none:
subscriber = batch ? subscriber.ice_batchOneway() : subscriber.ice_oneway()
case .twoway:
// Do nothing to the subscriber proxy. Its already twoway.
break
}
do {
_ = try topic.subscribeAndGetPublisher(theQoS: qos, subscriber: subscriber)
} catch is IceStorm.AlreadySubscribed {
// Must never happen when subscribing with an UUID
precondition(id != nil)
print("reactivating persistent subscriber")
}
communicator.waitForShutdown()
try topic.unsubscribe(subscriber)
return 0
} catch {
print("Error: \(error)\n")
return 1
}
}
exit(run())
| gpl-2.0 | 72467d48abf879887e6740a116b8fd61 | 29.016484 | 109 | 0.508695 | 4.713546 | false | false | false | false |
mmcguill/StrongBox | FavIcon-Swift/DownloadTextOperation.swift | 1 | 1492 | //
// FavIcon
// Copyright © 2016 Leon Breedt
//
// 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;
// Attempts to download the text content for a URL, and returns
// `URLResult.TextDownloaded` as the result if it does.
final class DownloadTextOperation: URLRequestOperation {
override func processResult(_ data: Data?, response: HTTPURLResponse, completion: @escaping (URLResult) -> Void) {
let (mimeType, encoding) = response.contentTypeAndEncoding()
if mimeType == "application/json" || mimeType.hasPrefix("text/") {
if let data = data, let text = String(data: data, encoding: encoding) { // ?? String.Encoding.utf8
completion(.textDownloaded(url: response.url!, text: text, mimeType: mimeType))
} else {
completion(.failed(error: URLRequestError.invalidTextEncoding))
}
} else {
completion(.failed(error: URLRequestError.notPlainText))
}
}
}
| agpl-3.0 | b4bd9196d9225145e9621ae4adf89097 | 41.6 | 118 | 0.688129 | 4.359649 | false | false | false | false |
obrichak/discounts | discounts/Classes/UI/MainMenu/MainMenuView.swift | 1 | 1439 | //
// MainMenuView.swift
// discounts
//
// Created by Alexandr Chernyy on 9/10/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import Foundation
import UIKit
let cellName = "CellIdent"
class MainMenuView: UIView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var owner:UIViewController!
var selectedIndex:Int!
func setupView(categoryIndex:Int)
{
DiscountsManager.sharedManager.loadDataFromJSON("Company")
DiscountsManager.sharedManager.getCompanyWithCategory(categoryIndex)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return DiscountsManager.sharedManager.discountsCategoryArrayData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var cell:DiscountTableViewCell = self.tableView.dequeueReusableCellWithIdentifier(cellName) as DiscountTableViewCell
var tmp_cmp:CompanyObject = DiscountsManager.sharedManager.discountsCategoryArrayData[indexPath.row]
cell.company = tmp_cmp
cell.setupCell()
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
selectedIndex = indexPath.row
owner?.performSegueWithIdentifier("showDiscount", sender: owner)
}
}
| gpl-3.0 | 9c9fa20806b60523de40024b71f78f40 | 29.617021 | 124 | 0.727589 | 5.309963 | false | false | false | false |
dmoroz0v/TouchesWindow | Sources/DMZTouchesWindow/DMZTouchesWindow.swift | 1 | 6497 | //
// DMZTouchesWindow.swift
// DMZTouchesWindowSample
//
// Created by dmoroz0v on 05/11/16.
// Copyright © 2016 DMZ. All rights reserved.
//
import UIKit
// MARK: DMZTouchesWindow
open class DMZTouchesWindow : UIWindow
{
// Color of touch circles. Default is black with 50% opacity
public var dmz_touchesColor: UIColor = UIColor(white: 0, alpha: 0.5)
// Radius of touch circles. Default is 20.0
public var dmz_touchesRadius: CGFloat = 20.0
// Determines visible touch circles. true - touch circles are visible.
// false - touch circles are not visible. Default is false
public var dmz_touchesEnabled: Bool = false {
didSet {
if dmz_touchesEnabled && dmz_views == nil
{
dmz_views = Set<DMZTouchEntity>()
}
else if !dmz_touchesEnabled && dmz_views != nil
{
dmz_views.forEach({ $0.view.removeFromSuperview() })
dmz_views = nil
}
}
}
// Color of touch force circles. Default is nil.
// If is nil, then will light color of dmz_touchesColor
public var dmz_touchesForceColor: UIColor?
// Determines visible touch force circles. true - touch force circles are no visible.
// false - touch force circles are visible. Default is false
public var dmz_touchesForceDisabled: Bool = false
private var dmz_views: Set<DMZTouchEntity>!
open override func sendEvent(_ event: UIEvent)
{
if dmz_views != nil, let allTOuches = event.allTouches
{
var beganTouches = Set<UITouch>()
var endedTouches = Set<UITouch>()
for touch in allTOuches
{
switch (touch.phase) {
case .began:
beganTouches.insert(touch)
case .ended, .cancelled:
endedTouches.insert(touch)
case .moved, .stationary, .regionEntered, .regionMoved, .regionExited:
// do nothing
break
@unknown default:
fatalError()
}
}
dmz_touchesBegan(touches: beganTouches)
dmz_touchesMoved(touches: allTOuches)
dmz_touchesEnded(touches: endedTouches)
}
super.sendEvent(event)
}
private func dmz_touchEntity(forTouch touch: UITouch) -> DMZTouchEntity?
{
for touchEntity in dmz_views
{
if touchEntity.touch == touch
{
return touchEntity
}
}
return nil
}
private func dmz_touchesBegan(touches: Set<UITouch>)
{
for touch in touches
{
var forceColor = dmz_touchesForceColor
if forceColor == nil
{
let alpha = dmz_touchesColor.dmz_alpha
forceColor = dmz_touchesColor.withAlphaComponent(alpha/2)
}
let view = DMZTouchView(radius: dmz_touchesRadius)
view.setCoreColor(dmz_touchesColor)
view.setForceColor(forceColor!)
view.layer.zPosition = CGFloat(Float.greatestFiniteMagnitude)
let touchEntity = DMZTouchEntity(touch: touch, view: view)
dmz_views.insert(touchEntity)
addSubview(view)
}
}
private func dmz_touchesMoved(touches: Set<UITouch>)
{
for touch in touches
{
var forceRadius: CGFloat = 0
if !dmz_touchesForceDisabled && dmz_forceTouchAvailable
{
forceRadius = (touch.force - 0.5) / (touch.maximumPossibleForce - 0.5)
forceRadius = max(0, forceRadius)
}
let touchEntity = dmz_touchEntity(forTouch:touch)!
touchEntity.hasBeenMoved = (touchEntity.hasBeenMoved || (touch.force == 0 && touch.phase == .moved))
touchEntity.view.center = touchEntity.touch.location(in: self)
touchEntity.view.setForceRadius(touchEntity.hasBeenMoved == false ? forceRadius : 0)
}
}
func dmz_touchesEnded(touches: Set<UITouch>)
{
for touch in touches
{
let touchEntity = dmz_touchEntity(forTouch:touch)!
touchEntity.view.removeFromSuperview()
dmz_views.remove(touchEntity)
}
}
}
// MARK: UIColor alpha extension
fileprivate extension UIColor
{
var dmz_alpha: CGFloat
{
return CIColor(color: self).alpha
}
}
// MARK: UIWindow force touch extension
fileprivate extension UIWindow
{
var dmz_forceTouchAvailable: Bool
{
if #available(iOS 9.0, *)
{
return traitCollection.forceTouchCapability == .available
}
return false
}
}
// MARK: DMZTouchView
fileprivate class DMZTouchView : UIView
{
private let core: UIView
private let force: UIView
public init(radius: CGFloat)
{
let frame = CGRect(x: 0, y: 0, width: radius * 2, height: radius * 2)
force = UIView(frame: frame)
force.autoresizingMask = [.flexibleWidth, .flexibleHeight]
force.layer.masksToBounds = true
force.layer.cornerRadius = radius
core = UIView(frame: frame)
core.autoresizingMask = [.flexibleWidth, .flexibleHeight]
core.layer.masksToBounds = true
core.layer.cornerRadius = radius
super.init(frame: frame)
addSubview(force)
addSubview(core)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setCoreColor(_ coreColor: UIColor)
{
core.backgroundColor = coreColor
}
public func setForceColor(_ forceColor: UIColor)
{
force.backgroundColor = forceColor
}
public func setForceRadius(_ forceRadius: CGFloat)
{
let scale = 1.0 + 0.6 * forceRadius
force.transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
// MARK: DMZTouchEntity
fileprivate class DMZTouchEntity: Hashable
{
let touch: UITouch
let view: DMZTouchView
var hasBeenMoved: Bool = false
init(touch: UITouch, view: DMZTouchView) {
self.touch = touch
self.view = view
}
func hash(into hasher: inout Hasher) {
hasher.combine(touch.hashValue)
}
public static func ==(lhs: DMZTouchEntity, rhs: DMZTouchEntity) -> Bool
{
return lhs.touch == rhs.touch
}
}
| mit | a37d28d3e9e87e260b270bedcb82dae4 | 26.179916 | 112 | 0.591749 | 4.333556 | false | false | false | false |
wess/Cargo | Sources/cargo/main.swift | 2 | 536 | import Foundation
import resource
class Goose : Resource, JSONResource {
let firstname = "Wess"
let lastname = "Cope"
let username = Property(.text, validation:[.required])
let birds = Relationship<Goose>(.hasMany)
}
let z = Goose()
z["username"] = "wesscope"
if z.isValid {
print("--- NAME: \(Goose.tableName)")
print("value: \(z["username"])")
print("Properties: \(z.properties)")
print("json: \(z.json)")
print("jsonString: \(z.jsonString)")
} else {
print("Errrrrrrr")
print("Err: \(z.errors)")
}
| mit | e9915b02825d839f851d58256ff24e7d | 22.304348 | 57 | 0.636194 | 3.329193 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/TextElement.swift | 1 | 1994 | //
// TextElement.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 24.4.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// A text element is para is a set of character data that can be used as para content
final class TextElement: ParaContent, Copyable
{
// ATTRIBUTES ------------
var charData: [CharData]
// COMPUTED PROPERTIES ----
var text: String { return CharData.text(of: charData) }
var toUSX: String { return charData.reduce("", { $0 + $1.toUSX }) }
var properties: [String : PropertyValue] { return ["text": charData.value] }
// Whether this text element contains no text whatsoever
var isEmpty: Bool { return charData.forAll { $0.isEmpty } }
// INIT --------------------
init(charData: [CharData] = [])
{
self.charData = charData
}
// Parses a text element from a JSON property set
static func parse(from properties: PropertySet) -> TextElement
{
return TextElement(charData: CharData.parseArray(from: properties["text"].array(), using: CharData.parse))
}
static func empty() -> TextElement
{
return TextElement(charData: [CharData(text: "")])
}
// IMPLEMENTED METHODS ----
func toAttributedString(options: [String : Any]) -> NSAttributedString
{
let attStr = NSMutableAttributedString()
charData.forEach { attStr.append($0.toAttributedString(options: options)) }
return attStr
}
func copy() -> TextElement
{
return TextElement(charData: charData)
}
// OPERATORS ------------
// Combines two text elements into a third text element
// Does not affect the two parameters in any way
static func +(_ left: TextElement, _ right: TextElement) -> TextElement
{
return TextElement(charData: left.charData + right.charData)
}
// OTHER METHODS --------
func emptyCopy() -> TextElement
{
return TextElement(charData: charData.map{ $0.emptyCopy() })
}
func contentEquals(with other: TextElement) -> Bool
{
return charData == other.charData
}
}
| mit | 9b736aedaeb4a0ed15312d2037782800 | 22.174419 | 108 | 0.67436 | 3.552585 | false | false | false | false |
YusukeHosonuma/swift-heredoc | swift-heredoc/Converter.swift | 1 | 3914 | //
// Converter.swift
// swift-heredoc
//
// Created by Yusuke on 2017/03/04.
//
//
import Foundation
typealias Indent = Int
private let RegexBeginComment = Regex("/\\*")!
private let RegexEndComment = Regex("\\*/")!
private let RegexLetString = Regex("let ([0-9A-Za-z]+)\\s*=\\s*\"")!
private let RegexHeredoc = Regex("(\\s*)<< DOC;")!
fileprivate extension String {
var isBeginComment: Bool {
return RegexBeginComment.isMatch(self)
}
var isEndComment: Bool {
return RegexEndComment.isMatch(self)
}
func matchHeredoc() -> Indent? {
guard RegexHeredoc.isMatch(self) else { return nil }
let space = RegexHeredoc.match(self)?._1
return space?.characters.count
}
}
/// 指定されたコード全体を変換したものを返す
///
/// - Parameter string: ソースコード全体
/// - Returns: 変換後のソースコード
func convert(from text: String) -> String {
// コメント中か?
var inComment: Bool = false
// ヒアドキュメントの文字列を記憶
var heredocLines: [String] = []
// ヒアドキュメントのインデント
var indent: Int? = nil
// 変換結果
var results: [String] = []
for line in text.lines() {
// here-docを解析して記録
if inComment {
// ヒアドキュメント開始
if let spaceIndent = line.matchHeredoc() {
indent = spaceIndent
results.append(line)
continue
}
// コメント終了
if line.isEndComment {
inComment = false
results.append(line)
continue
}
// スペーストリム
let trimmed = line.substring(from: line.index(line.startIndex, offsetBy: indent ?? 0))
heredocLines.append(trimmed)
results.append(line)
continue
} else {
// コメント開始
if line.isBeginComment {
inComment = true
results.append(line)
continue
}
// コメントの外に到達してヒアドキュメントが含まれていたら
if !heredocLines.isEmpty {
if let indentSpace = indent, RegexLetString.isMatch(line) {
let variable = RegexLetString.match(line)!._1
// 文字列リテラルに変換
let newLine = convertHeredocToSource(heredocLines,
variable: variable,
indent: indentSpace - 1)
results.append(newLine)
heredocLines = []
indent = nil
continue
}
heredocLines = []
indent = nil
}
}
// その他の行
results.append(line)
}
return String.unlines(results)
}
/// here-docコードから文字列リテラル宣言コードに変換
///
/// - Parameters:
/// - lines: here-docコード
/// - variable: 変数名
/// - indent: インデント
/// - Returns: 変換後のコード
func convertHeredocToSource(_ lines: [String], variable: String, indent: Int?) -> String {
let code = lines
.map{ $0.escapeStringLiteralCharacters() }
.joined(separator: "\\n")
let newLine = "let \(variable) = \"\(code)\""
if let indent = indent {
return newLine.leftPad(indent)
} else {
return newLine
}
}
| apache-2.0 | 70726077f99912a017936f5f68c4a801 | 24.007092 | 98 | 0.478729 | 4.128806 | false | false | false | false |
dclelland/AudioKit | AudioKit/Common/Internals/AKMicrophoneRecorder.swift | 1 | 1503 | //
// AKMicrophoneRecorder.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
import Foundation
/// Simple microphone recorder class
public class AKMicrophoneRecorder {
private var internalRecorder: AVAudioRecorder
private var recordingSession: AVAudioSession
/// Initialize the recorder
///
/// - parameter file: Path to the audio file
/// - parameter settings: File format settings (defaults to WAV)
///
public init(_ file: String, settings: [String: AnyObject] = AudioKit.format.settings) {
self.recordingSession = AVAudioSession.sharedInstance()
do {
try recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)
try recordingSession.setActive(true)
} catch {
print("lacking permission to record!\n")
}
let url = NSURL.fileURLWithPath(file, isDirectory: false)
try! internalRecorder = AVAudioRecorder(URL: url, settings: settings)
}
/// Record audio
public func record() {
if internalRecorder.recording == false {
internalRecorder.prepareToRecord()
internalRecorder.record()
}
}
/// Stop recording
public func stop() {
if internalRecorder.recording == true {
internalRecorder.stop()
}
}
} | mit | 38d0d0c336f32f4a6438ea9c5e0e5da9 | 29.06 | 141 | 0.647803 | 5.364286 | false | false | false | false |
osjup/EasyAPNS | Sources/EasyAPNS/Utils/String+tokenString.swift | 1 | 3801 | //
// String+tokenString.swift
// EasyAPNS
//
// Created by Damian Malarczyk on 31.01.2017.
//
//
import Foundation
import Core
import CTLS
public enum TokenError: Error {
case invalidAuthKey
case invalidTokenString
case errorCreatingTemporaryKeyFile
case dataError
}
extension UnsafeMutablePointer {
func buffer(withLength length: Int) -> [Pointee] {
return (0 ..< length).map {
self[$0]
}
}
}
extension String {
func tokenString() throws -> (privateKey: Bytes, publicKey: Bytes?) {
let fileString = try String(contentsOfFile: self, encoding: .utf8)
let beginPrivateKey = "-----BEGIN PRIVATE KEY-----"
let endPrivateKey = "-----END PRIVATE KEY-----"
guard let privateKeyString = fileString
.among(beginPrivateKey, endPrivateKey)?
.flop(character: " ")
.components(separatedBy: .newlines)
.joined(separator: "")
else {
throw TokenError.invalidTokenString
}
let newKeyContent = "\(beginPrivateKey)\n\(privateKeyString.split(withLength: 64).joined(separator: "\n"))\n\(endPrivateKey)"
let tmpFile = "\(self).tmp"
try newKeyContent.write(toFile: tmpFile, atomically: true, encoding: .utf8)
var pKey = EVP_PKEY_new()
let fp = fopen(tmpFile, "r")
guard fp != nil else {
throw TokenError.errorCreatingTemporaryKeyFile
}
PEM_read_PrivateKey(fp, &pKey, nil, nil)
fclose(fp)
try FileManager.default.removeItem(atPath: tmpFile)
let ecKey = EVP_PKEY_get1_EC_KEY(pKey)
EC_KEY_set_conv_form(ecKey, POINT_CONVERSION_UNCOMPRESSED)
var pub: UnsafeMutablePointer<UInt8>? = nil
let pub_len = i2o_ECPublicKey(ecKey, &pub)
let publicKey: Bytes? = pub?.buffer(withLength: Int(pub_len))
let bn = EC_KEY_get0_private_key(ecKey!)
guard let privKeyBigNum = BN_bn2hex(bn) else {
throw TokenError.dataError
}
let privateKey = "00\(String(validatingUTF8: privKeyBigNum)!)"
var build = privateKey
for _ in 0 ..< 100 {
build += privateKey
}
CRYPTO_free(privKeyBigNum)
EVP_PKEY_free(pKey)
guard let privData = privateKey.hexToData() else {
throw TokenError.dataError
}
return (privData.makeBytes(), publicKey)
}
// http://codereview.stackexchange.com/questions/135424/hex-string-to-bytes-nsdata
func hexToData() -> Data? {
// Convert 0 ... 9, a ... f, A ...F to their decimal value,
// return nil for all other input characters
func decodeNibble(u: UInt16) -> UInt8? {
switch(u) {
case 0x30 ... 0x39:
return UInt8(u - 0x30)
case 0x41 ... 0x46:
return UInt8(u - 0x41 + 10)
case 0x61 ... 0x66:
return UInt8(u - 0x61 + 10)
default:
return nil
}
}
let utf16 = self.utf16
var data = Data(capacity: utf16.count/2)
var i = utf16.startIndex
while i != utf16.endIndex {
guard let
hi = decodeNibble(u: utf16[i]),
let lo = decodeNibble(u: utf16[utf16.index(i, offsetBy: 1)])
else {
return nil
}
var value = hi << 4 + lo
data.append(&value, count: 1)
i = utf16.index(i, offsetBy: 2)
}
return data
}
}
| apache-2.0 | b52c635888fca823ea3cd0b8f837ba6c | 27.578947 | 133 | 0.527493 | 4.228031 | false | false | false | false |
lfaoro/Cast | Carthage/Checkouts/RxSwift/RxCocoa/Common/Observables/NSObject+Rx+CoreGraphics.swift | 1 | 5066 | //
// NSObject+Rx+CoreGraphics.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 7/30/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import CoreGraphics
#if arch(x86_64) || arch(arm64)
let CGRectType = "{CGRect={CGPoint=dd}{CGSize=dd}}"
let CGSizeType = "{CGSize=dd}"
let CGPointType = "{CGPoint=dd}"
#elseif arch(i386) || arch(arm)
let CGRectType = "{CGRect={CGPoint=ff}{CGSize=ff}}"
let CGSizeType = "{CGSize=ff}"
let CGPointType = "{CGPoint=ff}"
#endif
// rx_observe + CoreGraphics
extension NSObject {
public func rx_observe(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial), retainSelf: Bool = true) -> Observable<CGRect?> {
return rx_observe(keyPath, options: options, retainSelf: retainSelf)
.map { (value: NSValue?) in
if let value = value {
if strcmp(value.objCType, CGRectType) != 0 {
return nil
}
var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0)
value.getValue(&typedValue)
return typedValue
}
else {
return nil
}
}
}
public func rx_observe(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial), retainSelf: Bool = true) -> Observable<CGSize?> {
return rx_observe(keyPath, options: options, retainSelf: retainSelf)
.map { (value: NSValue?) in
if let value = value {
if strcmp(value.objCType, CGSizeType) != 0 {
return nil
}
var typedValue = CGSize(width: 0, height: 0)
value.getValue(&typedValue)
return typedValue
}
else {
return nil
}
}
}
public func rx_observe(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial), retainSelf: Bool = true) -> Observable<CGPoint?> {
return rx_observe(keyPath, options: options, retainSelf: retainSelf)
.map { (value: NSValue?) in
if let value = value {
if strcmp(value.objCType, CGPointType) != 0 {
return nil
}
var typedValue = CGPoint(x: 0, y: 0)
value.getValue(&typedValue)
return typedValue
}
else {
return nil
}
}
}
}
#if !DISABLE_SWIZZLING
// rx_observeWeakly + CoreGraphics
extension NSObject {
public func rx_observeWeakly(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial)) -> Observable<CGRect?> {
return rx_observeWeakly(keyPath, options: options)
.map { (value: NSValue?) in
if let value = value {
if strcmp(value.objCType, CGRectType) != 0 {
return nil
}
var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0)
value.getValue(&typedValue)
return typedValue
}
else {
return nil
}
}
}
public func rx_observeWeakly(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial)) -> Observable<CGSize?> {
return rx_observeWeakly(keyPath, options: options)
.map { (value: NSValue?) in
if let value = value {
if strcmp(value.objCType, CGSizeType) != 0 {
return nil
}
var typedValue = CGSize(width: 0, height: 0)
value.getValue(&typedValue)
return typedValue
}
else {
return nil
}
}
}
public func rx_observeWeakly(keyPath: String, options: NSKeyValueObservingOptions = NSKeyValueObservingOptions.New.union(NSKeyValueObservingOptions.Initial)) -> Observable<CGPoint?> {
return rx_observeWeakly(keyPath, options: options)
.map { (value: NSValue?) in
if let value = value {
if strcmp(value.objCType, CGPointType) != 0 {
return nil
}
var typedValue = CGPoint(x: 0, y: 0)
value.getValue(&typedValue)
return typedValue
}
else {
return nil
}
}
}
}
#endif
| mit | e96d3e4495eecd1125ff02c841ecf025 | 36.525926 | 206 | 0.528227 | 5.106855 | false | false | false | false |
zachmokahn/SUV | Sources/SUV/Handle/StreamHandle.swift | 1 | 1613 | public class StreamHandle: HandleType {
public typealias Pointer = UnsafeMutablePointer<UVStreamType>
public let pointer: Pointer
public let loop: Loop
public init<T: HandleType>(_ handle: T) {
self.pointer = UnsafeMutablePointer(handle.pointer)
self.loop = handle.loop
}
public init(_ pointer: Pointer) {
self.pointer = pointer
self.loop = Loop(pointer.memory.loop)
}
public func listen(uv_listen uv_listen: Listen = UVListen, backlog: Backlog = .Max, callback: (StreamHandle, Status) -> Void) -> Status {
self.pointer.memory.data = Cast.toVoid(callback)
return Status(uv_listen(self.pointer, backlog.amount) { stream, status in
let callback: (StreamHandle, Status) -> Void = Cast.fromVoid(stream.memory.data)!
callback(StreamHandle(stream), Status(status))
})
}
public func accept(input: StreamHandle, uv_accept: Accept = UVAccept) -> Status {
return Status(uv_accept(input.pointer, self.pointer))
}
public func read(uv_read_start uv_read_start: ReadStart = UVReadStart, alloc: OnAlloc = .Default, callback: (StreamHandle, Int, Buffer) -> Void) -> Status {
self.pointer.memory.data = Cast.toVoid(callback)
return Status(uv_read_start(self.pointer, alloc.callback) { client, size, buffer in
let callback: (StreamHandle, Int, Buffer) -> Void = Cast.fromVoid(client.memory.data)!
callback(StreamHandle(client), size, Buffer(buffer, buffer.memory.len))
})
}
public func close(uv_close uv_close: Close = UVClose, _ callback: (Handle -> Void)) {
Handle(self).close(uv_close: uv_close) { callback($0) }
}
}
| mit | 5b54c433c927440e7fb04c2f2bbacc30 | 37.404762 | 158 | 0.696218 | 3.649321 | false | false | false | false |
stevewight/DuoKit | DuoKit/DuoImprovement.swift | 1 | 676 | //
// DuoImprovement.swift
// Linguist
//
// Created by Steve on 10/30/16.
// Copyright © 2016 31Labs. All rights reserved.
//
import UIKit
public class DuoImprovement: NSObject {
public var value = 0
public var datetime = Date()
public init?(rawJson:[String:AnyObject]) {
super.init()
if let newValue = rawJson["improvement"] as? Int {
value = newValue
}
if let newDatetime = rawJson["datetime"] as? Int {
let timeInterval = TimeInterval(newDatetime)/1000.0
datetime = Date(
timeIntervalSince1970: timeInterval
)
}
}
}
| mit | b729bea4af0ff94ae969859907c4ed90 | 20.774194 | 63 | 0.561481 | 4.299363 | false | false | false | false |
gbuela/kanjiryokucha | KanjiRyokucha/ReviewEntry.swift | 1 | 1479 | //
// ReviewEntry.swift
// KanjiRyokucha
//
// Created by German Buela on 12/8/16.
// Copyright © 2016 German Buela. All rights reserved.
//
import Foundation
import RealmSwift
enum CardAnswer: Int {
case unanswered = 0
case no = 1
case yes = 2
case easy = 3
case delete = 4
case skip = 5
case hard = 6
// new API accepts strings - keep ints inernally for back compatibility with locally saved answers
var srtingForBackend: String? {
switch self {
case .no:
return "no"
case .yes:
return "yes"
case .easy:
return "easy"
case .delete:
return "delete"
case .skip:
return "skip"
case .hard:
return "hard"
case .unanswered:
return nil
}
}
}
class ReviewEntry : Object {
@objc dynamic var cardId = 0
@objc dynamic var rawAnswer = 0
@objc dynamic var keyword = ""
@objc dynamic var frameNumber = 0
@objc dynamic var strokeCount = 0
@objc dynamic var submitted = false
var cardAnswer: CardAnswer {
get {
if let answer = CardAnswer(rawValue: rawAnswer) {
return answer
} else {
return .unanswered
}
}
set {
rawAnswer = newValue.rawValue
}
}
override static func primaryKey() -> String? {
return "cardId"
}
}
| mit | 6d81e8ef5a06e3277ffe30981e204988 | 21.393939 | 102 | 0.538566 | 4.347059 | false | false | false | false |
hakopako/PKNotification | Demo/Demo/ViewController.swift | 1 | 5689 | //
// ViewController.swift
// PKNotification
//
// Created by hakopako on 2014/12/24.
// Copyright (c) 2014年 hakopako. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var alertButton: UIButton!
@IBOutlet weak var alertButtonOptions: UIButton!
@IBOutlet weak var alertWithTextField: UIButton!
@IBOutlet weak var actionsheetButton: UIButton!
@IBOutlet weak var toastButton: UIButton!
@IBOutlet weak var loadingButton: UIButton!
@IBOutlet weak var successButton: UIButton!
@IBOutlet weak var failedButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
PKNotification.alertCornerRadius = 3
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func alertButtonDown(sender: AnyObject) {
PKNotification.alert(
title: "Success !!",
message: "Foooooooooooooo\nDisplay this default style pop up view.\nBaaaaaar",
items: nil,
cancelButtonTitle: "O K",
tintColor: nil)
}
@IBAction func alertButtonOptionsDown(sender: AnyObject) {
let foo:PKButton = PKButton(title: "Foo",
action: { (messageLabel, items) -> Bool in
NSLog("Foo is clicked.")
return true
},
fontColor: UIColor.purpleColor(),
backgroundColor: nil)
let bar:PKButton = PKButton(title: "Not Dismiss",
action: { (messageLabel, items) -> Bool in
NSLog("Not Dismiss is clicked.")
messageLabel?.text = "not dismiss button is clicked."
return false
},
fontColor: nil,
backgroundColor: nil)
PKNotification.alert(
title: "Notice",
message: "Foooooooooooooo\nDisplay this default style pop up view.\nBaaaaaar",
items: [foo, bar],
cancelButtonTitle: "Cancel",
tintColor: nil)
}
@IBAction func alertWithTextFieldDown(sender: AnyObject) {
let email:UITextField = UITextField()
email.placeholder = "[email protected]"
email.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 1.0, alpha: 1.0)
email.textColor = UIColor.darkGrayColor()
let passwd:UITextField = UITextField()
passwd.placeholder = "password"
passwd.backgroundColor = UIColor(red: 0.95, green: 0.96, blue: 1.0, alpha: 1.0)
passwd.textColor = UIColor.darkGrayColor()
let foo:PKButton = PKButton(title: "Login",
action: { (messageLabel, items) -> Bool in
NSLog("Login is clicked.")
let tmpEmail: UITextField = items[0] as! UITextField //items index number
let tmpPassed: UITextField = items[1] as! UITextField //items index number
NSLog("email = \(tmpEmail.text)")
NSLog("passwd = \(tmpPassed.text)")
if (tmpEmail.text == "" || tmpPassed.text == ""){
messageLabel?.text = "please check email and password again."
tmpEmail.backgroundColor = UIColor(red: 0.95, green: 0.8, blue: 0.8, alpha: 1.0)
tmpPassed.backgroundColor = UIColor(red: 0.95, green: 0.8, blue: 0.8, alpha: 1.0)
return false
}
return true
},
fontColor: UIColor(red: 0, green: 0.55, blue: 0.9, alpha: 1.0),
backgroundColor: nil)
PKNotification.alert(
title: "Login",
message: "Welcome to example.\nThis is a simple login form.",
items: [email, passwd, foo],
cancelButtonTitle: "Cancel",
tintColor: nil)
}
@IBAction func actionsheetButtonDown(sender: AnyObject) {
PKNotification.actionSheetCornerRadius = 3
let foo:PKButton = PKButton(title: "Foo",
action: { (m, i) -> Bool in
NSLog("Foo is clicked.")
return true
},
fontColor: UIColor(red: 0, green: 0.55, blue: 0.9, alpha: 1.0),
backgroundColor: nil)
let bar:PKButton = PKButton(title: "Bar",
action: { (m, i) -> Bool in
NSLog("Bar is clicked.")
return true
},
fontColor: UIColor.purpleColor(),
backgroundColor: nil)
PKNotification.actionSheet(
title: "Title",
items: [foo, bar],
cancelButtonTitle: "Cancel",
tintColor: nil)
}
@IBAction func toastButtonDown(sender: AnyObject) {
PKNotification.toastBackgroundColor = UIColor.purpleColor()
PKNotification.toast("hogehogehogehoge")
}
@IBAction func loadingButtonDown(sender: AnyObject) {
PKNotification.loading(true)
NSLog("start loading...")
NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector:"onUpdate:", userInfo: nil, repeats: false)
}
func onUpdate(timer: NSTimer) {
NSLog("finish loading...")
PKNotification.loading(false)
}
@IBAction func successButtonDown(sender: AnyObject) {
PKNotification.successBackgroundColor = UIColor(red: 0, green: 0.55, blue: 0.9, alpha: 1.0)
PKNotification.success(nil)
}
@IBAction func failedButtonDown(sender: AnyObject) {
PKNotification.failed("Failed ...")
}
}
| mit | 4dec9c6418d6823e7f585b559359a20c | 34.322981 | 118 | 0.576051 | 4.631107 | false | false | false | false |
L3-DANT/findme-app | Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift | 2 | 2061 | //
// PCBM.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/03/16.
// Copyright © 2016 Marcin Krzyzanowski. All rights reserved.
//
// Propagating Cipher Block Chaining (PCBC)
//
struct PCBCModeEncryptGenerator: BlockModeGenerator {
typealias Element = Array<UInt8>
let options: BlockModeOptions = [.InitializationVectorRequired, .PaddingRequired]
private let iv: Element
private let inputGenerator: AnyGenerator<Element>
private let cipherOperation: CipherOperationOnBlock
private var prevCiphertext: Element?
init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock, inputGenerator: AnyGenerator<Array<UInt8>>) {
self.iv = iv
self.cipherOperation = cipherOperation
self.inputGenerator = inputGenerator
}
mutating func next() -> Element? {
guard let plaintext = inputGenerator.next(),
let encrypted = cipherOperation(block: xor(prevCiphertext ?? iv, plaintext))
else {
return nil
}
self.prevCiphertext = xor(plaintext, encrypted)
return encrypted
}
}
struct PCBCModeDecryptGenerator: BlockModeGenerator {
typealias Element = Array<UInt8>
let options: BlockModeOptions = [.InitializationVectorRequired, .PaddingRequired]
private let iv: Element
private let inputGenerator: AnyGenerator<Element>
private let cipherOperation: CipherOperationOnBlock
private var prevCiphertext: Element?
init(iv: Array<UInt8>, cipherOperation: CipherOperationOnBlock, inputGenerator: AnyGenerator<Element>) {
self.iv = iv
self.cipherOperation = cipherOperation
self.inputGenerator = inputGenerator
}
mutating func next() -> Element? {
guard let ciphertext = inputGenerator.next(),
let decrypted = cipherOperation(block: ciphertext)
else {
return nil
}
let plaintext = xor(prevCiphertext ?? iv, decrypted)
self.prevCiphertext = xor(plaintext, ciphertext)
return plaintext
}
} | mit | 45d04e6c9dd0020a91b60acdbe47aa79 | 30.227273 | 113 | 0.68932 | 4.916468 | false | false | false | false |
GEOSwift/GEOSwift | Sources/GEOSwift/GEOS/GEOSObject.swift | 2 | 1891 | import geos
public enum GEOSObjectType {
case point
case lineString
case linearRing
case polygon
case multiPoint
case multiLineString
case multiPolygon
case geometryCollection
}
protocol GEOSObjectInitializable {
init(geosObject: GEOSObject) throws
}
protocol GEOSObjectConvertible {
func geosObject(with context: GEOSContext) throws -> GEOSObject
}
final class GEOSObject {
let context: GEOSContext
let pointer: OpaquePointer
var parent: GEOSObject? {
didSet {
// make sure we're not mixing objects from different contexts
precondition(parent == nil || parent?.context === context)
}
}
init(context: GEOSContext, pointer: OpaquePointer) {
self.context = context
self.pointer = pointer
}
init(parent: GEOSObject, pointer: OpaquePointer) {
self.context = parent.context
self.pointer = pointer
self.parent = parent
}
deinit {
if parent == nil {
GEOSGeom_destroy_r(context.handle, pointer)
}
}
var type: GEOSObjectType? {
// returns negative upon error
let value = GEOSGeomTypeId_r(context.handle, pointer)
guard value >= 0 else {
return nil
}
switch GEOSGeomTypes(UInt32(value)) {
case GEOS_POINT:
return .point
case GEOS_LINESTRING:
return .lineString
case GEOS_LINEARRING:
return .linearRing
case GEOS_POLYGON:
return .polygon
case GEOS_MULTIPOINT:
return .multiPoint
case GEOS_MULTILINESTRING:
return .multiLineString
case GEOS_MULTIPOLYGON:
return .multiPolygon
case GEOS_GEOMETRYCOLLECTION:
return .geometryCollection
default:
return nil
}
}
}
| mit | acb42b95e123a56f98255a7bd405705f | 23.881579 | 73 | 0.606557 | 4.873711 | false | false | false | false |
mspegagne/ToDoReminder-iOS | ToDoReminder/ToDoReminder/ToDoController.swift | 1 | 3982 | //
// ToDoController.swift
// ToDoReminder
//
// Created by Mathieu Spegagne on 05/04/2015.
// Copyright (c) 2015 Mathieu Spegagne. All rights reserved.
//
import UIKit
import CoreData
class ToDoController: UITableViewController, NSFetchedResultsControllerDelegate {
var log = [ToDo]()
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
override func viewWillAppear(animated: Bool) {
super.viewDidLoad()
fetchLog()
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func fetchLog() {
let fetchRequest = NSFetchRequest(entityName: "ToDo")
let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [ToDo] {
log = fetchResults
}
}
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
func taskFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "ToDo")
let sortDescriptor = NSSortDescriptor(key: "title", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return log.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let task = fetchedResultController.objectAtIndexPath(indexPath) as ToDo
cell.textLabel?.text = task.title
cell.detailTextLabel?.text = task.text
if task.history.boolValue{
cell.accessoryType = .Checkmark
}
else{
cell.accessoryType = .None
}
return cell
}
func controllerDidChangeContent(controller: NSFetchedResultsController!) {
tableView.reloadData()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
var tappedItem: ToDo = self.log[indexPath.row] as ToDo
tappedItem.history = !tappedItem.history.boolValue
var error : NSError?
if !self.managedObjectContext!.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
tableView.reloadData()
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as NSManagedObject
managedObjectContext?.deleteObject(managedObject)
managedObjectContext?.save(nil)
tableView.dataSource = self;
self.fetchLog()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
| mit | fbac5f15c4d0e73fa6b35b484285ff9d | 32.183333 | 180 | 0.655701 | 6.38141 | false | false | false | false |
inoity/nariko | Nariko/Classes/Extensions.swift | 1 | 3341 |
//
// Extensions.swift
// Nariko
//
// Created by Zsolt Papp on 14/06/16.
// Copyright © 2016 Nariko. All rights reserved.
import Foundation
import UIKit
extension UIColor{
class var gradTop: UIColor{
return UIColor(red: 1.0/255.0, green: 54.0/255.0, blue: 94.0/255.0, alpha: 1.0)
}
class var gradBottom: UIColor{
return UIColor(red: 84.0/255.0, green: 203.0/255.0, blue: 103.0/255.0, alpha: 1.0)
}
}
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
extension String {
var parseJSONString: AnyObject? {
let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
if let jsonData = data {
do{
return try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject?
} catch {
print("error")
return nil
}
} else {
return nil
}
}
}
| mit | f075544d67f4c2c861a6b569d4f7995b | 39.240964 | 146 | 0.491617 | 3.901869 | false | false | false | false |
thisfin/IconfontPreview | IconfontPreview/AppDelegate.swift | 1 | 4782 | //
// AppDelegate.swift
// IconfontPreview
//
// Created by wenyou on 2017/1/7.
// Copyright © 2017年 wenyou. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject {
fileprivate var hasOpenFile = false
}
extension AppDelegate: NSApplicationDelegate {
// 自定义的 NSDocumentController 在此初始化, 因为是单例, 之后 NSDocumentController.shared() / DocumentController.shared() 效果一样
func applicationWillFinishLaunching(_ notification: Notification) {
_ = DocumentController.shared
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
// 菜单
NSApp.mainMenu = NSMenu().next {
$0.addItem(NSMenuItem().next {
$0.submenu = NSMenu().next {
$0.addItem(withTitle: "About \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.orderFrontStandardAboutPanel(_:)), keyEquivalent: "")
$0.addItem(NSMenuItem.separator())
$0.addItem(withTitle: "Hide \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.hide(_:)), keyEquivalent: "h")
$0.addItem(NSMenuItem(title: "Hide Others", action: #selector(NSApp.hideOtherApplications(_:)), keyEquivalent: "h").next {
$0.keyEquivalentModifierMask = [.command, .option]
})
$0.addItem(withTitle: "Show All", action: #selector(NSApp.unhideWithoutActivation), keyEquivalent: "")
$0.addItem(NSMenuItem.separator())
$0.addItem(withTitle: "Quit \(ProcessInfo.processInfo.processName)", action: #selector(NSApp.terminate(_:)), keyEquivalent: "q")
}
})
$0.addItem(NSMenuItem().next {
$0.submenu = NSMenu(title: "File").next {
$0.addItem(withTitle: "Open…", action: #selector(NSDocumentController.openDocument(_:)), keyEquivalent: "o")
/* 这个地方不知道系统自动做了什么处理, 人肉添加的 menu 并不会动态做 recent 的增删, 以后再搞吧.
view 和 close window 两个 menu 系统会自动做处理. 此外, 通过 storyboard 生成的 open recent submenu 会被加上 delegate, 可以通过这个跟踪下
$0.addItem(NSMenuItem(title: "Open Recent", action: nil, keyEquivalent: "").next {
$0.submenu = NSMenu().next {
$0.addItem(withTitle: "Clear Menu", action: #selector(NSDocumentController.clearRecentDocuments(_:)), keyEquivalent: "")
}
})*/
$0.addItem(NSMenuItem.separator())
$0.addItem(withTitle: "Close Window", action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w") // 这个地方根据窗口变化系统会自己添加
}
})
$0.addItem(NSMenuItem().next {
$0.submenu = NSMenu(title: "View")
})
$0.addItem(NSMenuItem().next {
$0.submenu = NSMenu(title: "Window").next {
$0.addItem(withTitle: "Minimize", action: #selector(NSWindow.performMiniaturize(_:)), keyEquivalent: "m")
$0.addItem(withTitle: "Zoom", action: #selector(NSWindow.performZoom(_:)), keyEquivalent: "")
$0.addItem(NSMenuItem.separator())
$0.addItem(withTitle: "Merge All Windows", action: #selector(NSWindow.mergeAllWindows(_:)), keyEquivalent: "")
$0.addItem(NSMenuItem.separator())
$0.addItem(withTitle: "Bring All to Front", action: #selector(NSApp.arrangeInFront(_:)), keyEquivalent: "")
}
})
}
// 启动时候打开文件选择 panel
if !hasOpenFile {
NSDocumentController.shared.openDocument(self)
}
}
// 当 window 都关闭的时候, 显示文件选择菜单
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
// NSDocumentController.shared().openDocument(self)
// return false
if #available(OSX 10.13, *) { // 10.13 时, panel open 的时候会触发 LastWindowClosed, 正式版本出来后再观察
return false
}
return true
}
// finder 中右键打开, 执行顺序在 applicationDidFinishLaunching 前, 通过一个标志位来做空页面的传递
func application(_ sender: NSApplication, openFile filename: String) -> Bool {
hasOpenFile = true
NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filename), display: true) { _, _, _ in
}
return true
}
}
| mit | d44e16f71acd8c6c0a92122a98b165e6 | 48.211111 | 167 | 0.591781 | 4.561277 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/System/Floating Create Button/FloatingActionButton.swift | 1 | 1396 | /// A rounded button with a shadow intended for use as a "Floating Action Button"
class FloatingActionButton: UIButton {
private var shadowLayer: CALayer?
private enum Constants {
static let shadowColor: UIColor = UIColor.gray(.shade20)
static let shadowRadius: CGFloat = 3
}
convenience init(image: UIImage) {
self.init(frame: .zero)
setImage(image, for: .normal)
}
override init(frame: CGRect) {
super.init(frame: frame)
layer.backgroundColor = UIColor.primary.cgColor
tintColor = .white
refreshShadow()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
super.draw(rect)
layer.cornerRadius = rect.size.width / 2
}
private func refreshShadow() {
layer.shadowColor = Constants.shadowColor.cgColor
layer.shadowOffset = .zero
layer.shadowRadius = Constants.shadowRadius
if #available(iOS 12.0, *) {
layer.shadowOpacity = traitCollection.userInterfaceStyle == .light ? 1 : 0
} else {
layer.shadowOpacity = 1
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
refreshShadow()
}
}
| gpl-2.0 | 0b79d639f2fa8d98ca8b9c65916e009e | 26.92 | 91 | 0.638968 | 4.932862 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageGraph/Pubgrub/Term.swift | 2 | 6806 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A term represents a statement about a package that may be true or false.
public struct Term: Equatable, Hashable {
public let node: DependencyResolutionNode
public let requirement: VersionSetSpecifier
public let isPositive: Bool
public init(node: DependencyResolutionNode, requirement: VersionSetSpecifier, isPositive: Bool) {
self.node = node
self.requirement = requirement
self.isPositive = isPositive
}
public init(_ node: DependencyResolutionNode, _ requirement: VersionSetSpecifier) {
self.init(node: node, requirement: requirement, isPositive: true)
}
/// Create a new negative term.
public init(not node: DependencyResolutionNode, _ requirement: VersionSetSpecifier) {
self.init(node: node, requirement: requirement, isPositive: false)
}
/// The same term with an inversed `isPositive` value.
public var inverse: Term {
return Term(
node: node,
requirement: requirement,
isPositive: !isPositive)
}
/// Check if this term satisfies another term, e.g. if `self` is true,
/// `other` must also be true.
public func satisfies(_ other: Term) -> Bool {
// TODO: This probably makes more sense as isSatisfied(by:) instead.
guard self.node == other.node else { return false }
return self.relation(with: other) == .subset
}
/// Create an intersection with another term.
public func intersect(with other: Term) -> Term? {
guard self.node == other.node else { return nil }
return intersect(withRequirement: other.requirement, andPolarity: other.isPositive)
}
/// Create an intersection with a requirement and polarity returning a new
/// term which represents the version constraints allowed by both the current
/// and given term.
///
/// - returns: `nil` if an intersection is not possible.
public func intersect(
withRequirement requirement: VersionSetSpecifier,
andPolarity otherIsPositive: Bool
) -> Term? {
let lhs = self.requirement
let rhs = requirement
let intersection: VersionSetSpecifier?
let isPositive: Bool
switch (self.isPositive, otherIsPositive) {
case (false, false):
intersection = lhs.union(rhs)
isPositive = false
case (true, true):
intersection = lhs.intersection(rhs)
isPositive = true
case (true, false):
intersection = lhs.difference(rhs)
isPositive = true
case (false, true):
intersection = rhs.difference(lhs)
isPositive = true
}
guard let versionIntersection = intersection, versionIntersection != .empty else {
return nil
}
return Term(node: node, requirement: versionIntersection, isPositive: isPositive)
}
public func difference(with other: Term) -> Term? {
return self.intersect(with: other.inverse)
}
/// Verify if the term fulfills all requirements to be a valid choice for
/// making a decision in the given partial solution.
/// - There has to exist a positive derivation for it.
/// - There has to be no decision for it.
/// - The package version has to match all assignments.
public func isValidDecision(for solution: PartialSolution) -> Bool {
for assignment in solution.assignments where assignment.term.node == node {
assert(!assignment.isDecision, "Expected assignment to be a derivation.")
guard satisfies(assignment.term) else { return false }
}
return true
}
// From: https://github.com/dart-lang/pub/blob/master/lib/src/solver/term.dart
public func relation(with other: Term) -> SetRelation {
if self.node != other.node {
assertionFailure("attempting to compute relation between different packages \(self) \(other)")
return .error
}
if other.isPositive {
if self.isPositive {
// If the second requirement contains all the elements of
// the first requirement, then it is a subset relation.
if other.requirement.containsAll(self.requirement) {
return .subset
}
// If second requirement contains any requirements of
// the first, then the relation is overlapping.
if other.requirement.containsAny(self.requirement) {
return .overlap
}
// Otherwise it is disjoint.
return .disjoint
} else {
if self.requirement.containsAll(other.requirement) {
return .disjoint
}
return .overlap
}
} else {
if self.isPositive {
if !other.requirement.containsAny(self.requirement) {
return .subset
}
if other.requirement.containsAll(self.requirement) {
return .disjoint
}
return .overlap
} else {
if self.requirement.containsAll(other.requirement) {
return .subset
}
return .overlap
}
}
}
public enum SetRelation: Equatable {
/// The sets have nothing in common.
case disjoint
/// The sets have elements in common but first set is not a subset of second.
case overlap
/// The second set contains all elements of the first set.
case subset
// for error condition
case error
}
}
extension Term: CustomStringConvertible {
public var description: String {
let pkg = "\(node)"
let req = requirement.description
if !isPositive {
return "¬\(pkg) \(req)"
}
return "\(pkg) \(req)"
}
}
fileprivate extension VersionSetSpecifier {
func containsAll(_ other: VersionSetSpecifier) -> Bool {
return self.intersection(other) == other
}
func containsAny(_ other: VersionSetSpecifier) -> Bool {
return self.intersection(other) != .empty
}
}
| apache-2.0 | 472d4c97ab48f19d3cc4f715309f87e6 | 35.196809 | 106 | 0.592506 | 5.07079 | false | false | false | false |
abunur/quran-ios | Quran/TranslationTextTypeSelectionTableViewController.swift | 1 | 3355 | //
// TranslationTextTypeSelectionTableViewController.swift
// Quran
//
// Created by Mohamed Afifi on 6/19/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import GenericDataSources
import UIKit
private class TableViewCell: UITableViewCell {
static let font = UIFont.systemFont(ofSize: 17)
let label: UILabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
private func setUp() {
contentView.addAutoLayoutSubview(label)
contentView.pinParentAllDirections(label, leadingValue: 15, trailingValue: 15, topValue: 0, bottomValue: 0)
}
}
private class DataSource: BasicDataSource<String, TableViewCell> {
var selectedIndex: Int?
override func ds_collectionView(_ collectionView: GeneralCollectionView,
configure cell: TableViewCell,
with item: String,
at indexPath: IndexPath) {
cell.label.text = item
cell.accessoryType = indexPath.item == selectedIndex ? .checkmark : .none
}
}
class TranslationTextTypeSelectionTableViewController: UITableViewController {
private let dataSource = DataSource()
var selectionChanged: ((Int) -> Void)?
var retainedPopoverPresentationHandler: UIPopoverPresentationControllerDelegate? {
didSet {
popoverPresentationController?.delegate = retainedPopoverPresentationHandler
}
}
init(selectedIndex: Int?, items: [String]) {
super.init(style: .plain)
dataSource.selectedIndex = selectedIndex
dataSource.items = items
let block = BlockSelectionHandler<String, TableViewCell>()
dataSource.setSelectionHandler(block)
block.didSelectBlock = { [weak self] (_, _, indexPath) in
self?.selectionChanged?(indexPath.item)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
popoverPresentationController?.backgroundColor = .white
view.backgroundColor = .white
tableView.ds_register(cellClass: TableViewCell.self)
tableView.ds_useDataSource(dataSource)
tableView.rowHeight = 44
let itemsWidths = dataSource.items.map { $0.size(withFont: TableViewCell.font).width }
let width = unwrap(itemsWidths.max()) + 70
let height = tableView.rowHeight * CGFloat(dataSource.items.count)
preferredContentSize = CGSize(width: width, height: height)
}
}
| gpl-3.0 | fb4f165a56785925ef56722577e2564f | 34.691489 | 115 | 0.677198 | 4.904971 | false | false | false | false |
mayasaxena/corner-judge-trainer-web | Sources/App/Models/Match/Match+JSON.swift | 1 | 1785 | //
// Match+JSON.swift
// corner-judge-trainer-webPackageDescription
//
// Created by Maya Saxena on 12/12/17.
//
import JSON
import Vapor
extension Match: JSONConvertible {
private struct JSONKey {
static let id = "id"
static let type = "type"
static let date = "date"
static let red = "red"
static let blue = "blue"
static let name = "name"
static let score = "score"
static let penalties = "penalties"
}
public convenience init(json: JSON) throws {
let id: Int? = try? json.get(JSONKey.id)
do {
let redName: String = try json.get("\(JSONKey.red)-\(JSONKey.name)")
let blueName: String = try json.get("\(JSONKey.blue)-\(JSONKey.name)")
let type: MatchType? = try json.get(path: [JSONKey.type]) { MatchType(rawValue: $0) }
self.init(id: id, redPlayerName: redName, bluePlayerName: blueName, type: type)
} catch {
throw Abort.badRequest
}
}
public func makeJSON() throws -> JSON {
var json = JSON()
try json.set(JSONKey.id, id)
try json.set(JSONKey.type, type.rawValue)
try json.set(JSONKey.date, date.timeIntervalSince1970)
var redJSON = JSON()
try redJSON.set(JSONKey.name, redPlayer.displayName.uppercased())
try redJSON.set(JSONKey.score, redScore)
try redJSON.set(JSONKey.penalties, redPenalties)
try json.set(JSONKey.red, redJSON)
var blueJSON = JSON()
try blueJSON.set(JSONKey.name, bluePlayer.displayName.uppercased())
try blueJSON.set(JSONKey.score, blueScore)
try blueJSON.set(JSONKey.penalties, bluePenalties)
try json.set(JSONKey.blue, blueJSON)
return json
}
}
| mit | f3a654c9a2b85ea57382ff8bfcf67964 | 30.875 | 97 | 0.612885 | 3.765823 | false | false | false | false |
lorentey/GlueKit | Sources/OwnedSink.swift | 1 | 978 | //
// StrongMethodSink.swift
// GlueKit
//
// Created by Károly Lőrentey on 2016-10-24.
// Copyright © 2015–2017 Károly Lőrentey.
//
import SipHash
protocol UniqueOwnedSink: SinkType {
associatedtype Owner: AnyObject
var owner: Owner { get }
}
extension UniqueOwnedSink {
var hashValue: Int {
return ObjectIdentifier(owner).hashValue
}
static func ==(left: Self, right: Self) -> Bool {
return left.owner === right.owner
}
}
protocol OwnedSink: SinkType, SipHashable {
associatedtype Owner: AnyObject
associatedtype Identifier: Hashable
var owner: Owner { get }
var identifier: Identifier { get }
}
extension OwnedSink {
func appendHashes(to hasher: inout SipHasher) {
hasher.append(ObjectIdentifier(owner))
hasher.append(identifier)
}
static func ==(left: Self, right: Self) -> Bool {
return left.owner === right.owner && left.identifier == right.identifier
}
}
| mit | 9d5f3ebcd35c3815b16a8be621b62513 | 21.068182 | 80 | 0.664264 | 4.167382 | false | false | false | false |
shineycode/cocoaconf-ble | talk-demo/source/ping/PeripheralViewController.swift | 1 | 1009 | //
// PeripheralViewController.swift
// talk-demo
//
// Created by Benjamin Deming on 10/25/15.
// Copyright © 2015 Benjamin Deming. All rights reserved.
//
import UIKit
class PeripheralViewController: UIViewController {
var peripheral = Peripheral()
@IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Peripheral"
peripheral.currentStateChangedHandler = { [unowned self] (state: Peripheral.State) -> Void in
var text = ""
switch state {
case .Idle:
text = "Not ready to advertise."
case .Advertising:
text = "Advertising."
case .Acknowledged(let rtt):
text = String(format: "Round trip time:\n%.f msec", rtt * 1000)
}
dispatch_async(dispatch_get_main_queue(), { [unowned self] () -> Void in
self.label.text = text
})
}
}
} | mit | 4b56c6f812ac964a52c4071a3814f9cb | 27.027778 | 101 | 0.550595 | 4.561086 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/MainWindowsController.swift | 1 | 748 | //
// MainWindowsController.swift
// RsyncOSX
//
// Created by Thomas Evensen on 01/12/2020.
// Copyright © 2020 Thomas Evensen. All rights reserved.
//
import Cocoa
import Foundation
class MainWindowsController: NSWindowController {
func addtoolbar() {
globalMainQueue.async { () in
let toolbar = NSToolbar(identifier: "Toolbar")
toolbar.allowsUserCustomization = false
toolbar.autosavesConfiguration = false
toolbar.displayMode = .iconOnly
toolbar.delegate = self
self.window?.toolbar = toolbar
}
window?.toolbar?.validateVisibleItems()
}
override func windowDidLoad() {
super.windowDidLoad()
addtoolbar()
}
}
| mit | 84e137ffadd8d90a2327e5c64c049234 | 24.758621 | 58 | 0.637216 | 4.850649 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/ViewControllers/Settings/General.swift | 1 | 4848 | import SwiftUI
class GeneralSettingsObservable: ObservableObject {
@Published var addBooksToTop: Bool = GeneralSettings.addBooksToTopOfCustom {
didSet {
GeneralSettings.addBooksToTopOfCustom = addBooksToTop
}
}
@Published var progressType = GeneralSettings.defaultProgressType {
didSet { GeneralSettings.defaultProgressType = progressType }
}
@Published var prepopulateLastLanguageSelection = GeneralSettings.prepopulateLastLanguageSelection {
didSet {
GeneralSettings.prepopulateLastLanguageSelection = prepopulateLastLanguageSelection
if !prepopulateLastLanguageSelection { LightweightDataStore.lastSelectedLanguage = nil }
}
}
@Published var restrictSearchResultsTo: LanguageSelection = {
if let languageRestriction = GeneralSettings.searchLanguageRestriction {
return .some(languageRestriction)
} else {
return LanguageSelection.none
}
}() {
didSet {
if case .some(let selection) = restrictSearchResultsTo {
GeneralSettings.searchLanguageRestriction = selection
} else {
GeneralSettings.searchLanguageRestriction = .none
}
}
}
}
struct General: View {
@EnvironmentObject var hostingSplitView: HostingSettingsSplitView
@ObservedObject var settings = GeneralSettingsObservable()
private var inset: Bool {
hostingSplitView.isSplit
}
private let languageOptions = [LanguageSelection.none] + LanguageIso639_1.allCases.filter { $0.canFilterGoogleSearchResults }.map { .some($0) }
var body: some View {
SwiftUI.List {
Section(
header: HeaderText("Sort Options", inset: hostingSplitView.isSplit),
footer: FooterText("""
Configure whether newly added books get added to the top or the bottom of the \
reading list when Custom ordering is used.
""", inset: hostingSplitView.isSplit
)
) {
Toggle(isOn: $settings.addBooksToTop) {
Text("Add Books to Top")
}
}
Section(
header: HeaderText("Progress", inset: inset),
footer: FooterText("Choose whether to default to Page Number or Percentage when setting progress.", inset: inset)
) {
NavigationLink(
destination: SelectionForm<ProgressType>(
options: [.page, .percentage],
selectedOption: $settings.progressType
).navigationBarTitle("Default Progress Type")
) {
HStack {
Text("Progress Type")
Spacer()
Text(settings.progressType.description)
.foregroundColor(.secondary)
}
}
}
Section(
header: HeaderText("Language", inset: inset),
footer: FooterText("""
By default, Reading List prioritises search results based on their language and your location. To instead \
restrict search results to be of a specific language only, select a language above.
""", inset: inset)
) {
Toggle(isOn: $settings.prepopulateLastLanguageSelection) {
Text("Remember Last Selection")
}
NavigationLink(
destination: SelectionForm<LanguageSelection>(
options: languageOptions,
selectedOption: $settings.restrictSearchResultsTo
).navigationBarTitle("Language Restriction")
) {
HStack {
Text("Restrict Search Results")
Spacer()
Text(settings.restrictSearchResultsTo.description).foregroundColor(.secondary)
}
}
}
}
.possiblyInsetGroupedListStyle(inset: hostingSplitView.isSplit)
}
}
extension ProgressType: Identifiable {
var id: Int { rawValue }
}
extension LanguageSelection: Identifiable {
var id: String {
switch self {
case .none: return ""
// Not in practise used by this form; return some arbitrary unique value
case .blank: return "!"
case .some(let language): return language.rawValue
}
}
}
struct General_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
General().environmentObject(HostingSettingsSplitView())
}
}
}
| gpl-3.0 | 4781c2d61b59c7df10ad0b333d611138 | 36.292308 | 147 | 0.570338 | 5.778308 | false | false | false | false |
manfengjun/KYMart | Section/Order/Controller/KYOrderShipViewController.swift | 1 | 2234 | //
// KYOrderShipViewController.swift
// KYMart
//
// Created by JUN on 2017/7/12.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import WebKit
import SVProgressHUD
class KYOrderShipViewController: BaseViewController {
var order_id:Int?{
didSet {
let url = URL(string: SJBRequestUrl.returnOrderShipUrl(order_id: order_id!))
let request = URLRequest(url: url!)
webView.load(request)
}
}
/// 详情展示WebView
fileprivate lazy var webView : WKWebView = {
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
webView.uiDelegate = self
webView.navigationDelegate = self
webView.scrollView.isScrollEnabled = true
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
// Do any additional setup after loading the view.
}
func setupUI() {
setBackButtonInNav()
view.addSubview(webView)
SVProgressHUD.show()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension KYOrderShipViewController:WKUIDelegate,WKNavigationDelegate{
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("加载中")
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
print("内容开始返回")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("加载完成")
SVProgressHUD.dismiss()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("加载失败")
}
}
| mit | 275e14e647f4b9efb8a7a6f41888993b | 28.186667 | 106 | 0.6455 | 4.84292 | false | false | false | false |
jdbateman/Lendivine | Lendivine/CountriesMapViewController.swift | 1 | 5653 | //
// CountriesMapViewController.swift
// Lendivine
//
// Created by john bateman on 5/7/16.
// Copyright © 2016 John Bateman. All rights reserved.
//
// This is the Countries Map View Controller which presents an MKMapView that the user can touch to initiate a search for loans in the selected country.
import UIKit
import MapKit
class CountriesMapViewController: MapViewController, UIGestureRecognizerDelegate {
var tapRecognizer: UITapGestureRecognizer? = nil
var annotation: MKAnnotation?
var countryName: String?
var cityName: String?
override func viewDidLoad() {
super.viewDidLoad()
modifyBarButtonItems()
initTapRecognizer()
setMapRegionToAfrica()
}
func modifyBarButtonItems() {
navigationItem.title = "Map Search"
let loansByListButton = UIBarButtonItem(image: UIImage(named: "Donate-32"), style: .Plain, target: self, action: #selector(CountriesMapViewController.onLoansByListButtonTap))
navigationItem.setRightBarButtonItems([loansByListButton], animated: true)
// remove back button
navigationItem.hidesBackButton = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
initTapRecognizer()
}
override func viewWillDisappear(animated: Bool) {
deinitTapRecognizer()
}
// MARK: Tap gesture recognizer
func initTapRecognizer() {
tapRecognizer = UITapGestureRecognizer(target: self, action:#selector(CountriesMapViewController.handleSingleTap(_:)))
if let tr = tapRecognizer {
tr.numberOfTapsRequired = 1
self.mapView.addGestureRecognizer(tr)
self.mapView.userInteractionEnabled = true
}
}
func deinitTapRecognizer() {
self.mapView.removeGestureRecognizer(self.tapRecognizer!)
}
// User tapped somewhere on the view. End editing.
func handleSingleTap(recognizer: UITapGestureRecognizer) {
// clear pins
if let annotation = self.annotation {
self.mapView.removeAnnotation(annotation)
}
if let point = tapRecognizer?.locationInView(self.mapView) {
let tapPoint:CLLocationCoordinate2D = self.mapView.convertPoint(point, toCoordinateFromView: self.mapView)
let location = CLLocation(latitude: tapPoint.latitude , longitude: tapPoint.longitude)
// add a pin on the map
let pin = MKPointAnnotation()
pin.coordinate = tapPoint
self.mapView.addAnnotation(pin)
self.annotation = pin
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) {
placemarks, error in
if placemarks != nil {
if let placemark = placemarks?.first {
self.countryName = placemark.country
if let city = placemark.addressDictionary!["City"] as? String {
self.cityName = city
}
// show CountryLoans view controller
self.presentCountryLoansController()
}
} else {
if (error?.domain == kCLErrorDomain) && (error?.code == 2) {
LDAlert(viewController: self).displayErrorAlertView("No Internet Connection", message: "Unable to Search for loans in the selected country.")
} else {
self.showAlert()
}
}
}
}
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CountriesMapToCountryLoans" {
let controller = segue.destinationViewController as! CountryLoansTableViewController
let activityIndicator = DVNActivityIndicator()
activityIndicator.startActivityIndicator(self.view)
var theCountry: Country?
if let countries = DVNCountries.sharedInstance().fetchCountriesFilteredByNameOn(self.countryName) as? [Country] {
theCountry = countries.first
}
controller.country = theCountry
activityIndicator.stopActivityIndicator()
}
}
/* Modally present the MapViewController on the main thread. */
func presentCountryLoansController() {
dispatch_async(dispatch_get_main_queue()) {
self.performSegueWithIdentifier("CountriesMapToCountryLoans", sender: self)
}
}
// MARK: Helpers
func showAlert() {
let alertController = UIAlertController(title: "Country Not Found", message: "Zoom in and try again.\n\nHint: Tap near the center of the country." , preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
// do nothing
}
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | 80e5609c54890ac62d3353efd11089ff | 32.844311 | 182 | 0.588287 | 5.987288 | false | false | false | false |
joeytat/Eww | Eww/Classes/Network/LoadingPlugin.swift | 1 | 1959 | //
// ATLoadingPlugin.swift
// AlphaTrion
//
// Created by Joey on 27/05/2017.
// Copyright © 2017 JieJing. All rights reserved.
//
import Foundation
import Moya
import UIKit
import Result
private let kLoadingTag = 230001
public final class LoadingPlugin: PluginType {
public init() {}
public func willSend(_ request: RequestType, target: TargetType) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
guard let window = UIApplication.shared.keyWindow,
(window.viewWithTag(kLoadingTag) == nil) else { return }
let loading = loadingViewConstructor()
window.addSubview(loading)
loading.snp.makeConstraints { make in
make.center.equalTo(window)
make.width.equalTo(80)
make.height.equalTo(60)
}
delay(0.4) {
UIView.animate(withDuration: 0.1, animations: {
loading.alpha = 1
})
}
}
public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
guard let window = UIApplication.shared.keyWindow,
let loading = window.viewWithTag(kLoadingTag)
else { return }
UIView.animate(withDuration: 0.15, animations: {
loading.alpha = 0.0
}) { _ in
loading.removeFromSuperview()
}
}
}
private func loadingViewConstructor() -> UIView {
let view = UIView()
view.backgroundColor = UIColor(hue:0.00, saturation:0.00, brightness:0.6, alpha:0.7)
view.cornerRadius = 4
view.tag = kLoadingTag
view.alpha = 0.0
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
indicator.startAnimating()
view.addSubview(indicator)
indicator.snp.makeConstraints { make in
make.center.equalTo(view)
}
return view
}
| mit | 92e7bec4f373b7ea994563edbe1a8013 | 27.794118 | 92 | 0.632789 | 4.532407 | false | false | false | false |
asurinsaka/swift_examples_2.1 | MRCodes/MRCodes/CameraPreviewView.swift | 1 | 4301 | //
// CameraPreviewView.swift
// MRCodes
//
// Created by larryhou on 13/12/2015.
// Copyright © 2015 larryhou. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
class CameraPreviewView:UIView
{
override static func layerClass()->AnyClass
{
return AVCaptureVideoPreviewLayer.self
}
var session:AVCaptureSession!
{
get
{
return (self.layer as! AVCaptureVideoPreviewLayer).session
}
set
{
(self.layer as! AVCaptureVideoPreviewLayer).session = newValue
}
}
}
class CameraOverlayView:UIView
{
@IBOutlet weak var label:UILabel!
@IBOutlet weak var type:UILabel!
private var codes:[AVMetadataMachineReadableCodeObject]!
private var faces:[AVMetadataFaceObject]!
func setMetadataObjects(codes:[AVMetadataMachineReadableCodeObject], faces:[AVMetadataFaceObject])
{
self.codes = codes
self.faces = faces
setNeedsDisplay()
}
func getMRCEdges(from:AVMetadataMachineReadableCodeObject)->CGPath
{
var points:[CGPoint] = []
for corner in (from.corners as! [NSDictionary])
{
let x = corner.valueForKeyPath("X") as! CGFloat
let y = corner.valueForKeyPath("Y") as! CGFloat
points.append(CGPoint(x: x, y: y))
}
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, points[0].x, points[0].y)
for i in 1..<points.count
{
CGPathAddLineToPoint(path, nil, points[i].x, points[i].y)
}
CGPathAddLineToPoint(path, nil, points[0].x, points[0].y)
return path
}
func getFaceEdges(from:AVMetadataFaceObject)->CGPath
{
let path = CGPathCreateMutable()
let radius:CGFloat = floor(min(5.0, from.bounds.width / 2, from.bounds.height))
CGPathAddRoundedRect(path, nil, from.bounds, radius, radius)
return path
}
override func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
var target:CGPath!
label.textColor = UIColor.whiteColor()
label.text = ""
type.text = ""
if codes != nil && codes.count > 0
{
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0).CGColor)
CGContextSetLineJoin(context, .Miter)
CGContextSetLineCap(context, .Square)
CGContextSetLineWidth(context, 2.0)
for mrc in codes
{
let path = getMRCEdges(mrc)
CGContextAddPath(context, path)
if target == nil
{
target = path
type.text = mrc.type
label.text = mrc.stringValue
label.sizeToFit()
if mrc.stringValue != nil
{
UIPasteboard.generalPasteboard().string = mrc.stringValue
}
}
}
CGContextStrokePath(context)
CGContextRestoreGState(context)
}
if target != nil
{
CGContextSaveGState(context)
CGContextAddPath(context, target)
CGContextSetFillColorWithColor(context, UIColor(red: 1.0, green: 1.0, blue: 0.0, alpha: 0.2).CGColor)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
if faces != nil && faces.count > 0
{
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0).CGColor)
CGContextSetLineJoin(context, .Miter)
CGContextSetLineCap(context, .Square)
CGContextSetLineWidth(context, 1.0)
for mrc in faces
{
CGContextAddPath(context, getFaceEdges(mrc))
}
CGContextStrokePath(context)
CGContextRestoreGState(context)
}
}
} | mit | 133c44be3ca92a8b28f2a48fccc72e75 | 28.458904 | 115 | 0.55093 | 5.174489 | false | false | false | false |
nathawes/swift | test/SILOptimizer/Inputs/cross-module.swift | 7 | 4965 | import Submodule
private enum PE<T> {
case A
case B(T)
}
public struct Container {
private final class Base {
}
@inline(never)
public func testclass<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testclass_gen<T>(_ t: T) -> T {
var arr = Array<Base>()
arr.append(Base())
print(arr)
return t
}
@inline(never)
public func testenum<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func testenum_gen<T>(_ t: T) -> T {
var arr = Array<PE<T>>()
arr.append(.B(t))
print(arr)
return t
}
public init() { }
}
private class PrivateBase<T> {
var t: T
func foo() -> Int { return 27 }
init(_ t: T) { self.t = t }
}
private class PrivateDerived<T> : PrivateBase<T> {
override func foo() -> Int { return 28 }
}
@inline(never)
private func getClass<T>(_ t : T) -> PrivateBase<T> {
return PrivateDerived<T>(t)
}
@inline(never)
public func createClass<T>(_ t: T) -> Int {
return getClass(t).foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func createClass_gen<T>(_ t: T) -> Int {
return getClass(t).foo()
}
private struct PrivateError: Error { }
public func returnPrivateError<V>(_ v: V) -> Error {
return PrivateError()
}
struct InternalError: Error { }
public func returnInternalError<V>(_ v: V) -> Error {
return InternalError()
}
private protocol PrivateProtocol {
func foo() -> Int
}
open class OpenClass<T> {
public init() { }
@inline(never)
fileprivate func bar(_ t: T) {
print(t)
}
}
extension OpenClass {
@inline(never)
public func testit() -> Bool {
return self is PrivateProtocol
}
}
@inline(never)
public func checkIfClassConforms<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func checkIfClassConforms_gen<T>(_ t: T) {
let x = OpenClass<T>()
print(x.testit())
}
@inline(never)
public func callClassMethod<T>(_ t: T) {
let k = OpenClass<T>()
k.bar(t)
}
extension Int : PrivateProtocol {
func foo() -> Int { return self }
}
@inline(never)
@_semantics("optimize.no.crossmodule")
private func printFooExistential(_ p: PrivateProtocol) {
print(p.foo())
}
@inline(never)
private func printFooGeneric<T: PrivateProtocol>(_ p: T) {
print(p.foo())
}
@inline(never)
public func callFoo<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFoo_gen<T>(_ t: T) {
printFooExistential(123)
printFooGeneric(1234)
}
fileprivate protocol PrivateProto {
func foo()
}
public class FooClass: PrivateProto {
func foo() {
print(321)
}
}
final class Internalclass {
public var publicint: Int = 27
}
final public class Outercl {
var ic: Internalclass = Internalclass()
}
@inline(never)
public func classWithPublicProperty<T>(_ t: T) -> Int {
return createInternal().ic.publicint
}
@inline(never)
func createInternal() -> Outercl {
return Outercl()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
fileprivate func callProtocolFoo<T: PrivateProto>(_ t: T) {
t.foo()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callFooViaConformance<T>(_ t: T) {
let c = FooClass()
callProtocolFoo(c)
}
@inline(never)
public func callGenericSubmoduleFunc<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func callGenericSubmoduleFunc_gen<T>(_ t: T) {
genericSubmoduleFunc(t)
}
@inline(never)
public func genericClosure<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
@inline(never)
@_semantics("optimize.sil.specialize.generic.never")
public func genericClosure_gen<T>(_ t: T) -> T {
let c : () -> T = { return t }
return c()
}
struct Abc {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Myclass {
var x: Int { return 27 }
var y: Int { return 28 }
}
class Derived : Myclass {
override var x: Int { return 29 }
override var y: Int { return 30 }
}
@inline(never)
func getStructKeypath<T>(_ t: T) -> KeyPath<Abc, Int> {
return \Abc.x
}
@inline(never)
public func useStructKeypath<T>(_ t: T) -> Int {
let abc = Abc()
return abc[keyPath: getStructKeypath(t)]
}
@inline(never)
func getClassKeypath<T>(_ t: T) -> KeyPath<Myclass, Int> {
return \Myclass.x
}
@inline(never)
public func useClassKeypath<T>(_ t: T) -> Int {
let c = Derived()
return c[keyPath: getClassKeypath(t)]
}
@inline(never)
func unrelated<U>(_ u: U) {
print(u)
}
@inline(never)
public func callUnrelated<T>(_ t: T) -> T {
unrelated(43)
return t
}
public let globalLet = 529387
| apache-2.0 | 47235e37b2ef79ce37838bca57f61d90 | 17.388889 | 59 | 0.652165 | 3.072401 | false | false | false | false |
crazypoo/PTools | Pods/CryptoSwift/Sources/CryptoSwift/BlockEncryptor.swift | 2 | 2327 | // CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
@usableFromInline
final class BlockEncryptor: Cryptor, Updatable {
private let blockSize: Int
private var worker: CipherModeWorker
private let padding: Padding
// Accumulated bytes. Not all processed bytes.
private var accumulated = Array<UInt8>(reserveCapacity: 16)
private var lastBlockRemainder = 0
@usableFromInline
init(blockSize: Int, padding: Padding, _ worker: CipherModeWorker) throws {
self.blockSize = blockSize
self.padding = padding
self.worker = worker
}
// MARK: Updatable
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> {
self.accumulated += bytes
if isLast {
self.accumulated = self.padding.add(to: self.accumulated, blockSize: self.blockSize)
}
var encrypted = Array<UInt8>(reserveCapacity: accumulated.count)
for chunk in self.accumulated.batched(by: self.blockSize) {
if isLast || chunk.count == self.blockSize {
encrypted += self.worker.encrypt(block: chunk)
}
}
// Stream encrypts all, so it removes all elements
self.accumulated.removeFirst(encrypted.count)
if var finalizingWorker = worker as? FinalizingEncryptModeWorker, isLast == true {
encrypted = Array(try finalizingWorker.finalize(encrypt: encrypted.slice))
}
return encrypted
}
@usableFromInline
func seek(to: Int) throws {
fatalError("Not supported")
}
}
| mit | 10990e3c04abe9541e7cfcb6a23feeb8 | 36.516129 | 217 | 0.733018 | 4.481696 | false | false | false | false |
tomquist/Equals | Sources/Equals/HashableHelper.swift | 1 | 2597 | /// Helper which contains the property
private struct PropertyHasher<T, E> {
private let property: (T) -> E
private let hasher: (E) -> Int
fileprivate init(_ property: @escaping (T) -> E, _ hasher: @escaping (E) -> Int) {
self.property = property
self.hasher = hasher
}
fileprivate func hashValue(_ value: T) -> Int {
return hasher(property(value))
}
}
private struct AnyPropertyHasher<T> {
fileprivate let hasher: (T) -> Int
fileprivate init<E>(_ property: @escaping (T) -> E, _ hasher: @escaping (E) -> Int) {
self.hasher = PropertyHasher(property, hasher).hashValue
}
}
/// Internal helper to support hashable implementations.
struct HashableHelper<T>: HashesType {
private var hashers = [AnyPropertyHasher<T>]()
let constant: Int
let initial: Int
init(constant: Int, initial: Int) {
self.constant = constant
self.initial = initial
}
mutating func append<E>(_ property: @escaping (T) -> E, hasher: @escaping (E) -> Int) {
hashers.append(AnyPropertyHasher(property, hasher))
}
func hashValue(_ value: T) -> Int {
return hashers.reduce(initial) {
return $0 &* constant &+ $1.hasher(value)
}
}
}
fileprivate extension Hashable {
fileprivate static func getHashValue(value: Self) -> Int {
return value.hashValue
}
}
fileprivate extension Optional where Wrapped: Hashable {
fileprivate static func getHashValue(value: Optional<Wrapped>) -> Int {
if let value = value {
return value.hashValue
}
return 0
}
}
fileprivate extension Collection where Iterator.Element: Hashable {
fileprivate static func getHashValue(initial: Int, constant: Int) -> (Self) -> Int {
return {
return $0.reduce(initial) {
return $0 &* constant &+ $1.hashValue
}
}
}
}
// MARK: Hashable
extension HashableHelper {
mutating func append<E: Hashable>(_ property: @escaping (T) -> E) {
append(property, hasher: E.getHashValue)
}
}
// MARK: Optional<Hashable>
extension HashableHelper {
mutating func append<E: Hashable>(_ property: @escaping (T) -> E?) {
append(property, hasher: Optional<E>.getHashValue)
}
}
// MARK: Collection<Hashable>
extension HashableHelper {
mutating func append<E: Collection>(_ property: @escaping (T) -> E) where E.Iterator.Element: Hashable {
append(property, hasher: E.getHashValue(initial: initial, constant: constant))
}
}
| mit | 6d2c7f6e46693d63fd41e083b36843bb | 26.62766 | 108 | 0.619561 | 4.148562 | false | false | false | false |
dipen30/Qmote | KodiRemote/Pods/UPnAtom/Source/Logging/PropertyPrinter.swift | 1 | 5757 | //
// PropertyPrinter.swift
//
// Copyright (c) 2015 David Robles
//
// 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
public protocol ExtendedPrintable: CustomStringConvertible {
var className: String { get }
}
public struct PropertyPrinter {
fileprivate var _properties = [String: String]()
public init() { }
public mutating func add<T>(_ propertyName: String, property: T?) {
_properties[propertyName] = prettyPrint(property)
}
public mutating func add<T: CustomStringConvertible>(_ propertyName: String, property: T?) {
_properties[propertyName] = prettyPrint(property)
}
public mutating func add<T>(_ propertyName: String, property: [T]?) {
_properties[propertyName] = prettyPrint(property)
}
public mutating func add<T: CustomStringConvertible>(_ propertyName: String, property: [T]?) {
_properties[propertyName] = prettyPrint(property)
}
public mutating func add<K, V>(_ propertyName: String, property: [K: V]?) {
_properties[propertyName] = prettyPrint(property)
}
public mutating func add<K, V: CustomStringConvertible>(_ propertyName: String, property: [K: V]?) {
_properties[propertyName] = prettyPrint(property)
}
// subscript(key: String) -> Any? { // subscripts can't be used as the subscript function can't be Generic only class/struct-wide generic declarations can be made which isn't useful here
// get {
// return nil
// }
// set {
// add(key, property: newValue)
// }
// }
}
extension PropertyPrinter: CustomStringConvertible {
public var description: String {
return dictionaryDescription(_properties, pointsToSymbol: "=")
}
}
/// helpPrint(), dictionaryDescription(), and arrayDescription() have so many variants due to the limitation in the Swift for detecting swift-protocol conformance at runtime. This restriction will be removed in a future release of swift: http://stackoverflow.com/questions/26909974/protocols-why-is-objc-required-for-conformance-checking-and-optional-requireme
func prettyPrint<K, V>(_ someDictionary: [K: V]?) -> String {
if let someDictionary = someDictionary {
return prettyPrint(dictionaryDescription(someDictionary, pointsToSymbol: ":"))
}
return "nil"
}
func prettyPrint<K, V: CustomStringConvertible>(_ someDictionary: [K: V]?) -> String {
if let someDictionary = someDictionary {
return prettyPrint(dictionaryDescription(someDictionary, pointsToSymbol: ":"))
}
return "nil"
}
func prettyPrint<T: CustomStringConvertible>(_ someArray: [T]?) -> String {
if let someArray = someArray {
return prettyPrint(arrayDescription(someArray))
}
return "nil"
}
func prettyPrint<T>(_ someArray: [T]?) -> String {
if let someArray = someArray {
return prettyPrint(arrayDescription(someArray))
}
return "nil"
}
func prettyPrint<T: CustomStringConvertible>(_ something: T?) -> String {
if let something = something {
return something.description.replacingOccurrences(of: "\n", with: "\n\t", options: .literal)
}
return "nil"
}
func prettyPrint<T>(_ something: T?) -> String {
if let something = something {
return "\(something)".replacingOccurrences(of: "\n", with: "\n\t", options: .literal)
}
return "nil"
}
func dictionaryDescription<K, V: CustomStringConvertible>(_ properties: [K: V], pointsToSymbol: String) -> String {
var description = "{ \n"
for (key, value) in properties {
let valueDescription = value.description.replacingOccurrences(of: "\n", with: "\n\t", options: .literal)
description += "\t\(key) \(pointsToSymbol) \(valueDescription) \n"
}
description += "}"
return description
}
func dictionaryDescription<K, V>(_ properties: [K: V], pointsToSymbol: String) -> String {
var description = "{ \n"
for (key, value) in properties {
description += "\t\(key) \(pointsToSymbol) \(value) \n"
}
description += "}"
return description
}
func arrayDescription<T: CustomStringConvertible>(_ array: [T]) -> String {
var description = "{ \n"
for item in array {
let itemDescription = item.description.replacingOccurrences(of: "\n", with: "\n\t", options: .literal)
description += "\t\(itemDescription)\n"
}
description += "}"
return description
}
func arrayDescription<T>(_ array: [T]) -> String {
var description = "{ \n"
for item in array {
description += "\t\(item)\n"
}
description += "}"
return description
}
| apache-2.0 | d7679c98752faeb70866bd7693c8561c | 34.98125 | 360 | 0.667883 | 4.367982 | false | false | false | false |
noahprince22/StrollSafe_iOS | Stroll Safe/AppDelegate.swift | 1 | 7140 | //
// AppDelegate.swift
// Stroll Safe
//
// Created by Guest User (Mitchell) on 3/21/15.
// Copyright (c) 2015 Stroll Safe. All rights reserved.
//
import UIKit
import CoreData
import Fabric
import Crashlytics
import DigitsKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
static var VERSION: String!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//application.statusBarHidden = true
Fabric.with([Crashlytics.self(), Digits.self()])
let pageController = UIPageControl.appearance()
pageController.pageIndicatorTintColor = UIColor.lightGrayColor()
pageController.currentPageIndicatorTintColor = UIColor.blackColor()
pageController.backgroundColor = UIColor.whiteColor()
if let bundleVersion = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String {
if let shortVersionString = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String {
AppDelegate.VERSION = shortVersionString + "." + bundleVersion
}
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "edu.illinois.Stroll_Safe" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Stroll_Safe", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Stroll_Safe.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| apache-2.0 | 612eb3df746e674c835f70335c773368 | 49.638298 | 290 | 0.693978 | 5.847666 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ChatListFilterPredicate.swift | 1 | 11119 | //
// ChatListFilterPredicate.swift
// Telegram
//
// Created by Mikhail Filimonov on 02.03.2020.
// Copyright © 2020 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
func chatListFilterPredicate(for filter: ChatListFilter?) -> ChatListFilterPredicate? {
guard let filter = filter?.data else {
return nil
}
let includePeers = Set(filter.includePeers.peers)
let excludePeers = Set(filter.excludePeers)
var includeAdditionalPeerGroupIds: [PeerGroupId] = []
if !filter.excludeArchived {
includeAdditionalPeerGroupIds.append(Namespaces.PeerGroup.archive)
}
var messageTagSummary: ChatListMessageTagSummaryResultCalculation?
if filter.excludeRead || filter.excludeMuted {
messageTagSummary = ChatListMessageTagSummaryResultCalculation(addCount: ChatListMessageTagSummaryResultComponent(tag: .unseenPersonalMessage, namespace: Namespaces.Message.Cloud), subtractCount: ChatListMessageTagActionsSummaryResultComponent(type: PendingMessageActionType.consumeUnseenPersonalMessage, namespace: Namespaces.Message.Cloud))
}
return ChatListFilterPredicate(includePeerIds: includePeers, excludePeerIds: excludePeers, pinnedPeerIds: filter.includePeers.pinnedPeers, messageTagSummary: messageTagSummary, includeAdditionalPeerGroupIds: includeAdditionalPeerGroupIds, include: { peer, isMuted, isUnread, isContact, messageTagSummaryResult in
if filter.excludeRead {
var effectiveUnread = isUnread
if let messageTagSummaryResult = messageTagSummaryResult, messageTagSummaryResult {
effectiveUnread = true
}
if !effectiveUnread {
return false
}
}
if filter.excludeMuted {
if isMuted {
if let messageTagSummaryResult = messageTagSummaryResult, messageTagSummaryResult {
} else {
return false
}
}
}
if !filter.categories.contains(.contacts) && isContact {
if let user = peer as? TelegramUser {
if user.botInfo == nil {
return false
}
} else if let _ = peer as? TelegramSecretChat {
return false
}
}
if !filter.categories.contains(.nonContacts) && !isContact {
if let user = peer as? TelegramUser {
if user.botInfo == nil {
return false
}
} else if let _ = peer as? TelegramSecretChat {
return false
}
}
if !filter.categories.contains(.bots) {
if let user = peer as? TelegramUser {
if user.botInfo != nil {
return false
}
}
}
if !filter.categories.contains(.groups) {
if let _ = peer as? TelegramGroup {
return false
} else if let channel = peer as? TelegramChannel {
if case .group = channel.info {
return false
}
}
}
if !filter.categories.contains(.channels) {
if let channel = peer as? TelegramChannel {
if case .broadcast = channel.info {
return false
}
}
}
return true
})
}
public enum ChatListControllerLocation {
case chatList(groupId: PeerGroupId)
case forum(peerId: PeerId)
}
struct ChatListViewUpdate {
let list: EngineChatList
let type: ViewUpdateType
let scroll: TableScrollState?
var removeNextAnimation: Bool
}
func chatListViewForLocation(chatListLocation: ChatListControllerLocation, location: ChatListIndexRequest, filter: ChatListFilter?, account: Account) -> Signal<ChatListViewUpdate, NoError> {
switch chatListLocation {
case let .chatList(groupId):
let filterPredicate: ChatListFilterPredicate? = chatListFilterPredicate(for: filter)
switch location {
case let .Initial(count, st):
let signal: Signal<(ChatListView, ViewUpdateType), NoError>
signal = account.viewTracker.tailChatListView(groupId: groupId, filterPredicate: filterPredicate, count: count)
return signal
|> map { view, updateType -> ChatListViewUpdate in
return ChatListViewUpdate(list: EngineChatList(view), type: updateType, scroll: st, removeNextAnimation: false)
}
case let .Index(index, st):
guard case let .chatList(index) = index else {
return .never()
}
var first = true
return account.viewTracker.aroundChatListView(groupId: groupId, filterPredicate: filterPredicate, index: index, count: 80)
|> map { view, updateType -> ChatListViewUpdate in
let genericType: ViewUpdateType
if first {
first = false
genericType = ViewUpdateType.UpdateVisible
} else {
genericType = updateType
}
return ChatListViewUpdate(list: EngineChatList(view), type: genericType, scroll: st, removeNextAnimation: st != nil)
}
}
case let .forum(peerId):
let viewKey: PostboxViewKey = .messageHistoryThreadIndex(
id: peerId,
summaryComponents: ChatListEntrySummaryComponents(
components: [
ChatListEntryMessageTagSummaryKey(
tag: .unseenPersonalMessage,
actionType: PendingMessageActionType.consumeUnseenPersonalMessage
): ChatListEntrySummaryComponents.Component(
tagSummary: ChatListEntryMessageTagSummaryComponent(namespace: Namespaces.Message.Cloud),
actionsSummary: ChatListEntryPendingMessageActionsSummaryComponent(namespace: Namespaces.Message.Cloud)
),
ChatListEntryMessageTagSummaryKey(
tag: .unseenReaction,
actionType: PendingMessageActionType.readReaction
): ChatListEntrySummaryComponents.Component(
tagSummary: ChatListEntryMessageTagSummaryComponent(namespace: Namespaces.Message.Cloud),
actionsSummary: ChatListEntryPendingMessageActionsSummaryComponent(namespace: Namespaces.Message.Cloud)
)
]
)
)
var isFirst = false
return account.postbox.combinedView(keys: [viewKey])
|> map { views -> ChatListViewUpdate in
guard let view = views.views[viewKey] as? MessageHistoryThreadIndexView else {
preconditionFailure()
}
var items: [EngineChatList.Item] = []
for item in view.items {
guard let peer = view.peer else {
continue
}
guard let data = item.info.get(MessageHistoryThreadData.self) else {
continue
}
var hasUnseenMentions = false
var isMuted = false
if case .muted = data.notificationSettings.muteState {
isMuted = true
}
if let info = item.tagSummaryInfo[ChatListEntryMessageTagSummaryKey(
tag: .unseenPersonalMessage,
actionType: PendingMessageActionType.consumeUnseenPersonalMessage
)] {
hasUnseenMentions = (info.tagSummaryCount ?? 0) > (info.actionsSummaryCount ?? 0)
}
var hasUnseenReactions = false
if let info = item.tagSummaryInfo[ChatListEntryMessageTagSummaryKey(
tag: .unseenReaction,
actionType: PendingMessageActionType.readReaction
)] {
hasUnseenReactions = (info.tagSummaryCount ?? 0) != 0// > (info.actionsSummaryCount ?? 0)
}
let pinnedIndex: EngineChatList.Item.PinnedIndex
if let index = item.pinnedIndex {
pinnedIndex = .index(index)
} else {
pinnedIndex = .none
}
let readCounters = EnginePeerReadCounters(state: CombinedPeerReadState(states: [(Namespaces.Message.Cloud, .idBased(maxIncomingReadId: 1, maxOutgoingReadId: 1, maxKnownId: 1, count: data.incomingUnreadCount, markedUnread: false))]), isMuted: false)
var draft: EngineChatList.Draft?
if let embeddedState = item.embeddedInterfaceState, let _ = embeddedState.overrideChatTimestamp {
if let opaqueState = _internal_decodeStoredChatInterfaceState(state: embeddedState) {
if let text = opaqueState.synchronizeableInputState?.text {
draft = EngineChatList.Draft(text: text, entities: opaqueState.synchronizeableInputState?.entities ?? [])
}
}
}
items.append(EngineChatList.Item(
id: .forum(item.id),
index: .forum(pinnedIndex: pinnedIndex, timestamp: item.index.timestamp, threadId: item.id, namespace: item.index.id.namespace, id: item.index.id.id),
messages: item.topMessage.flatMap { [EngineMessage($0)] } ?? [],
readCounters: readCounters,
isMuted: isMuted,
draft: draft,
threadData: data,
renderedPeer: EngineRenderedPeer(peer: EnginePeer(peer)),
presence: nil,
hasUnseenMentions: hasUnseenMentions,
hasUnseenReactions: hasUnseenReactions,
forumTopicData: nil,
hasFailed: false,
isContact: false
))
}
let list = EngineChatList(
items: items.reversed(),
groupItems: [],
additionalItems: [],
hasEarlier: false,
hasLater: false,
isLoading: view.isLoading
)
let type: ViewUpdateType
if isFirst {
type = .Initial
} else {
type = .Generic
}
isFirst = false
return ChatListViewUpdate(list: list, type: type, scroll: nil, removeNextAnimation: false)
}
}
}
| gpl-2.0 | 7c4fbdce74ea0dc24a12e082449d68ce | 41.926641 | 350 | 0.559093 | 5.545137 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/ThumbUtils.swift | 1 | 20651 | //
// ThumbUtils.swift
// TelegramMac
//
// Created by keepcoder on 15/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
import TGUIKit
private let extensionImageCache = Atomic<[String: CGImage]>(value: [:])
private let redColors: (UInt32, UInt32) = (0xf0625d, 0xde524e)
private let greenColors: (UInt32, UInt32) = (0x72ce76, 0x54b658)
private let blueColors: (UInt32, UInt32) = (0x60b0e8, 0x4597d1)
private let yellowColors: (UInt32, UInt32) = (0xf5c565, 0xe5a64e)
private let extensionColorsMap: [String: (UInt32, UInt32)] = [
"ppt": redColors,
"pptx": redColors,
"pdf": redColors,
"key": redColors,
"xls": greenColors,
"xlsx": greenColors,
"csv": greenColors,
"zip": yellowColors,
"rar": yellowColors,
"gzip": yellowColors,
"ai": yellowColors
]
func generateExtensionImage(colors: (UInt32, UInt32), ext:String) -> CGImage? {
return generateImage(CGSize(width: 42.0, height: 42.0), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.round(CGRect(origin: CGPoint(), size: size), flags: [.left, .bottom, .right])
context.translateBy(x: size.width / 2.0, y: size.height / 2.0)
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: -size.width / 2.0 + 1.0, y: -size.height / 2.0 + 1.0)
let radius: CGFloat = .cornerRadius
let cornerSize: CGFloat = 10.0
context.setFillColor(NSColor(rgb: colors.0).cgColor)
context.beginPath()
context.move(to: CGPoint(x: 0.0, y: radius))
if !radius.isZero {
context.addArc(tangent1End: CGPoint(x: 0.0, y: 0.0), tangent2End: CGPoint(x: radius, y: 0.0), radius: radius)
}
context.addLine(to: CGPoint(x: size.width - cornerSize, y: 0.0))
context.addLine(to: CGPoint(x: size.width - cornerSize + cornerSize / 4.0, y: cornerSize - cornerSize / 4.0))
context.addLine(to: CGPoint(x: size.width, y: cornerSize))
context.addLine(to: CGPoint(x: size.width, y: size.height - radius))
if !radius.isZero {
context.addArc(tangent1End: CGPoint(x: size.width, y: size.height), tangent2End: CGPoint(x: size.width - radius, y: size.height), radius: radius)
}
context.addLine(to: CGPoint(x: radius, y: size.height))
if !radius.isZero {
context.addArc(tangent1End: CGPoint(x: 0.0, y: size.height), tangent2End: CGPoint(x: 0.0, y: size.height - 5), radius: 5)
}
context.closePath()
context.fillPath()
context.setFillColor(NSColor(rgb: colors.1).cgColor)
context.beginPath()
context.move(to: CGPoint(x: size.width - cornerSize, y: 0.0))
context.addLine(to: CGPoint(x: size.width, y: cornerSize))
context.addLine(to: CGPoint(x: size.width - cornerSize + radius, y: cornerSize))
if !radius.isZero {
context.addArc(tangent1End: CGPoint(x: size.width - cornerSize, y: cornerSize), tangent2End: CGPoint(x: size.width - cornerSize, y: cornerSize - radius), radius: radius)
}
context.closePath()
context.fillPath()
let layout = TextViewLayout(.initialize(string: ext, color: .white, font: .medium(.short)), maximumNumberOfLines: 1, truncationType: .middle)
layout.measure(width: size.width - 4)
if !layout.lines.isEmpty {
let line = layout.lines[0]
context.textMatrix = CGAffineTransform(scaleX: 1.0, y: -1.0)
context.textPosition = NSMakePoint(floorToScreenPixels(System.backingScale, (size.width - line.frame.width)/2.0) - 1, floorToScreenPixels(System.backingScale, (size.height )/2.0) + 4)
CTLineDraw(line.line, context)
}
})
}
func generateMediaEmptyLinkThumb(color: NSColor, textColor: NSColor, host:String) -> CGImage? {
return generateImage(CGSize(width: 40, height: 40), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
let host = host.isEmpty ? "L" : host
context.round(size, .cornerRadius)
context.setFillColor(color.cgColor)
context.fill(CGRect(origin: CGPoint(), size: size))
if !host.isEmpty {
let layout = TextViewLayout(.initialize(string: host, color: textColor, font: .bold(.huge)), maximumNumberOfLines: 1, truncationType: .middle)
layout.measure(width: size.width - 4)
let line = layout.lines[0]
context.textMatrix = CGAffineTransform(scaleX: 1.0, y: 1.0)
context.textPosition = NSMakePoint(floorToScreenPixels(System.backingScale, (size.width - line.frame.width)/2.0) , floorToScreenPixels(System.backingScale, (size.height - line.frame.width)/2.0))
CTLineDraw(line.line, context)
}
})
}
func extensionImage(fileExtension: String) -> CGImage? {
let colors: (UInt32, UInt32)
if let extensionColors = extensionColorsMap[fileExtension] {
colors = extensionColors
} else {
colors = blueColors
}
if let cachedImage = (extensionImageCache.with { dict in
return dict[fileExtension]
}) {
return cachedImage
} else if let image = generateExtensionImage(colors: colors, ext: fileExtension) {
let _ = extensionImageCache.modify { dict in
var dict = dict
dict[fileExtension] = image
return dict
}
return image
} else {
return nil
}
}
func capIcon(for text:NSAttributedString, size:NSSize = NSMakeSize(50, 50), cornerRadius:CGFloat = 4, background:NSColor = .border) -> CGImage? {
return generateImage(size, contextGenerator: { (size, ctx) in
ctx.clear(NSMakeRect(0, 0, size.width, size.height))
ctx.round(size, cornerRadius)
ctx.setFillColor(background.cgColor)
ctx.fill(NSMakeRect(0, 0, size.width, size.height))
let line = CTLineCreateWithAttributedString(text)
let rect = CTLineGetBoundsWithOptions(line, [.excludeTypographicLeading])
ctx.textMatrix = CGAffineTransform(scaleX: 1.0, y: 1.0)
ctx.textPosition = NSMakePoint(floorToScreenPixels(System.backingScale, (size.width - rect.width)/2.0), floorToScreenPixels(System.backingScale, (size.height - rect.height)/2.0) + 6 )
CTLineDraw(line, ctx)
})
}
let playerPlayThumb = generateImage(NSMakeSize(40.0,40.0), contextGenerator: { size, context in
context.clear(NSMakeRect(0.0,0.0,size.width,size.height))
let position:NSPoint = NSMakePoint(14.0, 10.0)
context.move(to: position)
context.addLine(to: NSMakePoint(position.x, position.y + 20.0))
context.addLine(to: NSMakePoint(position.x + 15.0, position.y + 10.0 ))
context.setFillColor(NSColor.white.cgColor)
context.fillPath()
})
let playerPauseThumb = generateImage(CGSize(width: 40, height: 40), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.setFillColor(NSColor.white.cgColor)
//20 - 2
context.fill(CGRect(x: 14, y: 12, width: 4.0, height: 16))
context.fill(CGRect(x: 22, y: 12, width: 4.0, height: 16))
})
let stopFetchStreamableControl = generateImage(CGSize(width: 6, height: 6), contextGenerator: { size, context in
context.clear(CGRect(origin: CGPoint(), size: size))
context.round(size, 2)
context.setFillColor(NSColor.white.cgColor)
context.fill(NSMakeRect(0, 0, size.width, size.height))
})
public struct PreviewOptions: OptionSet {
public var rawValue: UInt32
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
public init() {
self.rawValue = 0
}
public init(_ flags: PreviewOptions) {
var rawValue: UInt32 = 0
if flags.contains(PreviewOptions.file) {
rawValue |= PreviewOptions.file.rawValue
}
if flags.contains(PreviewOptions.media) {
rawValue |= PreviewOptions.media.rawValue
}
self.rawValue = rawValue
}
public static let media = PreviewOptions(rawValue: 1)
public static let file = PreviewOptions(rawValue: 8)
}
func takeSenderOptions(for urls:[URL]) -> [PreviewOptions] {
var options:[PreviewOptions] = []
for url in urls {
let mime = MIMEType(url.path)
if mime.hasPrefix("image") {
if let image = NSImage(contentsOf: url) {
if image.size.width / 10 > image.size.height || image.size.height < 40 {
continue
} else if image.size.height / 10 > image.size.width || image.size.width < 40 {
continue
}
} else {
continue
}
}
let media = mime.hasPrefix("image") || mime.hasSuffix("gif") || mime.hasPrefix("video/mp4") || mime.hasPrefix("video/mov") || mime.hasSuffix("m4v")
if media {
if !options.contains(.media) {
options.append(.media)
}
} else {
if !options.contains(.file) {
options.append(.file)
}
}
}
if options.isEmpty {
options.append(.file)
}
return options
}
fileprivate let minDiameter: CGFloat = 3.5
fileprivate let maxDiameter: CGFloat = 8.0
func interpolate(from: CGFloat, to: CGFloat, value: CGFloat) -> CGFloat {
return (1.0 - value) * from + value * to
}
func radiusFunction(_ value: CGFloat, timeOffset: CGFloat) -> CGFloat {
var clampedValue: CGFloat = value + timeOffset
if clampedValue > 1.0 {
clampedValue = clampedValue - floor(clampedValue)
}
if clampedValue < 0.4 {
return interpolate(from: minDiameter, to: maxDiameter, value: clampedValue / 0.4)
}
else if clampedValue < 0.8 {
return interpolate(from: maxDiameter, to: minDiameter, value: (clampedValue - 0.4) / 0.4)
}
else {
return minDiameter
}
}
private func generateTextAnimatedImage(_ animationValue:CGFloat, color:UInt32) -> CGImage {
return generateImage(NSMakeSize(26, 20), contextGenerator: { (size, context) in
context.clear(NSMakeRect(0,0,size.width, size.height))
let leftPadding: CGFloat = 5.0
let topPadding: CGFloat = 7
let distance: CGFloat = 12.0 / 2.0
let minAlpha: CGFloat = 0.75
let deltaAlpha: CGFloat = 1.0 - minAlpha
var radius: CGFloat = 0.0
var ellipse:NSRect = NSZeroRect
radius = radiusFunction(animationValue, timeOffset: 0.4)
radius = (max(minDiameter, radius) - minDiameter) / (maxDiameter - minDiameter)
radius = radius * 1.5
var dotsColor: NSColor = NSColor(color, (radius * deltaAlpha + minAlpha))
context.setFillColor(dotsColor.cgColor)
ellipse = NSMakeRect(leftPadding - minDiameter / 2.0 - radius / 2.0, topPadding - minDiameter / 2.0 - radius / 2.0, minDiameter + radius, minDiameter + radius)
context.fillEllipse(in: ellipse)
radius = radiusFunction(animationValue, timeOffset: 0.2)
radius = (max(minDiameter, radius) - minDiameter) / (maxDiameter - minDiameter)
radius = radius * 1.5
dotsColor = NSColor(color, (radius * deltaAlpha + minAlpha))
context.setFillColor(dotsColor.cgColor)
ellipse = NSMakeRect(leftPadding + distance - minDiameter / 2.0 - radius / 2.0, topPadding - minDiameter / 2.0 - radius / 2.0, minDiameter + radius, minDiameter + radius)
context.fillEllipse(in: ellipse)
radius = radiusFunction(animationValue, timeOffset: 0.0)
radius = (max(minDiameter, radius) - minDiameter) / (maxDiameter - minDiameter)
radius = radius * 1.5
dotsColor = NSColor(color, (radius * deltaAlpha + minAlpha))
context.setFillColor(dotsColor.cgColor)
ellipse = NSMakeRect(leftPadding + distance * 2.0 - minDiameter / 2.0 - radius / 2.0, topPadding - minDiameter / 2.0 - radius / 2.0, minDiameter + radius, minDiameter + radius)
context.fillEllipse(in: ellipse)
})!
}
private func generateRecordingAnimatedImage(_ animationValue:CGFloat, color:UInt32) -> CGImage {
return generateImage(NSMakeSize(26, 20), contextGenerator: { (size, context) in
context.clear(NSMakeRect(0,0,size.width, size.height))
context.setStrokeColor(NSColor(color).cgColor)
context.setLineCap(.round)
context.setLineWidth(3)
let delta: CGFloat = 5.0
let x: CGFloat = 4
let y: CGFloat = 7.0
let angle = CGFloat(18.0 * .pi / 180.0)
let animationValue: CGFloat = animationValue * delta
var radius: CGFloat = 0.0
var alpha: CGFloat = 0.0
radius = animationValue
alpha = radius/(3*delta);
alpha = 1.0 - pow(cos(alpha * (CGFloat.pi/2)), 50);
context.setAlpha(alpha);
context.beginPath();
context.addArc(center: NSMakePoint(x, y), radius: radius, startAngle: -angle, endAngle: angle, clockwise: false)
context.strokePath();
radius = animationValue + delta;
alpha = radius / (3.0 * delta);
alpha = 1.0 - pow(cos(alpha * CGFloat.pi), 10);
context.setAlpha(alpha);
context.beginPath();
context.addArc(center: NSMakePoint(x, y), radius: radius, startAngle: -angle, endAngle: angle, clockwise: false)
context.strokePath();
radius = animationValue + delta*2;
alpha = radius / (3.0 * delta);
alpha = 1.0 - pow(cos(alpha * CGFloat.pi), 10);
context.setAlpha(alpha);
context.beginPath();
context.addArc(center: NSMakePoint(x, y), radius: radius, startAngle: -angle, endAngle: angle, clockwise: false)
context.strokePath();
})!
}
private func generateChoosingStickerAnimatedImage(_ animationValue:CGFloat, color:NSColor) -> CGImage {
return generateImage(NSMakeSize(24, 20), contextGenerator: { (size, context) in
context.clear(size.bounds)
context.setFillColor(color.cgColor)
context.setStrokeColor(color.cgColor)
var heightProgress: CGFloat = animationValue * 4.0
if heightProgress > 3.0 {
heightProgress = 4.0 - heightProgress
} else if heightProgress > 2.0 {
heightProgress = heightProgress - 2.0
heightProgress *= heightProgress
} else if heightProgress > 1.0 {
heightProgress = 2.0 - heightProgress
} else {
heightProgress *= heightProgress
}
var pupilProgress: CGFloat = animationValue * 4.0
if pupilProgress > 2.0 {
pupilProgress = 3.0 - pupilProgress
}
pupilProgress = min(1.0, max(0.0, pupilProgress))
pupilProgress *= pupilProgress
var positionProgress: CGFloat = animationValue * 2.0
if positionProgress > 1.0 {
positionProgress = 2.0 - positionProgress
}
let eyeWidth: CGFloat = 6.0
let eyeHeight: CGFloat = 11.0 - 2.0 * heightProgress
let eyeOffset: CGFloat = -1.0 + positionProgress * 2.0
let leftCenter = CGPoint(x: size.bounds.width / 2.0 - eyeWidth - 1.0 + eyeOffset, y: size.bounds.height / 2.0)
let rightCenter = CGPoint(x: size.bounds.width / 2.0 + 1.0 + eyeOffset, y: size.bounds.height / 2.0)
let pupilSize: CGFloat = 4.0
let pupilCenter = CGPoint(x: -1.0 + pupilProgress * 2.0, y: 0.0)
context.strokeEllipse(in: CGRect(x: leftCenter.x - eyeWidth / 2.0, y: leftCenter.y - eyeHeight / 2.0, width: eyeWidth, height: eyeHeight))
context.fillEllipse(in: CGRect(x: leftCenter.x - pupilSize / 2.0 + pupilCenter.x * eyeWidth / 4.0, y: leftCenter.y - pupilSize / 2.0, width: pupilSize, height: pupilSize))
context.strokeEllipse(in: CGRect(x: rightCenter.x - eyeWidth / 2.0, y: rightCenter.y - eyeHeight / 2.0, width: eyeWidth, height: eyeHeight))
context.fillEllipse(in: CGRect(x: rightCenter.x - pupilSize / 2.0 + pupilCenter.x * eyeWidth / 4.0, y: rightCenter.y - pupilSize / 2.0, width: pupilSize, height: pupilSize))
})!
}
private func generateUploadFileAnimatedImage(_ animationValue:CGFloat, backgroundColor:UInt32, foregroundColor: UInt32) -> CGImage {
return generateImage(NSMakeSize(26, 20), contextGenerator: { (size, context) in
context.clear(NSMakeRect(0,0,size.width, size.height))
let leftPadding: CGFloat = 7.0
let topPadding: CGFloat = 4.0
let progressWidth: CGFloat = 26.0 / 2.0
let progressHeight: CGFloat = 10.0 / 2.0
var progress: CGFloat = 0.0
// let round: CGFloat = 1.25
var dotsColor = NSColor(backgroundColor)
context.setFillColor(dotsColor.cgColor)
context.addPath(CGPath(roundedRect: CGRect(x: leftPadding, y: topPadding, width: progressWidth, height: progressHeight), cornerWidth: 2, cornerHeight: 2, transform: nil))
context.closePath()
context.fillPath()
// context.fill(CGRect(x: leftPadding, y: topPadding, width: progressWidth, height: progressHeight))
dotsColor = NSColor(foregroundColor, 0.3)
context.setFillColor(dotsColor.cgColor)
context.addPath(CGPath(roundedRect: CGRect(x: leftPadding, y: topPadding, width: progressWidth, height: progressHeight), cornerWidth: 2, cornerHeight: 2, transform: nil))
context.closePath()
context.fillPath()
// context.fill(CGRect(x: leftPadding, y: topPadding, width: progressWidth, height: progressHeight))
progress = interpolate(from: 0.0, to: progressWidth * 2.0, value: animationValue)
dotsColor = NSColor(foregroundColor, 1.0)
context.setFillColor(dotsColor.cgColor)
context.setBlendMode(.sourceIn)
// context.fill(CGRect(x: CGFloat(leftPadding - progressWidth + progress), y: topPadding, width: progressWidth, height: progressHeight))
context.addPath(CGPath(roundedRect: CGRect(x: CGFloat(leftPadding - progressWidth + progress), y: topPadding, width: progressWidth, height: progressHeight), cornerWidth: 2, cornerHeight: 2, transform: nil))
context.closePath()
context.fillPath()
})!
}
let recordVoiceActivityAnimationBlue:[CGImage] = {
var steps:[CGImage] = []
var animationValue:CGFloat = 0
for i in 0 ..< 42 {
steps.append(generateRecordingAnimatedImage( CGFloat(i) / 42, color: 0x2481cc))
}
return steps
}()
let textActivityAnimationBlue:[CGImage] = {
var steps:[CGImage] = []
var animationValue:CGFloat = 0
for i in 0 ..< 42 {
steps.append(generateTextAnimatedImage( CGFloat(i) / 42, color: 0x2481cc))
}
return steps
}()
let recordVoiceActivityAnimationWhite:[CGImage] = {
var steps:[CGImage] = []
var animationValue:CGFloat = 0
for i in 0 ..< 42 {
steps.append(generateRecordingAnimatedImage( CGFloat(i) / 42, color: 0xffffff))
}
return steps
}()
let textActivityAnimationWhite:[CGImage] = {
var steps:[CGImage] = []
for i in 0 ..< 42 {
steps.append(generateTextAnimatedImage( CGFloat(i) / 42, color: 0xffffff))
}
return steps
}()
func recordVoiceActivityAnimation(_ color: NSColor) -> [CGImage] {
var steps:[CGImage] = []
for i in 0 ..< 42 {
steps.append(generateRecordingAnimatedImage( CGFloat(i) / 42, color: color.rgb))
}
return steps
}
func choosingStickerActivityAnimation(_ color: NSColor) -> [CGImage] {
var steps:[CGImage] = []
for i in 0 ..< 120 {
steps.append(generateChoosingStickerAnimatedImage( CGFloat(i) / 120, color: color))
}
return steps
}
func uploadFileActivityAnimation(_ foregroundColor: NSColor, _ backgroundColor: NSColor) -> [CGImage] {
var steps:[CGImage] = []
for i in 0 ..< 105 {
steps.append(generateUploadFileAnimatedImage( CGFloat(i) / 105, backgroundColor: backgroundColor.rgb, foregroundColor: foregroundColor.rgb))
}
return steps
}
func textActivityAnimation(_ color: NSColor) -> [CGImage] {
var steps:[CGImage] = []
for i in 0 ..< 42 {
steps.append(generateTextAnimatedImage( CGFloat(i) / 42, color: color.rgb))
}
return steps
}
| gpl-2.0 | 69612c1e87bc4212001307181a54f397 | 37.742964 | 214 | 0.629298 | 3.94084 | false | false | false | false |
cristik/CKPromise.Swift | CKPromise.Swift/CKPromise.swift | 1 | 9337 | //
// CKPromise.swift
// CKPromise
//
// Created by Cristian Kocza on 06/06/16.
// Copyright © 2016 Cristik. All rights reserved.
//
import Dispatch
/// A promise represents the eventual result of an asynchronous operation.
/// The primary way of interacting with a promise is through its `then` method,
/// which registers callbacks to receive either a promise’s eventual value or
/// the reason why the promise cannot be fulfilled.
public final class Promise<S, E> {
internal var state: PromiseState<S,E> = .pending
private var mutex = pthread_mutex_t()
private var successHandlers: [(S) -> Void] = []
private var failureHandlers: [(E) -> Void] = []
/// Creates a pending promise
public required init() {
var attr = pthread_mutexattr_t()
guard pthread_mutexattr_init(&attr) == 0 else {
preconditionFailure()
}
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)
guard pthread_mutex_init(&mutex, &attr) == 0 else {
preconditionFailure()
}
}
deinit {
pthread_mutex_destroy(&mutex)
}
/// Creates a fulfilled promise
public convenience init(fulfilledWith value: S) {
self.init()
state = .fulfilled(value)
}
/// Creates a rejected promise
public convenience init(rejectedWith reason: E) {
self.init()
state = .rejected(reason)
}
/// Returns a promise that waits for the gived promises to either success
/// or fail. Reports success if at least one of the promises succeeded, and
/// failure if all of them failed.
public static func whenAll<S2,E2>(promises: [Promise<S2,E2>]) -> Promise<[S2],E2> {
let promise2 = Promise<[S2],E2>()
var remainingPromises: Int = promises.count
var values = [S2]()
var errors = [E2]()
let check = {
if remainingPromises == 0 {
if promises.count > 0 && errors.count == promises.count {
promise2.reject(errors.first!)
} else {
promise2.resolve(values)
}
}
}
for promise in promises {
promise.registerSuccess {
remainingPromises -= 1
values.append($0);
check()
}
promise.registerFailure {
remainingPromises -= 1
errors.append($0);
check()
}
}
return promise2
}
/// This is the `then` method. It allows clients to observe the promise's
/// result - either success or failure.
/// The success/failure handlers are dispatched on the main thread, in an
/// async manner, thus after the current runloop cycle ends
/// Returns a promise that gets fulfilled with the result of the
/// success/failure callback
@discardableResult
public func on<V>(success: @escaping (S) -> V, failure: @escaping (E) -> V) -> Promise<V,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<V,E>()
self.registerSuccess { promise2.resolve(success($0)) }
self.registerFailure { promise2.resolve(failure($0)) }
return promise2
}
@discardableResult
public func on<V>(success: @escaping (S) -> Promise<V,E>, failure: @escaping (E) -> V) -> Promise<V,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<V,E>()
self.registerSuccess { promise2.resolve(success($0)) }
self.registerFailure { promise2.resolve(failure($0)) }
return promise2
}
@discardableResult
public func on<V>(success: @escaping (S) -> V, failure: @escaping (E) -> Promise<V,E>) -> Promise<V,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<V,E>()
self.registerSuccess { promise2.resolve(success($0)) }
self.registerFailure { promise2.resolve(failure($0)) }
return promise2
}
/// Returns a promise that gets fulfilled with the result of the
/// success/failure callback.
@discardableResult
public func on<V>(success: @escaping (S) -> Promise<V,E>, failure: @escaping (E) -> Promise<V,E>) -> Promise<V,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<V,E>()
self.registerSuccess { promise2.resolve(success($0)) }
self.registerFailure { promise2.resolve(failure($0)) }
return promise2
}
/// Returns a promise that gets fulfilled with the result of the
/// success callback
@discardableResult
public func onSuccess<V>(_ success: @escaping (S) -> V) -> Promise<V,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<V,E>()
self.registerSuccess { promise2.resolve(success($0)) }
self.registerFailure { promise2.reject($0) }
return promise2
}
/// Returns a promise that gets fulfilled with the result of the
/// success callback
@discardableResult
public func onSuccess<V>(_ success: @escaping (S) -> Promise<V,E>) -> Promise<V,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<V,E>()
self.registerSuccess { promise2.resolve(success($0)) }
self.registerFailure { promise2.reject($0) }
return promise2
}
/// Registers a failure callback. The returned promise gets resolved with
/// the value returned by the callback
@discardableResult
public func onFailure(_ failure: @escaping (E) -> S) -> Promise<S,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<S,E>()
self.registerSuccess { promise2.resolve($0) }
self.registerFailure { promise2.resolve(failure($0)) }
return promise2
}
/// Registers a failure callback. The returned promise gets resolved with
/// the value returned by the callback
@discardableResult
public func onFailure(_ failure: @escaping (E) -> Promise<S,E>) -> Promise<S,E> {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
let promise2 = Promise<S,E>()
self.registerSuccess { promise2.resolve($0) }
self.registerFailure { promise2.resolve(failure($0)) }
return promise2
}
/// Registers a failure callback. Returns nothing, this is an helper to be
// used at the end of promise chains
public func onFailure(failure: @escaping (E) -> Void) {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
self.registerFailure { failure($0) }
}
/// Resolves the promise with the given value. Executes all registered
/// callbacks, in the order they were scheduled
public func resolve(_ value: S) {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
guard case .pending = self.state else { return }
self.state = .fulfilled(value)
for handler in self.successHandlers {
self.dispatch(value, handler)
}
self.successHandlers.removeAll()
self.failureHandlers.removeAll()
}
/// Resolves the promise with the given promise. This makes the receiver
// take the state of the given promise
public func resolve(_ promise: Promise<S,E>) {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
guard case .pending = self.state, promise !== self else { return }
promise.registerSuccess { self.resolve($0) }
promise.registerFailure { self.reject($0) }
}
/// Rejects the promise with the given reason. Executes all registered
/// failure callbacks, in the order they were scheduled
public func reject(_ reason: E) {
pthread_mutex_lock(&mutex)
defer { pthread_mutex_unlock(&mutex) }
guard case .pending = self.state else { return }
self.state = .rejected(reason)
for handler in self.failureHandlers {
self.dispatch(reason, handler)
}
self.successHandlers.removeAll()
self.failureHandlers.removeAll()
}
private func registerSuccess(handler: @escaping (S)->Void) {
switch state {
case .pending: successHandlers.append(handler)
case .fulfilled(let value): dispatch(value, handler)
case .rejected: break
}
}
private func registerFailure(handler: @escaping (E)->Void) {
switch state {
case .pending: failureHandlers.append(handler)
case .fulfilled: break
case .rejected(let reason): dispatch(reason, handler)
}
}
private func dispatch<T>(_ arg: T, _ handler: @escaping (T) -> Void) {
DispatchQueue.main.async {
handler(arg)
}
}
}
internal enum PromiseState<S,E> {
case pending
case fulfilled(S)
case rejected(E)
}
| bsd-2-clause | 52936ec02c27bf09933740e3690559f1 | 34.222642 | 119 | 0.597922 | 4.319297 | false | false | false | false |
Nefuln/LNAddressBook | LNAddressBook/LNAddressBook/LNAddressBookUI/Edit/View/LNDetaiTableView.swift | 1 | 3502 | //
// LNDetaiTableView.swift
// LNAddressBook
//
// Created by 浪漫满屋 on 2017/8/1.
// Copyright © 2017年 com.man.www. All rights reserved.
//
import UIKit
import Contacts
class LNDetaiTableView: UITableView {
// MARK:- Public property
var contact: CNContact?
var detailPhoneBlock: ((_ phone: String) -> Void)?
var sendSmsBlock: (([[String : String]]) -> Void)?
var scrollBlock: ((_ contentOffset: CGPoint) -> Void)?
// MARK:- Public func
public func reload(with contact: CNContact) {
self.contact = contact
self.reloadData()
}
// MARK:- Override
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- Private func
private func initUI() {
tableFooterView = UIView()
separatorStyle = .none
register(LNDetailPhoneCell.self, forCellReuseIdentifier: NSStringFromClass(LNDetailPhoneCell.self))
register(LNDetailCommonCell.self, forCellReuseIdentifier: NSStringFromClass(LNDetailCommonCell.self))
dataSource = self
delegate = self
}
}
extension LNDetaiTableView: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contact?.mPhones == nil ? 1 : (self.contact?.mPhones!.count)! + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row < (self.contact?.mPhones?.count)! {
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(LNDetailPhoneCell.self), for: indexPath) as! LNDetailPhoneCell
cell.titleLabel.text = self.contact?.mPhones?[indexPath.row].keys.first
var phone = self.contact?.mPhones?[indexPath.row].values.first
if !(phone?.contains("-"))! {
phone?.insert("-", at: (phone?.index((phone?.startIndex)!, offsetBy: 3))!)
phone?.insert("-", at: (phone?.index((phone?.startIndex)!, offsetBy: 7))!)
}
cell.phoneLabel.text = phone
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(LNDetailCommonCell.self), for: indexPath) as! LNDetailCommonCell
switch indexPath.row - (self.contact?.mPhones?.count)! {
case 0:
cell.titleLabel.text = "发送信息"
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row < (self.contact?.mPhones?.count)! && (detailPhoneBlock != nil) {
detailPhoneBlock!((tableView.cellForRow(at: indexPath) as! LNDetailPhoneCell).phoneLabel.text!)
}
if indexPath.row - (self.contact?.mPhones?.count)! == 0 && sendSmsBlock != nil {
sendSmsBlock!((self.contact?.mPhones)!)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollBlock != nil {
scrollBlock!(self.contentOffset)
}
}
}
| mit | 5196e1d13e12903f25b3b226906a0e64 | 34.540816 | 149 | 0.627046 | 4.564875 | false | false | false | false |
ITzTravelInTime/TINU | TINU/FileAliasManager.swift | 1 | 2249 | /*
TINU, the open tool to create bootable macOS installers.
Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import Foundation
public final class FileAliasManager{
@inline(__always) class func resolve(at url: URL) -> String? {
var origin: URL!
if process(url, resolvedURL: &origin) != nil{
return origin?.path
}
return nil
}
@inline(__always) class func resolve(at path: String) -> String? {
return resolve(at: URL(fileURLWithPath: path, isDirectory: true))
}
@inline(__always) class func isAlias(_ url: URL) -> Bool?{
var origin: URL!
return process(url, resolvedURL: &origin)
}
@inline(__always) class func isAlias(_ path: String) -> Bool?{
return isAlias(URL(fileURLWithPath: path))
}
@inline(__always) class func finderAlias(_ path: String, resolvedPath: inout String?) -> Bool?{
var tmp: URL?
let res = process(URL(fileURLWithPath: path, isDirectory: true), resolvedURL: &tmp)
resolvedPath = tmp?.path
return res
}
class func process(_ url: URL, resolvedURL: inout URL?) -> Bool?{
do {
if try !url.resourceValues(forKeys: [.isAliasFileKey]).isAliasFile! {
resolvedURL = url
return false
}
let original = try URL(resolvingAliasFileAt: url)
if !FileManager.default.fileExists(atPath: original.path){
resolvedURL = nil
return nil
}
if process(original ,resolvedURL: &resolvedURL) == nil{
resolvedURL = nil
return nil
}
resolvedURL = original
return true
} catch {
print(error)
resolvedURL = nil
return nil
}
}
}
| gpl-2.0 | bb4ad7ba2c83b2a72883f29cb47915ec | 26.765432 | 96 | 0.706981 | 3.699013 | false | false | false | false |
JakeLin/IBAnimatable | Sources/ActivityIndicators/Animations/ActivityIndicatorAnimationBallPulseSync.swift | 2 | 2013 | //
// Created by Tom Baranes on 21/08/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallPulseSync: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 0.6
fileprivate var size: CGSize = .zero
fileprivate var circleSize: CGFloat = 0
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
self.size = size
circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - circleSize) / 2
let beginTime = layer.currentMediaTime
let beginTimes: [CFTimeInterval] = [0.07, 0.14, 0.21]
let animation = defaultAnimation
// Draw circles
for i in 0 ..< 3 {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallPulseSync {
var defaultAnimation: CAKeyframeAnimation {
let deltaY = (size.height / 2 - circleSize / 2) / 2
let timingFunction: TimingFunctionType = .easeInOut
let animation = CAKeyframeAnimation(keyPath: .translationY)
animation.keyTimes = [0, 0.33, 0.66, 1]
animation.timingFunctionsType = [timingFunction, timingFunction, timingFunction]
animation.values = [0, deltaY, -deltaY, 0]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
| mit | c68925b48f2f1ac1c326d60b46e4faef | 30.936508 | 125 | 0.679423 | 4.501119 | false | false | false | false |
joeblau/gitignore.io | Sources/App/Controllers/TemplateController.swift | 1 | 3696 | //
// TemplateController.swift
// GitignoreIO
//
// Created by Joe Blau on 12/17/16.
//
//
import Foundation
internal struct TemplateController: ReadOnlyTemplateManagerProtocol {
internal var order = [String: Int]()
internal var count = 0
internal var templates = [String: IgnoreTemplateModel]()
/// Create Template Controller
///
/// - Returns: Template Controller
init(dataDirectory: URL, orderFile: URL) {
do {
order = try parseFile(orderFile: orderFile)
templates = try parseTemplateDirectory(dataDirectory: dataDirectory)
try templates.patchTemplates(dataDirectory: dataDirectory)
try templates.stackTempaltes(dataDirectory: dataDirectory)
count = templates.count
} catch {
print("‼️ You might not have done a recursive clone to update your submodules:\n‼️ `git submodule update --init --recursive`")
}
}
// MARK: - Private
/// Parse file which defines template order precedence
///
/// - Parameter orderFile: The dependency order file
/// - Returns: List of templates in order precedence
private func parseFile(orderFile: URL) throws -> [String: Int] {
return try String(contentsOf: orderFile, encoding: String.Encoding.utf8)
.replacingOccurrences(of: "\r\n", with: "\n", options: .regularExpression)
.components(separatedBy: "\n")
.map({ (line) -> String in
line.trimmingCharacters(in: .whitespaces).lowercased()
})
.filter({ (line) -> Bool in
!line.hasPrefix("#") && !line.isEmpty
})
.enumerated()
.reduce([String: Int](), { (orderedDict, line : (offset: Int, text: String)) -> [String: Int] in
var mutableOrderedDict = orderedDict
mutableOrderedDict[line.text] = line.offset
return mutableOrderedDict
})
}
/// Parse template directory
///
/// - Parameter dataDirectory: The path to the data directory
/// - Returns: Ignore template model dictionary
private func parseTemplateDirectory(dataDirectory: URL) throws -> [String: IgnoreTemplateModel] {
return try FileManager().enumerator(at: dataDirectory, includingPropertiesForKeys: nil)!
.allObjects
.compactMap({ (templatePath: Any) -> URL? in
templatePath as? URL
})
.filter({ (templatePath: URL) -> Bool in
templatePath.pathExtension == TemplateSuffix.template.extension
})
.compactMap({ (templatePath: URL) -> (key: String, model: IgnoreTemplateModel) in
let fileContents = try String(contentsOf: templatePath, encoding: String.Encoding.utf8)
.replacingOccurrences(of: "\r\n", with: "\n", options: .regularExpression)
return (key: templatePath.name.lowercased(),
model: IgnoreTemplateModel(key: templatePath.name.lowercased(),
name: templatePath.name,
fileName: templatePath.fileName,
contents: TemplateSuffix.template.header(name: templatePath.name).appending(fileContents)))
})
.reduce([String: IgnoreTemplateModel]()) { (currentTemplateModels, templateData) in
var mutableCurrentTemplates = currentTemplateModels
mutableCurrentTemplates[templateData.key] = templateData.model
return mutableCurrentTemplates
}
}
}
| mit | 4738bc2f57f438d19573032b76060319 | 43.433735 | 142 | 0.595174 | 5.086897 | false | false | false | false |
nodekit-io/nodekit-darwin | src/samples/sample-nodekit/platform-ios/SamplePlugin.swift | 1 | 2404 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import UIKit
import NodeKit
protocol SamplePluginProtocol: NKScriptExport {
func logconsole(text: AnyObject?) -> Void
func alertSync(text: AnyObject?) -> String
}
class SamplePlugin: NSObject, SamplePluginProtocol {
class func attachTo(context: NKScriptContext) {
context.loadPlugin(SamplePlugin(), namespace: "io.nodekit.test", options: ["PluginBridge": NKScriptExportType.NKScriptExport.rawValue])
}
func logconsole(text: AnyObject?) -> Void {
NKLogging.log(text as? String! ?? "")
}
func alertSync(text: AnyObject?) -> String {
let alertBlock = { () -> Void in
self._alert(title: text as? String, message: nil)
}
if (NSThread.isMainThread()) {
alertBlock()
} else {
dispatch_async(dispatch_get_main_queue(), alertBlock)
}
return "OK"
}
private func _alert(title title: String?, message: String?) {
let buttons: [String] = ["Ok"]
let title: String = title ?? ""
let message: String = message ?? ""
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
for i in 0 ..< buttons.count {
let buttonTitle: String = buttons[i] ?? ""
let buttonAction = UIAlertAction(title: buttonTitle, style: (buttonTitle == "Cancel" ? .Cancel : .Default), handler: nil)
alertController.addAction(buttonAction)
}
guard let viewController = UIApplication.sharedApplication().delegate!.window!?.rootViewController else {return;}
viewController.presentViewController(alertController, animated: true, completion: nil)
}
}
| apache-2.0 | 7282bd09b4b50499a8bcd6bf8a594db6 | 34.880597 | 143 | 0.650166 | 4.55303 | false | false | false | false |
nofelmahmood/CustomTransitions-sample | CustomTransitions-sample/ViewController.swift | 1 | 2173 | //
// ViewController.swift
// CustomTransitions-sample
//
// Created by Nofel Mahmood on 06/09/2017.
// Copyright © 2017 nineish. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var anotherViewController: UIViewController!
var dismissInteractionController: InteractionController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func handleButtonTap(sender: AnyObject) {
performSegue(withIdentifier: "Show", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Show" {
let destinationViewController = segue.destination
anotherViewController = segue.destination
destinationViewController.modalPresentationStyle = .custom
dismissInteractionController = InteractionController(presentedViewController: segue.destination)
destinationViewController.transitioningDelegate = self
}
}
}
extension ViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController = AnimationController()
return animationController
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animationController = AnimationController()
animationController.direction = .Dismiss
return animationController
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return dismissInteractionController.isInteracting ? dismissInteractionController: nil
}
}
| mit | 30c28fff8122c53896d236d7356026fa | 32.9375 | 170 | 0.712247 | 6.724458 | false | false | false | false |
chamander/Sampling-Reactive | Source/RotatingContent/RotatingContentController.swift | 2 | 5482 | // Copyright © 2016 Gavan Chan. All rights reserved.
import Foundation
import RxCocoa
import RxSwift
import UIKit
final class RotatingContentController: UIViewController {
private weak var currentController: UIViewController? = nil
private let disposables: CompositeDisposable = CompositeDisposable()
private var transitionDisposableKey: CompositeDisposable.DisposeKey? = nil
deinit { disposables.dispose() }
internal var contentProducer: Observable<UIViewController?> = .empty() {
didSet {
if let key: CompositeDisposable.DisposeKey = transitionDisposableKey { disposables.remove(for: key) }
let disposable: Disposable = transitions
.observeOn(MainScheduler.asyncInstance)
.subscribe { [weak self] in self?.perform(transition: $0) }
transitionDisposableKey = disposables.insert(disposable)
}
}
internal var animationDuration: TimeInterval = 0.5
internal var animationOptions: UIViewAnimationOptions = [.transitionCrossDissolve]
internal var animatesTransitions: Bool { return !animationOptions.isEmpty }
override func viewDidLoad() {
super.viewDidLoad()
contentProducer = testObservable
}
private var _animationDuration: TimeInterval {
return animatesTransitions ? animationDuration : 0.0
}
private var transitions: Observable<Transition<UIViewController>> {
return contentProducer
.map(WeakBox.init)
.combiningPrevious(startingWith: WeakBox(containing: currentController))
.map { Transition(from: $0.value, to: $1.value) }
.ignoringNil()
}
private func perform(transition: Transition<UIViewController>) {
switch transition {
case let .appearing(content):
perform(appearingTransitionTo: content)
case let .disappearing(content):
perform(disappearingTransitionFrom: content)
case let .transitioning(source, destination):
performTransition(from: source, to: destination)
}
}
private func perform(appearingTransitionTo destination: UIViewController) {
addChildViewController(destination)
currentController = destination
DispatchQueue.main.async {
destination.view.frame = self.view.bounds
let animation: (() -> Void) = {
self.view.removeSubviews()
self.view.addSubview(destination.view)
}
let completion: ((Bool) -> Void) = { _ in
destination.didMove(toParentViewController: self)
}
UIView.transition(
with: self.view,
duration: self._animationDuration,
options: self.animationOptions,
animations: animation,
completion: completion)
}
}
private func perform(disappearingTransitionFrom current: UIViewController) {
current.willMove(toParentViewController: nil)
DispatchQueue.main.async {
let animation: (() -> Void) = {
// Must remember to load no content view.`
current.view.removeFromSuperview()
}
let completion: ((Bool) -> Void) = { _ in
current.removeFromParentViewController()
self.currentController = nil
current.didMove(toParentViewController: nil)
}
UIView.transition(
with: self.view,
duration: self._animationDuration,
options: self.animationOptions,
animations: animation,
completion: completion)
}
}
private func performTransition(from source: UIViewController, to destination: UIViewController) {
addChildViewController(destination)
currentController = destination
source.willMove(toParentViewController: nil)
DispatchQueue.main.async {
let completion: ((Bool) -> Void) = { _ in
source.removeFromParentViewController()
destination.didMove(toParentViewController: self)
}
self.transition(
from: source,
to: destination,
duration: self._animationDuration,
options: self.animationOptions,
animations: nil,
completion: completion)
}
}
private var testObservable: Observable<UIViewController?> {
return Observable<UIViewController>.create { observer in
var disposed: Bool = false
func dispatch(_ work: @escaping (() -> Void)) {
if !disposed { DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute: work) }
}
let restartBlock: (() -> Void) = {
let restart: UIViewController = PlaceholderActionViewController(withPlaceholderText: "Lorem Ipsum.", buttonText: "Restart") { [unowned self] in
self.contentProducer = self.testObservable
}
observer.onNext(restart)
observer.onCompleted()
}
let quxBazBlock: (() -> Void) = {
let quxBaz: UIViewController = PlaceholderTextViewController(with: "Qux Baz...!")
observer.onNext(quxBaz)
dispatch(restartBlock)
}
let fooBarBlock: (() -> Void) = {
let fooBar: UIViewController = PlaceholderTextViewController(with: "Foo Bar?!")
observer.onNext(fooBar)
dispatch(quxBazBlock)
}
DispatchQueue.main.async {
let helloWorld: UIViewController = PlaceholderTextViewController(with: "Hello World!")
observer.onNext(helloWorld)
dispatch(fooBarBlock)
}
return Disposables.create { disposed = true }
}.map(Optional.init)
}
}
fileprivate extension UIView {
func removeSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
}
| mit | 7170b0a566b47fd03835cd0858812ae5 | 28.31016 | 151 | 0.676336 | 5.060942 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBSelectionDialogView.swift | 1 | 15831 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
/// 選択ダイアログビューのオプション設定
public struct NBSelectionDialogViewOption {
/// イニシャライザ
public init(title: String? = nil) {
self.title = title
}
/// タイトル
public var title: String? = nil
/// 選択肢を選択した時点で選択完了とするかどうか(trueでOK/キャンセルボタンを非表示にします)
public var shouldCommitWhenSelectedItem = false
/// タイトルがnilの場合にタイトル部分をビューから削除するかどうか
public var shouldRemoveTitleLabelIfGivenNil = false
/// セットアップデリゲート
public weak var setupDelegate: NBSelectionDialogViewSetupDelegate? = nil
/// ダイアログオプション
public var dialogOption = NBDialogPresentationOption(cancellable: true)
/// 選択肢アイテムの高さ
public var itemHeight: CGFloat = 44.0
/// 選択肢アイテムの文字色
public var itemColor: UIColor = UIColor.darkTextColor()
/// 選択肢アイテムのフォント
public var itemFont: UIFont = UIFont.systemFontOfSize(16.0)
/// 選択肢の選択スタイル(チェックマークを付ける時)
public var itemCheckingSelectionStyle: UITableViewCellSelectionStyle = .None
/// 選択肢の選択スタイル(選択によって確定させる時)
public var itemSelectingSelectionStyle: UITableViewCellSelectionStyle = .Default
/// 上部タイトル部分の高さ
public var titleHeight: CGFloat = 44.0
/// 上部タイトルの文字色
public var titleColor: UIColor = UIColor.darkTextColor()
/// 上部タイトルのフォント
public var titleFont: UIFont = UIFont.systemFontOfSize(12.0)
/// OKボタンの文言
public var commitButtonText = "OK"
/// キャンセルボタの文言
public var cancelButtonText = "Cancel"
/// 下部ボタンの高さ
public var controlButtonHeight: CGFloat = 44.0
/// 下部ボタンの文字色
public var controlButtonColor: UIColor = UIColor.blueColor()
/// 下部ボタンのフォント
public var controlButtonFont: UIFont = UIFont.systemFontOfSize(16.0)
/// セパレータの幅
public var separatorWidth: CGFloat = 1.0
/// セパレータの色
public var separatorColor: UIColor = UIColor.lightGrayColor()
/// 全体背景色
public var backgroundColor: UIColor = UIColor.whiteColor()
/// コーナーの丸み
public var cornerRadius: CGFloat = 6.0
/// 左右両端のマージン
public var horizontalSideMargin: CGFloat = 64.0
/// チェック済みの画像
public var checkedImage: UIImage?
/// 未チェックの画像
public var uncheckedImage: UIImage?
/// 一度に表示する選択肢の数(渡したitemsの数がこの値以上ならばスクロールする)
public var maximumItemNumber: Int = 5
}
/// 選択ダイアログビューのセットアップ用デリゲート
@objc public protocol NBSelectionDialogViewSetupDelegate {
/// セットアップが始まる直前に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
optional func selectionDialogViewWillSetup(dialogView: NBSelectionDialogView)
/// タイトル用ラベルがセットアップされた直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
/// - parameter titleLabel: タイトル用ラベルの参照
optional func selectionDialogView(dialogView: NBSelectionDialogView, didSetupTitleLabel titleLabel: UILabel)
/// 選択肢用テーブルビューがセットアップされた直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
/// - parameter itemsTableView: 選択肢用テーブルビュー
optional func selectionDialogView(dialogView: NBSelectionDialogView, didSetupItemsTableView itemsTableView: UITableView)
/// 確定用ボタンがセットアップされた直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
/// - parameter commitButton: 確定用ボタンの参照
optional func selectionDialogView(dialogView: NBSelectionDialogView, didSetupCommitButton commitButton: UIButton)
/// キャンセル用ボタンがセットアップされた直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
/// - parameter cancelButton: キャンセル用ボタンの参照
optional func selectionDialogView(dialogView: NBSelectionDialogView, didSetupCancelButton cancelButton: UIButton)
/// 選択肢用テーブルビューセルが生成された直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
/// - parameter cell: テーブルビューセルの参照
optional func selectionDialogView(dialogView: NBSelectionDialogView, didCreateItemTableViewCell cell: UITableViewCell)
/// 選択肢用テーブルビューセルがセットアップされた直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
/// - parameter cell: テーブルビューセルの参照
/// - parameter index: インデックス
optional func selectionDialogView(dialogView: NBSelectionDialogView, didSetupItemTableViewCell cell: UITableViewCell, atIndex index: Int)
/// セットアップされた直後に呼ばれる
/// - parameter dialogView: 選択ダイアログビューの参照
optional func selectionDialogViewDidSetup(dialogView: NBSelectionDialogView)
}
/// 選択ダイアログビュークラス
public class NBSelectionDialogView: UIView, UITableViewDelegate, UITableViewDataSource {
public typealias NBSelectionDialogHandler = (Int)->Void
private let CellID = "cell"
// MARK: プライベートプロパティ
private var items : [String]!
private var index = 0
private var handler : NBSelectionDialogHandler?
private var option : NBSelectionDialogViewOption!
private var itemsTableView = UITableView()
private var titleLabel = UILabel()
private var commitButton = UIButton()
private var cancelButton = UIButton()
/// 選択ダイアログビューを表示する
/// - parameter items: 選択肢文字列の配列
/// - parameter defaultIndex: 初期で選択されているインデックス番号
/// - parameter option: 選択ダイアログビューオプション
/// - parameter handler: 選択された時の処理
public class func show(items: [String], defaultIndex: Int = 0, option: NBSelectionDialogViewOption? = nil, handler: NBSelectionDialogHandler? = nil) {
let dialog = NBSelectionDialogView()
dialog.items = items
dialog.index = defaultIndex
dialog.handler = handler
dialog.option = option ?? dialog.defaultOption
dialog.setup()
dialog.presentAsDialog(dialog.properDialogOption)
}
// MARK: セットアップ
private func setup() {
let opt = self.option
let w = App.Dimen.Screen.Width - (opt.horizontalSideMargin * 2)
var h: CGFloat = 0, y: CGFloat = 0
opt.setupDelegate?.selectionDialogViewWillSetup?(self)
// タイトルがnilであり、オプション「shouldRemoveTitleLabelIfGivenNil」がtrueの場合は、ラベルを生成しない
if opt.title != nil || !opt.shouldRemoveTitleLabelIfGivenNil {
// タイトル
h = opt.titleHeight
self.titleLabel.frame = cr(0, y, w, h)
self.setupTitleLabel(self.titleLabel, opt: opt)
opt.setupDelegate?.selectionDialogView?(self, didSetupTitleLabel: self.titleLabel)
self.addSubview(self.titleLabel)
y += h
// セパレータ
h = self.drawHorizontalSeparator(w, y, opt)
y += h
}
// 選択肢用テーブルビュー
h = opt.itemHeight * CGFloat(self.displayedItemNumber)
self.itemsTableView.frame = cr(0, y, w, h)
self.itemsTableView.layer.cornerRadius = opt.cornerRadius
self.setupTableView(self.itemsTableView, opt: opt)
opt.setupDelegate?.selectionDialogView?(self, didSetupItemsTableView: self.itemsTableView)
self.addSubview(self.itemsTableView)
y += h
// オプション「shouldCommitWhenSelectedItem」がtrueならば、ボタンは設置しない
if !opt.shouldCommitWhenSelectedItem {
// セパレータ
h = self.drawHorizontalSeparator(w, y, opt)
y += h
// ボタン
h = opt.controlButtonHeight
let controlButtons = [self.commitButton, self.cancelButton]
for (i, controlButton) in controlButtons.enumerate() {
let bw = w / CGFloat(controlButtons.count)
let bx = bw * CGFloat(i)
controlButton.frame = CGRectMake(bx, y, bw, h)
if controlButton == self.commitButton {
self.setupControlButton(controlButton, opt: opt, text: opt.commitButtonText, action: "didTapCommitButton")
opt.setupDelegate?.selectionDialogView?(self, didSetupCommitButton: controlButton)
} else if controlButton == self.cancelButton {
self.setupControlButton(controlButton, opt: opt, text: opt.cancelButtonText, action: "didTapCancelButton")
opt.setupDelegate?.selectionDialogView?(self, didSetupCancelButton: controlButton)
}
self.addSubview(controlButton)
}
y += h
}
self.backgroundColor = opt.backgroundColor
self.layer.cornerRadius = opt.cornerRadius
self.frame = cr(0, 0, w, y)
opt.setupDelegate?.selectionDialogViewDidSetup?(self)
}
// MARK: コンポーネントのセットアップ
/// タイトル用ラベル
private func setupTitleLabel(label: UILabel, opt: NBSelectionDialogViewOption) {
label.text = opt.title
label.textColor = opt.titleColor
label.font = opt.titleFont
label.textAlignment = .Center
}
/// 選択肢用テーブルビュー
private func setupTableView(table: UITableView, opt: NBSelectionDialogViewOption) {
table.delegate = self
table.dataSource = self
table.separatorStyle = .None
table.rowHeight = opt.itemHeight
table.userInteractionEnabled = true
if self.items.count <= opt.maximumItemNumber {
table.scrollEnabled = false
}
}
/// ボタン
private func setupControlButton(button: UIButton, opt: NBSelectionDialogViewOption, text: String, action: String) {
button.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
button.setTitle(text, forState: .Normal)
button.setTitleColor(opt.controlButtonColor, forState: .Normal)
button.setTitleColor(opt.controlButtonColor.colorWithAlphaComponent(0.2), forState: .Highlighted)
}
// MARK: 汎用プライベート処理(メソッド/プロパティ)
/// デフォルトのオプション
private var defaultOption: NBSelectionDialogViewOption {
var ret = NBSelectionDialogViewOption()
ret.dialogOption.cancellable = true
return ret
}
/// 表示される選択肢の数(選択肢がこの数以上あればスクロールされる)
private var displayedItemNumber: Int {
let num = self.items.count
let max = self.option.maximumItemNumber
return num > max ? max : num
}
/// 水平線(セパレータ)を描画する共通処理
private func drawHorizontalSeparator(w: CGFloat, _ y: CGFloat, _ opt: NBSelectionDialogViewOption) -> CGFloat {
let separator = UIView(frame: cr(0, y, w, opt.separatorWidth))
separator.backgroundColor = opt.separatorColor
self.addSubview(separator)
return opt.separatorWidth
}
/// デフォルトのオプション
private var properDialogOption: NBDialogPresentationOption {
var opt = self.option
if opt.shouldCommitWhenSelectedItem {
opt.dialogOption.cancellable = true
} else {
opt.dialogOption.cancellable = false
}
return opt.dialogOption
}
// MARK: ボタンイベント
/// 確定ボタン押下時
@objc private func didTapCommitButton() {
self.handler?(self.index)
UIView.dismissPresentedDialog(self.option.dialogOption, completionHandler: nil)
}
/// キャンセルボタン押下時
@objc private func didTapCancelButton() {
UIView.dismissPresentedDialog(self.option.dialogOption, completionHandler: nil)
}
// MARK: テーブルビュー
/// 行数
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.items.count
}
/// セル返却
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let opt = self.option
let cell = tableView.dequeueReusableCellWithIdentifier(self.CellID) ?? self.createCell(opt)
self.setupCell(opt, index: indexPath.row, cell: cell)
return cell
}
/// 選択時
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
self.index = indexPath.row
if self.option.shouldCommitWhenSelectedItem {
self.didTapCommitButton()
} else {
tableView.reloadData()
}
}
/// セル生成
private func createCell(opt: NBSelectionDialogViewOption) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: self.CellID)
cell.selectionStyle = opt.shouldCommitWhenSelectedItem ? opt.itemSelectingSelectionStyle : opt.itemCheckingSelectionStyle
cell.textLabel!.font = opt.itemFont
cell.textLabel!.textColor = opt.itemColor
opt.setupDelegate?.selectionDialogView?(self, didCreateItemTableViewCell: cell)
return cell
}
/// セルのセットアップ
private func setupCell(opt: NBSelectionDialogViewOption, index: Int, cell: UITableViewCell) {
cell.textLabel!.text = self.items[index]
cell.accessoryView = nil
if index == self.index { // if selected
if let checkedImage = opt.checkedImage {
cell.accessoryView = UIImageView(image: checkedImage)
} else {
cell.accessoryType = .Checkmark
}
} else {
if let uncheckedImage = opt.uncheckedImage {
cell.accessoryView = UIImageView(image: uncheckedImage)
} else {
cell.accessoryType = .None
}
}
opt.setupDelegate?.selectionDialogView?(self, didSetupItemTableViewCell: cell, atIndex: index)
}
}
| apache-2.0 | db731447a64eb639441581c10bb9f4b5 | 35.637097 | 154 | 0.646122 | 4.372474 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Message Details/MessageDetailsViewController.swift | 1 | 8638 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireDataModel
/**
* A view controller wrapping the message details.
*/
final class MessageDetailsViewController: UIViewController, ModalTopBarDelegate {
/**
* The collection of view controllers displaying the content.
*/
enum ViewControllers {
/// We are displaying the combined view.
case combinedView(readReceipts: MessageDetailsContentViewController, reactions: MessageDetailsContentViewController)
/// We are displaying the single view.
case singleView(MessageDetailsContentViewController)
/// The read receipts view controller.
var readReceipts: MessageDetailsContentViewController {
switch self {
case .combinedView(let readReceipts, _): return readReceipts
case .singleView(let viewController): return viewController
}
}
/// The reactions view controller.
var reactions: MessageDetailsContentViewController {
switch self {
case .combinedView(_, let reactions): return reactions
case .singleView(let viewController): return viewController
}
}
/// All the view controllers.
var all: [MessageDetailsContentViewController] {
switch self {
case .combinedView(let readReceipts, let reactions):
return [readReceipts, reactions]
case .singleView(let viewController):
return [viewController]
}
}
}
// MARK: - Properties
/// The displayed message.
let message: ZMConversationMessage
/// The data source for the message details.
let dataSource: MessageDetailsDataSource
// MARK: - UI Elements
let container: TabBarController
let topBar = ModalTopBar()
let viewControllers: ViewControllers
// MARK: - Initialization
/**
* Creates a details view controller for the specified message displaying the first available tab by default.
* - parameter message: The message to display the details of.
*/
convenience init(message: ZMConversationMessage) {
self.init(message: message, preferredDisplayMode: .receipts)
}
/**
* Creates a details view controller for the specified message.
* - parameter message: The message to display the details of.
* - parameter preferredDisplayMode: The display mode to display by default when there are multiple
* tabs. Note that this object is only an indication, and will not override the displayed content
* if the data source says it is unavailable for the message.
*/
init(message: ZMConversationMessage, preferredDisplayMode: MessageDetailsDisplayMode) {
self.message = message
self.dataSource = MessageDetailsDataSource(message: message)
// Setup the appropriate view controllers
switch dataSource.displayMode {
case .combined:
let readReceiptsViewController = MessageDetailsContentViewController(contentType: .receipts(enabled: dataSource.supportsReadReceipts), conversation: dataSource.conversation)
let reactionsViewController = MessageDetailsContentViewController(contentType: .reactions, conversation: dataSource.conversation)
viewControllers = .combinedView(readReceipts: readReceiptsViewController, reactions: reactionsViewController)
case .reactions:
let reactionsViewController = MessageDetailsContentViewController(contentType: .reactions, conversation: dataSource.conversation)
viewControllers = .singleView(reactionsViewController)
case .receipts:
let readReceiptsViewController = MessageDetailsContentViewController(contentType: .receipts(enabled: dataSource.supportsReadReceipts), conversation: dataSource.conversation)
viewControllers = .singleView(readReceiptsViewController)
}
container = TabBarController(viewControllers: viewControllers.all)
if case .combined = dataSource.displayMode {
let tabIndex = preferredDisplayMode == .reactions ? 1 : 0
container.selectIndex(tabIndex, animated: false)
}
super.init(nibName: nil, bundle: nil)
self.modalPresentationStyle = .formSheet
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ColorScheme.default.statusBarStyle
}
// MARK: - Configuration
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = SemanticColors.View.backgroundDefault
dataSource.observer = self
// Configure the top bar
view.addSubview(topBar)
topBar.delegate = self
topBar.needsSeparator = false
topBar.backgroundColor = SemanticColors.View.backgroundDefault
topBar.configure(title: dataSource.title, subtitle: nil, topAnchor: safeTopAnchor)
reloadFooters()
// Configure the content
addChild(container)
view.addSubview(container.view)
container.didMove(toParent: self)
container.isTabBarHidden = dataSource.displayMode != .combined
container.isEnabled = dataSource.displayMode == .combined
// Create the constraints
configureConstraints()
// Display initial data
reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIAccessibility.post(notification: .layoutChanged, argument: topBar)
}
private func configureConstraints() {
topBar.translatesAutoresizingMaskIntoConstraints = false
container.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// topBar
topBar.topAnchor.constraint(equalTo: view.topAnchor),
topBar.leadingAnchor.constraint(equalTo: view.leadingAnchor),
topBar.trailingAnchor.constraint(equalTo: view.trailingAnchor),
// container
container.view.topAnchor.constraint(equalTo: topBar.bottomAnchor),
container.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
container.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
container.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
// MARK: - Data
func reloadData() {
switch dataSource.displayMode {
case .combined:
viewControllers.reactions.updateData(dataSource.reactions)
viewControllers.readReceipts.updateData(dataSource.readReceipts)
case .reactions:
viewControllers.reactions.updateData(dataSource.reactions)
case .receipts:
viewControllers.readReceipts.updateData(dataSource.readReceipts)
}
}
private func reloadFooters() {
viewControllers.all.forEach {
$0.subtitle = dataSource.subtitle
$0.accessibleSubtitle = dataSource.accessibilitySubtitle
}
}
// MARK: - Top Bar
override func accessibilityPerformEscape() -> Bool {
dismiss(animated: true)
return true
}
func modelTopBarWantsToBeDismissed(_ topBar: ModalTopBar) {
dismiss(animated: true)
}
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return wr_supportedInterfaceOrientations
}
}
// MARK: - MessageDetailsDataSourceObserver
extension MessageDetailsViewController: MessageDetailsDataSourceObserver {
func dataSourceDidChange(_ dataSource: MessageDetailsDataSource) {
reloadData()
}
func detailsFooterDidChange(_ dataSource: MessageDetailsDataSource) {
reloadFooters()
}
}
| gpl-3.0 | 661f28d4a6ddd3db70cc0e1490d1440d | 34.113821 | 185 | 0.689975 | 5.598185 | false | false | false | false |
einsteinx2/iSub | Classes/Data Model/PlaylistRepository.swift | 1 | 15995 | //
// PlaylistRepository.swift
// iSub
//
// Created by Benjamin Baron on 1/16/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
// Important note: Playlist table song indexes are 0 based to better interact with Swift/ObjC arrays.
// Normally SQLite table primary key fields start at 1 rather than 0. We force it to start at 0
// by inserting the first record with a manually chosen songIndex of 0.
struct PlaylistRepository: ItemRepository {
static let si = PlaylistRepository()
fileprivate let gr = GenericItemRepository.si
let table = "playlists"
let cachedTable = "playlists"
let itemIdField = "playlistId"
fileprivate func playlistTableName(playlistId: Int64, serverId: Int64) -> String {
return "playlist\(playlistId)_server\(serverId)"
}
func playlist(playlistId: Int64, serverId: Int64, loadSubItems: Bool = false) -> Playlist? {
return gr.item(repository: self, itemId: playlistId, serverId: serverId, loadSubItems: loadSubItems)
}
func allPlaylists(serverId: Int64? = nil, isCachedTable: Bool = false) -> [Playlist] {
let playlists: [Playlist] = gr.allItems(repository: self, serverId: serverId, isCachedTable: isCachedTable)
let excludedIds = [Playlist.playQueuePlaylistId, Playlist.downloadQueuePlaylistId, Playlist.downloadedSongsPlaylistId]
return playlists.filter({!excludedIds.contains($0.playlistId)})
}
func isPersisted(playlist: Playlist, isCachedTable: Bool = false) -> Bool {
return gr.isPersisted(repository: self, item: playlist, isCachedTable: isCachedTable)
}
func isPersisted(playlistId: Int64, serverId: Int64, isCachedTable: Bool = false) -> Bool {
return gr.isPersisted(repository: self, itemId: playlistId, serverId: serverId, isCachedTable: isCachedTable)
}
func delete(playlist: Playlist, isCachedTable: Bool = false) -> Bool {
return gr.delete(repository: self, item: playlist, isCachedTable: isCachedTable)
}
func replace(playlist: Playlist, isCachedTable: Bool = false) -> Bool {
var success = true
Database.si.write.inDatabase { db in
do {
let query = "REPLACE INTO \(self.table) VALUES (?, ?, ?, ?)"
try db.executeUpdate(query, playlist.playlistId, playlist.serverId, playlist.name, n2N(playlist.coverArtId))
try self.createPlaylistTable(db: db, playlistId: playlist.playlistId, serverId: playlist.serverId, name: playlist.name)
} catch {
success = false
printError(error)
}
}
return success
}
func hasCachedSubItems(playlist: Playlist) -> Bool {
let tableName = playlistTableName(playlistId: playlist.playlistId, serverId: playlist.serverId)
let query = "SELECT COUNT(*) FROM \(tableName) JOIN cachedSongs where \(tableName).songId = cachedSongs.songId"
return Database.si.read.boolForQuery(query)
}
fileprivate func createPlaylistTable(db: FMDatabase, playlistId: Int64, serverId: Int64, name: String) throws {
let table = playlistTableName(playlistId: playlistId, serverId: serverId)
try db.executeUpdate("CREATE TABLE IF NOT EXISTS \(table) (songIndex INTEGER PRIMARY KEY, songId INTEGER, serverId INTEGER)")
try db.executeUpdate("CREATE INDEX IF NOT EXISTS \(table)_songIdServerId ON \(table) (songId, serverId)")
}
func playlist(playlistId: Int64? = nil, name: String, serverId: Int64) -> Playlist {
if let playlistId = playlistId {
if let playlist = playlist(playlistId: playlistId, serverId: serverId) {
return playlist
}
Database.si.write.inDatabase { db in
try? db.executeUpdate("INSERT INTO playlists VALUES (?, ?, ?, ?)", playlistId, serverId, name, NSNull())
try? self.createPlaylistTable(db: db, playlistId: playlistId, serverId: serverId, name: name)
}
return playlist(playlistId: playlistId, serverId: serverId)!
} else {
var newPlaylistId: Int64 = -1
// Get the ID and create the playlist table in the same block to avoid threading issues
Database.si.write.inDatabase { db in
// Find the first available playlist id. Local playlists (before being synced) start from NSIntegerMax and count down.
// So since NSIntegerMax is so huge, look for the lowest ID above NSIntegerMax - 1,000,000 to give room for virtually
// unlimited local playlists without ever hitting the server playlists which start from 0 and go up.
let lastPlaylistId = db.int64ForQuery("SELECT playlistId FROM playlists WHERE playlistId > ? AND serverId = ?", Int64.max - 1000000, serverId)
// Next available ID
newPlaylistId = lastPlaylistId - 1
try? db.executeUpdate("INSERT INTO playlists VALUES (?, ?, ?, ?)", newPlaylistId, serverId, name, NSNull())
try? self.createPlaylistTable(db: db, playlistId: newPlaylistId, serverId: serverId, name: name)
}
return playlist(playlistId: newPlaylistId, serverId: serverId)!
}
}
func loadSubItems(playlist: Playlist) {
var songs = [Song]()
Database.si.read.inDatabase { db in
do {
let query = "SELECT songId, serverId FROM \(playlist.tableName)"
let result = try db.executeQuery(query)
while result.next() {
let songId = result.longLongInt(forColumnIndex: 0)
let serverId = result.longLongInt(forColumnIndex: 1)
if let song = SongRepository.si.song(songId: songId, serverId: serverId) {
songs.append(song)
}
}
} catch {
printError(error)
}
}
playlist.songs = songs
}
func overwriteSubItems(playlist: Playlist) {
Database.si.write.inDatabase { db in
do {
let query = "DELETE FROM \(playlist.tableName)"
try db.executeUpdate(query)
for song in playlist.songs {
let query = "INSERT INTO \(playlist.tableName) (songId, serverId) VALUES (?, ?)"
try db.executeUpdate(query, song.songId, song.serverId)
}
} catch {
printError(error)
}
}
}
func createDefaultPlaylists(serverId: Int64) {
_ = PlaylistRepository.si.playlist(playlistId: Playlist.playQueuePlaylistId, name: "Play Queue", serverId: serverId)
_ = PlaylistRepository.si.playlist(playlistId: Playlist.downloadQueuePlaylistId, name: "Download Queue", serverId: serverId)
_ = PlaylistRepository.si.playlist(playlistId: Playlist.downloadedSongsPlaylistId, name: "Downloaded Songs", serverId: serverId)
}
}
extension Playlist {
var tableName: String {
return PlaylistRepository.si.playlistTableName(playlistId: playlistId, serverId: serverId)
}
var songCount: Int {
// SELECT COUNT(*) is O(n) while selecting the max rowId is O(1)
// Since songIndex is our primary key field, it's an alias
// for rowId. So SELECT MAX instead of SELECT COUNT here.
var maxId = 0
Database.si.read.inDatabase { db in
let query = "SELECT MAX(songIndex) FROM \(self.tableName)"
maxId = db.intForQuery(query)
}
return maxId
}
func contains(song: Song) -> Bool {
return contains(songId: song.songId, serverId: song.serverId)
}
func contains(songId: Int64, serverId: Int64) -> Bool {
var count = 0
Database.si.read.inDatabase { db in
let query = "SELECT COUNT(*) FROM \(self.tableName) WHERE songId = ? AND serverId = ?"
count = db.intForQuery(query, songId, serverId)
}
return count > 0
}
func indexOf(songId: Int64, serverId: Int64) -> Int? {
var index: Int?
Database.si.read.inDatabase { db in
let query = "SELECT songIndex FROM \(self.tableName) WHERE songId = ? AND serverId = ?"
index = db.intOptionalForQuery(query, songId, serverId)
}
if let index = index {
return index - 1
}
return nil
}
func song(atIndex index: Int) -> Song? {
guard index >= 0 else {
return nil
}
var songId: Int64?
var serverId: Int64?
Database.si.read.inDatabase { db in
let query = "SELECT songId, serverId FROM \(self.tableName) WHERE songIndex = ?"
do {
let result = try db.executeQuery(query, index + 1)
if result.next() {
songId = result.longLongInt(forColumnIndex: 0)
serverId = result.longLongInt(forColumnIndex: 1)
}
result.close()
} catch {
printError(error)
}
}
if let songId = songId, let serverId = serverId {
return SongRepository.si.song(songId: songId, serverId: serverId)
} else {
return nil
}
}
func add(song: Song, notify: Bool = false) {
add(songId: song.songId, serverId: song.serverId, notify: notify)
}
func add(songId: Int64, serverId: Int64, notify: Bool = false) {
let query = "INSERT INTO \(self.tableName) (songId, serverId) VALUES (?, ?)"
Database.si.write.inDatabase { db in
do {
try db.executeUpdate(query, songId, serverId)
} catch {
printError(error)
}
}
if notify {
notifyPlaylistChanged()
}
}
func add(songs: [Song], notify: Bool = false) {
for song in songs {
add(song: song, notify: false)
}
if notify {
notifyPlaylistChanged()
}
}
func insert(song: Song, index: Int, notify: Bool = false) {
insert(songId: song.songId, serverId: song.serverId, index: index, notify: notify)
}
func insert(songId: Int64, serverId: Int64, index: Int, notify: Bool = false) {
Database.si.write.inDatabase { db in
do {
let query1 = "UPDATE \(self.tableName) SET songIndex = -songIndex WHERE songIndex >= ?"
try db.executeUpdate(query1, index + 1)
let query2 = "INSERT INTO \(self.tableName) VALUES (?, ?, ?)"
try db.executeUpdate(query2, index + 1, songId, serverId)
let query3 = "UPDATE \(self.tableName) SET songIndex = (-songIndex) + 1 WHERE songIndex < 0"
try db.executeUpdate(query3)
} catch {
printError(error)
}
}
if notify {
notifyPlaylistChanged()
}
}
func remove(songAtIndex index: Int, notify: Bool = false) {
Database.si.write.inDatabase { db in
do {
let query1 = "DELETE FROM \(self.tableName) WHERE songIndex = ?"
try db.executeUpdate(query1, index + 1)
let query2 = "UPDATE \(self.tableName) SET songIndex = songIndex - 1 WHERE songIndex > ?"
try db.executeUpdate(query2, index + 1)
} catch {
printError(error)
}
}
if notify {
notifyPlaylistChanged()
}
}
func remove(songsAtIndexes indexes: IndexSet, notify: Bool = false) {
for index in indexes {
remove(songAtIndex: index, notify: false)
}
if notify {
notifyPlaylistChanged()
}
}
func remove(song: Song, notify: Bool = false) {
remove(songId: song.songId, serverId: song.serverId, notify: notify)
}
func remove(songId: Int64, serverId: Int64, notify: Bool = false) {
if let index = indexOf(songId: songId, serverId: serverId) {
remove(songAtIndex: index, notify: notify)
}
}
func remove(songs: [Song], notify: Bool = false) {
for song in songs {
remove(song: song, notify: false)
}
if notify {
notifyPlaylistChanged()
}
}
func removeAllSongs(_ notify: Bool = false) {
Database.si.write.inDatabase { db in
do {
let query1 = "DELETE FROM \(self.tableName)"
try db.executeUpdate(query1)
} catch {
printError(error)
}
}
if notify {
notifyPlaylistChanged()
}
}
func moveSong(fromIndex: Int, toIndex: Int, notify: Bool = false) -> Bool {
if fromIndex != toIndex, let song = song(atIndex: fromIndex) {
let finalToIndex = fromIndex < toIndex ? toIndex - 1 : toIndex
if finalToIndex >= 0 && finalToIndex < songCount {
remove(songAtIndex: fromIndex, notify: false)
insert(song: song, index: finalToIndex, notify: notify)
return true
}
}
return false
}
}
extension Playlist {
static let playQueuePlaylistId = Int64.max - 1
static let downloadQueuePlaylistId = Int64.max - 2
static let downloadedSongsPlaylistId = Int64.max - 3
static var playQueue: Playlist {
return PlaylistRepository.si.playlist(playlistId: playQueuePlaylistId, serverId: SavedSettings.si.currentServerId)!
}
static var downloadQueue: Playlist {
return PlaylistRepository.si.playlist(playlistId: downloadQueuePlaylistId, serverId: SavedSettings.si.currentServerId)!
}
static var downloadedSongs: Playlist {
return PlaylistRepository.si.playlist(playlistId: downloadedSongsPlaylistId, serverId: SavedSettings.si.currentServerId)!
}
}
extension Playlist: PersistedItem {
convenience init(result: FMResultSet, repository: ItemRepository = PlaylistRepository.si) {
let playlistId = result.longLongInt(forColumnIndex: 0)
let serverId = result.longLongInt(forColumnIndex: 1)
let name = result.string(forColumnIndex: 2) ?? ""
let coverArtId = result.string(forColumnIndex: 3)
let repository = repository as! PlaylistRepository
self.init(playlistId: playlistId, serverId: serverId, name: name, coverArtId: coverArtId, repository: repository)
}
class func item(itemId: Int64, serverId: Int64, repository: ItemRepository = AlbumRepository.si) -> Item? {
return (repository as? AlbumRepository)?.album(albumId: itemId, serverId: serverId)
}
var isPersisted: Bool {
return repository.isPersisted(playlist: self)
}
var hasCachedSubItems: Bool {
return repository.hasCachedSubItems(playlist: self)
}
@discardableResult func replace() -> Bool {
return repository.replace(playlist: self)
}
@discardableResult func cache() -> Bool {
// Not implemented
return false
}
@discardableResult func delete() -> Bool {
return repository.delete(playlist: self)
}
@discardableResult func deleteCache() -> Bool {
// Not implemented
return false
}
func loadSubItems() {
repository.loadSubItems(playlist: self)
}
func overwriteSubItems() {
repository.overwriteSubItems(playlist: self)
}
}
| gpl-3.0 | 765c7d031e1939e3a2cf533e34fea30d | 37.263158 | 158 | 0.590409 | 4.719386 | false | false | false | false |
goyuanfang/SXSwiftWeibo | 103 - swiftWeibo/103 - swiftWeibo/Classes/UI/Main/SXMainTabBarController.swift | 1 | 1857 | //
// SXMainTabBarController.swift
// 103 - swiftWeibo
//
// Created by 董 尚先 on 15/3/5.
// Copyright (c) 2015年 shangxianDante. All rights reserved.
//
import UIKit
class SXMainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
addControllers()
weak var weakSelf = self // $$$$$
mainTabBar.composedButtonClicked = {
let sb = UIStoryboard(name: "Compose", bundle: nil)
weakSelf!.presentViewController(sb.instantiateInitialViewController() as! UIViewController, animated: true, completion: nil)
}
}
@IBOutlet weak var mainTabBar: SXMainTabBar!
func addControllers(){
addchildController("Home", "首页", "tabbar_home", "tabbar_home_highlighted")
addchildController("Message", "消息", "tabbar_message_center", "tabbar_message_center_highlighted")
addchildController("Discover", "发现", "tabbar_discover", "tabbar_discover_highlighted")
addchildController("Profile", "我", "tabbar_profile", "tabbar_profile_highlighted")
}
func addchildController(name:String , _ title:String, _ imageName:String, _ hightlight:String){
let sb = UIStoryboard(name: name, bundle: nil)
let nav = sb.instantiateInitialViewController() as! UINavigationController
nav.tabBarItem.image = UIImage(named: imageName)
nav.tabBarItem.selectedImage = UIImage(named: hightlight)?.imageWithRenderingMode(.AlwaysOriginal) // $$$$$
nav.title = title
nav.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: UIControlState.Selected)
self.addChildViewController(nav) // $$$$$
}
deinit{
println("主控制器被释放")
}
}
| mit | 2a551b356da9d1d3fd85c3c70c104b78 | 33.358491 | 136 | 0.654585 | 4.868984 | false | false | false | false |
Zipabout/ZPBTTracker | Example/ManualTracking/ManualTracking/FourthViewController.swift | 1 | 2049 | //
// FourthViewController.swift
// ManualTracking
//
// Created by Siju Satheesachandran on 12/01/2017.
// Copyright © 2017 Siju Satheesachandran. All rights reserved.
//
import UIKit
import ZPBTTracker
class FourthViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var txtFourthValue: UITextField!
@IBOutlet weak var txtFourth: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
txtFourthValue.delegate = self
txtFourth.delegate = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let session:ZPBTSessionManager = ZPBTSessionManager.sharedInstance()
//track current page
session.trackSession(inPage: NSStringFromClass(type(of: self)))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@IBAction func sendEventFourth(_ sender: AnyObject) {
txtFourthValue.resignFirstResponder()
txtFourth.resignFirstResponder()
let event:ZPBTEventManager = ZPBTEventManager.sharedInstance()
var customParameter: [String: String] = [:]
customParameter[txtFourth.text!] = txtFourthValue.text!
event.trackEvent(inPage: NSStringFromClass(type(of: self)), customParameter: customParameter)
}
@IBOutlet weak var sendEventFourth: UIButton!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 5c7d25e9916778a0073c350f46178cc5 | 30.030303 | 106 | 0.679688 | 4.796253 | false | false | false | false |
googlecreativelab/justaline-ios | LineGeometry.swift | 1 | 5028 | // Copyright 2018 Google 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 SceneKit
import Metal
enum Radius: Float {
case small = 0.006
case medium = 0.011
case large = 0.020
}
class LineGeometry : SCNGeometry {
var vectors = [SCNVector3]()
var sides = [Float]()
var width: Float = 0
var lengths = [Float]()
var endCapPosition: Float = 0
/// Code currently all happens in init because I can't call init'ed functions until super.init is called, and you can only call one super.init. I am relying on the built-in init(sources:elements:) convenience method for drawing the geometry
convenience init(vectors: [SCNVector3], sides: [Float], width: Float, lengths: [Float], endCapPosition: Float) {
var indices = [Int32]()
// Loop through center points
for i in 0..<vectors.count {
indices.append(Int32(i))
}
let source = SCNGeometrySource(vertices: vectors)
let indexData = Data(bytes: indices,
count: indices.count * MemoryLayout<Int32>.size)
// Now without runtime error
let element = SCNGeometryElement(data: indexData,
primitiveType: .triangleStrip,
primitiveCount: indices.count - 2,
bytesPerIndex: MemoryLayout<Int32>.size)
// self.init()
self.init(sources: [source], elements: [element])
self.vectors = vectors
self.sides = sides
self.width = width
self.lengths = lengths
self.endCapPosition = endCapPosition
self.wantsAdaptiveSubdivision = true
let lineProgram = SCNProgram()
lineProgram.vertexFunctionName = "basic_vertex"
lineProgram.fragmentFunctionName = "basic_fragment"
program = lineProgram
program?.isOpaque = false
let endCapImage = UIImage(named: "linecap")!
let endCapTexture = SCNMaterialProperty(contents: endCapImage)
self.setValue(endCapTexture, forKey: "endCapTexture")
// let borderImage = UIImage(named: "texture")!
// let borderTexture = SCNMaterialProperty(contents: borderImage)
// self.setValue(borderTexture, forKey: "borderTexture")
// let resolution = CGPoint(x: UIScreen.main.bounds.size.width, y: UIScreen.main.bounds.size.height)
// let color = UIColor.white.cgColor
// self.setValue(resolution, forKey:"resolution")
// self.setValue(color, forKey: "color")
// lineProgram.handleBinding(ofBufferNamed: "myUniforms", frequency: .perShadable, handler: { (bufferStream, renderedNode, geometry, renderer) in
// var resolution = float2(Float(UIScreen.main.bounds.size.width), Float(UIScreen.main.bounds.size.height))
// var color = float4(1,1,1,1)
//
// bufferStream.writeBytes(&resolution, count: MemoryLayout<Float>.size*2)
// bufferStream.writeBytes(&color, count: MemoryLayout<Float>.size*4)
// })
program?.handleBinding(ofBufferNamed: "vertices", frequency: .perShadable, handler: { (bufferStream, renderedNode, geometry, renderer) in
if let line = renderedNode.geometry as? LineGeometry {
var programVertices = line.generateVertexData()
bufferStream.writeBytes(&programVertices, count: MemoryLayout<MyVertex>.size*programVertices.count)
}
})
}
// deinit {
// print("Deinit line geometry")
// }
func generateVertexData()->[MyVertex] {
var vertexArray = [MyVertex]()
var vertex: MyVertex = MyVertex()
for i in 0..<vectors.count {
vertex.position = float3(x: vectors[i].x, y:vectors[i].y, z: vectors[i].z)
vertex.vertexCount = Int32(vectors.count)
// vertex.previous = stroke.mPrevious[i]
// vertex.next = stroke.mNext[i]
vertex.side = sides[i]
vertex.width = width
vertex.length = lengths[i]
vertex.endCap = endCapPosition
vertex.color = float4(1,1,1,1)
// vertex.counters = stroke.mCounters[i]
vertex.resolution = float2(Float(UIScreen.main.bounds.size.width), Float(UIScreen.main.bounds.size.height))
vertexArray.append(vertex)
}
return vertexArray
}
}
| apache-2.0 | 0ec9735bfecffc2732637907fae98732 | 38.590551 | 245 | 0.619332 | 4.353247 | false | false | false | false |
zSher/BulletThief | BulletThief/BulletThief/PlayerData.swift | 1 | 3886 | //
// PlayerData.swift
// BulletThief
//
// Created by Zachary on 4/25/15.
// Copyright (c) 2015 Zachary. All rights reserved.
//
import Foundation
///Singleton class that holds all player info
class PlayerData: NSObject, NSCoding {
var gold: UInt = 0 //Standard currency
var farthestTraveled: UInt = 0 //"highscore" per say
var speedLevel: UInt = 1
var bulletDelayLevel: UInt = 1
var bulletNumber: UInt = 1
var bulletDamage: UInt = 1
var bulletTexture = "pelletBullet"
var bulletSet: BulletSet?
var controlScheme: ControlSchemes = ControlSchemes.Tap
var purchasedBulletSetFlags: [String: UInt] = ["Basic Gun": 2, "DblX Gun":1, "Hyper Gun": 1] //array of flags, >1 means purchased
var path = documentDirectory.stringByAppendingPathComponent("BulletThief.archive")
//MARK - Init -
override init(){
super.init()
bulletSet = DefaultSet(data: self)
}
//Init with set properties
convenience init(gold:UInt, farthestTraveled: UInt, controlScheme: ControlSchemes, speed: UInt, bulletDelay: UInt, bulletNum: UInt, bulletDamage: UInt, bulletSet: BulletSet?, bulletSetFlags:[String:UInt]?) {
self.init()
self.gold = gold
self.farthestTraveled = farthestTraveled
self.controlScheme = controlScheme
self.speedLevel = speed
self.bulletDelayLevel = bulletDelay
self.bulletNumber = bulletNum
self.bulletDamage = bulletDamage
self.bulletSet = bulletSet ?? DefaultSet(data: self)
self.purchasedBulletSetFlags = bulletSetFlags ?? self.purchasedBulletSetFlags
}
//MARK: - NSCoder -
required convenience init(coder aDecoder: NSCoder) {
//Grab data, call convience init
var gold = aDecoder.decodeObjectForKey("gold") as UInt
var travel = aDecoder.decodeObjectForKey("travel") as UInt
var controlScheme = aDecoder.decodeObjectForKey("controlScheme") as Int
var bullets = aDecoder.decodeObjectForKey("bullets") as? UInt ?? 1
var speed = aDecoder.decodeObjectForKey("speed") as? UInt ?? 1
var bulletDelay = aDecoder.decodeObjectForKey("bDelay") as? UInt ?? 1
var bulletDamage = aDecoder.decodeObjectForKey("bDamage") as? UInt ?? 1
var bulletSet = aDecoder.decodeObjectForKey("bSet") as? BulletSet
var bulletSetFlags = aDecoder.decodeObjectForKey("bSetFlags") as? [String:UInt]
//TODO: BulletEffects
self.init(gold: gold, farthestTraveled: travel, controlScheme: ControlSchemes(rawValue: controlScheme)!, speed: speed, bulletDelay: bulletDelay, bulletNum: bullets, bulletDamage: bulletDamage, bulletSet: bulletSet, bulletSetFlags: bulletSetFlags)
}
//Serialize Data
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(gold, forKey: "gold")
aCoder.encodeObject(farthestTraveled, forKey: "travel")
aCoder.encodeObject(self.controlScheme.rawValue, forKey: "controlScheme")
aCoder.encodeObject(speedLevel, forKey: "speed")
aCoder.encodeObject(bulletDelayLevel, forKey: "bDelay")
aCoder.encodeObject(bulletNumber, forKey: "bullets")
aCoder.encodeObject(bulletDamage, forKey: "bDamage")
aCoder.encodeObject(purchasedBulletSetFlags, forKey: "bSetFlags")
}
//Save all player data
func savePlayerData(){
if NSKeyedArchiver.archiveRootObject(self, toFile: path) {
println("Success writing to file!")
}
else {
println("Unable to write to file!")
}
}
//Load player data
func loadPlayerData() -> PlayerData? {
if let data = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? PlayerData {
return data
}
else {
return nil
}
}
}
var playerData: PlayerData = PlayerData() //SINGLETON | mit | 8a4178382a9a8b4198e978341979c96a | 39.072165 | 254 | 0.671642 | 4.420933 | false | false | false | false |
SoneeJohn/WWDC | ConfCore/FocusesJSONAdapter.swift | 1 | 550 | //
// FocusesJSONAdapter.swift
// WWDC
//
// Created by Guilherme Rambo on 08/02/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import SwiftyJSON
final class FocusesJSONAdapter: Adapter {
typealias InputType = JSON
typealias OutputType = Focus
func adapt(_ input: JSON) -> Result<Focus, AdapterError> {
guard let name = input.string else {
return .error(.invalidData)
}
let focus = Focus()
focus.name = name
return .success(focus)
}
}
| bsd-2-clause | 4df67d18d0dfcefd31d63fe81f3d2cd7 | 19.333333 | 62 | 0.635701 | 4.097015 | false | false | false | false |
3drobotics/SwiftIO | Sources/TCPServer.swift | 2 | 2711 | //
// Server.swift
// SwiftIO
//
// Created by Jonathan Wight on 12/9/15.
// Copyright © 2015 schwa.io. All rights reserved.
//
import SwiftUtilities
public class TCPServer {
public let addresses: [Address]
public var clientShouldConnect: (Address -> Bool)?
public var clientWillConnect: (TCPChannel -> Void)?
public var clientDidConnect: (TCPChannel -> Void)?
public var clientDidDisconnect: (TCPChannel -> Void)?
public var errorDidOccur: (ErrorType -> Void)? = {
(error) in
log?.debug("Server got: \(error)")
}
public var listenersByAddress: [Address: TCPListener] = [:]
public var connections = Atomic(Set <TCPChannel> ())
private let queue = dispatch_queue_create("io.schwa.TCPServer", DISPATCH_QUEUE_SERIAL)
public init(address: Address) throws {
self.addresses = [address]
}
public func startListening() throws {
for address in addresses {
try startListening(address)
}
}
private func startListening(address: Address) throws {
let listener = try TCPListener(address: address, queue: queue)
listener.clientShouldConnect = clientShouldConnect
listener.clientWillConnect = {
[weak self] channel in
guard let strong_self = self else {
return
}
channel.state.addObserver(strong_self, queue: dispatch_get_main_queue()) {
(old, new) in
guard let strong_self = self else {
return
}
if new == .Disconnected {
strong_self.connections.value.remove(channel)
strong_self.clientDidDisconnect?(channel)
}
}
strong_self.clientWillConnect?(channel)
}
listener.clientDidConnect = {
[weak self] channel in
guard let strong_self = self else {
return
}
strong_self.connections.value.insert(channel)
strong_self.clientDidConnect?(channel)
}
listener.errorDidOccur = errorDidOccur
try listener.startListening()
listenersByAddress[address] = listener
}
public func stopListening() throws {
for (address, listener) in listenersByAddress {
try listener.stopListening()
listenersByAddress[address] = nil
}
}
public func disconnectAllClients() throws {
for connection in connections.value {
connection.disconnect() {
(result) in
log?.debug("Server disconnect all: \(result)")
}
}
}
}
| mit | c94394d91fd7e146f935e3c06bbd213d | 26.373737 | 90 | 0.580443 | 4.839286 | false | false | false | false |
halo/LinkLiar | LinkLiar/Classes/DefaultSubmenu.swift | 1 | 4533 | /*
* Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar
*
* 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 Cocoa
class DefaultSubmenu {
func update() {
updateStates()
updateEnability()
updateAddress()
}
private func updateStates() {
ignoreItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .ignore ? 1 : 0)
randomizeItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .random ? 1 : 0)
specifyItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .specify ? 1 : 0)
originalizeItem.state = NSControl.StateValue(rawValue: Config.instance.unknownInterface.action == .original ? 1 : 0)
}
private func updateEnability() {
self.enableAll(ConfigWriter.isWritable)
}
private func updateAddress() {
specifiedAddressItem.isHidden = Config.instance.unknownInterface.action != .specify
guard let address = Config.instance.unknownInterface.address else { return }
specifiedAddressItem.title = address.formatted
}
private func enableAll(_ enableOrDisable: Bool) {
ignoreItem.isEnabled = enableOrDisable
randomizeItem.isEnabled = enableOrDisable
specifyItem.isEnabled = enableOrDisable
originalizeItem.isEnabled = enableOrDisable
}
lazy var menuItem: NSMenuItem = {
let item = NSMenuItem(title: "Default", action: nil, keyEquivalent: "")
item.target = Controller.self
item.submenu = self.defaultSubMenuItem
item.toolTip = "Interfaces marked as \"Default\" have this value."
self.update()
return item
}()
private lazy var defaultSubMenuItem: NSMenu = {
let submenu: NSMenu = NSMenu()
submenu.autoenablesItems = false
submenu.addItem(self.ignoreItem)
submenu.addItem(self.randomizeItem)
submenu.addItem(self.specifyItem)
submenu.addItem(self.originalizeItem)
submenu.addItem(NSMenuItem.separator())
submenu.addItem(self.specifiedAddressItem)
return submenu
}()
private lazy var ignoreItem: NSMenuItem = {
let item = NSMenuItem(title: "Do nothing", action: #selector(Controller.ignoreDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "New Interfaces will not be modified in any way."
return item
}()
private lazy var randomizeItem: NSMenuItem = {
let item = NSMenuItem(title: "Random", action: #selector(Controller.randomizeDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "Randomize the MAC address of new Interfaces."
return item
}()
private lazy var specifyItem: NSMenuItem = {
let item = NSMenuItem(title: "Define manually", action: #selector(Controller.specifyDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "Assign a specific MAC address to new Interfaces."
return item
}()
private lazy var originalizeItem: NSMenuItem = {
let item = NSMenuItem(title: "Keep original", action: #selector(Controller.originalizeDefaultInterface), keyEquivalent: "")
item.target = Controller.self
item.toolTip = "Ensure new Interfaces are kept at their original hardware MAC address."
return item
}()
private lazy var specifiedAddressItem: NSMenuItem = {
let item = NSMenuItem(title: "Loading...", action: nil, keyEquivalent: "")
item.isEnabled = false
item.isHidden = true
item.toolTip = "The specific MAC address assigned to new Interfaces."
return item
}()
}
| mit | d0d4910ad6b577fa056c5c97c93a4d5e | 41.364486 | 133 | 0.736819 | 4.46601 | false | true | false | false |
cristianames92/PortalView | Sources/UIKit/PortalMapView.swift | 2 | 2291 | //
// MapView.swift
// Portal
//
// Created by Guido Marucci Blas on 12/18/16.
// Copyright © 2016 Guido Marucci Blas. All rights reserved.
//
import UIKit
import MapKit
fileprivate let PortalMapViewAnnotationIdentifier = "PortalMapViewAnnotation"
internal final class PortalMapView: MKMapView {
fileprivate var placemarks: [MapPlacemarkAnnotation : MapPlacemark] = [:]
init(placemarks: [MapPlacemark]) {
super.init(frame: CGRect.zero)
for placemark in placemarks {
let annotation = MapPlacemarkAnnotation(placemark: placemark)
self.addAnnotation(annotation)
self.placemarks[annotation] = placemark
}
self.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PortalMapView: MKMapViewDelegate {
public func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard
let annotation = annotation as? MapPlacemarkAnnotation,
let placemark = placemark(for: annotation)
else { return .none }
let annotationView = dequeueReusableAnnotationView(for: annotation)
annotationView.image = placemark.icon?.asUIImage
return annotationView
}
}
extension PortalMapView {
fileprivate func placemark(for annotation: MapPlacemarkAnnotation) -> MapPlacemark? {
return placemarks[annotation]
}
fileprivate func dequeueReusableAnnotationView(for annotation: MapPlacemarkAnnotation) -> MKAnnotationView {
if let annotationView = dequeueReusableAnnotationView(withIdentifier: PortalMapViewAnnotationIdentifier) {
return annotationView
} else {
return MKAnnotationView(annotation: annotation, reuseIdentifier: PortalMapViewAnnotationIdentifier)
}
}
}
fileprivate final class MapPlacemarkAnnotation: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
init(placemark: MapPlacemark) {
self.coordinate = CLLocationCoordinate2D(
latitude: placemark.coordinates.latitude,
longitude: placemark.coordinates.longitude
)
}
}
| mit | 5cf748fd67c86b9f9091a726711caca3 | 28.74026 | 114 | 0.679476 | 5.413712 | false | false | false | false |
ta2yak/loqui | loqui/ViewModels/PostViewModel.swift | 1 | 7663 | //
// PostViewModel.swift
// loqui
//
// Created by Kawasaki Tatsuya on 2017/07/11.
// Copyright © 2017年 Kawasaki Tatsuya. All rights reserved.
//
import Eureka
import RxEureka
import ImageRow
import RxSwift
import MaterialComponents
import Cartography
protocol PostViewModeling {
var form: Form { get }
}
struct PostViewModel: PostViewModeling {
let disposeBag = DisposeBag()
let form: Form
var isLoading = Variable<Bool>(false)
var isSaved = Variable<Bool>(false)
var successMessage = Store.successMessage
var errorMessage = Store.errorMessage
private let _headerSection: Section
private let _textRow: TextAreaRow
private let _section: Section
private let _boyAgeRow: PhoneRow
private let _girlAgeRow: PhoneRow
private let _timingRow: TextRow
private let _placeRow: TextRow
private let _priceRow: PhoneRow
init() {
self.form = Form()
self._headerSection = Section(){ section in
section.header = {
var header = HeaderFooterView<UIView>(.callback({
let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 80))
view.backgroundColor = UIColor.accentColor()
let label = UILabel()
label.text = "ウェディングプランナーに聞いてみよう"
label.font = MDCTypography.captionFont()
label.alpha = MDCTypography.captionFontOpacity()
label.textColor = UIColor.mainTextColor()
view.addSubview(label)
constrain(view, label) { view, label in
label.width == view.width - 16
label.left == view.left + 8
label.right == view.right - 8
label.bottom == view.bottom - 8
}
return view
}))
header.height = { 132 }
return header
}()
}
self._section = Section(){ section in
section.header = {
var header = HeaderFooterView<UIView>(.callback({
let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 60))
view.backgroundColor = UIColor.accentColor()
let label = UILabel()
label.text = "良ければこちらもご入力ください"
label.font = MDCTypography.captionFont()
label.alpha = MDCTypography.captionFontOpacity()
label.textColor = UIColor.mainTextColor()
view.addSubview(label)
constrain(view, label) { view, label in
label.width == view.width - 16
label.left == view.left + 8
label.right == view.right - 8
label.bottom == view.bottom - 8
}
return view
}))
header.height = { 60 }
return header
}()
section.footer = {
var footer = HeaderFooterView<UIView>(.callback({
let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 160))
view.backgroundColor = UIColor.accentColor()
return view
}))
footer.height = { 160 }
return footer
}()
}
self._textRow = TextAreaRow() { row in
row.title = "ウェディングプランナーに尋ねたいこと"
row.placeholder = "\n花が好きなので、花に囲まれた挙式をしたいです。身内と親しい友人だけを招こうと思ってます。"
row.textAreaHeight = .fixed(cellHeight: UIScreen.main.bounds.size.height - 340)
row.cell.textView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
row.add(rule: RuleRequired())
}.cellSetup({ (cell, row) in
cell.textLabel?.font = MDCTypography.captionFont()
})
self._boyAgeRow = PhoneRow() { row in
row.title = "新郎の年齢"
row.placeholder = ""
}
self._girlAgeRow = PhoneRow() { row in
row.title = "新婦の年齢"
row.placeholder = ""
}
self._timingRow = TextRow() { row in
row.title = "時期"
row.placeholder = "例. 来年の6月"
}
self._placeRow = TextRow() { row in
row.title = "場所"
row.placeholder = "例. 都内近郊"
}
self._priceRow = PhoneRow() { row in
row.title = "予算(万円)"
row.placeholder = ""
}
self.form
+++ self._headerSection
<<< self._textRow
+++ self._section
<<< self._boyAgeRow
<<< self._girlAgeRow
<<< self._timingRow
<<< self._placeRow
<<< self._priceRow
}
func post() {
if (Store.currentUser.value.uid == "") {
return
}
self.isLoading.value = true
let text = self._textRow.value == "" ? "(未入力)" : self._textRow.value ?? "(未入力)"
let boyAge = self._boyAgeRow.value == "" ? "(未入力)" : self._boyAgeRow.value ?? "(未入力)"
let girlAge = self._girlAgeRow.value == "" ? "(未入力)" : self._girlAgeRow.value ?? "(未入力)"
let timing = self._timingRow.value == "" ? "(未入力)" : self._timingRow.value ?? "(未入力)"
let place = self._placeRow.value == "" ? "(未入力)" : self._placeRow.value ?? "(未入力)"
let price = self._priceRow.value == "" ? "(未入力)" : self._priceRow.value ?? "(未入力)"
let postText = "\(text)" +
"\n" +
"\n" +
"新郎年齢:\(boyAge) 歳 \n" +
"新婦年齢:\(girlAge) 歳 \n" +
"時期:\(timing) \n" +
"場所:\(place) \n" +
"予算:\(price) 万円 \n"
GlobalChat.save(uid:Store.currentUser.value.uid,
name:Store.currentUser.value.name,
text: postText).then { Void -> Void in
self.isSaved.value = true
self.successMessage.value = AlertMessage(title:"質問しました",
message: "プランナーの回答があるまで、しばらくお待ちください")
self._textRow.value = ""
self._boyAgeRow.value = ""
self._girlAgeRow.value = ""
self._timingRow.value = ""
self._placeRow.value = ""
self._priceRow.value = ""
self._textRow.reload()
self._boyAgeRow.reload()
self._girlAgeRow.reload()
self._timingRow.reload()
self._placeRow.reload()
self._priceRow.reload()
}.always {
self.isLoading.value = false
}.catch { error in
}
}
}
| mit | 1248a2c3af28be3d4e14f0c3fd130eb6 | 32.962441 | 117 | 0.473459 | 4.432598 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/XMLDocument.swift | 4 | 11854 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
// Input options
// NSXMLNodeOptionsNone
// NSXMLNodePreserveAll
// NSXMLNodePreserveNamespaceOrder
// NSXMLNodePreserveAttributeOrder
// NSXMLNodePreserveEntities
// NSXMLNodePreservePrefixes
// NSXMLNodePreserveCDATA
// NSXMLNodePreserveEmptyElements
// NSXMLNodePreserveQuotes
// NSXMLNodePreserveWhitespace
// NSXMLNodeLoadExternalEntities
// NSXMLNodeLoadExternalEntitiesSameOriginOnly
// NSXMLDocumentTidyHTML
// NSXMLDocumentTidyXML
// NSXMLDocumentValidate
// Output options
// NSXMLNodePrettyPrint
// NSXMLDocumentIncludeContentTypeDeclaration
extension XMLDocument {
/*!
@typedef XMLDocument.ContentKind
@abstract Define what type of document this is.
@constant XMLDocument.ContentKind.xml The default document type
@constant XMLDocument.ContentKind.xhtml Set if XMLNode.Options.documentTidyHTML is set and HTML is detected
@constant XMLDocument.ContentKind.html Outputs empty tags without a close tag, eg <br>
@constant XMLDocument.ContentKind.text Output the string value of the document
*/
public enum ContentKind : UInt {
case xml
case xhtml
case html
case text
}
}
/*!
@class XMLDocument
@abstract An XML Document
@discussion Note: if the application of a method would result in more than one element in the children array, an exception is thrown. Trying to add a document, namespace, attribute, or node with a parent also throws an exception. To add a node with a parent first detach or create a copy of it.
*/
open class XMLDocument : XMLNode {
private var _xmlDoc: _CFXMLDocPtr {
return _CFXMLDocPtr(_xmlNode)
}
public init() {
NSUnimplemented()
}
/*!
@method initWithXMLString:options:error:
@abstract Returns a document created from either XML or HTML, if the HTMLTidy option is set. Parse errors are returned in <tt>error</tt>.
*/
public convenience init(xmlString string: String, options mask: XMLNode.Options = []) throws {
guard let data = string.data(using: .utf8) else {
// TODO: Throw an error
fatalError("String: '\(string)' could not be converted to NSData using UTF-8 encoding")
}
try self.init(data: data, options: mask)
}
/*!
@method initWithContentsOfURL:options:error:
@abstract Returns a document created from the contents of an XML or HTML URL. Connection problems such as 404, parse errors are returned in <tt>error</tt>.
*/
public convenience init(contentsOf url: URL, options mask: XMLNode.Options = []) throws {
let data = try Data(contentsOf: url, options: .mappedIfSafe)
try self.init(data: data, options: mask)
}
/*!
@method initWithData:options:error:
@abstract Returns a document created from data. Parse errors are returned in <tt>error</tt>.
*/
public init(data: Data, options mask: XMLNode.Options = []) throws {
let docPtr = _CFXMLDocPtrFromDataWithOptions(data._cfObject, UInt32(mask.rawValue))
super.init(ptr: _CFXMLNodePtr(docPtr))
if mask.contains(.documentValidate) {
try validate()
}
}
/*!
@method initWithRootElement:
@abstract Returns a document with a single child, the root element.
*/
public init(rootElement element: XMLElement?) {
precondition(element?.parent == nil)
super.init(kind: .document, options: [])
if let element = element {
_CFXMLDocSetRootElement(_xmlDoc, element._xmlNode)
_childNodes.insert(element)
}
}
open class func replacementClass(for cls: AnyClass) -> AnyClass {
NSUnimplemented()
}
/*!
@method characterEncoding
@abstract Sets the character encoding to an IANA type.
*/
open var characterEncoding: String? {
get {
return _CFXMLDocCopyCharacterEncoding(_xmlDoc)?._swiftObject
}
set {
if let value = newValue {
_CFXMLDocSetCharacterEncoding(_xmlDoc, value)
} else {
_CFXMLDocSetCharacterEncoding(_xmlDoc, nil)
}
}
}
/*!
@method version
@abstract Sets the XML version. Should be 1.0 or 1.1.
*/
open var version: String? {
get {
return _CFXMLDocCopyVersion(_xmlDoc)?._swiftObject
}
set {
if let value = newValue {
precondition(value == "1.0" || value == "1.1")
_CFXMLDocSetVersion(_xmlDoc, value)
} else {
_CFXMLDocSetVersion(_xmlDoc, nil)
}
}
}
/*!
@method standalone
@abstract Set whether this document depends on an external DTD. If this option is set the standalone declaration will appear on output.
*/
open var isStandalone: Bool {
get {
return _CFXMLDocStandalone(_xmlDoc)
}
set {
_CFXMLDocSetStandalone(_xmlDoc, newValue)
}
}//primitive
/*!
@method documentContentKind
@abstract The kind of document.
*/
open var documentContentKind: XMLDocument.ContentKind {
get {
let properties = _CFXMLDocProperties(_xmlDoc)
if properties & Int32(_kCFXMLDocTypeHTML) != 0 {
return .html
}
return .xml
}
set {
var properties = _CFXMLDocProperties(_xmlDoc)
switch newValue {
case .html:
properties |= Int32(_kCFXMLDocTypeHTML)
default:
properties &= ~Int32(_kCFXMLDocTypeHTML)
}
_CFXMLDocSetProperties(_xmlDoc, properties)
}
}//primitive
/*!
@method MIMEType
@abstract Set the MIME type, eg text/xml.
*/
open var mimeType: String?
/*!
@method DTD
@abstract Set the associated DTD. This DTD will be output with the document.
*/
/*@NSCopying*/ open var dtd: XMLDTD? {
get {
return XMLDTD._objectNodeForNode(_CFXMLDocDTD(_xmlDoc)!)
}
set {
if let currDTD = _CFXMLDocDTD(_xmlDoc) {
if _CFXMLNodeGetPrivateData(currDTD) != nil {
let DTD = XMLDTD._objectNodeForNode(currDTD)
_CFXMLUnlinkNode(currDTD)
_childNodes.remove(DTD)
} else {
_CFXMLFreeDTD(currDTD)
}
}
if let value = newValue {
guard let dtd = value.copy() as? XMLDTD else {
fatalError("Failed to copy DTD")
}
_CFXMLDocSetDTD(_xmlDoc, dtd._xmlDTD)
_childNodes.insert(dtd)
} else {
_CFXMLDocSetDTD(_xmlDoc, nil)
}
}
}//primitive
/*!
@method setRootElement:
@abstract Set the root element. Removes all other children including comments and processing-instructions.
*/
open func setRootElement(_ root: XMLElement) {
precondition(root.parent == nil)
for child in _childNodes {
child.detach()
}
_CFXMLDocSetRootElement(_xmlDoc, root._xmlNode)
_childNodes.insert(root)
}
/*!
@method rootElement
@abstract The root element.
*/
open func rootElement() -> XMLElement? {
guard let rootPtr = _CFXMLDocRootElement(_xmlDoc) else {
return nil
}
return XMLNode._objectNodeForNode(rootPtr) as? XMLElement
}
/*!
@method insertChild:atIndex:
@abstract Inserts a child at a particular index.
*/
open func insertChild(_ child: XMLNode, at index: Int) {
_insertChild(child, atIndex: index)
}
/*!
@method insertChildren:atIndex:
@abstract Insert several children at a particular index.
*/
open func insertChildren(_ children: [XMLNode], at index: Int) {
_insertChildren(children, atIndex: index)
}
/*!
@method removeChildAtIndex:atIndex:
@abstract Removes a child at a particular index.
*/
open func removeChild(at index: Int) {
_removeChildAtIndex(index)
}
/*!
@method setChildren:
@abstract Removes all existing children and replaces them with the new children. Set children to nil to simply remove all children.
*/
open func setChildren(_ children: [XMLNode]?) {
_setChildren(children)
}
/*!
@method addChild:
@abstract Adds a child to the end of the existing children.
*/
open func addChild(_ child: XMLNode) {
_addChild(child)
}
/*!
@method replaceChildAtIndex:withNode:
@abstract Replaces a child at a particular index with another child.
*/
open func replaceChild(at index: Int, with node: XMLNode) {
_replaceChildAtIndex(index, withNode: node)
}
/*!
@method XMLData
@abstract Invokes XMLDataWithOptions with XMLNode.Options.none.
*/
/*@NSCopying*/ open var xmlData: Data { return xmlData() }
/*!
@method XMLDataWithOptions:
@abstract The representation of this node as it would appear in an XML document, encoded based on characterEncoding.
*/
open func xmlData(options: XMLNode.Options = []) -> Data {
let string = xmlString(options: options)
// TODO: support encodings other than UTF-8
return string.data(using: .utf8) ?? Data()
}
/*!
@method objectByApplyingXSLT:arguments:error:
@abstract Applies XSLT with arguments (NSString key/value pairs) to this document, returning a new document.
*/
open func object(byApplyingXSLT xslt: Data, arguments: [String : String]?) throws -> Any {
NSUnimplemented()
}
/*!
@method objectByApplyingXSLTString:arguments:error:
@abstract Applies XSLT as expressed by a string with arguments (NSString key/value pairs) to this document, returning a new document.
*/
open func object(byApplyingXSLTString xslt: String, arguments: [String : String]?) throws -> Any {
NSUnimplemented()
}
/*!
@method objectByApplyingXSLTAtURL:arguments:error:
@abstract Applies the XSLT at a URL with arguments (NSString key/value pairs) to this document, returning a new document. Error may contain a connection error from the URL.
*/
open func objectByApplyingXSLT(at xsltURL: URL, arguments argument: [String : String]?) throws -> Any {
NSUnimplemented()
}
open func validate() throws {
var unmanagedError: Unmanaged<CFError>? = nil
let result = _CFXMLDocValidate(_xmlDoc, &unmanagedError)
if !result,
let unmanagedError = unmanagedError {
let error = unmanagedError.takeRetainedValue()
throw error._nsObject
}
}
internal override class func _objectNodeForNode(_ node: _CFXMLNodePtr) -> XMLDocument {
precondition(_CFXMLNodeGetType(node) == _kCFXMLTypeDocument)
if let privateData = _CFXMLNodeGetPrivateData(node) {
return XMLDocument.unretainedReference(privateData)
}
return XMLDocument(ptr: node)
}
internal override init(ptr: _CFXMLNodePtr) {
super.init(ptr: ptr)
}
}
| apache-2.0 | e60297a723df2540828c9ca3fbef2396 | 30.695187 | 295 | 0.617176 | 4.562741 | false | false | false | false |
gmertk/SwiftSequence | SwiftSequence/GenericGenerators.swift | 1 | 2446 | public struct BuildGen<T> : GeneratorType {
private var cur: T
private let inc: T -> T
public mutating func next() -> T? {
defer { cur = inc(cur) }
return cur
}
public init(start: T, inc: T -> T) {
self.cur = start
self.inc = inc
}
}
public struct RollGen<T> : GeneratorType {
private var cur: T
private let inc: T -> T
public mutating func next() -> T? {
cur = inc(cur)
return cur
}
}
public struct RollSeq<T> : LazySequenceType {
private let start: T
private let inc : T -> T
public func generate() -> RollGen<T> {
return RollGen(cur: start, inc: inc)
}
}
public struct IncGenAfter<I : ForwardIndexType> : GeneratorType {
private var cur: I
public mutating func next() -> I? {
return ++cur
}
}
public struct IncGenAt<I : ForwardIndexType> : GeneratorType {
private var cur: I
public mutating func next() -> I? {
return cur++
}
}
public struct IncSeqAfter<I : ForwardIndexType> : LazySequenceType {
private let start: I
public func generate() -> IncGenAfter<I> {
return IncGenAfter(cur: start)
}
}
public struct IncSeqAt<I : ForwardIndexType> : LazySequenceType {
private let start: I
public func generate() -> IncGenAt<I> {
return IncGenAt(cur: start)
}
}
postfix operator ... {}
public postfix func ... <I : ForwardIndexType>(f: I) -> IncSeqAt <I> {
return IncSeqAt(start: f)
}
public postfix func ... <I : BidirectionalIndexType>(f: I) -> IncSeqAfter<I> {
return IncSeqAfter(start: f.predecessor())
}
public struct StrideForeverGen<T : Strideable> : GeneratorType {
private let strd: T.Stride
private var cur: T
public mutating func next() -> T? {
defer { cur = cur.advancedBy(strd) }
return cur
}
}
public struct StrideForeverSeq<T : Strideable> : LazySequenceType {
private let strd: T.Stride
private let strt: T
public func generate() -> StrideForeverGen<T> {
return StrideForeverGen(strd: strd, cur: strt)
}
}
/// Returns a stride sequence without an end
public func stride<T : Strideable>(from: T, by: T.Stride) -> StrideForeverSeq<T> {
return StrideForeverSeq(strd: by, strt: from)
}
/// Returns an infinite LazySequenceType generated by repeatedly applying `transform` to
/// `start`
/// ```swift
/// iterate(2) { $0 * 2 }
/// 2, 4, 8, 16, 32, 64...
/// ```
public func iterate<T>(start: T, transform: T->T) -> RollSeq<T> {
return RollSeq(start: start, inc: transform)
}
| mit | 26b3bf1fdb15ca8f2db9dbafc8286467 | 22.295238 | 88 | 0.653312 | 3.42577 | false | false | false | false |
xiwang126/BeeHive-swift | BeeHive-swift/Classes/BHWatchDog.swift | 1 | 1437 | //
// Created by UgCode on 2017/3/13.
//
import Foundation
typealias Handler = () -> Void
class PingThread: Thread {
var threshold: Double
var pingTaskIsRunning: Bool
var handler: Handler
init(threshold: Double, handler: @escaping Handler) {
self.pingTaskIsRunning = false
self.threshold = threshold
self.handler = handler
super.init()
}
override func main() {
let semaphore = DispatchSemaphore(value: 0)
while !self.isCancelled {
self.pingTaskIsRunning = true
DispatchQueue.main.async {
self.pingTaskIsRunning = false
semaphore.signal()
}
Thread.sleep(forTimeInterval: self.threshold)
if pingTaskIsRunning {
handler()
}
semaphore.wait()
}
}
}
typealias WatchdogFiredCallBack = () -> Void
class BHWatchDog {
var threshold: Double = 0.4
var pingThread: PingThread
init(threshold: Double, callBack: @escaping WatchdogFiredCallBack) {
self.threshold = threshold
self.pingThread = PingThread(threshold: threshold, handler: callBack)
self.pingThread.start()
}
convenience init(threshold: Double, strictMode: Bool) {
self.init(threshold: threshold, callBack: {
//TODO:
})
}
deinit {
self.pingThread.cancel()
}
}
| mit | 83fbad2b98480b8ef44f78b8c5162332 | 23.355932 | 77 | 0.589422 | 4.561905 | false | false | false | false |
Nukersson/Swift_iOS_Tutorial | FoodTracker/FoodTracker/RatingControl.swift | 1 | 4762 | //
// RatingControl.swift
// FoodTracker
//
// Created by nuke on 22.05.17.
// Copyright © 2017 Nukersson. All rights reserved.
//
import UIKit
@IBDesignable class RatingControl: UIStackView {
// MARK: Properties
private var ratingButtons = [UIButton]()
var rating = 0 {
didSet {
updateButtonSelectionStates()
}
}
@IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {
didSet {
setupButtons()
}
}
@IBInspectable var starCount: Int = 5 {
didSet {
setupButtons()
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
// MARK: Initialization
override init(frame: CGRect) {
// Super class initializer
super.init(frame: frame)
setupButtons()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setupButtons()
}
// MARK: Button Action
func ratingButtonTapped(button: UIButton) {
// print("Button pressed 👍")
guard let index = ratingButtons.index(of: button) else {
fatalError("The button, \(button), is not in the ratingButtons array: \(ratingButtons)")
}
// Calculate the rating of the selected button
let selectedRating = index + 1
if selectedRating == rating {
// If the selected star represents the current rating, reset the rating to 0.
rating = 0
} else {
// Otherwise set the rating to the selected star
rating = selectedRating
}
}
// MARK: Private Methods
private func setupButtons() {
// Clear any existing buttons
for button in ratingButtons {
removeArrangedSubview(button)
button.removeFromSuperview()
}
ratingButtons.removeAll()
// Load Button Images
let bundle = Bundle(for: type(of: self))
let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection)
let emptyStar = UIImage(named:"emptyStar", in: bundle, compatibleWith: self.traitCollection)
let highlightedStar = UIImage(named:"highlightedStar", in: bundle, compatibleWith: self.traitCollection)
// Create new buttons
for index in 0..<starCount {
// Create the button
let button = UIButton()
// button.backgroundColor = UIColor.red
// Set the button images
button.setImage(emptyStar, for: .normal)
button.setImage(filledStar, for: .selected)
button.setImage(highlightedStar, for: .highlighted)
button.setImage(highlightedStar, for: [.highlighted, .selected])
// Add constraints
button.translatesAutoresizingMaskIntoConstraints = false
button.heightAnchor.constraint(equalToConstant: starSize.height).isActive = true
button.widthAnchor.constraint(equalToConstant: starSize.width).isActive = true
// Set the accessibility label
button.accessibilityLabel = "Set \(index + 1) star rating"
// Setup the button action
button.addTarget(self, action:
#selector(RatingControl.ratingButtonTapped(button:)), for: .touchUpInside)
// Add the button to the stack
addArrangedSubview(button)
// Add the new button to the rating button array
ratingButtons.append(button)
}
updateButtonSelectionStates()
}
private func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerated() {
// If the index of a button is less than the rating, that button should be selected.
button.isSelected = index < rating
// Set the hint string for the currently selected star
let hintString: String?
if rating == index + 1 {
hintString = "Tap to reset the rating to zero."
} else {
hintString = nil
}
// Calculate the value string
let valueString: String
switch (rating) {
case 0:
valueString = "No rating set."
case 1:
valueString = "1 star set."
default:
valueString = "\(rating) stars set."
}
// Assign the hint string and value string
button.accessibilityHint = hintString
button.accessibilityValue = valueString
}
}
}
| gpl-3.0 | a49cb6cc915b461bc73eb5630e36d9c8 | 30.932886 | 112 | 0.586591 | 5.228571 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.