repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
rhwood/Doing-Time
Doing TimeTests/EventTests.swift
1
8253
// // EventTests.swift // Doing TimeTests // // Created by Randall Wood on 2020-11-22. // // Copyright 2020 Randall Wood DBA Alexandria Software // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest @testable import Doing_Time class EventTests: XCTestCase { var event: Event? override func setUpWithError() throws { event = Event(title: "Test", start: Calendar.current.date(byAdding: .day, value: -1, to: Date())!, end: Calendar.current.date(byAdding: .day, value: 1, to: Date())!, includeEnd: true) } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. // Nothing to do } func testSingleDayIncludeEndTodayIsComplete() throws { let subject = Event() XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.todayIs, .complete) XCTAssertEqual(subject.totalDuration, 1) XCTAssertEqual(subject.completedDuration, 1) XCTAssertEqual(subject.remainingDuration, 0) XCTAssertEqual(subject.completedPercentage, 1.0, accuracy: 0.0) XCTAssertEqual(subject.remainingPercentage, 0.0, accuracy: 0.0) XCTAssertEqual(subject.todayPercentage, 0.0, accuracy: 0.0) } func testSingleDayIncludeEndTodayIsRemaining() throws { let subject = Event(todayIs: .remaining) XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.todayIs, .remaining) XCTAssertEqual(subject.totalDuration, 1) XCTAssertEqual(subject.completedDuration, 0) XCTAssertEqual(subject.remainingDuration, 1) XCTAssertEqual(subject.completedPercentage, 0.0, accuracy: 0.0) XCTAssertEqual(subject.remainingPercentage, 1.0, accuracy: 0.0) XCTAssertEqual(subject.todayPercentage, 0.0, accuracy: 0.0) } func testLastDayIncludeEnd() throws { let subject = try XCTUnwrap(event) XCTAssertTrue(subject.includeEnd) XCTAssertEqual(Calendar.current.component(.hour, from: subject.lastDay), 23) XCTAssertEqual(Calendar.current.component(.minute, from: subject.lastDay), 59) XCTAssertEqual(Calendar.current.component(.second, from: subject.lastDay), 59) XCTAssertEqual(Calendar.current.component(.day, from: subject.lastDay), Calendar.current.component(.day, from: subject.end)) XCTAssertEqual(subject.totalDuration, 3) XCTAssertEqual(subject.totalDurationAsString, "3") } func testLastDayExcludeEnd() throws { let subject = try XCTUnwrap(event) subject.includeEnd = false XCTAssertFalse(subject.includeEnd) XCTAssertEqual(Calendar.current.component(.hour, from: subject.lastDay), 23) XCTAssertEqual(Calendar.current.component(.minute, from: subject.lastDay), 59) XCTAssertEqual(Calendar.current.component(.second, from: subject.lastDay), 59) XCTAssertEqual(Calendar.current.component(.day, from: subject.lastDay), Calendar.current.component(.day, from: subject.end) - 1) XCTAssertEqual(subject.totalDuration, 2) XCTAssertEqual(subject.totalDurationAsString, "2") } func testDurationsIncludeEndTodayIsUncounted() throws { let subject = try XCTUnwrap(event) subject.todayIs = .uncounted XCTAssertEqual(subject.todayIs, .uncounted) XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 3) XCTAssertEqual(subject.completedDuration, 1) XCTAssertEqual(subject.remainingDuration, 1) XCTAssertEqual(subject.completedPercentage, 0.33, accuracy: 0.01) XCTAssertEqual(subject.remainingPercentage, 0.33, accuracy: 0.01) XCTAssertEqual(subject.todayPercentage, 0.33, accuracy: 0.01) } func testDurationsIncludeEndTodayIsRemaining() throws { let subject = try XCTUnwrap(event) subject.todayIs = .remaining XCTAssertEqual(subject.todayIs, .remaining) XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 3) XCTAssertEqual(subject.completedDuration, 1) XCTAssertEqual(subject.remainingDuration, 2) XCTAssertEqual(subject.completedPercentage, 0.33, accuracy: 0.01) XCTAssertEqual(subject.remainingPercentage, 0.66, accuracy: 0.01) XCTAssertEqual(subject.todayPercentage, 0.0, accuracy: 0.0) } func testDurationsIncludeEndTodayIsCompleted() throws { let subject = try XCTUnwrap(event) subject.todayIs = .complete XCTAssertEqual(subject.todayIs, .complete) XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 3) XCTAssertEqual(subject.completedDuration, 2) XCTAssertEqual(subject.remainingDuration, 1) XCTAssertEqual(subject.completedPercentage, 0.66, accuracy: 0.01) XCTAssertEqual(subject.remainingPercentage, 0.33, accuracy: 0.01) XCTAssertEqual(subject.todayPercentage, 0.0, accuracy: 0.0) } func testSetDurationIncludeEnd() throws { let subject = try XCTUnwrap(event) subject.includeEnd = true XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 3) subject.totalDurationAsString = "4" XCTAssertEqual(subject.totalDuration, 4) // when adding duration to firstDay to match expected value with includeEnd, // add 1 less than total duration XCTAssertEqual(subject.end, Calendar.current.date(byAdding: .day, value: 3, to: subject.firstDay)) } func testSetDurationExcludeEnd() throws { let subject = try XCTUnwrap(event) subject.includeEnd = false XCTAssertFalse(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 2) subject.totalDuration = 3 XCTAssertEqual(subject.totalDuration, 3) // when adding duration to firstDay to match expected value with out includeEnd, // use total duration XCTAssertEqual(subject.end, Calendar.current.date(byAdding: .day, value: 3, to: subject.firstDay)) } func testInPast() throws { let subject = try XCTUnwrap(event) subject.start = Calendar.current.date(byAdding: .day, value: -10, to: Date())! subject.end = Calendar.current.date(byAdding: .day, value: -9, to: Date())! XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 2) XCTAssertEqual(subject.completedDuration, 2) XCTAssertEqual(subject.remainingDuration, 0) XCTAssertEqual(subject.completedPercentage, 1.0, accuracy: 0.01) XCTAssertEqual(subject.remainingPercentage, 0.0, accuracy: 0.01) XCTAssertEqual(subject.todayPercentage, 0.0, accuracy: 0.0) } func testInFuture() throws { let subject = try XCTUnwrap(event) subject.start = Calendar.current.date(byAdding: .day, value: 9, to: Date())! subject.end = Calendar.current.date(byAdding: .day, value: 10, to: Date())! XCTAssertTrue(subject.includeEnd) XCTAssertEqual(subject.totalDuration, 2) XCTAssertEqual(subject.completedDuration, 0) XCTAssertEqual(subject.remainingDuration, 2) XCTAssertEqual(subject.completedPercentage, 0.0, accuracy: 0.01) XCTAssertEqual(subject.remainingPercentage, 1.0, accuracy: 0.01) XCTAssertEqual(subject.todayPercentage, 0.0, accuracy: 0.0) } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
mit
0f255eaa674f382a308222b43845bafb
43.610811
111
0.689083
4.512302
false
true
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV1/Models/MessageInput.swift
1
5396
/** * (C) Copyright IBM Corp. 2017, 2020. * * 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 IBMSwiftSDKCore /** An input object that includes the input text. */ public struct MessageInput: Codable, Equatable { /** The text of the user input. This string cannot contain carriage return, newline, or tab characters. */ public var text: String? /** Whether to use spelling correction when processing the input. This property overrides the value of the **spelling_suggestions** property in the workspace settings. */ public var spellingSuggestions: Bool? /** Whether to use autocorrection when processing the input. If spelling correction is used and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. */ public var spellingAutoCorrect: Bool? /** Any suggested corrections of the input text. This property is returned only if spelling correction is enabled and autocorrection is disabled. */ public var suggestedText: String? /** The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. */ public var originalText: String? /// Additional properties associated with this model. public var additionalProperties: [String: JSON] // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case text = "text" case spellingSuggestions = "spelling_suggestions" case spellingAutoCorrect = "spelling_auto_correct" case suggestedText = "suggested_text" case originalText = "original_text" static let allValues = [text, spellingSuggestions, spellingAutoCorrect, suggestedText, originalText] } /** Initialize a `MessageInput` with member variables. - parameter text: The text of the user input. This string cannot contain carriage return, newline, or tab characters. - parameter spellingSuggestions: Whether to use spelling correction when processing the input. This property overrides the value of the **spelling_suggestions** property in the workspace settings. - parameter spellingAutoCorrect: Whether to use autocorrection when processing the input. If spelling correction is used and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - returns: An initialized `MessageInput`. */ public init( text: String? = nil, spellingSuggestions: Bool? = nil, spellingAutoCorrect: Bool? = nil, additionalProperties: [String: JSON] = [:] ) { self.text = text self.spellingSuggestions = spellingSuggestions self.spellingAutoCorrect = spellingAutoCorrect self.additionalProperties = additionalProperties } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) text = try container.decodeIfPresent(String.self, forKey: .text) spellingSuggestions = try container.decodeIfPresent(Bool.self, forKey: .spellingSuggestions) spellingAutoCorrect = try container.decodeIfPresent(Bool.self, forKey: .spellingAutoCorrect) let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self) additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(text, forKey: .text) try container.encodeIfPresent(spellingSuggestions, forKey: .spellingSuggestions) try container.encodeIfPresent(spellingAutoCorrect, forKey: .spellingAutoCorrect) try container.encodeIfPresent(suggestedText, forKey: .suggestedText) try container.encodeIfPresent(originalText, forKey: .originalText) var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self) try dynamicContainer.encodeIfPresent(additionalProperties) } }
apache-2.0
20ca34e70e83616739ff2d05fee184ce
44.728814
121
0.721831
5.061914
false
false
false
false
0xfeedface1993/Xs8-Safari-Block-Extension-Mac
Sex8BlockExtension/Sex8BlockExtension/ListTableViewController.swift
1
21583
// // ListTableViewController.swift // Sex8BlockExtension // // Created by virus1994 on 2017/6/25. // Copyright © 2017年 ascp. All rights reserved. // import Cocoa import WebKit let TableViewRefreshName = NSNotification.Name(rawValue: "refreshTableView") let DeleteActionName = NSNotification.Name(rawValue: "deleteNetDisk") let SelectItemName = NSNotification.Name(rawValue: "selectItem") let UnSelectItemName = NSNotification.Name(rawValue: "unSelectItem") let ShowImagesName = NSNotification.Name(rawValue: "showImages") let ShowDonwloadAddressName = NSNotification.Name(rawValue: "showAddress") let SearchName = NSNotification.Name(rawValue: "search") let PageDataMessage = "pageData" class ListTableViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource, Reciver { @IBOutlet weak var tableview: NSTableView! let IdenitfierKey = "identifier" let TitleKey = "title" var datas = [NetDisk]() var isFetching = false lazy var menus : [ListCategrory] = { guard let fileURL = Bundle.main.url(forResource: "categrory", withExtension: "plist") else { return [ListCategrory]() } do { let file = try Data(contentsOf: fileURL) let decoder = PropertyListDecoder() let plist = try decoder.decode([ListCategrory].self, from: file).filter({ $0.segue == "com.ascp.netdisk.list" }) return plist } catch { print(error) return [ListCategrory]() } }() lazy var popver : NSPopover = { let pop = NSPopover() pop.animates = true pop.appearance = NSAppearance(named: NSAppearance.Name.aqua) let storyboard = NSStoryboard(name: "Main", bundle: Bundle.main) let xpics = storyboard.instantiateController(withIdentifier: "PicsCollectionViewController") as! PicsCollectionViewController pop.contentViewController = xpics pop.contentSize = CGSize(width: 800, height: 600) return pop }() private lazy var fetchJS : String = { let url = Bundle.main.url(forResource: "fetch", withExtension: "js")! do { let content = try String(contentsOf: url) return content } catch { print("read js file error: \(error)") return "" } }() let bot = FetchBot(start: 0, offset: 10) override func viewDidLoad() { super.viewDidLoad() // Do view setup here. tableview.delegate = self tableview.dataSource = self tableview.removeTableColumn(tableview.tableColumns.first!) let coloums = [[TitleKey:"标题", IdenitfierKey:"title"], [TitleKey:"解压密码", IdenitfierKey:"password"], [TitleKey:"文件名", IdenitfierKey:"filename"], [TitleKey:"是否有码", IdenitfierKey:"msk"], [TitleKey:"时间", IdenitfierKey:"time"], [TitleKey:"格式", IdenitfierKey:"format"], [TitleKey:"大小", IdenitfierKey:"size"]] for item in coloums { let coloum = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: item[IdenitfierKey]!)) coloum.title = item[TitleKey]! coloum.width = 150 tableview.addTableColumn(coloum) } NotificationCenter.default.addObserver(self, selector: #selector(reloadTableView(notification:isDelete:)), name: TableViewRefreshName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(delete(notification:)), name: DeleteActionName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(showImages), name: ShowImagesName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(showAddress), name: ShowDonwloadAddressName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(uploadServer(notification:)), name: UploadName, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(searchNotification(notification:)), name: NSControl.textDidChangeNotification, object: nil) addRemoteNetdisk(oberserver: self, selector: #selector(reciver(notification:))) reloadTableView(notification: nil) } deinit { NotificationCenter.default.removeObserver(self, name: TableViewRefreshName, object: nil) NotificationCenter.default.removeObserver(self, name: DeleteActionName, object: nil) NotificationCenter.default.removeObserver(self, name: ShowImagesName, object: nil) NotificationCenter.default.removeObserver(self, name: UploadName, object: nil) NotificationCenter.default.removeObserver(self, name: NSControl.textDidChangeNotification, object: nil) removeRemoteNetdisk(oberserver: self) } @objc func reciver(notification: Notification) { print(">>>>>>>>>> \(notification)") guard let jsonString = notification.object as? String, let data = jsonString.data(using: .utf8, allowLossyConversion: false) else { print("****** Not Json String ******") return } do { let json = try JSONDecoder().decode(RemoteNetDisk.self, from: data) DataBase.share.saveRemoteDownloadLink(data: json) { (state) in switch state { case .success: print("保存 1 项成功") NotificationCenter.default.post(name: DownloadAddressName, object: json.downloadLink) DispatchQueue.main.async { self.reloadTableView(notification: nil) let pasteBoard = NSPasteboard.general pasteBoard.clearContents() let copysObjects = [json.downloadLink] pasteBoard.writeObjects(copysObjects as [NSPasteboardWriting]) (NSApp.delegate as! AppDelegate).selectItem = self.datas.first NotificationCenter.default.post(name: RemoteDownloadAddressName, object: json.downloadLink) } break case .failed: print("保存远程请求失败") break } } } catch { print(error) } } override func viewDidAppear() { super.viewDidAppear() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { self.view.window?.makeFirstResponder(self.tableview) } } @objc func uploadServer(notification: NSNotification?) { let webservice = Webservice.share if let flag = notification?.object as? Int, flag == 444 { webservice.cancelAllTask() return } // let encoder = JSONEncoder() // var count = 0 // for (_, data) in datas.enumerated() { // let links = (data.link?.allObjects as? [Link] ?? []).map({ $0.link! }) // let pics = (data.pic?.allObjects as? [Pic] ?? []).map({ $0.pic! }) // let title = data.title ?? UUID().uuidString // let page = data.pageurl ?? "" // let msk = data.msk ?? "" // let time = data.time ?? "" // let format = data.format ?? "" // let size = data.size ?? "" // let dic = MovieModal(title: title, page: page, pics: pics, msk: msk, time: time, format: format, size: size, downloads: links) // // do { // let json = try encoder.encode(dic) // let caller = WebserviceCaller<MovieAddRespnse>(baseURL: WebserviceBaseURL.main, way: WebServiceMethod.post, method: "addMovie", paras: nil, rawData: json, execute: { (result, err, response) in // count += 1 // if count < self.datas.count { // DispatchQueue.main.async { // self.showProgress(text: "已提交第 \(count)/\(self.datas.count) 项数据...") // } // } else { // DispatchQueue.main.async { // self.showProgress(text: "已提交 \(self.datas.count) 项数据") // } // } // guard let message = result else { // if let e = err { // print("error: \(e)") // } // return // } // print("movieID: \(message.movieID)") // }) // try webservice.read(caller: caller) // } catch { // print("upload faild: json error \(error)") // } // } } //MARK: - NSTableViewDelegate func numberOfRows(in tableView: NSTableView) -> Int { return datas.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { if let coloum = tableColumn, row < datas.count { switch coloum.identifier.rawValue { case "title": return datas[row].title case "password": return datas[row].passwod ?? "无密码" case "filename": return datas[row].fileName ?? "未知" case "careatetime": let calender = Calendar.current if let date = datas[row].creattime { var comp = calender.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date) comp.timeZone = TimeZone(identifier: "Asia/Beijing") let cool = "\(comp.year!)/\(comp.month!)/\(comp.day!) \(comp.hour!):\(comp.minute!)" return cool } case "msk": return datas[row].msk ?? "未知" case "time": return datas[row].time ?? "未知" case "format": return datas[row].format ?? "未知" case "size": return datas[row].size ?? "未知" default: break } } return "没有数据" } func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) { if let coloum = tableColumn { switch coloum.identifier.rawValue { case "title": datas[row].title = object as? String break case "password": datas[row].passwod = object as? String break case "filename": datas[row].fileName = object as? String break case "msk": datas[row].msk = object as? String break case "time": datas[row].time = object as? String break case "format": datas[row].format = object as? String break case "size": datas[row].size = object as? String break default: break } let app = NSApplication.shared.delegate as! AppDelegate app.saveAction(nil) } } func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool { if let coloum = tableColumn { switch coloum.identifier.rawValue { case "careatetime": return false default: break } } return true } override func moveDown(_ sender: Any?) { super.moveDown(sender) } func tableViewSelectionDidChange(_ notification: Notification) { // print((notification.object as! NSTableView).selectedRow) if let table = notification.object as? NSTableView { if tableview.selectedRow >= 0 { reloadImages(index: table.selectedRow) let data = datas[table.selectedRow] let app = NSApp.delegate as! AppDelegate app.selectItem = data NotificationCenter.default.post(name: SelectItemName, object: data) } else { popver.close() NotificationCenter.default.post(name: UnSelectItemName, object: nil) } } } override func keyDown(with event: NSEvent) { print(event.keyCode) switch event.keyCode { case 53: popver.close() break case 49: if popver.isShown { popver.close() } else { reloadImages(index: tableview.selectedRow) } return default: break } super.keyDown(with: event) } // 重新获取数据 @objc func reloadTableView(notification: Notification?, isDelete: Int = 1) { if let btn = notification?.object as? NSButton { if btn.tag == 110 { if !isFetching { loadList() } isFetching = true print("continute fetching !") } else { isFetching = false print("stop fetching !") } } print("reloadTableView:notification") let managedObjectContext = DataBase.share.managedObjectContext let employeesFetch = NSFetchRequest<NetDisk>(entityName: "NetDisk") let sort = NSSortDescriptor(key: "creattime", ascending: false) employeesFetch.sortDescriptors = [sort] do { let oldCount = datas.count datas = try managedObjectContext.fetch(employeesFetch) tableview.reloadData() if datas.count > 0 { if oldCount != datas.count { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: { self.tableview.selectRowIndexes([0], byExtendingSelection: false) NotificationCenter.default.post(name: SelectItemName, object: self.datas[0]) }) } else { if isDelete == 2 { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: { let selectIndex = self.tableview.selectedRow > 0 && self.tableview.selectedRow < self.datas.count ? self.tableview.selectedRow:0 self.tableview.selectRowIndexes([selectIndex], byExtendingSelection: false) NotificationCenter.default.post(name: SelectItemName, object: self.datas[selectIndex]) }) } } } else { NotificationCenter.default.post(name: SelectItemName, object: nil) } } catch { fatalError("Failed to fetch employees: \(error)") } } // 删除 @objc func delete(notification: Notification) { if tableview.selectedRow >= 0 { let alert = NSAlert() alert.addButton(withTitle: "删除") alert.addButton(withTitle: "取消") alert.messageText = "确定删除选中项?" alert.informativeText = "删除后不可恢复!" alert.alertStyle = .warning alert.beginSheetModal(for: view.window!, completionHandler: { code in switch code { case NSApplication.ModalResponse.alertFirstButtonReturn: let index = self.tableview.selectedRow let managedObjectContext = DataBase.share.managedObjectContext do { managedObjectContext.delete(self.datas[index]) self.datas.remove(at: index) try managedObjectContext.save() // if self.tableview.selectedRow >= 0 { // self.tableview.deselectRow(self.tableview.selectedRow) // self.tableview.reloadData() // } self.reloadTableView(notification: nil, isDelete: 2) } catch { print ("There was an error: \(error.localizedDescription)") } break case NSApplication.ModalResponse.alertSecondButtonReturn: break default: break } }) } } // 通知 @objc func showImages() { if popver.isShown { popver.close() } } @objc func showAddress(notification: Notification) { if tableview.selectedRow >= 0 { let data = datas[tableview.selectedRow].link?.allObjects as? [Link] ?? [] print(data.map({ item in return item.link ?? "" })) } } func reloadImages(index: Int) { // let pics = popver.contentViewController as! PicsCollectionViewController // let data = datas[index].pic?.allObjects as? [Pic] ?? [] // let rect = parent?.view.frame // if !popver.isShown { // popver.show(relativeTo: rect!, of: tableview, preferredEdge: .maxX) // } // pics.clearCacheImages() // pics.collectionView.reloadData() // pics.collectionView.scroll(NSPoint(x: 0, y: 0)) // NotificationCenter.default.post(name: SelectItemName, object: data) } /// 展示提示文字 /// /// - Parameter text: 提示文字 func showProgress(text: String) { NotificationCenter.default.post(name: ShowExtennalTextName, object: text) } func loadList() { bot.delegate = self DispatchQueue.global().async { var site = Site.netdisk site.categrory = self.menus.last! self.bot.start(withSite: site) } } } func opFetch() { let opRequest = NSFetchRequest<OPMovie>(entityName: "OPMovie") opRequest.predicate = NSPredicate(value: true) let managedObjectContext = DataBase.share.managedObjectContext do { let count = try managedObjectContext.count(for: opRequest) print(">>> opmovie count: \(count)") } catch { print(error) } } // MARK: - FetchBot Delegate extension ListTableViewController : FetchBotDelegate { func bot(_ bot: FetchBot, didLoardContent content: ContentInfo, atIndexPath index: Int) { let message = "正在接收 \(index) 项数据..." print(message) DispatchQueue.main.async { self.showProgress(text: message) } } func bot(didStartBot bot: FetchBot) { let message = "正在加载链接数据..." showProgress(text: message) print(message) } func bot(_ bot: FetchBot, didFinishedContents contents: [ContentInfo], failedLink : [FetchURL]) { let message = "已成功接收 \(bot.count - failedLink.count) 项数据, \(failedLink.count) 项接收失败" print(message) isFetching = false DataBase.share.save(downloadLinks: contents) { (state) in switch state { case .success: print("保存 \(contents.count) 项成功") break case .failed: print("批量保存失败") break } DispatchQueue.main.async { self.showProgress(text: message) NotificationCenter.default.post(name: StopFetchName, object: nil) self.reloadTableView(notification: nil) } } } } extension ListTableViewController { @objc func searchNotification(notification: NSNotification?) { if let searchField = notification?.object as? NSSearchField { filiter(keyword: searchField.stringValue) } } func filiter(keyword: String) { let managedObjectContext = DataBase.share.managedObjectContext let employeesFetch = NSFetchRequest<NetDisk>(entityName: "NetDisk") let sort = NSSortDescriptor(key: "creattime", ascending: false) employeesFetch.sortDescriptors = [sort] do { datas = try managedObjectContext.fetch(employeesFetch) if keyword != "" { datas = datas.filter({ (disk) -> Bool in return (disk.title ?? "").contains(keyword) }) } tableview.reloadData() if datas.count > 0 { self.tableview.selectRowIndexes([0], byExtendingSelection: false) NotificationCenter.default.post(name: SelectItemName, object: self.datas[0]) } else { NotificationCenter.default.post(name: SelectItemName, object: nil) } } catch { fatalError("Failed to fetch employees: \(error)") } } }
apache-2.0
3cfe898c0affe77476dfff0f4a26004c
38.078899
210
0.543572
4.970362
false
false
false
false
MyBar/MyBarMusic
MyBarMusic/MyBarMusic/Classes/Utility/PlayerManager/MBPlayerManager.swift
1
12552
// // MBPlayerManager.swift // MyBarMusic // // Created by lijingui2010 on 2017/7/18. // Copyright © 2017年 MyBar. All rights reserved. // import Foundation import AVFoundation //播放模式 enum MBPlayingSortType { case Sequence // 顺序播放 case SingleLoop // 单曲循环 case Random // 随机播放 } //播放状态枚举值 enum MBPlayerManagerStatus { case none case failed case readyToPlay case unknown case loadSongModel case playing case paused case stopped } class MBPlayerManager: NSObject { private static var playerManager: MBPlayerManager? class var shared: MBPlayerManager { if self.playerManager == nil { self.playerManager = MBPlayerManager() } return self.playerManager! } deinit { self.removeObserverFromPlayer() self.removeObserverFromPlayerCurrentItem() } //监控时间进度 var timeObserver: Any? //播放器 var player: AVPlayer? //播放器播放状态 var playerManagerStatus: MBPlayerManagerStatus = .none //是否正在播放 var isPlaying: Bool? //是否立即播放 var startToPlayAfterLoadingSongModel: Bool? //歌曲列表 var songInfoList: [MBSongInfoModel]? //当前播放歌曲 var currentSongInfoModel: MBSongInfoModel? //当前播放歌曲索引 var currentSongInfoModelIndex: Int? //歌曲播放模式 var playingSortType: MBPlayingSortType? = .Sequence //当前播放时间(秒) lazy var playTime: Float = 0.0 //总时长(秒) lazy var playDuration: Float = 0.0 //播放进度(%) lazy var progress: Float = 0.0 //开始播放 func startPlay() { self.player?.play() } //暂停播放 func pausePlay() { self.player?.pause() } //播放完毕 func endPlay() { guard (self.player != nil) else { return } //重置进度 self.playTime = 0 self.playDuration = 0 self.progress = 0 self.pausePlay() self.isPlaying = nil self.playerManagerStatus = .stopped NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) self.removeObserverFromPlayer() self.removeObserverFromPlayerCurrentItem() self.player = nil } //自然播放下一首 func playNext() { self.endPlay() switch self.playingSortType! { case MBPlayingSortType.SingleLoop: fallthrough case MBPlayingSortType.Sequence: if (self.currentSongInfoModelIndex! + 1 >= self.songInfoList!.count) { self.currentSongInfoModelIndex = 0 } else { self.currentSongInfoModelIndex = self.currentSongInfoModelIndex! + 1 } case MBPlayingSortType.Random: if (self.currentSongInfoModelIndex! + 1 >= self.songInfoList!.count) { self.currentSongInfoModelIndex = 0 } else { self.currentSongInfoModelIndex = self.currentSongInfoModelIndex! + 1 } } self.loadSongModel(startToPlay: true) } //播放上一首 func playPrevious() { self.endPlay() switch self.playingSortType! { case MBPlayingSortType.SingleLoop: fallthrough case MBPlayingSortType.Sequence: if (self.currentSongInfoModelIndex! - 1 < 0) { self.currentSongInfoModelIndex = self.songInfoList!.count - 1 } else { self.currentSongInfoModelIndex = self.currentSongInfoModelIndex! - 1 } case MBPlayingSortType.Random: if (self.currentSongInfoModelIndex! - 1 < 0) { self.currentSongInfoModelIndex = self.songInfoList!.count - 1 } else { self.currentSongInfoModelIndex = self.currentSongInfoModelIndex! - 1 } } self.loadSongModel(startToPlay: true) } //根据索引去播放一首歌曲 func playWithIndex(_ index: Int) { self.endPlay() if (index >= self.songInfoList!.count) { self.currentSongInfoModelIndex = 0 } else { self.currentSongInfoModelIndex = index } self.loadSongModel(startToPlay: true) } func loadSongModel(startToPlay: Bool = false) { self.currentSongInfoModel = self.songInfoList![self.currentSongInfoModelIndex!] if let file_duration = self.currentSongInfoModel?.file_duration { self.playDuration = Float(file_duration)! } MBNetworkManager.fetchSong(songID: self.currentSongInfoModel!.song_id!) { (isSuccess, songModel) in if isSuccess == true { if self.player?.currentItem != nil { self.removeObserverFromPlayerCurrentItem() } let playerItem = AVPlayerItem(url: URL(string: "\(songModel!.bitrate!.file_link!)")!) if self.player == nil { self.player = AVPlayer(playerItem: playerItem) self.player?.volume = 1 self.addObserverToPlayer() } else { self.player?.replaceCurrentItem(with: playerItem) } self.addObserverToPlayerCurrentItem() self.startToPlayAfterLoadingSongModel = startToPlay } else { } } self.playerManagerStatus = .loadSongModel NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) } //给AVPlayer添加监控 func addObserverToPlayer() { guard let player = self.player else { return } player.addObserver(self, forKeyPath: "rate", options: [.new, .old], context: nil) player.addObserver(self, forKeyPath: "currentItem", options: [.new, .old], context: nil) } //从AVPlayer移除监控 func removeObserverFromPlayer() { guard let player = self.player else { return } player.removeObserver(self, forKeyPath: "rate") player.removeObserver(self, forKeyPath: "currentItem") } //给AVPlayerItem、AVPlayer添加监控 func addObserverToPlayerCurrentItem() { guard let currentItem = self.player?.currentItem else { return } //监控状态属性,注意AVPlayer也有一个status属性,通过监控它的status也可以获得播放状态 currentItem.addObserver(self, forKeyPath: "status", options: [.new, .old], context: nil) //监控缓冲加载情况属性 currentItem.addObserver(self, forKeyPath: "loadedTimeRanges", options: [.new, .old], context: nil) //监控播放完成通知 NotificationCenter.default.addObserver(self, selector: #selector(self.playItemDidPlayToEndTimeAction(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: currentItem) //监控时间进度 self.timeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1), queue: DispatchQueue.main, using: { [weak self] (time) in self?.playTime = Float(CMTimeGetSeconds(time)) self?.playDuration = Float(CMTimeGetSeconds(currentItem.duration)) self?.progress = (self?.playTime)! / (self?.playDuration)! }) } //从AVPlayerItem、AVPlayer移除监控 func removeObserverFromPlayerCurrentItem() { guard let currentItem = self.player?.currentItem else { return } currentItem.removeObserver(self, forKeyPath: "status") currentItem.removeObserver(self, forKeyPath: "loadedTimeRanges") NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil) if self.timeObserver != nil { self.player?.removeTimeObserver(self.timeObserver!) self.timeObserver = nil } } //AVPlayerItem播放完成后动作 func playItemDidPlayToEndTimeAction(_ notification: Notification) { print("播放完成") self.playNext() } /** * 通过KVO监控播放器状态 * * @param keyPath 监控属性 * @param object 监视器 * @param change 状态改变 * @param context 上下文 */ override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "status" { let playerItem = object as! AVPlayerItem switch playerItem.status { case AVPlayerItemStatus.unknown: print("KVO:未知状态,此时不能播放") self.playerManagerStatus = .unknown NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) case AVPlayerItemStatus.readyToPlay: print("KVO:准备完毕,可以播放") self.playerManagerStatus = .readyToPlay NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) if self.startToPlayAfterLoadingSongModel == true { self.startPlay() } case AVPlayerItemStatus.failed: print("KVO:加载失败,网络或者服务器出现问题") self.playerManagerStatus = .failed NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) } } else if keyPath == "loadedTimeRanges" { print("KVO:loadedTimeRanges") } else if keyPath == "rate" { print("KVO:Rate") let rate = change![.newKey] as! Float if rate == 0 { self.isPlaying = false self.playerManagerStatus = .paused NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) } else { self.isPlaying = true self.playerManagerStatus = .playing NotificationCenter.default.post(name: NSNotification.Name("playerManagerStatus"), object: nil) } } else if keyPath == "currentItem" { print("KVO:CurrentItem") } } //切换歌曲播放模式 func switchToNextPlayingSortType(completionHandler: ((MBPlayingSortType) -> Void)? = nil ) { switch self.playingSortType! { case MBPlayingSortType.Sequence: self.playingSortType = MBPlayingSortType.SingleLoop case MBPlayingSortType.SingleLoop: self.playingSortType = MBPlayingSortType.Random case MBPlayingSortType.Random: self.playingSortType = MBPlayingSortType.Sequence } if completionHandler != nil { completionHandler!(self.playingSortType!) } } //从一个特定时间进度播放,progress: 0 to 1 func seekToProgress(_ progress: Float) { guard self.player != nil else { return } let time = CMTime(value: CMTimeValue(progress * self.playDuration), timescale: 1) self.player!.seek(to: time, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) { (finished) in self.startPlay() } } }
mit
a022d7e073421a4fa40366423b371d21
29.786082
191
0.557639
5.061441
false
false
false
false
vasarhelyia/Smogler
Smogler/APIService.swift
1
3479
// // APIService.swift // Smogler // // Created by Vasarhelyi Agnes on 2017. 02. 19.. // Copyright © 2017. vasarhelyia. All rights reserved. // import Foundation let token = "YOUR_TOKEN" let baseURLString = "https://api.waqi.info/feed" protocol AQIDelegate: class { func didUpdateAQILevel(aqiInfo: AQIInfo) func didFailWithError(err: String) } class APIService: NSObject, URLSessionDataDelegate { static var sharedInstance = APIService() private var locationManager = LocationManager() #if os(watchOS) weak var watchDelegate: AQIDelegate? #else weak var delegate: AQIDelegate? #endif override init() { super.init() self.locationManager.delegate = self } // Compose request private var geoLocURLRequest: URLRequest? { let location = self.locationManager.geoLoc() let latitude = location?.coordinate.latitude let longitude = location?.coordinate.longitude if let lat = latitude, let lng = longitude { let urlString = "\(baseURLString)/geo:\(lat);\(lng)/?token=\(token)" guard let url = URL(string: urlString) else { #if os(watchOS) watchDelegate?.didFailWithError(err: "could not create URL from string \(urlString)") #else delegate?.didFailWithError(err: "could not create URL from string \(urlString)") #endif return nil } return URLRequest(url: url) } else { #if os(watchOS) watchDelegate?.didFailWithError(err: "could not compose URL request, no location") #else delegate?.didFailWithError(err: "could not compose URL request, no location") #endif return nil } } func fetchAQI() { guard let request = geoLocURLRequest else { return } let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.urlCache = nil URLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil).dataTask(with: request).resume() } // Parse results private func parseResults(json: AnyObject) -> AQIInfo? { guard let dict = json as? [String:Any], let data = dict["data"] as? [String:Any], let aqi = data["aqi"] as? Int, let cityDict = data["city"] as? [String: Any], let city = cityDict["name"] as? String else { print("Error parsing JSON. Make sure you are using a valid API token. You can acquire it here: https://aqicn.org/data-platform/token/") return nil } return AQIInfo(aqiLevel: AQILevel(level: aqi), city: city) } private func refreshWithAQIInfo(aqiInfo: AQIInfo?) { guard let aqi = aqiInfo else { return } DispatchQueue.main.async { #if os(watchOS) self.watchDelegate?.didUpdateAQILevel(aqiInfo: aqi) #else self.delegate?.didUpdateAQILevel(aqiInfo: aqi) #endif } } // MARK: URLSessionDataTaskDelegate func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { let json = try? JSONSerialization.jsonObject(with: data, options: []) self.refreshWithAQIInfo(aqiInfo: self.parseResults(json: json as AnyObject)) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if let e = error { print("URL session completed with error: \(e.localizedDescription)") } } } // MARK: LocationManagerDelegate extension APIService: LocationManagerDelegate { func didChangeLocation() { self.fetchAQI() } }
mit
2e3c3547c710aeb8c9621e74bdc4b265
27.508197
143
0.677113
4.115976
false
false
false
false
richardpiazza/CodeQuickKit
Sources/CodeQuickKit/Foundation/String+Casing.swift
1
8546
import Foundation public extension String { /// Returns a sentence cased version of the string. /// /// This is a mixed-case style in which the first word of the sentence is capitalized. /// The following example transforms a string to sentence-cased letters: /// ``` /// let value = "The Fox Eats The Chicken." /// print(value.sentenceCased()) /// // Prints "The fox eats the chicken." /// ``` /// /// - parameter fragmentHandler: Allows caller to override fragment lower-casing (index > 0) /// - returns: A sentence-cased copy of the string. func sentenceCased(with locale: Locale? = nil, fragmentHandler: ((_ fragment: String) -> Bool)? = nil) -> String { return mixedCase(capitalizeFragments: false, locale: locale, fragmentHandler: fragmentHandler) } /// Returns a title cased version of the string. /// /// This is a mixed-case style with all words capitalized (except some articles, prepositions, and conjunctions) /// The following example transforms a string to sentence-cased letters: /// ``` /// let value = "The fox eats the chicken." /// print(value.titleCased()) /// // Prints "The Fox Eats The Chicken." /// ``` /// /// - parameter fragmentHandler: Allows caller to override fragment capitalization (index > 0) /// - returns: A title-cased copy of the string. func titleCased(with locale: Locale? = nil, fragmentHandler: ((_ fragment: String) -> Bool)? = nil) -> String { return mixedCase(capitalizeFragments: true, locale: locale, fragmentHandler: fragmentHandler) } /// Returns a camel cased version of the string. /// /// Punctuation & spaces are removed and the first character of each word is capitalized. /// The following example transforms a string to sentence-cased letters: /// ``` /// let value = "The fox eats the chicken." /// print(value.upperCamelCased()) /// // Prints "TheFoxEatsTheChicken" /// ``` /// /// - returns: A camel-cased copy of the string. func upperCamelCased(with locale: Locale? = nil) -> String { return camel(upperFirst: true, locale: locale) } /// Returns a camel cased version of the string. /// /// Punctuation & spaces are removed and the first character of each word is capitalized (except the first). /// The following example transforms a string to sentence-cased letters: /// ``` /// let value = "The fox eats the chicken." /// print(value.lowerCamelCased()) /// // Prints "theFoxEatsTheChicken" /// ``` /// /// - returns: A camel-cased copy of the string. func lowerCamelCased(with locale: Locale? = nil) -> String { return camel(upperFirst: false, locale: locale) } /// Returns a snake cased version of the string. /// /// Punctuation & spaces are removed and replaced by underscores. /// The following example transforms a string to sentence-cased letters: /// ``` /// let value = "The fox eats the chicken." /// print(value.snakeCased()) /// // Prints "The_fox_eats_the_chicken" /// ``` /// /// - returns: A snake-cased copy of the string. func snakeCased(with locale: Locale? = nil) -> String { return alphanumericsSeparated(separator: "_", locale: locale) } /// Returns a snake cased version of the string. /// /// Punctuation & spaces are removed and replaced by hyphens. /// The following example transforms a string to sentence-cased letters: /// ``` /// let value = "The fox eats the chicken." /// print(value.snakeCased()) /// // Prints "The-fox-eats-the-chicken" /// ``` /// /// - returns: A kebab-cased copy of the string. func kebabCased(with locale: Locale? = nil) -> String { return alphanumericsSeparated(separator: "-", locale: locale) } } private extension String { /// Produce a mixed-case string (sentence, title) /// - parameter capitalizedFragments: Force all fragments to be capitalized. /// - parameter fragmentHandler: A function block to execute with all fragments (index > 0) to determine capitalization. func mixedCase(capitalizeFragments: Bool, locale: Locale? = nil, fragmentHandler: ((_ fragment: String) -> Bool)? = nil) -> String { let fragments = self.splitBefore { (character) -> Bool in return (character.isPunctuation || character.isWhitespace || character.isNewline) } let outputFragments: [String] switch capitalizeFragments { case true: var collection: [String] = [] for (index, fragment) in fragments.enumerated() { let string = String(fragment).lowercased(with: locale) if index > 0 { if let handler = fragmentHandler, !handler(string) { collection.append(string) continue } } collection.append(string.capitalized(with: locale)) } outputFragments = collection case false: var collection: [String] = [] for (index, fragment) in fragments.enumerated() { let string = String(fragment).lowercased(with: locale) if index > 0 { if let handler = fragmentHandler, handler(string) { // capitalize } else { collection.append(string) continue } } collection.append(string.capitalized(with: locale)) } outputFragments = collection } return outputFragments.joined() } /// Produces a camel-cased string containing only alphanumeric characters. /// - parameter upperFirst: Controls wether the first character in the resulting string is 'capitalized'. func camel(upperFirst: Bool, locale: Locale? = nil) -> String { let nonLetters = CharacterSet.alphanumerics.inverted let fragments = self.splitBefore { (character) -> Bool in guard let scalar = character.unicodeScalars.first else { return false } return nonLetters.contains(scalar) } var stringFragments = fragments.map({ String($0) }) for (index, fragment) in stringFragments.enumerated() { let cleanFragment = fragment.replacingCharacters(in: nonLetters, with: "") stringFragments[index] = cleanFragment } stringFragments.removeAll(where: { $0 == "" }) let outputFragments: [String] if upperFirst { outputFragments = stringFragments.map({ $0.capitalized(with: locale) }) } else { var collection: [String] = [] for (index, fragment) in stringFragments.enumerated() { if index == 0 { collection.append(fragment.lowercased(with: locale)) } else { collection.append(fragment.capitalized(with: locale)) } } outputFragments = collection } return outputFragments.joined() } /// Produces a string that removes all non-alphanumeric characters, joining the /// resulting fragments with the provided `separator`. /// - parameter separator: String to use when joining cleaned fragments. func alphanumericsSeparated(separator: String, locale: Locale? = nil) -> String { let nonLetters = CharacterSet.alphanumerics.inverted let fragments = self.splitBefore { (character) -> Bool in guard let scalar = character.unicodeScalars.first else { return false } return nonLetters.contains(scalar) } var stringFragments = fragments.map({ String($0) }) for (index, fragment) in stringFragments.enumerated() { let cleanFragment = fragment.replacingCharacters(in: nonLetters, with: "") stringFragments[index] = cleanFragment } stringFragments.removeAll(where: { $0 == "" }) return stringFragments.joined(separator: separator) } }
mit
386eb2c4f7b682e2bd6b81f3c07a6643
38.934579
136
0.585069
4.939884
false
false
false
false
ColorPenBoy/ios-charts
Charts/Classes/Charts/BarLineChartViewBase.swift
2
60196
// // BarLineChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart. public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate { /// the maximum number of entried to which values will be drawn internal var _maxVisibleValueCount = 100 /// flag that indicates if auto scaling on the y axis is enabled private var _autoScaleMinMaxEnabled = false private var _autoScaleLastLowestVisibleXIndex: Int! private var _autoScaleLastHighestVisibleXIndex: Int! private var _pinchZoomEnabled = false private var _doubleTapToZoomEnabled = true private var _dragEnabled = true private var _scaleXEnabled = true private var _scaleYEnabled = true /// the color for the background of the chart-drawing area (everything behind the grid lines). public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0) public var borderColor = UIColor.blackColor() public var borderLineWidth: CGFloat = 1.0 /// flag indicating if the grid background should be drawn or not public var drawGridBackgroundEnabled = true /// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis. public var drawBordersEnabled = false /// the object representing the labels on the y-axis, this object is prepared /// in the pepareYLabels() method internal var _leftAxis: ChartYAxis! internal var _rightAxis: ChartYAxis! /// the object representing the labels on the x-axis internal var _xAxis: ChartXAxis! internal var _leftYAxisRenderer: ChartYAxisRenderer! internal var _rightYAxisRenderer: ChartYAxisRenderer! internal var _leftAxisTransformer: ChartTransformer! internal var _rightAxisTransformer: ChartTransformer! internal var _xAxisRenderer: ChartXAxisRenderer! internal var _tapGestureRecognizer: UITapGestureRecognizer! internal var _doubleTapGestureRecognizer: UITapGestureRecognizer! internal var _pinchGestureRecognizer: UIPinchGestureRecognizer! internal var _panGestureRecognizer: UIPanGestureRecognizer! /// flag that indicates if a custom viewport offset has been set private var _customViewPortEnabled = false public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _leftAxis = ChartYAxis(position: .Left) _rightAxis = ChartYAxis(position: .Right) _xAxis = ChartXAxis() _leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler) _leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer) _rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer) _xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer) _highlighter = ChartHighlighter(chart: self) _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) _doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:")) _doubleTapGestureRecognizer.numberOfTapsRequired = 2 _pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:")) _panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:")) _pinchGestureRecognizer.delegate = self _panGestureRecognizer.delegate = self self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_doubleTapGestureRecognizer) self.addGestureRecognizer(_pinchGestureRecognizer) self.addGestureRecognizer(_panGestureRecognizer) _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled _panGestureRecognizer.enabled = _dragEnabled } public override func drawRect(rect: CGRect) { super.drawRect(rect) if (_dataNotSet) { return } let context = UIGraphicsGetCurrentContext() calcModulus() if (_xAxisRenderer !== nil) { _xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } if (renderer !== nil) { renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus) } // execute all drawing commands drawGridBackground(context: context) if (_leftAxis.isEnabled) { _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) } if (_rightAxis.isEnabled) { _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) } _xAxisRenderer?.renderAxisLine(context: context) _leftYAxisRenderer?.renderAxisLine(context: context) _rightYAxisRenderer?.renderAxisLine(context: context) if (_autoScaleMinMaxEnabled) { let lowestVisibleXIndex = self.lowestVisibleXIndex, highestVisibleXIndex = self.highestVisibleXIndex if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex || _autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex) { calcMinMax() calculateOffsets() _autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex _autoScaleLastHighestVisibleXIndex = highestVisibleXIndex } } // make sure the graph values and grid cannot be drawn outside the content-rect CGContextSaveGState(context) CGContextClipToRect(context, _viewPortHandler.contentRect) if (_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } _xAxisRenderer?.renderGridLines(context: context) _leftYAxisRenderer?.renderGridLines(context: context) _rightYAxisRenderer?.renderGridLines(context: context) renderer?.drawData(context: context) if (!_xAxis.isDrawLimitLinesBehindDataEnabled) { _xAxisRenderer?.renderLimitLines(context: context) } if (!_leftAxis.isDrawLimitLinesBehindDataEnabled) { _leftYAxisRenderer?.renderLimitLines(context: context) } if (!_rightAxis.isDrawLimitLinesBehindDataEnabled) { _rightYAxisRenderer?.renderLimitLines(context: context) } // if highlighting is enabled if (valuesToHighlight()) { renderer?.drawHighlighted(context: context, indices: _indicesToHightlight) } // Removes clipping rectangle CGContextRestoreGState(context) renderer!.drawExtras(context: context) _xAxisRenderer.renderAxisLabels(context: context) _leftYAxisRenderer.renderAxisLabels(context: context) _rightYAxisRenderer.renderAxisLabels(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) // drawLegend() drawMarkers(context: context) drawDescription(context: context) } internal func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum) _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum) } internal func prepareOffsetMatrix() { _rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted) _leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted) } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() _leftAxis?._defaultValueFormatter = _defaultValueFormatter _rightAxis?._defaultValueFormatter = _defaultValueFormatter _leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum) _rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum) _xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals) if (_legend !== nil) { _legendRenderer?.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } internal override func calcMinMax() { if (_autoScaleMinMaxEnabled) { _data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex) } var minLeft = _data.getYMin(.Left) var maxLeft = _data.getYMax(.Left) var minRight = _data.getYMin(.Right) var maxRight = _data.getYMax(.Right) let leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft)) let rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight)) // in case all values are equal if (leftRange == 0.0) { maxLeft = maxLeft + 1.0 if (!_leftAxis.isStartAtZeroEnabled) { minLeft = minLeft - 1.0 } } if (rightRange == 0.0) { maxRight = maxRight + 1.0 if (!_rightAxis.isStartAtZeroEnabled) { minRight = minRight - 1.0 } } let topSpaceLeft = leftRange * Double(_leftAxis.spaceTop) let topSpaceRight = rightRange * Double(_rightAxis.spaceTop) let bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom) let bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom) _chartXMax = Double(_data.xVals.count - 1) _deltaX = CGFloat(abs(_chartXMax - _chartXMin)) // Consider sticking one of the edges of the axis to zero (0.0) if _leftAxis.isStartAtZeroEnabled { if minLeft < 0.0 && maxLeft < 0.0 { // If the values are all negative, let's stay in the negative zone _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = 0.0 } else if minLeft >= 0.0 { // We have positive values only, stay in the positive zone _leftAxis.axisMinimum = 0.0 _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)) _leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)) } } else { // Use the values as they are _leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft) _leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft) } if _rightAxis.isStartAtZeroEnabled { if minRight < 0.0 && maxRight < 0.0 { // If the values are all negative, let's stay in the negative zone _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = 0.0 } else if minRight >= 0.0 { // We have positive values only, stay in the positive zone _rightAxis.axisMinimum = 0.0 _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } else { // Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time) _rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)) _rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)) } } else { _rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight) _rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight) } _leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum) _rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum) } internal override func calculateOffsets() { if (!_customViewPortEnabled) { var offsetLeft = CGFloat(0.0) var offsetRight = CGFloat(0.0) var offsetTop = CGFloat(0.0) var offsetBottom = CGFloat(0.0) // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0 } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { let yOffset = _legend.textHeightMax; // It's possible that we do not need this offset anymore as it is available through the extraOffsets offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } } // offsets for y-labels if (leftAxis.needsOffset) { offsetLeft += leftAxis.requiredSize().width } if (rightAxis.needsOffset) { offsetRight += rightAxis.requiredSize().width } if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled) { let xlabelheight = xAxis.labelHeight * 2.0 // offsets for x-labels if (xAxis.labelPosition == .Bottom) { offsetBottom += xlabelheight } else if (xAxis.labelPosition == .Top) { offsetTop += xlabelheight } else if (xAxis.labelPosition == .BothSided) { offsetBottom += xlabelheight offsetTop += xlabelheight } } offsetTop += self.extraTopOffset offsetRight += self.extraRightOffset offsetBottom += self.extraBottomOffset offsetLeft += self.extraLeftOffset let minOffset = CGFloat(10.0) _viewPortHandler.restrainViewPort( offsetLeft: max(minOffset, offsetLeft), offsetTop: max(minOffset, offsetTop), offsetRight: max(minOffset, offsetRight), offsetBottom: max(minOffset, offsetBottom)) } prepareOffsetMatrix() prepareValuePxMatrix() } /// calculates the modulus for x-labels and grid internal func calcModulus() { if (_xAxis === nil || !_xAxis.isEnabled) { return } if (!_xAxis.isAxisModulusCustom) { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a))) } if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1 } } public override func getMarkerPosition(entry entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { let dataSetIndex = highlight.dataSetIndex var xPos = CGFloat(entry.xIndex) var yPos = entry.value if (self.isKindOfClass(BarChartView)) { let bd = _data as! BarChartData let space = bd.groupSpace let x = CGFloat(entry.xIndex * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(entry.xIndex) + space / 2.0 xPos += x if let barEntry = entry as? BarChartDataEntry { if barEntry.values != nil && highlight.range !== nil { yPos = highlight.range!.to } } } // position of the marker depends on selected value index and value var pt = CGPoint(x: xPos, y: CGFloat(yPos) * _animator.phaseY) getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt) return pt } /// draws the grid background internal func drawGridBackground(context context: CGContext?) { if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextSaveGState(context) } if (drawGridBackgroundEnabled) { // draw the grid background CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor) CGContextFillRect(context, _viewPortHandler.contentRect) } if (drawBordersEnabled) { CGContextSetLineWidth(context, borderLineWidth) CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextStrokeRect(context, _viewPortHandler.contentRect) } if (drawGridBackgroundEnabled || drawBordersEnabled) { CGContextRestoreGState(context) } } /// - returns: the Transformer class that contains all matrices and is /// responsible for transforming values into pixels on the screen and /// backwards. public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer { if (which == .Left) { return _leftAxisTransformer } else { return _rightAxisTransformer } } // MARK: - Gestures private enum GestureScaleAxis { case Both case X case Y } private var _isDragging = false private var _isScaling = false private var _gestureScaleAxis = GestureScaleAxis.Both private var _closestDataSetToTouch: ChartDataSet! private var _panGestureReachedEdge: Bool = false private weak var _outerScrollView: UIScrollView? private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationVelocity = CGPoint() @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) if (h === nil || h!.isEqual(self.lastHighlighted)) { self.highlightValue(highlight: nil, callDelegate: true) self.lastHighlighted = nil } else { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } @objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer) { if (_dataNotSet) { return } if (recognizer.state == UIGestureRecognizerState.Ended) { if (!_dataNotSet && _doubleTapToZoomEnabled) { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom) } self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y) } } } @objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration() if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled)) { _isScaling = true if (_pinchZoomEnabled) { _gestureScaleAxis = .Both } else { let x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x) let y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y) if (x > y) { _gestureScaleAxis = .X } else { _gestureScaleAxis = .Y } } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isScaling) { _isScaling = false // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } else if (recognizer.state == UIGestureRecognizerState.Changed) { let isZoomingOut = (recognizer.scale < 1) let canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX if (_isScaling) { if (canZoomMoreX || (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y && _scaleYEnabled)) { var location = recognizer.locationInView(self) location.x = location.x - _viewPortHandler.offsetLeft if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { location.y = -(location.y - _viewPortHandler.offsetTop) } else { location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom) } let scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0 let scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0 var matrix = CGAffineTransformMakeTranslation(location.x, location.y) matrix = CGAffineTransformScale(matrix, scaleX, scaleY) matrix = CGAffineTransformTranslate(matrix, -location.x, -location.y) matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY) } } recognizer.scale = 1.0 } } } @objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0) { stopDeceleration() if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut) { _isDragging = true _closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self)) let translation = recognizer.translationInView(self) if (!performPanChange(translation: translation)) { if (_outerScrollView !== nil) { // We can stop dragging right now, and let the scroll view take control _outerScrollView = nil _isDragging = false } } else { if (_outerScrollView !== nil) { // Prevent the parent scroll view from scrolling _outerScrollView?.scrollEnabled = false } } _lastPanPoint = recognizer.translationInView(self) } } else if (recognizer.state == UIGestureRecognizerState.Changed) { if (_isDragging) { let originalTranslation = recognizer.translationInView(self) let translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y) performPanChange(translation: translation) _lastPanPoint = originalTranslation } else if (isHighlightPerDragEnabled) { let h = getHighlightByTouchPoint(recognizer.locationInView(self)) let lastHighlighted = self.lastHighlighted if ((h === nil && lastHighlighted !== nil) || (h !== nil && lastHighlighted === nil) || (h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted))) { self.lastHighlighted = h self.highlightValue(highlight: h, callDelegate: true) } } } else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled) { if (_isDragging) { if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled) { stopDeceleration() _decelerationLastTime = CACurrentMediaTime() _decelerationVelocity = recognizer.velocityInView(self) _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } _isDragging = false } if (_outerScrollView !== nil) { _outerScrollView?.scrollEnabled = true _outerScrollView = nil } } } private func performPanChange(var translation translation: CGPoint) -> Bool { if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted) { if (self is HorizontalBarChartView) { translation.x = -translation.x } else { translation.y = -translation.y } } let originalMatrix = _viewPortHandler.touchMatrix var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y) matrix = CGAffineTransformConcat(originalMatrix, matrix) matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) if (delegate !== nil) { delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y) } // Did we managed to actually drag or did we reach the edge? return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationVelocity.x *= self.dragDecelerationFrictionCoef _decelerationVelocity.y *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) let distance = CGPoint( x: _decelerationVelocity.x * timeInterval, y: _decelerationVelocity.y * timeInterval ) if (!performPanChange(translation: distance)) { // We reached the edge, stop _decelerationVelocity.x = 0.0 _decelerationVelocity.y = 0.0 } _decelerationLastTime = currentTime if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001) { stopDeceleration() // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } } public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if (!super.gestureRecognizerShouldBegin(gestureRecognizer)) { return false } if (gestureRecognizer == _panGestureRecognizer) { if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset || (self.isFullyZoomedOut && !self.isHighlightPerDragEnabled)) { return false } } else if (gestureRecognizer == _pinchGestureRecognizer) { if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled)) { return false } } return true } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) || (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer))) { return true } if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && ( gestureRecognizer == _panGestureRecognizer )) { var scrollView = self.superview while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView)) { scrollView = scrollView?.superview } var foundScrollView = scrollView as? UIScrollView if (foundScrollView !== nil && !foundScrollView!.scrollEnabled) { foundScrollView = nil } var scrollViewPanGestureRecognizer: UIGestureRecognizer! if (foundScrollView !== nil) { for scrollRecognizer in foundScrollView!.gestureRecognizers! { if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer)) { scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer break } } } if (otherGestureRecognizer === scrollViewPanGestureRecognizer) { _outerScrollView = foundScrollView return true } } return false } /// MARK: Viewport modifiers /// Zooms in by 1.4, into the charts center. center. public func zoomIn() { let matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms out by 0.7, from the charts center. center. public func zoomOut() { let matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0)) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Zooms in or out by the given scale factor. x and y are the coordinates /// (in pixels) of the zoom center. /// /// - parameter scaleX: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter scaleY: if < 1 --> zoom out, if > 1 --> zoom in /// - parameter x: /// - parameter y: public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) { let matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y) _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Resets all zooming and dragging and makes the chart fit exactly it's bounds. public func fitScreen() { let matrix = _viewPortHandler.fitScreen() _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false) // Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets. calculateOffsets() setNeedsDisplay() } /// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat) { _viewPortHandler.setMinimumScaleX(scaleX) _viewPortHandler.setMinimumScaleY(scaleY) } /// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMaximum(maxXRange: CGFloat) { let xScale = _deltaX / maxXRange _viewPortHandler.setMinimumScaleX(xScale) } /// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed). /// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling. public func setVisibleXRangeMinimum(minXRange: CGFloat) { let xScale = _deltaX / minXRange _viewPortHandler.setMaximumScaleX(xScale) } /// Limits the maximum and minimum value count that can be visible by pinching and zooming. /// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed /// at once without scrolling public func setVisibleXRange(minXRange minXRange: CGFloat, maxXRange: CGFloat) { let maxScale = _deltaX / minXRange let minScale = _deltaX / maxXRange _viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale) } /// Sets the size of the area (range on the y-axis) that should be maximum visible at once. /// /// - parameter yRange: /// - parameter axis: - the axis for which this limit should apply public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency) { let yScale = getDeltaY(axis) / maxYRange _viewPortHandler.setMinimumScaleY(yScale) } /// Moves the left side of the current viewport to the specified x-index. public func moveViewToX(xIndex: Int) { if (_viewPortHandler.hasChartDimens) { var pt = CGPoint(x: CGFloat(xIndex), y: 0.0) getTransformer(.Left).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); }) } } /// Centers the viewport to the specified y-value on the y-axis. /// /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); }) } } /// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func moveViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// This will move the center of the current viewport to the specified x-index and y-value. /// /// - parameter xIndex: /// - parameter yValue: /// - parameter axis: - which axis should be used as a reference for the y-axis public func centerViewTo(xIndex xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency) { if (_viewPortHandler.hasChartDimens) { let valsInView = getDeltaY(axis) / _viewPortHandler.scaleY let xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0) getTransformer(axis).pointValueToPixel(&pt) _viewPortHandler.centerViewPort(pt: pt, chart: self) } else { _sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); }) } } /// Sets custom offsets for the current `ChartViewPort` (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use `resetViewPortOffsets()` to undo this. /// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use `setExtraOffsets(...)`. public func setViewPortOffsets(left left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { _customViewPortEnabled = true if (NSThread.isMainThread()) { self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom) prepareOffsetMatrix() prepareValuePxMatrix() } else { dispatch_async(dispatch_get_main_queue(), { self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom) }) } } /// Resets all custom offsets set via `setViewPortOffsets(...)` method. Allows the chart to again calculate all offsets automatically. public func resetViewPortOffsets() { _customViewPortEnabled = false calculateOffsets() } // MARK: - Accessors /// - returns: the delta-y value (y-value range) of the specified axis. public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat { if (axis == .Left) { return CGFloat(leftAxis.axisRange) } else { return CGFloat(rightAxis.axisRange) } } /// - returns: the position (in pixels) the provided Entry has inside the chart view public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value)) getTransformer(axis).pointValueToPixel(&vals) return vals } /// the number of maximum visible drawn values on the chart /// only active when `setDrawValues()` is enabled public var maxVisibleValueCount: Int { get { return _maxVisibleValueCount } set { _maxVisibleValueCount = newValue } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var dragEnabled: Bool { get { return _dragEnabled } set { if (_dragEnabled != newValue) { _dragEnabled = newValue } } } /// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling). public var isDragEnabled: Bool { return dragEnabled } /// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging). public func setScaleEnabled(enabled: Bool) { if (_scaleXEnabled != enabled || _scaleYEnabled != enabled) { _scaleXEnabled = enabled _scaleYEnabled = enabled _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled } } public var scaleXEnabled: Bool { get { return _scaleXEnabled } set { if (_scaleXEnabled != newValue) { _scaleXEnabled = newValue _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled } } } public var scaleYEnabled: Bool { get { return _scaleYEnabled } set { if (_scaleYEnabled != newValue) { _scaleYEnabled = newValue _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled } } } public var isScaleXEnabled: Bool { return scaleXEnabled; } public var isScaleYEnabled: Bool { return scaleYEnabled; } /// flag that indicates if double tap zoom is enabled or not public var doubleTapToZoomEnabled: Bool { get { return _doubleTapToZoomEnabled } set { if (_doubleTapToZoomEnabled != newValue) { _doubleTapToZoomEnabled = newValue _doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled } } } /// **default**: true /// - returns: true if zooming via double-tap is enabled false if not. public var isDoubleTapToZoomEnabled: Bool { return doubleTapToZoomEnabled } /// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled public var highlightPerDragEnabled = true /// If set to true, highlighting per dragging over a fully zoomed out chart is enabled /// You might want to disable this when using inside a `UIScrollView` /// /// **default**: true public var isHighlightPerDragEnabled: Bool { return highlightPerDragEnabled } /// **default**: true /// - returns: true if drawing the grid background is enabled, false if not. public var isDrawGridBackgroundEnabled: Bool { return drawGridBackgroundEnabled } /// **default**: false /// - returns: true if drawing the borders rectangle is enabled, false if not. public var isDrawBordersEnabled: Bool { return drawBordersEnabled } /// - returns: the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart. public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight? { if (_dataNotSet || _data === nil) { print("Can't select by touch. No data set.", terminator: "\n") return nil } return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y)) } /// - returns: the x and y values in the chart at the given touch point /// (encapsulated in a `CGPoint`). This method transforms pixel coordinates to /// coordinates / values in the chart. This is the opposite method to /// `getPixelsForValues(...)`. public func getValueByTouchPoint(var pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint { getTransformer(axis).pixelToValue(&pt) return pt } /// Transforms the given chart values into pixels. This is the opposite /// method to `getValueByTouchPoint(...)`. public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint { var pt = CGPoint(x: CGFloat(x), y: CGFloat(y)) getTransformer(axis).pointValueToPixel(&pt) return pt } /// - returns: the y-value at the given touch position (must not necessarily be /// a value contained in one of the datasets) public func getYValueByTouchPoint(pt pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat { return getValueByTouchPoint(pt: pt, axis: axis).y } /// - returns: the Entry object displayed at the touched position of the chart public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data!.getEntryForHighlight(h!) } return nil } /// - returns: the DataSet object displayed at the touched position of the chart public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet! { let h = getHighlightByTouchPoint(pt) if (h !== nil) { return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleChartDataSet! } return nil } /// - returns: the lowest x-index (value on the x-axis) that is still visible on he chart. public var lowestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0) } /// - returns: the highest x-index (value on the x-axis) that is still visible on the chart. public var highestVisibleXIndex: Int { var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom) getTransformer(.Left).pixelToValue(&pt) return (_data != nil && Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x) } /// - returns: the current x-scale factor public var scaleX: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleX } /// - returns: the current y-scale factor public var scaleY: CGFloat { if (_viewPortHandler === nil) { return 1.0 } return _viewPortHandler.scaleY } /// if the chart is fully zoomed out, return true public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; } /// - returns: the left y-axis object. In the horizontal bar-chart, this is the /// top axis. public var leftAxis: ChartYAxis { return _leftAxis } /// - returns: the right y-axis object. In the horizontal bar-chart, this is the /// bottom axis. public var rightAxis: ChartYAxis { return _rightAxis; } /// - returns: the y-axis object to the corresponding AxisDependency. In the /// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis { if (axis == .Left) { return _leftAxis } else { return _rightAxis } } /// - returns: the object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) public var xAxis: ChartXAxis { return _xAxis } /// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately public var pinchZoomEnabled: Bool { get { return _pinchZoomEnabled } set { if (_pinchZoomEnabled != newValue) { _pinchZoomEnabled = newValue _pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled } } } /// **default**: false /// - returns: true if pinch-zoom is enabled, false if not public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the x-axis. public func setDragOffsetX(offset: CGFloat) { _viewPortHandler.setDragOffsetX(offset) } /// Set an offset in dp that allows the user to drag the chart over it's /// bounds on the y-axis. public func setDragOffsetY(offset: CGFloat) { _viewPortHandler.setDragOffsetY(offset) } /// - returns: true if both drag offsets (x and y) are zero or smaller. public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; } /// The X axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartXAxisRenderer /// - returns: The current set X axis renderer public var xAxisRenderer: ChartXAxisRenderer { get { return _xAxisRenderer } set { _xAxisRenderer = newValue } } /// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set left Y axis renderer public var leftYAxisRenderer: ChartYAxisRenderer { get { return _leftYAxisRenderer } set { _leftYAxisRenderer = newValue } } /// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here. /// **default**: An instance of ChartYAxisRenderer /// - returns: The current set right Y axis renderer public var rightYAxisRenderer: ChartYAxisRenderer { get { return _rightYAxisRenderer } set { _rightYAxisRenderer = newValue } } public override var chartYMax: Double { return max(leftAxis.axisMaximum, rightAxis.axisMaximum) } public override var chartYMin: Double { return min(leftAxis.axisMinimum, rightAxis.axisMinimum) } /// - returns: true if either the left or the right or both axes are inverted. public var isAnyAxisInverted: Bool { return _leftAxis.isInverted || _rightAxis.isInverted } /// flag that indicates if auto scaling on the y axis is enabled. /// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes public var autoScaleMinMaxEnabled: Bool { get { return _autoScaleMinMaxEnabled; } set { _autoScaleMinMaxEnabled = newValue; } } /// **default**: false /// - returns: true if auto scaling on the y axis is enabled. public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; } /// Sets a minimum width to the specified y axis. public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.minWidth = width } else { _rightAxis.minWidth = width } } /// **default**: 0.0 /// - returns: the (custom) minimum width of the specified Y axis. public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.minWidth } else { return _rightAxis.minWidth } } /// Sets a maximum width to the specified y axis. /// Zero (0.0) means there's no maximum width public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat) { if (which == .Left) { _leftAxis.maxWidth = width } else { _rightAxis.maxWidth = width } } /// Zero (0.0) means there's no maximum width /// /// **default**: 0.0 (no maximum specified) /// - returns: the (custom) maximum width of the specified Y axis. public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.maxWidth } else { return _rightAxis.maxWidth } } /// - returns the width of the specified y axis. public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat { if (which == .Left) { return _leftAxis.requiredSize().width } else { return _rightAxis.requiredSize().width } } } /// Default formatter that calculates the position of the filled line. internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter { private weak var _chart: BarLineChartViewBase! internal init(chart: BarLineChartViewBase) { _chart = chart } internal func getFillLinePosition(dataSet dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Double, chartMinY: Double) -> CGFloat { var fillMin = CGFloat(0.0) if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0) { fillMin = 0.0 } else { if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled) { var max: Double, min: Double if (data.yMax > 0.0) { max = 0.0 } else { max = chartMaxY } if (data.yMin < 0.0) { min = 0.0 } else { min = chartMinY } fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max) } else { fillMin = 0.0 } } return fillMin } }
apache-2.0
c33e3181547d7628e1232b0c60a3f9ad
35.110378
238
0.583095
5.612681
false
false
false
false
XJAlex/DanTang
DanTang/DanTang/Classes/Base/Controller/XJNavigationController.swift
1
1454
// // XJNavigationController.swift // DanTang // // Created by qxj on 2017/3/7. // Copyright © 2017年 QinXJ. All rights reserved. // import UIKit class XJNavigationController: UINavigationController { internal override class func initialize() { super.initialize() let navBar = UINavigationBar.appearance() navBar.barTintColor = XJGlobalRedColor() navBar.tintColor = UIColor.white navBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 20)]; } /// 统一所有控制器左上角返回按钮 /// 让所有push进来的控制器左上角的返回按钮都一样 /// - Parameters: /// - viewController: 需要压栈的控制器 /// - animated: 是否动画 override func pushViewController(_ viewController: UIViewController, animated: Bool) { if viewControllers.count > 0 { viewController.hidesBottomBarWhenPushed = true viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: ""), style: .plain, target: self, action: #selector(navitationBackClick)) } } /// 返回按钮 func navitationBackClick() { if UIApplication.shared.isNetworkActivityIndicatorVisible { UIApplication.shared.isNetworkActivityIndicatorVisible = false } popViewController(animated: true) } }
mit
93aa0f3d3b4e7a8486a410378a717786
31.95122
173
0.681717
4.894928
false
false
false
false
am0oma/Swifter
SwifterCommon/Swifter.swift
1
7332
// // Swifter.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // 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 Accounts #if os(iOS) import UIKit #else import AppKit #endif class Swifter { typealias JSONSuccessHandler = (json: JSON, response: NSHTTPURLResponse) -> Void typealias FailureHandler = (error: NSError) -> Void struct CallbackNotification { static let notificationName = "SwifterCallbackNotificationName" static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey" } struct SwifterError { static let domain = "SwifterErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } struct DataParameters { static let dataKey = "SwifterDataParameterKey" static let fileNameKey = "SwifterDataParameterFilename" } var apiURL: NSURL var uploadURL: NSURL var streamURL: NSURL var userStreamURL: NSURL var siteStreamURL: NSURL var client: SwifterClientProtocol convenience init(consumerKey: String, consumerSecret: String) { self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, appOnly: false) } init(consumerKey: String, consumerSecret: String, appOnly: Bool) { if appOnly { self.client = SwifterAppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } else { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } self.apiURL = NSURL(string: "https://api.twitter.com/1.1/") self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/") self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/") self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/") self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/") } init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/") self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/") self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/") self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/") self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/") } init(account: ACAccount) { self.client = SwifterAccountsClient(account: account) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/") self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/") self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/") self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/") self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func jsonRequestWithPath(path: String, baseURL: NSURL, method: String, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let jsonDownloadProgressHandler: SwifterHTTPRequest.DownloadProgressHandler = { data, _, _, response in if !downloadProgress { return } var error: NSError? if let jsonResult = JSON.parseJSONData(data, error: &error) { downloadProgress?(json: jsonResult, response: response) } else { let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) let jsonChunks = jsonString.componentsSeparatedByString("\r\n") as String[] for chunk in jsonChunks { if chunk.utf16count == 0 { continue } let chunkData = chunk.dataUsingEncoding(NSUTF8StringEncoding) if let jsonResult = JSON.parseJSONData(data, error: &error) { downloadProgress?(json: jsonResult, response: response) } } } } let jsonSuccessHandler: SwifterHTTPRequest.SuccessHandler = { data, response in var error: NSError? if let jsonResult = JSON.parseJSONData(data, error: &error) { success?(json: jsonResult, response: response) } else { failure?(error: error!) } } if method == "GET" { self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } else { self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } } func getJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { self.jsonRequestWithPath(path, baseURL: baseURL, method: "GET", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } func postJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { self.jsonRequestWithPath(path, baseURL: baseURL, method: "POST", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } }
mit
806a91dedd1b4009d819aa05f50235fa
43.707317
292
0.681669
4.823684
false
false
false
false
rundfunk47/pest
pest/MainWindow.swift
1
3317
// // MainWindow.swift // pest // // Created by Narek M on 21/02/16. // Copyright © 2016 Narek M. All rights reserved. // import Cocoa class MainWindow: NSWindow, NSTableViewDataSource, NSTableViewDelegate { @IBOutlet weak var tableView: NSTableView! var commands = Command.getSavedCommands() override func awakeFromNib() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "editedCommands:", name:"EditedCommands", object: nil) } @objc private func editedCommands(notification: NSNotification) { self.commands = notification.object as! [Command] tableView.reloadData() } func numberOfRowsInTableView(aTableView: NSTableView) -> Int { return self.commands.count } func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { switch tableColumn!.identifier { case "name": return self.commands[row].name case "commandToExecute": return self.commands[row].commandToExecute case "character": return self.commands[row].character case "shift": return self.commands[row].shift case "control": return self.commands[row].control case "alt": return self.commands[row].alt case "command": return self.commands[row].command case "fn": return self.commands[row].fn default: return "" } } func tableView(tableView: NSTableView, setObjectValue object: AnyObject?, forTableColumn tableColumn: NSTableColumn?, row: Int) { let command = self.commands[row] switch tableColumn!.identifier { case "name": command.name = object as! String case "commandToExecute": command.commandToExecute = object as! String case "character": let string = (object as! String) //only save first character... let characterCount = string.characters.count if characterCount == 0 { command.character = "" } else { let char = string.substringToIndex(string.startIndex.advancedBy(1)) command.character = char } case "shift": command.shift = object as! Bool case "control": command.control = object as! Bool case "alt": command.alt = object as! Bool case "command": command.command = object as! Bool case "fn": command.fn = object as! Bool default: break } command.save() } @IBAction func addCommand(sender: AnyObject) { Command(name: "New Command", commandToExecute: "echo Hello world", character: "H", shift: true, control: true, alt: true, command: true, fn: true).save() } @IBAction func removeCommand(sender: AnyObject) { if (tableView.selectedRow != -1) { self.commands[tableView.selectedRow].remove() } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
gpl-3.0
be35c94e6b28548220327622eec58753
32.16
161
0.578709
5.070336
false
false
false
false
athiercelin/Localizations
TestProjects/LocalizedSampleApp/LocalizedSampleApp/MasterViewController.swift
1
3417
// // MasterViewController.swift // LocalizedSampleApp // // Created by Arnaud Thiercelin on 2/16/16. // Copyright © 2016 Arnaud Thiercelin. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() self.navigationController?.navigationBar.topItem?.title = NSLocalizedString("LocalizedSampleApp", comment: "Navigation bar title") let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // 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("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
bd20afc051718d4fe0bfb083394816ce
34.957895
154
0.762295
4.915108
false
false
false
false
functionaldude/XLPagerTabStrip
Sources/TwitterPagerTabStripViewController.swift
8
10172
// TwitterPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct TwitterPagerTabStripSettings { public struct Style { public var dotColor = UIColor(white: 1, alpha: 0.4) public var selectedDotColor = UIColor.white public var portraitTitleFont = UIFont.systemFont(ofSize: 18) public var landscapeTitleFont = UIFont.systemFont(ofSize: 15) public var titleColor = UIColor.white } public var style = Style() } open class TwitterPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripIsProgressiveDelegate { open var settings = TwitterPagerTabStripSettings() public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) pagerBehaviour = .progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) delegate = self datasource = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pagerBehaviour = .progressive(skipIntermediateViewControllers: true, elasticIndicatorLimit: true) delegate = self datasource = self } open override func viewDidLoad() { super.viewDidLoad() if titleView.superview == nil { navigationItem.titleView = titleView } // keep watching the frame of titleView titleView.addObserver(self, forKeyPath: "frame", options: [.new, .old], context: nil) guard let navigationController = navigationController else { fatalError("TwitterPagerTabStripViewController should be embedded in a UINavigationController") } titleView.frame = CGRect(x: 0, y: 0, width: navigationController.navigationBar.frame.width, height: navigationController.navigationBar.frame.height) titleView.addSubview(titleScrollView) titleView.addSubview(pageControl) reloadNavigationViewItems() } open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() guard isViewLoaded else { return } reloadNavigationViewItems() setNavigationViewItemsPosition(updateAlpha: true) } // MARK: - PagerTabStripDelegate open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int, withProgressPercentage progressPercentage: CGFloat, indexWasChanged: Bool) { // move indicator scroll view guard let distance = distanceValue else { return } var xOffset: CGFloat = 0 if fromIndex < toIndex { xOffset = distance * CGFloat(fromIndex) + distance * progressPercentage } else if fromIndex > toIndex { xOffset = distance * CGFloat(fromIndex) - distance * progressPercentage } else { xOffset = distance * CGFloat(fromIndex) } titleScrollView.contentOffset = CGPoint(x: xOffset, y: 0) // update alpha of titles setAlphaWith(offset: xOffset, andDistance: distance) // update page control page pageControl.currentPage = currentIndex } open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { fatalError() } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard object as AnyObject === titleView && keyPath == "frame" && change?[NSKeyValueChangeKey.kindKey] as? UInt == NSKeyValueChange.setting.rawValue else { return } let oldRect = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue let newRect = (change![NSKeyValueChangeKey.oldKey]! as AnyObject).cgRectValue if (oldRect?.equalTo(newRect!))! { titleScrollView.frame = CGRect(x: 0, y: 0, width: titleView.frame.width, height: titleScrollView.frame.height) setNavigationViewItemsPosition(updateAlpha: true) } } deinit { if isViewLoaded { titleView.removeObserver(self, forKeyPath: "frame") } } open override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() setNavigationViewItemsPosition(updateAlpha: false) } // MARK: - Helpers private lazy var titleView: UIView = { let navigationView = UIView() navigationView.autoresizingMask = [.flexibleWidth, .flexibleHeight] return navigationView }() private lazy var titleScrollView: UIScrollView = { [unowned self] in let titleScrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 44)) titleScrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleScrollView.bounces = true titleScrollView.scrollsToTop = false titleScrollView.delegate = self titleScrollView.showsVerticalScrollIndicator = false titleScrollView.showsHorizontalScrollIndicator = false titleScrollView.isPagingEnabled = true titleScrollView.isUserInteractionEnabled = false titleScrollView.alwaysBounceHorizontal = true titleScrollView.alwaysBounceVertical = false return titleScrollView }() private lazy var pageControl: FXPageControl = { [unowned self] in let pageControl = FXPageControl() pageControl.backgroundColor = .clear pageControl.dotSize = 3.8 pageControl.dotSpacing = 4.0 pageControl.dotColor = self.settings.style.dotColor pageControl.selectedDotColor = self.settings.style.selectedDotColor pageControl.isUserInteractionEnabled = false return pageControl }() private var childTitleLabels = [UILabel]() private func reloadNavigationViewItems() { // remove all child view controller header labels childTitleLabels.forEach { $0.removeFromSuperview() } childTitleLabels.removeAll() for (index, item) in viewControllers.enumerated() { let child = item as! IndicatorInfoProvider // swiftlint:disable:this force_cast let indicatorInfo = child.indicatorInfo(for: self) let navTitleLabel: UILabel = { let label = UILabel() label.text = indicatorInfo.title label.font = UIApplication.shared.statusBarOrientation.isPortrait ? settings.style.portraitTitleFont : settings.style.landscapeTitleFont label.textColor = settings.style.titleColor label.alpha = 0 return label }() navTitleLabel.alpha = currentIndex == index ? 1 : 0 navTitleLabel.textColor = settings.style.titleColor titleScrollView.addSubview(navTitleLabel) childTitleLabels.append(navTitleLabel) } } private func setNavigationViewItemsPosition(updateAlpha: Bool) { guard let distance = distanceValue else { return } let isPortrait = UIApplication.shared.statusBarOrientation.isPortrait let navBarHeight: CGFloat = navigationController!.navigationBar.frame.size.height for (index, label) in childTitleLabels.enumerated() { if updateAlpha { label.alpha = currentIndex == index ? 1 : 0 } label.font = isPortrait ? settings.style.portraitTitleFont : settings.style.landscapeTitleFont let viewSize = label.intrinsicContentSize let originX = distance - viewSize.width/2 + CGFloat(index) * distance let originY = (CGFloat(navBarHeight) - viewSize.height) / 2 label.frame = CGRect(x: originX, y: originY - 2, width: viewSize.width, height: viewSize.height) label.tag = index } let xOffset = distance * CGFloat(currentIndex) titleScrollView.contentOffset = CGPoint(x: xOffset, y: 0) pageControl.numberOfPages = childTitleLabels.count pageControl.currentPage = currentIndex let viewSize = pageControl.sizeForNumber(ofPages: childTitleLabels.count) let originX = distance - viewSize.width / 2 pageControl.frame = CGRect(x: originX, y: navBarHeight - 10, width: viewSize.width, height: viewSize.height) } private func setAlphaWith(offset: CGFloat, andDistance distance: CGFloat) { for (index, label) in childTitleLabels.enumerated() { label.alpha = { if offset < distance * CGFloat(index) { return (offset - distance * CGFloat(index - 1)) / distance } else { return 1 - ((offset - distance * CGFloat(index)) / distance) } }() } } private var distanceValue: CGFloat? { return navigationController.map { $0.navigationBar.convert($0.navigationBar.center, to: titleView) }?.x } }
mit
a7a5e90aa7ef76a1bae7a8aa51202f20
42.470085
185
0.682167
5.328444
false
false
false
false
modcloth-labs/XBot
XBot/Server.swift
1
2354
// // Server.swift // XBot // // Created by Geoffrey Nix on 9/30/14. // Copyright (c) 2014 ModCloth. All rights reserved. // import Foundation import Alamofire public class Server { public var port:String public var host:String public var user:String public var password:String public init(host:String, user:String, password:String, port:String = "20343") { self.host = host self.user = user self.password = password self.port = port } public func createBot(config:BotConfiguration, completion:(success: Bool, bot: Bot?) -> ()){ Alamofire.request(.POST, "https://\(self.host):\(self.port)/api/bots", parameters: config.dictionaryRepresentation as? [String : AnyObject], encoding: .JSON) .authenticate(user: user, password: password) .responseJSON { (request, response, jsonOptional, error) in if let json = jsonOptional as? Dictionary<String, AnyObject> { let bot = Bot(botDictionary: json, server: self) completion(success: response?.success ?? false, bot: bot) } else { completion(success: response?.success ?? false, bot: nil) } } } public func fetchDevices(completion:([Device]) -> () ) { let deviceListString = "/api/devices" Alamofire.request(.GET, "https://\(self.host):\(self.port)\(deviceListString)") .authenticate(user: user, password: password) .responseJSON { (request, response, jsonOptional, error) in if let json = jsonOptional as? Dictionary<String, AnyObject> { let devices = devicesFromDevicesJson(json) completion(devices) } } } public func fetchBots(completion:([Bot]) -> () ) { Alamofire.request(.GET, "https://\(self.host):\(self.port)/api/bots") .authenticate(user: user, password: password) .responseJSON { (request, response, jsonOptional, error) in if let json = jsonOptional as? Dictionary<String, AnyObject> { let bots = botsFromBotsJson(json, self) completion(bots) } } } }
mit
75d2180bf71a01c830142673a8c84173
35.230769
165
0.562872
4.606654
false
false
false
false
y16ra/CookieCrunch
CookieCrunch/GameScene.swift
1
16725
// // GameScene.swift // CookieCrunch // // Created by Ichimura Yuichi on 2015/07/31. // Copyright (c) 2015年 Ichimura Yuichi. All rights reserved. // import SpriteKit class GameScene: SKScene { var swipeHandler: ((Swap) -> ())? var level: Level! let TileWidth: CGFloat = 32.0 let TileHeight: CGFloat = 36.0 let gameLayer = SKNode() let cookiesLayer = SKNode() let tilesLayer = SKNode() var swipeFromColumn: Int? var swipeFromRow: Int? var selectionSprite = SKSpriteNode() let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false) let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false) let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false) let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false) let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false) let cropLayer = SKCropNode() let maskLayer = SKNode() required init?(coder aDecoder: NSCoder) { fatalError("init(coder) is not used in this app") } override init(size: CGSize) { super.init(size: size) anchorPoint = CGPoint(x: 0.5, y: 0.5) let background = SKSpriteNode(imageNamed: "Background") background.size = size addChild(background) // Add a new node that is the container for all other layers on the playing // field. This gameLayer is also centered in the screen. gameLayer.hidden = true addChild(gameLayer) let layerPosition = CGPoint( x: -TileWidth * CGFloat(NumColumns) / 2, y: -TileHeight * CGFloat(NumRows) / 2) // The tiles layer represents the shape of the level. It contains a sprite // node for each square that is filled in. tilesLayer.position = layerPosition gameLayer.addChild(tilesLayer) // We use a crop layer to prevent cookies from being drawn across gaps // in the level design. gameLayer.addChild(cropLayer) // The mask layer determines which part of the cookiesLayer is visible. maskLayer.position = layerPosition cropLayer.maskNode = maskLayer // This layer holds the Cookie sprites. The positions of these sprites // are relative to the cookiesLayer's bottom-left corner. cookiesLayer.position = layerPosition cropLayer.addChild(cookiesLayer) // nil means that these properties have invalid values. swipeFromColumn = nil swipeFromRow = nil SKLabelNode(fontNamed: "GillSans-BoldItalic") } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } func addSpritesForCookies(cookies: Set<Cookie>) { for cookie in cookies { let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row:cookie.row) cookiesLayer.addChild(sprite) cookie.sprite = sprite // Give each cookie sprite a small, random delay. Then fade them in. sprite.alpha = 0 sprite.xScale = 0.5 sprite.yScale = 0.5 sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(0.25, withRange: 0.5), SKAction.group([ SKAction.fadeInWithDuration(0.25), SKAction.scaleTo(1.0, duration: 0.25) ]) ])) } } func pointForColumn(column: Int, row: Int) -> CGPoint { return CGPoint( x: CGFloat(column)*TileWidth + TileWidth/2, y: CGFloat(row)*TileHeight + TileHeight/2) } func addTiles() { for row in 0..<NumRows { for column in 0..<NumColumns { // If there is a tile at this position, then create a new tile // sprite and add it to the mask layer. if let tile = level.tileAtColumn(column, row: row) { let tileNode = SKSpriteNode(imageNamed: "MaskTile") tileNode.position = pointForColumn(column, row: row) maskLayer.addChild(tileNode) } } } // The tile pattern is drawn *in between* the level tiles. That's why // there is an extra column and row of them. for row in 0...NumRows { for column in 0...NumColumns { let topLeft = (column > 0) && (row < NumRows) && level.tileAtColumn(column - 1, row: row) != nil let bottomLeft = (column > 0) && (row > 0) && level.tileAtColumn(column - 1, row: row - 1) != nil let topRight = (column < NumColumns) && (row < NumRows) && level.tileAtColumn(column, row: row) != nil let bottomRight = (column < NumColumns) && (row > 0) && level.tileAtColumn(column, row: row - 1) != nil // The tiles are named from 0 to 15, according to the bitmask that is // made by combining these four values. let value = Int(topLeft) | Int(topRight) << 1 | Int(bottomLeft) << 2 | Int(bottomRight) << 3 // Values 0 (no tiles), 6 and 9 (two opposite tiles) are not drawn. if value != 0 && value != 6 && value != 9 { let name = String(format: "Tile_%ld", value) let tileNode = SKSpriteNode(imageNamed: name) var point = pointForColumn(column, row: row) point.x -= TileWidth/2 point.y -= TileHeight/2 tileNode.position = point tilesLayer.addChild(tileNode) } } } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // 1 let touch = touches.first! let location = touch.locationInNode(cookiesLayer) // 2 let (success, column, row) = convertPoint(location) if success { // 3 if let cookie = level.cookieAtColumn(column, row: row) { // 4 swipeFromColumn = column swipeFromRow = row showSelectionIndicatorForCookie(cookie) } } } func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int) { if point.x >= 0 && point.x < CGFloat(NumColumns)*TileWidth && point.y >= 0 && point.y < CGFloat(NumRows)*TileHeight { return (true, Int(point.x / TileWidth), Int(point.y / TileHeight)) } else { return (false, 0, 0) // invalid location } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { // 1 if swipeFromColumn == nil { return } // 2 let touch = touches.first! let location = touch.locationInNode(cookiesLayer) let (success, column, row) = convertPoint(location) if success { // 3 var horzDelta = 0, vertDelta = 0 if column < swipeFromColumn! { // swipe left horzDelta = -1 } else if column > swipeFromColumn! { // swipe right horzDelta = 1 } else if row < swipeFromRow! { // swipe down vertDelta = -1 } else if row > swipeFromRow! { // swipe up vertDelta = 1 } // 4 if horzDelta != 0 || vertDelta != 0 { trySwapHorizontal(horzDelta, vertical: vertDelta) hideSelectionIndicator() // 5 swipeFromColumn = nil } } } func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int) { // 1 let toColumn = swipeFromColumn! + horzDelta let toRow = swipeFromRow! + vertDelta // 2 if toColumn < 0 || toColumn >= NumColumns { return } if toRow < 0 || toRow >= NumRows { return } // 3 if let toCookie = level.cookieAtColumn(toColumn, row: toRow) { if let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!) { // 4 print("*** swapping \(fromCookie) with \(toCookie)") if let handler = swipeHandler { let swap = Swap(cookieA: fromCookie, cookieB: toCookie) handler(swap) } } } } func animateSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.3 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut spriteA.runAction(moveA, completion: completion) let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteB.runAction(moveB) runAction(swapSound) } // Highlighting the Cookies func showSelectionIndicatorForCookie(cookie: Cookie) { if selectionSprite.parent != nil { selectionSprite.removeFromParent() } if let sprite = cookie.sprite { let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName) selectionSprite.size = texture.size() selectionSprite.runAction(SKAction.setTexture(texture)) sprite.addChild(selectionSprite) selectionSprite.alpha = 1.0 } } func hideSelectionIndicator() { selectionSprite.runAction(SKAction.sequence([ SKAction.fadeOutWithDuration(0.3), SKAction.removeFromParent()])) } func animateInvalidSwap(swap: Swap, completion: () -> ()) { let spriteA = swap.cookieA.sprite! let spriteB = swap.cookieB.sprite! spriteA.zPosition = 100 spriteB.zPosition = 90 let Duration: NSTimeInterval = 0.2 let moveA = SKAction.moveTo(spriteB.position, duration: Duration) moveA.timingMode = .EaseOut let moveB = SKAction.moveTo(spriteA.position, duration: Duration) moveB.timingMode = .EaseOut spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion) spriteB.runAction(SKAction.sequence([moveB, moveA])) runAction(invalidSwapSound) } func animateMatchedCookies(chains: Set<Chain>, completion: () -> ()) { for chain in chains { // Add this line: animateScoreForChain(chain) for cookie in chain.cookies { if let sprite = cookie.sprite { if sprite.actionForKey("removing") == nil { let scaleAction = SKAction.scaleTo(0.1, duration: 0.3) scaleAction.timingMode = .EaseOut sprite.runAction(SKAction.sequence([scaleAction, SKAction.removeFromParent()]), withKey:"removing") } } } } runAction(matchSound) runAction(SKAction.waitForDuration(0.3), completion: completion) } func animateFallingCookies(columns: [[Cookie]], completion: () -> ()) { // 1 var longestDuration: NSTimeInterval = 0 for array in columns { for (idx, cookie) in array.enumerate() { let newPosition = pointForColumn(cookie.column, row: cookie.row) // 2 let delay = 0.05 + 0.15*NSTimeInterval(idx) // 3 let sprite = cookie.sprite! let duration = NSTimeInterval(((sprite.position.y - newPosition.y) / TileHeight) * 0.1) // 4 longestDuration = max(longestDuration, duration + delay) // 5 let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(delay), SKAction.group([moveAction, fallingCookieSound])])) } } // 6 runAction(SKAction.waitForDuration(longestDuration), completion: completion) } func animateNewCookies(columns: [[Cookie]], completion: () -> ()) { // 1 var longestDuration: NSTimeInterval = 0 for array in columns { // 2 let startRow = array[0].row + 1 for (idx, cookie) in array.enumerate() { // 3 let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName) sprite.position = pointForColumn(cookie.column, row: startRow) cookiesLayer.addChild(sprite) cookie.sprite = sprite // 4 let delay = 0.1 + 0.2 * NSTimeInterval(array.count - idx - 1) // 5 let duration = NSTimeInterval(startRow - cookie.row) * 0.1 longestDuration = max(longestDuration, duration + delay) // 6 let newPosition = pointForColumn(cookie.column, row: cookie.row) let moveAction = SKAction.moveTo(newPosition, duration: duration) moveAction.timingMode = .EaseOut sprite.alpha = 0 sprite.runAction( SKAction.sequence([ SKAction.waitForDuration(delay), SKAction.group([ SKAction.fadeInWithDuration(0.05), moveAction, addCookieSound]) ])) } } // 7 runAction(SKAction.waitForDuration(longestDuration), completion: completion) } func animateScoreForChain(chain: Chain) { // Figure out what the midpoint of the chain is. let firstSprite = chain.firstCookie().sprite! let lastSprite = chain.lastCookie().sprite! let centerPosition = CGPoint( x: (firstSprite.position.x + lastSprite.position.x)/2, y: (firstSprite.position.y + lastSprite.position.y)/2 - 8) // Add a label for the score that slowly floats up. let scoreLabel = SKLabelNode(fontNamed: "GillSans-BoldItalic") scoreLabel.fontSize = 16 scoreLabel.text = String(format: "%ld", chain.score) scoreLabel.position = centerPosition scoreLabel.zPosition = 300 cookiesLayer.addChild(scoreLabel) let moveAction = SKAction.moveBy(CGVector(dx: 0, dy: 3), duration: 0.7) moveAction.timingMode = .EaseOut scoreLabel.runAction(SKAction.sequence([moveAction, SKAction.removeFromParent()])) } func animateGameOver(completion: () -> ()) { let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3) action.timingMode = .EaseIn gameLayer.runAction(action, completion: completion) } func animateBeginGame(completion: () -> ()) { gameLayer.hidden = false gameLayer.position = CGPoint(x: 0, y: size.height) let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3) action.timingMode = .EaseOut gameLayer.runAction(action, completion: completion) } func removeAllCookieSprites() { cookiesLayer.removeAllChildren() } func removeAllTiles() { tilesLayer.removeAllChildren() } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { swipeFromColumn = nil swipeFromRow = nil if selectionSprite.parent != nil && swipeFromColumn != nil { hideSelectionIndicator() } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { touchesEnded(touches!, withEvent: event) } }
mit
230ff2b6a60c1a924f5da4082b913479
37.180365
108
0.554625
5.020414
false
false
false
false
appsandwich/ppt2rk
ppt2rk/ArgsParser.swift
1
6317
// // ArgsParser.swift // ppt2rk // // Created by Vinny Coyne on 15/05/2017. // Copyright © 2017 App Sandwich Limited. All rights reserved. // import Foundation class Arg { var type: ArgumentType var key: String var value: String? init(key: String, type: ArgumentType, value: String?) { self.key = key self.type = type self.value = value } public func downloadValueIndexesForItemCount(_ itemCount: Int) -> [Int]? { guard self.type == .download, let v = self.value else { return nil } return DownloadArgumentValue.indexesForRawString(v, numberOfItems: itemCount) } } extension Arg: Equatable {} // MARK: Equatable func ==(lhs: Arg, rhs: Arg) -> Bool { return lhs.type == rhs.type } enum ArgumentType: String { case polarEmail = "email" case polarPassword = "password" case runkeeperEmail = "rkemail" case runkeeperPassword = "rkpassword" case download = "download" case reset = "reset" case keychain = "keychain" static func all() -> [ArgumentType] { return [.polarEmail, .polarPassword, .runkeeperEmail, .runkeeperPassword, .download, .reset, .keychain] } func expectsValue() -> Bool { switch self { case .reset: fallthrough case .keychain: return false default: return true } } func shortVersion() -> String { switch self { case .runkeeperEmail: return "-rke" case .runkeeperPassword: return "-rkp" default: return "-" + String(describing: self.rawValue.characters.first!) } } func longVersion() -> String { switch self { case .runkeeperEmail: return "--rkemail" case .runkeeperPassword: return "--rkpassword" default: return "--" + self.rawValue } } func matchesString(_ string: String) -> Bool { return self.shortVersion() == string || self.longVersion() == string } static func forString(_ string: String) -> ArgumentType? { guard string.hasPrefix("-") else { return nil } let isLongVersion = string.hasPrefix("--") if isLongVersion { let rawString = string.replacingOccurrences(of: "-", with: "") return ArgumentType(rawValue: rawString) } else { var arg: ArgumentType? = nil let allArgs = ArgumentType.all() allArgs.forEach({ (a) in if a.shortVersion() == string { arg = a return } }) return arg } } } enum DownloadArgumentValue: String { case all = "all" case first = "first" case last = "last" case sync = "sync" case runkeeper = "runkeeper" static func indexesForRawString(_ string: String, numberOfItems: Int) -> [Int]? { if let value = DownloadArgumentValue(rawValue: string) { switch value { case .all: return [-1] case .first: return [1] case .last: return [numberOfItems - 1] case .sync: fallthrough case .runkeeper: return nil } } else { if string.contains(DownloadArgumentValue.first.rawValue) { if let lastChar = string.characters.last { if let count = Int("\(lastChar)") , count > 0 { return Array(0...(count - 1)) } } } else if string.contains(DownloadArgumentValue.last.rawValue) { if let lastChar = string.characters.last { if let count = Int("\(lastChar)") , count > 0 { return Array(1...count).map({ (index) -> Int in return numberOfItems - index }) } } } } return [numberOfItems - 1] } } class ArgsParser { var arguments: [Arg] init(_ args: [String]) { self.arguments = [] for (index, argument) in args.enumerated() { if let type = ArgumentType.forString(argument) { if type.expectsValue() && (index + 1) < args.count { let value = args[index + 1] guard value.characters.count > 0 else { continue } let arg = Arg(key: argument, type:type, value: value) self.arguments.append(arg) } else if !type.expectsValue() { let arg = Arg(key: argument, type:type, value: nil) self.arguments.append(arg) } else { // Invalid arg } } } } public func argumentForType(_ type: ArgumentType) -> Arg? { guard self.arguments.count > 0 else { return nil } let args = self.arguments.filter { (arg) -> Bool in arg.type == type } guard args.count > 0 else { return nil } return args.first } public func valueForArgumentType(_ type: ArgumentType) -> String? { guard let arg = self.argumentForType(type) else { return nil } return arg.value } public func hasArgumentOfType(_ type: ArgumentType) -> Bool { return self.argumentForType(type) != nil } }
mit
4f2842d666abac7bb22eaf1c3b1d0529
24.163347
111
0.457251
5.155918
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSData.swift
1
20326
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif public struct NSDataReadingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let DataReadingMappedIfSafe = NSDataReadingOptions(rawValue: UInt(1 << 0)) public static let DataReadingUncached = NSDataReadingOptions(rawValue: UInt(1 << 1)) public static let DataReadingMappedAlways = NSDataReadingOptions(rawValue: UInt(1 << 2)) } public struct NSDataWritingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let DataWritingAtomic = NSDataWritingOptions(rawValue: UInt(1 << 0)) public static let DataWritingWithoutOverwriting = NSDataWritingOptions(rawValue: UInt(1 << 1)) } public struct NSDataSearchOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Backwards = NSDataSearchOptions(rawValue: UInt(1 << 0)) public static let Anchored = NSDataSearchOptions(rawValue: UInt(1 << 1)) } public struct NSDataBase64EncodingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let Encoding64CharacterLineLength = NSDataBase64EncodingOptions(rawValue: UInt(1 << 0)) public static let Encoding76CharacterLineLength = NSDataBase64EncodingOptions(rawValue: UInt(1 << 1)) public static let EncodingEndLineWithCarriageReturn = NSDataBase64EncodingOptions(rawValue: UInt(1 << 4)) public static let EncodingEndLineWithLineFeed = NSDataBase64EncodingOptions(rawValue: UInt(1 << 5)) } public struct NSDataBase64DecodingOptions : OptionSetType { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let IgnoreUnknownCharacters = NSDataBase64DecodingOptions(rawValue: UInt(1 << 0)) public static let Anchored = NSDataSearchOptions(rawValue: UInt(1 << 1)) } private class _NSDataDeallocator { var handler: (() -> ())? init(handler: (() -> ())?) { self.handler = handler } deinit { handler?() } } public class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { typealias CFType = CFDataRef private var _base = _CFInfo(typeID: CFDataGetTypeID()) private var _length: CFIndex = 0 private var _capacity: CFIndex = 0 private var deallocHandler: _NSDataDeallocator? private var _bytes: UnsafeMutablePointer<UInt8> = nil internal var _cfObject: CFType { get { if self.dynamicType === NSData.self || self.dynamicType === NSMutableData.self { return unsafeBitCast(self, CFType.self) } else { return CFDataCreate(kCFAllocatorSystemDefault, unsafeBitCast(self.bytes, UnsafePointer<UInt8>.self), self.length) } } } public override required convenience init() { self.init(bytes: nil, length: 0, copy: false, deallocator: nil) } deinit { deallocHandler = nil _CFDeinit(self) } internal init(bytes: UnsafeMutablePointer<Void>, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { deallocHandler = _NSDataDeallocator { deallocator?(bytes, length) } super.init() let options : CFOptionFlags = (self.dynamicType == NSMutableData.self) ? 0x1 | 0x2 : 0x0 if copy { _CFDataInit(unsafeBitCast(self, CFMutableDataRef.self), options, length, UnsafeMutablePointer<UInt8>(bytes), length, false) deallocHandler = nil deallocator?(bytes, length) } else { _CFDataInit(unsafeBitCast(self, CFMutableDataRef.self), options, length, UnsafeMutablePointer<UInt8>(bytes), length, true) } } public var length: Int { get { return CFDataGetLength(_cfObject) } } public var bytes: UnsafePointer<Void> { get { return UnsafePointer<Void>(CFDataGetBytePtr(_cfObject)) } } public func copyWithZone(zone: NSZone) -> AnyObject { return self } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { return NSMutableData(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public func encodeWithCoder(aCoder: NSCoder) { } public required convenience init?(coder aDecoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } override public var description: String { get { return "Fixme" } } override internal var _cfTypeID: CFTypeID { return CFDataGetTypeID() } } extension NSData { public convenience init(bytes: UnsafePointer<Void>, length: Int) { self.init(bytes: UnsafeMutablePointer<Void>(bytes), length: length, copy: true, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int) { self.init(bytes: bytes, length: length, copy: false, deallocator: nil) } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, freeWhenDone b: Bool) { self.init(bytes: bytes, length: length, copy: true) { buffer, length in if b { free(buffer) } } } public convenience init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { self.init(bytes: bytes, length: length, copy: false, deallocator: deallocator) } internal struct NSDataReadResult { var bytes: UnsafeMutablePointer<Void> var length: Int var deallocator: ((buffer: UnsafeMutablePointer<Void>, length: Int) -> Void)? } internal static func readBytesFromFileWithExtendedAttributes(path: String, options: NSDataReadingOptions) throws -> NSDataReadResult { let fd = _CFOpenFile(path, O_RDONLY) if fd < 0 { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } var info = stat() let ret = withUnsafeMutablePointer(&info) { infoPointer -> Bool in if fstat(fd, infoPointer) < 0 { return false } return true } if !ret { close(fd) throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } let length = Int(info.st_size) if options.contains(.DataReadingMappedAlways) { let data = mmap(nil, length, PROT_READ, MAP_PRIVATE, fd, 0) // Swift does not currently expose MAP_FAILURE if data != UnsafeMutablePointer<Void>(bitPattern: -1) { close(fd) return NSDataReadResult(bytes: data, length: length) { buffer, length in munmap(data, length) } } } let data = malloc(length) var remaining = Int(info.st_size) var total = 0 while remaining > 0 { let amt = read(fd, data.advancedBy(total), remaining) if amt < 0 { break } remaining -= amt total += amt } if remaining != 0 { close(fd) throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno), userInfo: nil) } return NSDataReadResult(bytes: data, length: length) { buffer, length in free(buffer) } } public convenience init(contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions) throws { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: readOptionsMask) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } public convenience init?(contentsOfFile path: String) { do { let readResult = try NSData.readBytesFromFileWithExtendedAttributes(path, options: []) self.init(bytes: readResult.bytes, length: readResult.length, copy: false, deallocator: readResult.deallocator) } catch { return nil } } public convenience init(data: NSData) { self.init(bytes:data.bytes, length: data.length) } public convenience init(contentsOfURL url: NSURL, options readOptionsMask: NSDataReadingOptions) throws { if url.fileURL { try self.init(contentsOfFile: url.path!, options: readOptionsMask) } else { let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) let cond = NSCondition() var resError: NSError? var resData: NSData? let task = session.dataTaskWithURL(url, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in resData = data resError = error cond.broadcast() }) task.resume() cond.wait() if resData == nil { throw resError! } self.init(data: resData!) } } public convenience init?(contentsOfURL url: NSURL) { do { try self.init(contentsOfURL: url, options: []) } catch { return nil } } } extension NSData { public func getBytes(buffer: UnsafeMutablePointer<Void>, length: Int) { CFDataGetBytes(_cfObject, CFRangeMake(0, length), UnsafeMutablePointer<UInt8>(buffer)) } public func getBytes(buffer: UnsafeMutablePointer<Void>, range: NSRange) { CFDataGetBytes(_cfObject, CFRangeMake(range.location, range.length), UnsafeMutablePointer<UInt8>(buffer)) } public func isEqualToData(other: NSData) -> Bool { if self === other { return true } if length != other.length { return false } let bytes1 = bytes let bytes2 = other.bytes if bytes1 == bytes2 { return true } return memcmp(bytes1, bytes2, length) == 0 } public func subdataWithRange(range: NSRange) -> NSData { if range.length == 0 { return NSData() } if range.location == 0 && range.length == self.length { return copyWithZone(nil) as! NSData } return NSData(bytes: bytes.advancedBy(range.location), length: range.length) } internal func makeTemporaryFileInDirectory(dirPath: String) throws -> (Int32, String) { let template = dirPath._nsObject.stringByAppendingPathComponent("tmp.XXXXXX") let maxLength = Int(PATH_MAX) + 1 var buf = [Int8](count: maxLength, repeatedValue: 0) template._nsObject.getFileSystemRepresentation(&buf, maxLength: maxLength) let fd = mkstemp(&buf) if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: dirPath) } let pathResult = NSFileManager.defaultManager().stringWithFileSystemRepresentation(buf, length: Int(strlen(buf))) return (fd, pathResult) } internal class func writeToFileDescriptor(fd: Int32, path: String? = nil, buf: UnsafePointer<Void>, length: Int) throws { var bytesRemaining = length while bytesRemaining > 0 { var bytesWritten : Int repeat { bytesWritten = write(fd, buf.advancedBy(length - bytesRemaining), bytesRemaining) } while (bytesWritten < 0 && errno == EINTR) if bytesWritten <= 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else { bytesRemaining -= bytesWritten } } } public func writeToFile(path: String, options writeOptionsMask: NSDataWritingOptions) throws { var fd : Int32 var mode : mode_t? = nil let useAuxiliaryFile = writeOptionsMask.contains(.DataWritingAtomic) var auxFilePath : String? = nil if useAuxiliaryFile { // Preserve permissions. var info = stat() if lstat(path, &info) == 0 { mode = info.st_mode } else if errno != ENOENT && errno != ENAMETOOLONG { throw _NSErrorWithErrno(errno, reading: false, path: path) } let (newFD, path) = try self.makeTemporaryFileInDirectory(path._nsObject.stringByDeletingLastPathComponent) fd = newFD auxFilePath = path fchmod(fd, 0o666) } else { var flags = O_WRONLY | O_CREAT | O_TRUNC if writeOptionsMask.contains(.DataWritingWithoutOverwriting) { flags |= O_EXCL } fd = _CFOpenFileWithMode(path, flags, 0o666) } if fd == -1 { throw _NSErrorWithErrno(errno, reading: false, path: path) } defer { close(fd) } try self.enumerateByteRangesUsingBlockRethrows { (buf, range, stop) in if range.length > 0 { do { try NSData.writeToFileDescriptor(fd, path: path, buf: buf, length: range.length) if fsync(fd) < 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } catch let err { if let auxFilePath = auxFilePath { do { try NSFileManager.defaultManager().removeItemAtPath(auxFilePath) } catch _ {} } throw err } } } if let auxFilePath = auxFilePath { if rename(auxFilePath, path) != 0 { do { try NSFileManager.defaultManager().removeItemAtPath(auxFilePath) } catch _ {} throw _NSErrorWithErrno(errno, reading: false, path: path) } if let mode = mode { chmod(path, mode) } } } public func writeToFile(path: String, atomically useAuxiliaryFile: Bool) -> Bool { do { try writeToFile(path, options: useAuxiliaryFile ? .DataWritingAtomic : []) } catch { return false } return true } public func writeToURL(url: NSURL, atomically: Bool) -> Bool { if url.fileURL { if let path = url.path { return writeToFile(path, atomically: atomically) } } return false } public func writeToURL(url: NSURL, options writeOptionsMask: NSDataWritingOptions) throws { NSUnimplemented() } internal func enumerateByteRangesUsingBlockRethrows(block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) throws -> Void) throws { var err : ErrorType? = nil self.enumerateByteRangesUsingBlock() { (buf, range, stop) -> Void in do { try block(buf, range, stop) } catch let e { err = e } } if let err = err { throw err } } public func enumerateByteRangesUsingBlock(block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<Bool>) -> Void) { var stop = false withUnsafeMutablePointer(&stop) { stopPointer in block(bytes, NSMakeRange(0, length), stopPointer) } } } extension NSData : _CFBridgable { } extension CFDataRef : _NSBridgable { typealias NSType = NSData internal var _nsObject: NSType { return unsafeBitCast(self, NSType.self) } } extension NSMutableData { internal var _cfMutableObject: CFMutableDataRef { return unsafeBitCast(self, CFMutableDataRef.self) } } public class NSMutableData : NSData { public required convenience init() { self.init(bytes: nil, length: 0) } public required convenience init?(coder aDecoder: NSCoder) { NSUnimplemented() } internal override init(bytes: UnsafeMutablePointer<Void>, length: Int, copy: Bool, deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?) { super.init(bytes: bytes, length: length, copy: copy, deallocator: deallocator) } public var mutableBytes: UnsafeMutablePointer<Void> { get { return UnsafeMutablePointer(CFDataGetMutableBytePtr(_cfMutableObject)) } } public override var length: Int { get { return CFDataGetLength(_cfObject) } set { CFDataSetLength(_cfMutableObject, newValue) } } public override func copyWithZone(zone: NSZone) -> AnyObject { return NSData(data: self) } } extension NSData { /* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64EncodedString base64String: String, options: NSDataBase64DecodingOptions) { NSUnimplemented() } /* Create a Base-64 encoded NSString from the receiver's contents using the given options. */ public func base64EncodedStringWithOptions(options: NSDataBase64EncodingOptions) -> String { NSUnimplemented() } /* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64. */ public convenience init?(base64EncodedData base64Data: NSData, options: NSDataBase64DecodingOptions) { NSUnimplemented() } /* Create a Base-64, UTF-8 encoded NSData from the receiver's contents using the given options. */ public func base64EncodedDataWithOptions(options: NSDataBase64EncodingOptions) -> NSData { NSUnimplemented() } } extension NSMutableData { public func appendBytes(bytes: UnsafePointer<Void>, length: Int) { CFDataAppendBytes(_cfMutableObject, UnsafePointer<UInt8>(bytes), length) } public func appendData(other: NSData) { appendBytes(other.bytes, length: other.length) } public func increaseLengthBy(extraLength: Int) { CFDataSetLength(_cfMutableObject, CFDataGetLength(_cfObject) + extraLength) } public func replaceBytesInRange(range: NSRange, withBytes bytes: UnsafePointer<Void>) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), length) } public func resetBytesInRange(range: NSRange) { bzero(mutableBytes.advancedBy(range.location), range.length) } public func setData(data: NSData) { length = data.length replaceBytesInRange(NSMakeRange(0, data.length), withBytes: data.bytes) } public func replaceBytesInRange(range: NSRange, withBytes replacementBytes: UnsafePointer<Void>, length replacementLength: Int) { CFDataReplaceBytes(_cfMutableObject, CFRangeMake(range.location, range.length), UnsafePointer<UInt8>(bytes), replacementLength) } } extension NSMutableData { public convenience init?(capacity: Int) { self.init(bytes: nil, length: 0) } public convenience init?(length: Int) { let memory = malloc(length) self.init(bytes: memory, length: length, copy: false) { buffer, amount in free(buffer) } } }
apache-2.0
8de0313ce5c9b3006220a02b594cf0e3
34.16609
155
0.613402
4.967253
false
false
false
false
sadawi/PrimarySource
Pod/iOS/MonthYearPickerCell.swift
1
1690
// // MonthYearPickerCell.swift // Pods // // Created by Sam Williams on 6/7/16. // // import Foundation import UIKit open class MonthYearPickerCell: PickerCell<Date> { open var dateFormatter: DateFormatter = DateFormatter() open var monthYearPicker: MonthYearPicker? { return self.picker as? MonthYearPicker } open override func buildView() { super.buildView() self.dateFormatter.dateFormat = "MM/YYYY" } open override func setDefaults() { super.setDefaults() self.toolbarShowsClearButton = false } open var dateComponentsValue: DateComponents? { get { return self.monthYearPicker?.dateComponents as DateComponents? } set { self.monthYearPicker?.dateComponents = newValue self.update() } } open override var value: Date? { get { return self.monthYearPicker?.date as Date? } set { self.monthYearPicker?.date = newValue self.update() } } open override func buildPicker() -> UIPickerView? { let picker = MonthYearPicker(minimumDate: Date(), maximumDate: Date().addingTimeInterval(15*365*24*60*60)) picker.onValueChange = { [weak self] components in self?.update() } return picker } open override var stringValue: String? { get { if let date = self.monthYearPicker?.date { return self.dateFormatter.string(from: date as Date) } return nil } set { // Input through picker } } }
mit
50553bea2be0168d42be8cd87924d781
23.852941
114
0.572189
4.747191
false
false
false
false
mrommel/TreasureDungeons
TreasureDungeons/Source/OpenGL/ObjLoader/ObjLoader.swift
1
10549
// // ObjLoader.swift // SwiftObjLoader // // Created by Hugo Tunius on 02/09/15. // Copyright © 2015 Hugo Tunius. All rights reserved. // import Foundation enum ObjLoading {} extension String { func appendingPathComponent(_ string: String) -> String { return URL(fileURLWithPath: self).appendingPathComponent(string).path } } extension ObjLoading { enum ObjLoadingError: Error { case unexpectedFileFormat(error: String) } public final class ObjLoader { // Represent the state of parsing // at any point in time class State { var objectName: NSString? var vertices: [Vector] = [] var normals: [Vector] = [] var textureCoords: [Vector] = [] var faces: [[VertexIndex]] = [] var material: Material? } // Source markers fileprivate static let commentMarker = "#".characters.first fileprivate static let vertexMarker = "v".characters.first fileprivate static let normalMarker = "vn" fileprivate static let textureCoordMarker = "vt" fileprivate static let objectMarker = "o".characters.first fileprivate static let groupMarker = "g".characters.first fileprivate static let faceMarker = "f".characters.first fileprivate static let materialLibraryMarker = "mtllib" fileprivate static let useMaterialMarker = "usemtl" fileprivate let scanner: ObjScanner fileprivate let basePath: String fileprivate var materialCache: [NSString: Material] = [:] fileprivate var state = State() fileprivate var vertexCount = 0 fileprivate var normalCount = 0 fileprivate var textureCoordCount = 0 // Init an objloader with the // source of the .obj file as a string // public init(source: String, basePath: String) { scanner = ObjScanner(source: source) self.basePath = basePath } // Read the specified source. // This operation is singled threaded and // should not be invoked again before // the call has returned public func read() throws -> [Shape] { var shapes: [Shape] = [] resetState() do { while scanner.dataAvailable { let marker = scanner.readMarker() guard let m = marker, m.length > 0 else { scanner.moveToNextLine() continue } let markerString = m as String if ObjLoader.isComment(markerString) { scanner.moveToNextLine() continue } if ObjLoader.isVertex(markerString) { if let v = try readVertex() { state.vertices.append(v) } scanner.moveToNextLine() continue } if ObjLoader.isNormal(markerString) { if let n = try readVertex() { state.normals.append(n) } scanner.moveToNextLine() continue } if ObjLoader.isTextureCoord(markerString) { if let vt = scanner.readTextureCoord() { state.textureCoords.append(vt) } scanner.moveToNextLine() continue } if ObjLoader.isObject(markerString) { if let s = buildShape() { shapes.append(s) } state = State() state.objectName = scanner.readLine() scanner.moveToNextLine() continue } if ObjLoader.isGroup(markerString) { if let s = buildShape() { shapes.append(s) } state = State() state.objectName = try scanner.readString() scanner.moveToNextLine() continue } if ObjLoader.isFace(markerString) { if let indices = try scanner.readFace() { state.faces.append(normalizeVertexIndices(indices)) } scanner.moveToNextLine() continue } if ObjLoader.isMaterialLibrary(markerString) { let filenames = try scanner.readTokens() try parseMaterialFiles(filenames) scanner.moveToNextLine() continue } if ObjLoader.isUseMaterial(markerString) { let materialName = try scanner.readString() guard let material = self.materialCache[materialName] else { throw ObjLoadingError.unexpectedFileFormat(error: "Material \(materialName) referenced before it was definied") } state.material = material scanner.moveToNextLine() continue } scanner.moveToNextLine() } if let s = buildShape() { shapes.append(s) } state = State() } catch let e { resetState() throw e } return shapes } fileprivate static func isComment(_ marker: String) -> Bool { return marker.characters.first == commentMarker } fileprivate static func isVertex(_ marker: String) -> Bool { return marker.characters.count == 1 && marker.characters.first == vertexMarker } fileprivate static func isNormal(_ marker: String) -> Bool { return marker.characters.count == 2 && marker == normalMarker //return marker.characters.count == 2 && marker.substring(to: marker.index(from: 2)) == normalMarker //return true } fileprivate static func isTextureCoord(_ marker: String) -> Bool { return marker.characters.count == 2 && marker == textureCoordMarker //return marker.characters.count == 2 && marker.substring(to: marker.index(from: 2)) == textureCoordMarker //return true } fileprivate static func isObject(_ marker: String) -> Bool { return marker.characters.count == 1 && marker.characters.first == objectMarker } fileprivate static func isGroup(_ marker: String) -> Bool { return marker.characters.count == 1 && marker.characters.first == groupMarker } fileprivate static func isFace(_ marker: String) -> Bool { return marker.characters.count == 1 && marker.characters.first == faceMarker } fileprivate static func isMaterialLibrary(_ marker: String) -> Bool { return marker == materialLibraryMarker } fileprivate static func isUseMaterial(_ marker: String) -> Bool { return marker == useMaterialMarker } fileprivate func readVertex() throws -> [Double]? { do { return try scanner.readVertex() } catch ScannerErrors.unreadableData(let error) { throw ObjLoadingError.unexpectedFileFormat(error: error) } } fileprivate func resetState() { scanner.reset() state = State() vertexCount = 0 normalCount = 0 textureCoordCount = 0 } fileprivate func buildShape() -> Shape? { if state.vertices.count == 0 && state.normals.count == 0 && state.textureCoords.count == 0 { return nil } let result = Shape(name: (state.objectName as String?), vertices: state.vertices, normals: state.normals, textureCoords: state.textureCoords, material: state.material, faces: state.faces) vertexCount += state.vertices.count normalCount += state.normals.count textureCoordCount += state.textureCoords.count return result } fileprivate func normalizeVertexIndices(_ unnormalizedIndices: [VertexIndex]) -> [VertexIndex] { return unnormalizedIndices.map { return VertexIndex(vIndex: ObjLoader.normalizeIndex($0.vIndex, count: vertexCount), nIndex: ObjLoader.normalizeIndex($0.nIndex, count: normalCount), tIndex: ObjLoader.normalizeIndex($0.tIndex, count: textureCoordCount)) } } fileprivate func parseMaterialFiles(_ filenames: [NSString]) throws { for filename in filenames { let fullPath = basePath.appendingPathComponent(filename as String) do { let fileContents = try NSString(contentsOfFile: fullPath, encoding: String.Encoding.utf8.rawValue) let loader = MaterialLoader(source: fileContents as String, basePath: basePath) let materials = try loader.read() for material in materials { materialCache[material.name] = material } } catch MaterialLoadingError.unexpectedFileFormat(let msg) { throw ObjLoadingError.unexpectedFileFormat(error: msg) } catch { throw ObjLoadingError.unexpectedFileFormat(error: "Invalid material file at \(fullPath)") } } } fileprivate static func normalizeIndex(_ index: Int?, count: Int) -> Int? { guard let i = index else { return nil } if i == 0 { return 0 } return i - count - 1 } } }
apache-2.0
e3ff2608b63ebf24987d50f9144f0525
34.755932
199
0.511282
5.670968
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/RedundantDiscardableLetRule.swift
1
3314
import SwiftSyntax struct RedundantDiscardableLetRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "redundant_discardable_let", name: "Redundant Discardable Let", description: "Prefer `_ = foo()` over `let _ = foo()` when discarding a result from a function.", kind: .style, nonTriggeringExamples: [ Example("_ = foo()\n"), Example("if let _ = foo() { }\n"), Example("guard let _ = foo() else { return }\n"), Example("let _: ExplicitType = foo()"), Example("while let _ = SplashStyle(rawValue: maxValue) { maxValue += 1 }\n"), Example("async let _ = await foo()") ], triggeringExamples: [ Example("↓let _ = foo()\n"), Example("if _ = foo() { ↓let _ = bar() }\n") ], corrections: [ Example("↓let _ = foo()\n"): Example("_ = foo()\n"), Example("if _ = foo() { ↓let _ = bar() }\n"): Example("if _ = foo() { _ = bar() }\n") ] ) func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? { Rewriter( locationConverter: file.locationConverter, disabledRegions: disabledRegions(file: file) ) } } private extension RedundantDiscardableLetRule { final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: VariableDeclSyntax) { if node.hasRedundantDiscardableLetViolation { violations.append(node.positionAfterSkippingLeadingTrivia) } } } final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter { private(set) var correctionPositions: [AbsolutePosition] = [] let locationConverter: SourceLocationConverter let disabledRegions: [SourceRange] init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) { self.locationConverter = locationConverter self.disabledRegions = disabledRegions } override func visit(_ node: VariableDeclSyntax) -> DeclSyntax { guard node.hasRedundantDiscardableLetViolation, !node.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) else { return super.visit(node) } correctionPositions.append(node.positionAfterSkippingLeadingTrivia) let newNode = node .withLetOrVarKeyword(nil) .withBindings(node.bindings.withLeadingTrivia(node.letOrVarKeyword.leadingTrivia)) return super.visit(newNode) } } } private extension VariableDeclSyntax { var hasRedundantDiscardableLetViolation: Bool { letOrVarKeyword.tokenKind == .letKeyword && bindings.count == 1 && bindings.first!.pattern.is(WildcardPatternSyntax.self) && bindings.first!.typeAnnotation == nil && modifiers?.contains(where: { $0.name.text == "async" }) != true } }
mit
68c826fb545abdf52382509d2aa8b5f7
37
105
0.606776
5.264331
false
false
false
false
ontouchstart/mythical-mind-bike
mythical-mind-bike.playgroundbook/Contents/Chapters/00.playgroundchapter/Pages/00.playgroundpage/LiveView.swift
1
1043
import UIKit import PlaygroundSupport extension UIViewController { func centerImageView(src: String, scale: CGFloat = 1) -> UIImageView? { guard let url = URL(string: src) else { return nil } guard let ciimage = CIImage(contentsOf: url) else { return nil } let image = UIImage(ciImage: ciimage, scale: scale, orientation: .up) let subView = UIImageView(image: image) self.view.addSubview(subView) subView.translatesAutoresizingMaskIntoConstraints = false let center_contraint = [ subView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), subView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), ] NSLayoutConstraint.activate(center_contraint) return subView } } let vc = UIViewController() let src = "https://pbs.twimg.com/media/C0GLE-8XUAAx0P4.jpg" let subView = vc.centerImageView(src: src, scale: 2) dump(vc.view) dump(vc.view!.frame) dump(subView) dump(subView!.frame) PlaygroundPage.current.liveView = vc
gpl-3.0
3270b73b85070331e6615846158a2361
39.153846
79
0.700863
4.138889
false
false
false
false
finngaida/wwdc
2015/Finn Gaida/FGSunUpWidget.swift
1
5026
// // FGSunUpWidget.swift // Finn Gaida // // Created by Finn Gaida on 24.04.15. // Copyright (c) 2015 Finn Gaida. All rights reserved. // import UIKit class FGSunUpWidget: UIView { var circle = UIButton() var darkMode:Bool = false var time = UILabel() var indicator = UIView() var delegate = FGStoryController() override init(frame: CGRect) { circle = UIButton(frame: CGRectMake((frame.width - frame.height * 0.75) / 2, (frame.height - frame.height * 0.75) / 2, frame.height * 0.75, frame.height * 0.75)) circle.layer.masksToBounds = true circle.layer.cornerRadius = circle.frame.width/2 circle.backgroundColor = UIColor(red: (208.0/255.0), green:(86.0/255.0), blue:(106.0/255.0), alpha: 1.0) time = UILabel(frame: CGRectMake(0, 0, circle.frame.width, circle.frame.height)) time.backgroundColor = UIColor.clearColor() time.textColor = UIColor.whiteColor() time.textAlignment = NSTextAlignment.Center time.font = UIFont(name: "HelveticaNeue-Light", size: 40) time.text = "06:00" circle.addSubview(time) indicator = UIView(frame: CGRectMake(0, 0, circle.frame.width, circle.frame.height)) indicator.backgroundColor = UIColor.clearColor() indicator.alpha = 0 let dot = UIView(frame: CGRectMake(indicator.frame.width/2-5, 0, 10, 10)) dot.layer.masksToBounds = true dot.layer.cornerRadius = dot.frame.width/2 dot.backgroundColor = UIColor.whiteColor() indicator.addSubview(dot) circle.addSubview(indicator) super.init(frame: frame) self.layer.masksToBounds = true self.layer.cornerRadius = 10 self.backgroundColor = UIColor(red: (86.0/255.0), green:(208.0/255.0), blue:(188.0/255.0), alpha: 1.0) circle.addTarget(self, action: "setDarkMode", forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(circle) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { indicator.alpha = 1 self.delegate.scrollView.scrollEnabled = false } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let point = touches.first!.locationInView(self as UIView) var angle:CGFloat let mid = CGPointMake(self.frame.width/2, self.frame.height/2) let calc = FGStuffCalculator() if (point.x < mid.x && point.y < mid.y) { angle = calc.angleForTriangleInScreenQuarter(FGScreenQuarter.TopLeft, toPoint: point, inView: self) } else if (point.x > mid.x && point.y < mid.y) { angle = calc.angleForTriangleInScreenQuarter(FGScreenQuarter.TopRight, toPoint: point, inView: self) } else if (point.x < mid.x && point.y > mid.y-1) { angle = calc.angleForTriangleInScreenQuarter(FGScreenQuarter.BottomLeft, toPoint: point, inView: self) } else /*if (point.x > self.mid.x && point.y > self.mid.y)*/ { angle = calc.angleForTriangleInScreenQuarter(FGScreenQuarter.BottomRight, toPoint: point, inView: self) } indicator.transform = CGAffineTransformMakeRotation(FGStuffCalculator.degreesToRadians(angle)) var hours = NSString(format: "%.f", FGStuffCalculator.unroundedFloatWithoutDecimalPlace(angle/360*12)) var minutes = NSString(format: "%.f", FGStuffCalculator.minutesAtDegree(angle, h24: false)) if (hours.length < 2) {hours = "0".stringByAppendingString(hours as String)} if (minutes.length < 2) {minutes = "0".stringByAppendingString(minutes as String)} time.text = "\(hours):\(minutes)" } func setDarkMode() { if (darkMode) { UIView.animateWithDuration(0.75, animations: { () -> Void in self.circle.backgroundColor = UIColor(red: (208.0/255.0), green:(86.0/255.0), blue:(106.0/255.0), alpha: 1.0) self.backgroundColor = UIColor(red: (86.0/255.0), green:(208.0/255.0), blue:(188.0/255.0), alpha: 1.0) }) darkMode = !darkMode } else { UIView.animateWithDuration(0.75, animations: { () -> Void in self.circle.backgroundColor = UIColor.blackColor() self.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.2, alpha: 1.0) }) darkMode = !darkMode } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { indicator.alpha = 0 self.delegate.scrollView.scrollEnabled = true } }
gpl-2.0
e0f2c33d0877df8f9d22ee39fee4d57e
37.661538
169
0.59809
4.146865
false
false
false
false
gb-6k-house/YsSwift
Sources/Rabbit/Cache.swift
1
1549
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: 图片缓存对象 ** Copyright © 2017年 尧尚信息科技(www.yourshares.cn). All rights reserved ******************************************************************************/ import Foundation import UIKit #if YSSWIFT_DEBUG import YsSwift #endif //内存缓存 public final class ImageCache { public class CachedImage: CachedItem { public var value: AnyObject public var memCost: Int { guard let image = self.value as? Image else{ fatalError("value prop must be Image type") } return image.ys.memSize } public init(value: Image){ self.value = value } } public static let shared: Cache<CachedImage> = Cache() } extension Request { //请求的key值 public var cacheKey: AnyHashable { return AnyHashable(Request.makeCacheKey(self)) } //生成请求的key。 这里相同的请求key相同 private static func makeCacheKey(_ request: Request) -> Key { return Key(request: request) { $0.container.urlString == $1.container.urlString } } } public extension Cache where T: ImageCache.CachedImage { /// Accesses the image associated with the given request. public subscript(request: Request) -> T? { get { return self[request.cacheKey]} set { self[request.cacheKey] = newValue} } }
mit
814dcb767ad3195ece37b05f25567193
25.836364
80
0.54878
4.513761
false
false
false
false
OpenTimeApp/OpenTimeIOSSDK
OpenTimeSDK/Classes/OTMeetingAPI.swift
1
2934
// // OTMeetingAPI.swift // OpenTimeSDK // // Created by Josh Woodcock on 12/23/15. // Copyright © 2015 Connecting Open Time, LLC. All rights reserved. // import AFNetworking public class OTMeetingAPI { public static func create(createMeetingData: OTCreateMeetingData, done: @escaping (_ response: OTCreateMeetingResponse)->Void) -> Void { // Setup request manager. let requestManager = OTAPIAuthorizedRequestOperationManager(); _ = requestManager.post(OpenTimeSDK.getServer() + "/api/meeting", parameters: createMeetingData.getParameters(), success: { (operation: AFHTTPRequestOperation!, responseObject: Any) -> Void in let response = OTAPIResponse.loadFromReqeustOperationWithResponse(operation); if(response.rawData != nil){ done(OTCreateMeetingResponse(success: response.success, message: response.message, rawData: response.rawData!)); }else{ let reply = OTCreateMeetingResponse(success: false, message: "", rawData: nil); reply.makeEmpty(); done(reply); } }, failure: { (operation: AFHTTPRequestOperation?, error: Error) -> Void in requestManager.apiResult(operation, error: error as NSError!, done: {(response: OTAPIResponse)->Void in done(OTCreateMeetingResponse(success: response.success, message: response.message, rawData: nil)); }); } ); } public static func getAllMyMeetings(done: @escaping (_ response: OTGetAllMyMeetingsResponse)->Void) { let requestManager = OTAPIAuthorizedRequestOperationManager(); _ = requestManager.get(OpenTimeSDK.getServer() + "/api/meeting/all", parameters: [], success: { (operation: AFHTTPRequestOperation!, responseObject: Any) -> Void in let response = OTAPIResponse.loadFromReqeustOperationWithResponse(operation); if(response.rawData != nil){ done(OTGetAllMyMeetingsResponse(success: response.success, message: response.message, rawData: response.rawData!)); }else{ let reply = OTGetAllMyMeetingsResponse(success: false, message: "", rawData: nil); reply.makeEmpty(); done(reply); } }, failure: { (operation: AFHTTPRequestOperation?, error: Error) -> Void in requestManager.apiResult(operation, error: error as NSError!, done: {(response: OTAPIResponse)->Void in done(OTGetAllMyMeetingsResponse(success: response.success, message: response.message, rawData: nil)); }); } ) } }
mit
434540596e30b2e49d644b55cec2908f
43.439394
140
0.58643
5.200355
false
false
false
false
RevenueCat/purchases-ios
Sources/Error Handling/ErrorDetails.swift
1
1554
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // ErrorDetails.swift // // Created by Joshua Liebowitz on 7/12/21. // import Foundation extension NSError.UserInfoKey { static let attributeErrors: NSError.UserInfoKey = "attribute_errors" static let attributeErrorsResponse: NSError.UserInfoKey = "attributes_error_response" static let statusCode: NSError.UserInfoKey = "rc_response_status_code" static let readableErrorCode: NSError.UserInfoKey = "readable_error_code" static let backendErrorCode: NSError.UserInfoKey = "rc_backend_error_code" static let extraContext: NSError.UserInfoKey = "extra_context" static let file: NSError.UserInfoKey = "source_file" static let function: NSError.UserInfoKey = "source_function" } enum ErrorDetails { static let attributeErrorsKey = NSError.UserInfoKey.attributeErrors as String static let attributeErrorsResponseKey = NSError.UserInfoKey.attributeErrorsResponse as String static let statusCodeKey = NSError.UserInfoKey.statusCode as String static let readableErrorCodeKey = NSError.UserInfoKey.readableErrorCode as String static let extraContextKey = NSError.UserInfoKey.extraContext as String static let fileKey = NSError.UserInfoKey.file as String static let functionKey = NSError.UserInfoKey.function as String }
mit
85b17b774b65e89373d95d1879c21fa1
36
97
0.764479
4.452722
false
false
false
false
jtsmrd/Intrview
ViewControllers/AddEditInterviewQuestionVC.swift
1
6936
// // AddEditInterviewQuestionVC.swift // SnapInterview // // Created by JT Smrdel on 1/18/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import UIKit class AddEditInterviewQuestionVC: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate { @IBOutlet weak var interviewQuestionTextView: UITextView! @IBOutlet weak var timeLimitTextField: UITextField! @IBOutlet weak var deleteButton: CustomButton! let pickerViewValues = [10, 20, 30, 45, 60] var interviewQuestion: InterviewQuestion! var interviewTemplate: InterviewTemplate! var currentFirstResponder: UIView! var navToolBar: UIToolbar! override func viewDidLoad() { super.viewDidLoad() let saveBarButtonItem = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneButtonAction)) saveBarButtonItem.tintColor = UIColor.white navigationItem.rightBarButtonItem = saveBarButtonItem let backBarButtonItem = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(backButtonAction)) backBarButtonItem.tintColor = UIColor.white navigationItem.leftBarButtonItem = backBarButtonItem if interviewQuestion != nil { if let question = interviewQuestion.question { interviewQuestionTextView.text = question } if let timeLimit = interviewQuestion.timeLimitInSeconds { timeLimitTextField.text = String(describing: timeLimit) } } else { interviewQuestionTextView.text = "Interview Question" deleteButton.isHidden = true } navToolBar = createKeyboardToolBar() } @objc func doneButtonAction() { if currentFirstResponder != nil { currentFirstResponder.resignFirstResponder() } if interviewQuestion != nil { interviewQuestion.question = interviewQuestionTextView.text interviewQuestion.timeLimitInSeconds = Int(timeLimitTextField.text!) } else { interviewQuestion = InterviewQuestion() interviewQuestion.question = interviewQuestionTextView.text interviewQuestion.timeLimitInSeconds = Int(timeLimitTextField.text!) interviewTemplate.interviewQuestions.append(interviewQuestion) } let _ = navigationController?.popViewController(animated: true) } @objc func backButtonAction() { if currentFirstResponder != nil { currentFirstResponder.resignFirstResponder() } let _ = navigationController?.popViewController(animated: true) } @IBAction func deleteButtonAction(_ sender: Any) { let index = interviewTemplate.interviewQuestions.index { (question) -> Bool in question.question == self.interviewQuestion.question } if let questionIndex = index { interviewTemplate.interviewQuestions.remove(at: questionIndex) } let _ = navigationController?.popViewController(animated: true) } func textFieldDidBeginEditing(_ textField: UITextField) { currentFirstResponder = textField textField.inputAccessoryView = navToolBar let numberPicker = UIPickerView() numberPicker.dataSource = self numberPicker.delegate = self textField.inputView = numberPicker if textField.text != "" { let index = pickerViewValues.index(of: Int(textField.text!)!) numberPicker.selectRow(index!, inComponent: 0, animated: false) } else { textField.text = String(pickerViewValues[0]) } } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { textView.inputAccessoryView = navToolBar return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard let existingText = textView.text else { return true } let newLength = existingText.characters.count + text.characters.count - range.length return newLength <= 300 } func textViewDidBeginEditing(_ textView: UITextView) { currentFirstResponder = textView } // MARK: - UIPickerView Methods func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerViewValues.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return String(pickerViewValues[row]) } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { timeLimitTextField.text = String(pickerViewValues[row]) } // MARK: - Keyboard toolbar @objc func doneAction() { if currentFirstResponder != nil { currentFirstResponder.resignFirstResponder() } } @objc func previousAction() { if let previousField = currentFirstResponder.superview!.viewWithTag(currentFirstResponder.tag - 100) { previousField.becomeFirstResponder() } } @objc func nextAction() { if let nextField = currentFirstResponder.superview!.viewWithTag(currentFirstResponder.tag + 100) { nextField.becomeFirstResponder() } } fileprivate func createKeyboardToolBar() -> UIToolbar { let keyboardToolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) keyboardToolBar.barStyle = .default let previous = UIBarButtonItem(image: UIImage(named: "left_icon"), style: .plain, target: self, action: #selector(previousAction)) previous.width = 50 previous.tintColor = Global.greenColor let next = UIBarButtonItem(image: UIImage(named: "right_icon"), style: .plain, target: self, action: #selector(nextAction)) next.width = 50 next.tintColor = Global.greenColor let done = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneAction)) done.tintColor = Global.greenColor let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) keyboardToolBar.items = [previous, next, flexSpace, done] keyboardToolBar.sizeToFit() return keyboardToolBar } }
mit
d8e846a02a1b6683402958ab06de2eae
34.025253
149
0.639942
5.50834
false
false
false
false
manGoweb/MimeLib
Sources/MimeType.swift
1
31184
// // MimeType.swift // MimeLibGenerator // // Created by Ondrej Rafaj on 14/12/2016. // Copyright © 2016 manGoweb UK Ltd. All rights reserved. // // Data has been extracted from an apache.org svn repository located on http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types import Foundation // Warning: Do not change, following code has been automatically generated! public enum MimeType: String { case ez = "application/andrew-inset" case aw = "application/applixware" case atom = "application/atom+xml" case atomcat = "application/atomcat+xml" case atomsvc = "application/atomsvc+xml" case ccxml = "application/ccxml+xml" case cdmia = "application/cdmi-capability" case cdmic = "application/cdmi-container" case cdmid = "application/cdmi-domain" case cdmio = "application/cdmi-object" case cdmiq = "application/cdmi-queue" case cu = "application/cu-seeme" case davmount = "application/davmount+xml" case dbk = "application/docbook+xml" case dssc = "application/dssc+der" case xdssc = "application/dssc+xml" case ecma = "application/ecmascript" case emma = "application/emma+xml" case epub = "application/epub+zip" case exi = "application/exi" case pfr = "application/font-tdpfr" case gml = "application/gml+xml" case gpx = "application/gpx+xml" case gxf = "application/gxf" case stk = "application/hyperstudio" case ink = "application/inkml+xml" case ipfix = "application/ipfix" case jar = "application/java-archive" case ser = "application/java-serialized-object" case _class = "application/java-vm" case js = "application/javascript" case json = "application/json" case jsonml = "application/jsonml+json" case lostxml = "application/lost+xml" case hqx = "application/mac-binhex40" case cpt = "application/mac-compactpro" case mads = "application/mads+xml" case mrc = "application/marc" case mrcx = "application/marcxml+xml" case ma = "application/mathematica" case mathml = "application/mathml+xml" case mbox = "application/mbox" case mscml = "application/mediaservercontrol+xml" case metalink = "application/metalink+xml" case meta4 = "application/metalink4+xml" case mets = "application/mets+xml" case mods = "application/mods+xml" case m21 = "application/mp21" case mp4s = "application/mp4" case doc = "application/msword" case mxf = "application/mxf" case bin = "application/octet-stream" case oda = "application/oda" case opf = "application/oebps-package+xml" case ogx = "application/ogg" case omdoc = "application/omdoc+xml" case onetoc = "application/onenote" case oxps = "application/oxps" case xer = "application/patch-ops-error+xml" case pdf = "application/pdf" case pgp = "application/pgp-encrypted" case asc = "application/pgp-signature" case prf = "application/pics-rules" case p10 = "application/pkcs10" case p7m = "application/pkcs7-mime" case p7s = "application/pkcs7-signature" case p8 = "application/pkcs8" case ac = "application/pkix-attr-cert" case cer = "application/pkix-cert" case crl = "application/pkix-crl" case pkipath = "application/pkix-pkipath" case pki = "application/pkixcmp" case pls = "application/pls+xml" case ai = "application/postscript" case cww = "application/prs.cww" case pskcxml = "application/pskc+xml" case rdf = "application/rdf+xml" case rif = "application/reginfo+xml" case rnc = "application/relax-ng-compact-syntax" case rl = "application/resource-lists+xml" case rld = "application/resource-lists-diff+xml" case rs = "application/rls-services+xml" case gbr = "application/rpki-ghostbusters" case mft = "application/rpki-manifest" case roa = "application/rpki-roa" case rsd = "application/rsd+xml" case rss = "application/rss+xml" case rtf = "application/rtf" case sbml = "application/sbml+xml" case scq = "application/scvp-cv-request" case scs = "application/scvp-cv-response" case spq = "application/scvp-vp-request" case spp = "application/scvp-vp-response" case sdp = "application/sdp" case setpay = "application/set-payment-initiation" case setreg = "application/set-registration-initiation" case shf = "application/shf+xml" case smi = "application/smil+xml" case rq = "application/sparql-query" case srx = "application/sparql-results+xml" case gram = "application/srgs" case grxml = "application/srgs+xml" case sru = "application/sru+xml" case ssdl = "application/ssdl+xml" case ssml = "application/ssml+xml" case tei = "application/tei+xml" case tfi = "application/thraud+xml" case tsd = "application/timestamped-data" case plb = "application/vnd.3gpp.pic-bw-large" case psb = "application/vnd.3gpp.pic-bw-small" case pvb = "application/vnd.3gpp.pic-bw-var" case tcap = "application/vnd.3gpp2.tcap" case pwn = "application/vnd.3m.post-it-notes" case aso = "application/vnd.accpac.simply.aso" case imp = "application/vnd.accpac.simply.imp" case acu = "application/vnd.acucobol" case atc = "application/vnd.acucorp" case air = "application/vnd.adobe.air-application-installer-package+zip" case fcdt = "application/vnd.adobe.formscentral.fcdt" case fxp = "application/vnd.adobe.fxp" case xdp = "application/vnd.adobe.xdp+xml" case xfdf = "application/vnd.adobe.xfdf" case ahead = "application/vnd.ahead.space" case azf = "application/vnd.airzip.filesecure.azf" case azs = "application/vnd.airzip.filesecure.azs" case azw = "application/vnd.amazon.ebook" case acc = "application/vnd.americandynamics.acc" case ami = "application/vnd.amiga.ami" case apk = "application/vnd.android.package-archive" case cii = "application/vnd.anser-web-certificate-issue-initiation" case fti = "application/vnd.anser-web-funds-transfer-initiation" case atx = "application/vnd.antix.game-component" case mpkg = "application/vnd.apple.installer+xml" case m3u8 = "application/vnd.apple.mpegurl" case swi = "application/vnd.aristanetworks.swi" case iota = "application/vnd.astraea-software.iota" case aep = "application/vnd.audiograph" case mpm = "application/vnd.blueice.multipass" case bmi = "application/vnd.bmi" case rep = "application/vnd.businessobjects" case cdxml = "application/vnd.chemdraw+xml" case mmd = "application/vnd.chipnuts.karaoke-mmd" case cdy = "application/vnd.cinderella" case cla = "application/vnd.claymore" case rp9 = "application/vnd.cloanto.rp9" case c4g = "application/vnd.clonk.c4group" case c11amc = "application/vnd.cluetrust.cartomobile-config" case c11amz = "application/vnd.cluetrust.cartomobile-config-pkg" case csp = "application/vnd.commonspace" case cdbcmsg = "application/vnd.contact.cmsg" case cmc = "application/vnd.cosmocaller" case clkx = "application/vnd.crick.clicker" case clkk = "application/vnd.crick.clicker.keyboard" case clkp = "application/vnd.crick.clicker.palette" case clkt = "application/vnd.crick.clicker.template" case clkw = "application/vnd.crick.clicker.wordbank" case wbs = "application/vnd.criticaltools.wbs+xml" case pml = "application/vnd.ctc-posml" case ppd = "application/vnd.cups-ppd" case car = "application/vnd.curl.car" case pcurl = "application/vnd.curl.pcurl" case dart = "application/vnd.dart" case rdz = "application/vnd.data-vision.rdz" case uvf = "application/vnd.dece.data" case uvt = "application/vnd.dece.ttml+xml" case uvx = "application/vnd.dece.unspecified" case uvz = "application/vnd.dece.zip" case fe_launch = "application/vnd.denovo.fcselayout-link" case dna = "application/vnd.dna" case mlp = "application/vnd.dolby.mlp" case dpg = "application/vnd.dpgraph" case dfac = "application/vnd.dreamfactory" case kpxx = "application/vnd.ds-keypoint" case ait = "application/vnd.dvb.ait" case svc = "application/vnd.dvb.service" case geo = "application/vnd.dynageo" case mag = "application/vnd.ecowin.chart" case nml = "application/vnd.enliven" case esf = "application/vnd.epson.esf" case msf = "application/vnd.epson.msf" case qam = "application/vnd.epson.quickanime" case slt = "application/vnd.epson.salt" case ssf = "application/vnd.epson.ssf" case es3 = "application/vnd.eszigno3+xml" case ez2 = "application/vnd.ezpix-album" case ez3 = "application/vnd.ezpix-package" case fdf = "application/vnd.fdf" case mseed = "application/vnd.fdsn.mseed" case seed = "application/vnd.fdsn.seed" case gph = "application/vnd.flographit" case ftc = "application/vnd.fluxtime.clip" case fm = "application/vnd.framemaker" case fnc = "application/vnd.frogans.fnc" case ltf = "application/vnd.frogans.ltf" case fsc = "application/vnd.fsc.weblaunch" case oas = "application/vnd.fujitsu.oasys" case oa2 = "application/vnd.fujitsu.oasys2" case oa3 = "application/vnd.fujitsu.oasys3" case fg5 = "application/vnd.fujitsu.oasysgp" case bh2 = "application/vnd.fujitsu.oasysprs" case ddd = "application/vnd.fujixerox.ddd" case xdw = "application/vnd.fujixerox.docuworks" case xbd = "application/vnd.fujixerox.docuworks.binder" case fzs = "application/vnd.fuzzysheet" case txd = "application/vnd.genomatix.tuxedo" case ggb = "application/vnd.geogebra.file" case ggt = "application/vnd.geogebra.tool" case gex = "application/vnd.geometry-explorer" case gxt = "application/vnd.geonext" case g2w = "application/vnd.geoplan" case g3w = "application/vnd.geospace" case gmx = "application/vnd.gmx" case kml = "application/vnd.google-earth.kml+xml" case kmz = "application/vnd.google-earth.kmz" case gqf = "application/vnd.grafeq" case gac = "application/vnd.groove-account" case ghf = "application/vnd.groove-help" case gim = "application/vnd.groove-identity-message" case grv = "application/vnd.groove-injector" case gtm = "application/vnd.groove-tool-message" case tpl = "application/vnd.groove-tool-template" case vcg = "application/vnd.groove-vcard" case hal = "application/vnd.hal+xml" case zmm = "application/vnd.handheld-entertainment+xml" case hbci = "application/vnd.hbci" case les = "application/vnd.hhe.lesson-player" case hpgl = "application/vnd.hp-hpgl" case hpid = "application/vnd.hp-hpid" case hps = "application/vnd.hp-hps" case jlt = "application/vnd.hp-jlyt" case pcl = "application/vnd.hp-pcl" case pclxl = "application/vnd.hp-pclxl" case sfdHdstx = "application/vnd.hydrostatix.sof-data" case mpy = "application/vnd.ibm.minipay" case afp = "application/vnd.ibm.modcap" case irm = "application/vnd.ibm.rights-management" case sc = "application/vnd.ibm.secure-container" case icc = "application/vnd.iccprofile" case igl = "application/vnd.igloader" case ivp = "application/vnd.immervision-ivp" case ivu = "application/vnd.immervision-ivu" case igm = "application/vnd.insors.igm" case xpw = "application/vnd.intercon.formnet" case i2g = "application/vnd.intergeo" case qbo = "application/vnd.intu.qbo" case qfx = "application/vnd.intu.qfx" case rcprofile = "application/vnd.ipunplugged.rcprofile" case irp = "application/vnd.irepository.package+xml" case xpr = "application/vnd.is-xpr" case fcs = "application/vnd.isac.fcs" case jam = "application/vnd.jam" case rms = "application/vnd.jcp.javame.midlet-rms" case jisp = "application/vnd.jisp" case joda = "application/vnd.joost.joda-archive" case ktz = "application/vnd.kahootz" case karbon = "application/vnd.kde.karbon" case chrt = "application/vnd.kde.kchart" case kfo = "application/vnd.kde.kformula" case flw = "application/vnd.kde.kivio" case kon = "application/vnd.kde.kontour" case kpr = "application/vnd.kde.kpresenter" case ksp = "application/vnd.kde.kspread" case kwd = "application/vnd.kde.kword" case htke = "application/vnd.kenameaapp" case kia = "application/vnd.kidspiration" case kne = "application/vnd.kinar" case skp = "application/vnd.koan" case sse = "application/vnd.kodak-descriptor" case lasxml = "application/vnd.las.las+xml" case lbd = "application/vnd.llamagraphics.life-balance.desktop" case lbe = "application/vnd.llamagraphics.life-balance.exchange+xml" case _123 = "application/vnd.lotus-1-2-3" case apr = "application/vnd.lotus-approach" case pre = "application/vnd.lotus-freelance" case nsf = "application/vnd.lotus-notes" case org = "application/vnd.lotus-organizer" case scm = "application/vnd.lotus-screencam" case lwp = "application/vnd.lotus-wordpro" case portpkg = "application/vnd.macports.portpkg" case mcd = "application/vnd.mcd" case mc1 = "application/vnd.medcalcdata" case cdkey = "application/vnd.mediastation.cdkey" case mwf = "application/vnd.mfer" case mfm = "application/vnd.mfmp" case flo = "application/vnd.micrografx.flo" case igx = "application/vnd.micrografx.igx" case mif = "application/vnd.mif" case daf = "application/vnd.mobius.daf" case dis = "application/vnd.mobius.dis" case mbk = "application/vnd.mobius.mbk" case mqy = "application/vnd.mobius.mqy" case msl = "application/vnd.mobius.msl" case plc = "application/vnd.mobius.plc" case txf = "application/vnd.mobius.txf" case mpn = "application/vnd.mophun.application" case mpc = "application/vnd.mophun.certificate" case xul = "application/vnd.mozilla.xul+xml" case cil = "application/vnd.ms-artgalry" case cab = "application/vnd.ms-cab-compressed" case xls = "application/vnd.ms-excel" case xlam = "application/vnd.ms-excel.addin.macroenabled.12" case xlsb = "application/vnd.ms-excel.sheet.binary.macroenabled.12" case xlsm = "application/vnd.ms-excel.sheet.macroenabled.12" case xltm = "application/vnd.ms-excel.template.macroenabled.12" case eot = "application/vnd.ms-fontobject" case chm = "application/vnd.ms-htmlhelp" case ims = "application/vnd.ms-ims" case lrm = "application/vnd.ms-lrm" case thmx = "application/vnd.ms-officetheme" case cat = "application/vnd.ms-pki.seccat" case stl = "application/vnd.ms-pki.stl" case ppt = "application/vnd.ms-powerpoint" case ppam = "application/vnd.ms-powerpoint.addin.macroenabled.12" case pptm = "application/vnd.ms-powerpoint.presentation.macroenabled.12" case sldm = "application/vnd.ms-powerpoint.slide.macroenabled.12" case ppsm = "application/vnd.ms-powerpoint.slideshow.macroenabled.12" case potm = "application/vnd.ms-powerpoint.template.macroenabled.12" case mpp = "application/vnd.ms-project" case docm = "application/vnd.ms-word.document.macroenabled.12" case dotm = "application/vnd.ms-word.template.macroenabled.12" case wps = "application/vnd.ms-works" case wpl = "application/vnd.ms-wpl" case xps = "application/vnd.ms-xpsdocument" case mseq = "application/vnd.mseq" case mus = "application/vnd.musician" case msty = "application/vnd.muvee.style" case taglet = "application/vnd.mynfc" case nlu = "application/vnd.neurolanguage.nlu" case ntf = "application/vnd.nitf" case nnd = "application/vnd.noblenet-directory" case nns = "application/vnd.noblenet-sealer" case nnw = "application/vnd.noblenet-web" case ngdat = "application/vnd.nokia.n-gage.data" case nGage = "application/vnd.nokia.n-gage.symbian.install" case rpst = "application/vnd.nokia.radio-preset" case rpss = "application/vnd.nokia.radio-presets" case edm = "application/vnd.novadigm.edm" case edx = "application/vnd.novadigm.edx" case ext = "application/vnd.novadigm.ext" case odc = "application/vnd.oasis.opendocument.chart" case otc = "application/vnd.oasis.opendocument.chart-template" case odb = "application/vnd.oasis.opendocument.database" case odf = "application/vnd.oasis.opendocument.formula" case odft = "application/vnd.oasis.opendocument.formula-template" case odg = "application/vnd.oasis.opendocument.graphics" case otg = "application/vnd.oasis.opendocument.graphics-template" case odi = "application/vnd.oasis.opendocument.image" case oti = "application/vnd.oasis.opendocument.image-template" case odp = "application/vnd.oasis.opendocument.presentation" case otp = "application/vnd.oasis.opendocument.presentation-template" case ods = "application/vnd.oasis.opendocument.spreadsheet" case ots = "application/vnd.oasis.opendocument.spreadsheet-template" case odt = "application/vnd.oasis.opendocument.text" case odm = "application/vnd.oasis.opendocument.text-master" case ott = "application/vnd.oasis.opendocument.text-template" case oth = "application/vnd.oasis.opendocument.text-web" case xo = "application/vnd.olpc-sugar" case dd2 = "application/vnd.oma.dd2+xml" case oxt = "application/vnd.openofficeorg.extension" case pptx = "application/vnd.openxmlformats-officedocument.presentationml.presentation" case sldx = "application/vnd.openxmlformats-officedocument.presentationml.slide" case ppsx = "application/vnd.openxmlformats-officedocument.presentationml.slideshow" case potx = "application/vnd.openxmlformats-officedocument.presentationml.template" case xlsx = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" case xltx = "application/vnd.openxmlformats-officedocument.spreadsheetml.template" case docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" case dotx = "application/vnd.openxmlformats-officedocument.wordprocessingml.template" case mgp = "application/vnd.osgeo.mapguide.package" case dp = "application/vnd.osgi.dp" case esa = "application/vnd.osgi.subsystem" case pdb = "application/vnd.palm" case paw = "application/vnd.pawaafile" case str = "application/vnd.pg.format" case ei6 = "application/vnd.pg.osasli" case efif = "application/vnd.picsel" case wg = "application/vnd.pmi.widget" case plf = "application/vnd.pocketlearn" case pbd = "application/vnd.powerbuilder6" case box = "application/vnd.previewsystems.box" case mgz = "application/vnd.proteus.magazine" case qps = "application/vnd.publishare-delta-tree" case ptid = "application/vnd.pvi.ptid1" case qxd = "application/vnd.quark.quarkxpress" case bed = "application/vnd.realvnc.bed" case mxl = "application/vnd.recordare.musicxml" case musicxml = "application/vnd.recordare.musicxml+xml" case cryptonote = "application/vnd.rig.cryptonote" case cod = "application/vnd.rim.cod" case rm = "application/vnd.rn-realmedia" case rmvb = "application/vnd.rn-realmedia-vbr" case link66 = "application/vnd.route66.link66+xml" case st = "application/vnd.sailingtracker.track" case see = "application/vnd.seemail" case sema = "application/vnd.sema" case semd = "application/vnd.semd" case semf = "application/vnd.semf" case ifm = "application/vnd.shana.informed.formdata" case itp = "application/vnd.shana.informed.formtemplate" case iif = "application/vnd.shana.informed.interchange" case ipk = "application/vnd.shana.informed.package" case twd = "application/vnd.simtech-mindmapper" case mmf = "application/vnd.smaf" case teacher = "application/vnd.smart.teacher" case sdkm = "application/vnd.solent.sdkm+xml" case dxp = "application/vnd.spotfire.dxp" case sfs = "application/vnd.spotfire.sfs" case sdc = "application/vnd.stardivision.calc" case sda = "application/vnd.stardivision.draw" case sdd = "application/vnd.stardivision.impress" case smf = "application/vnd.stardivision.math" case sdw = "application/vnd.stardivision.writer" case sgl = "application/vnd.stardivision.writer-global" case smzip = "application/vnd.stepmania.package" case sm = "application/vnd.stepmania.stepchart" case sxc = "application/vnd.sun.xml.calc" case stc = "application/vnd.sun.xml.calc.template" case sxd = "application/vnd.sun.xml.draw" case std = "application/vnd.sun.xml.draw.template" case sxi = "application/vnd.sun.xml.impress" case sti = "application/vnd.sun.xml.impress.template" case sxm = "application/vnd.sun.xml.math" case sxw = "application/vnd.sun.xml.writer" case sxg = "application/vnd.sun.xml.writer.global" case stw = "application/vnd.sun.xml.writer.template" case sus = "application/vnd.sus-calendar" case svd = "application/vnd.svd" case sis = "application/vnd.symbian.install" case xsm = "application/vnd.syncml+xml" case bdm = "application/vnd.syncml.dm+wbxml" case xdm = "application/vnd.syncml.dm+xml" case tao = "application/vnd.tao.intent-module-archive" case pcap = "application/vnd.tcpdump.pcap" case tmo = "application/vnd.tmobile-livetv" case tpt = "application/vnd.trid.tpt" case mxs = "application/vnd.triscape.mxs" case tra = "application/vnd.trueapp" case ufd = "application/vnd.ufdl" case utz = "application/vnd.uiq.theme" case umj = "application/vnd.umajin" case unityweb = "application/vnd.unity" case uoml = "application/vnd.uoml+xml" case vcx = "application/vnd.vcx" case vsd = "application/vnd.visio" case vis = "application/vnd.visionary" case vsf = "application/vnd.vsf" case wbxml = "application/vnd.wap.wbxml" case wmlc = "application/vnd.wap.wmlc" case wmlsc = "application/vnd.wap.wmlscriptc" case wtb = "application/vnd.webturbo" case nbp = "application/vnd.wolfram.player" case wpd = "application/vnd.wordperfect" case wqd = "application/vnd.wqd" case stf = "application/vnd.wt.stf" case xar = "application/vnd.xara" case xfdl = "application/vnd.xfdl" case hvd = "application/vnd.yamaha.hv-dic" case hvs = "application/vnd.yamaha.hv-script" case hvp = "application/vnd.yamaha.hv-voice" case osf = "application/vnd.yamaha.openscoreformat" case osfpvg = "application/vnd.yamaha.openscoreformat.osfpvg+xml" case saf = "application/vnd.yamaha.smaf-audio" case spf = "application/vnd.yamaha.smaf-phrase" case cmp = "application/vnd.yellowriver-custom-menu" case zir = "application/vnd.zul" case zaz = "application/vnd.zzazz.deck+xml" case vxml = "application/voicexml+xml" case wgt = "application/widget" case hlp = "application/winhlp" case wsdl = "application/wsdl+xml" case wspolicy = "application/wspolicy+xml" case _7z = "application/x-7z-compressed" case abw = "application/x-abiword" case ace = "application/x-ace-compressed" case dmg = "application/x-apple-diskimage" case aab = "application/x-authorware-bin" case aam = "application/x-authorware-map" case aas = "application/x-authorware-seg" case bcpio = "application/x-bcpio" case torrent = "application/x-bittorrent" case blb = "application/x-blorb" case bz = "application/x-bzip" case bz2 = "application/x-bzip2" case cbr = "application/x-cbr" case vcd = "application/x-cdlink" case cfs = "application/x-cfs-compressed" case chat = "application/x-chat" case pgn = "application/x-chess-pgn" case nsc = "application/x-conference" case cpio = "application/x-cpio" case csh = "application/x-csh" case deb = "application/x-debian-package" case dgc = "application/x-dgc-compressed" case dir = "application/x-director" case wad = "application/x-doom" case ncx = "application/x-dtbncx+xml" case dtb = "application/x-dtbook+xml" case res = "application/x-dtbresource+xml" case dvi = "application/x-dvi" case evy = "application/x-envoy" case eva = "application/x-eva" case bdf = "application/x-font-bdf" case gsf = "application/x-font-ghostscript" case psf = "application/x-font-linux-psf" case pcf = "application/x-font-pcf" case snf = "application/x-font-snf" case pfa = "application/x-font-type1" case arc = "application/x-freearc" case spl = "application/x-futuresplash" case gca = "application/x-gca-compressed" case ulx = "application/x-glulx" case gnumeric = "application/x-gnumeric" case gramps = "application/x-gramps-xml" case gtar = "application/x-gtar" case hdf = "application/x-hdf" case install = "application/x-install-instructions" case iso = "application/x-iso9660-image" case jnlp = "application/x-java-jnlp-file" case latex = "application/x-latex" case lzh = "application/x-lzh-compressed" case mie = "application/x-mie" case prc = "application/x-mobipocket-ebook" case application = "application/x-ms-application" case lnk = "application/x-ms-shortcut" case wmd = "application/x-ms-wmd" case wmz = "application/x-ms-wmz" case xbap = "application/x-ms-xbap" case mdb = "application/x-msaccess" case obd = "application/x-msbinder" case crd = "application/x-mscardfile" case clp = "application/x-msclip" case exe = "application/x-msdownload" case mvb = "application/x-msmediaview" case wmf = "application/x-msmetafile" case mny = "application/x-msmoney" case pub = "application/x-mspublisher" case scd = "application/x-msschedule" case trm = "application/x-msterminal" case wri = "application/x-mswrite" case nc = "application/x-netcdf" case nzb = "application/x-nzb" case p12 = "application/x-pkcs12" case p7b = "application/x-pkcs7-certificates" case p7r = "application/x-pkcs7-certreqresp" case rar = "application/x-rar-compressed" case ris = "application/x-research-info-systems" case sh = "application/x-sh" case shar = "application/x-shar" case swf = "application/x-shockwave-flash" case xap = "application/x-silverlight-app" case sql = "application/x-sql" case sit = "application/x-stuffit" case sitx = "application/x-stuffitx" case srt = "application/x-subrip" case sv4cpio = "application/x-sv4cpio" case sv4crc = "application/x-sv4crc" case t3 = "application/x-t3vm-image" case gam = "application/x-tads" case tar = "application/x-tar" case tcl = "application/x-tcl" case tex = "application/x-tex" case tfm = "application/x-tex-tfm" case texinfo = "application/x-texinfo" case obj = "application/x-tgif" case ustar = "application/x-ustar" case src = "application/x-wais-source" case der = "application/x-x509-ca-cert" case fig = "application/x-xfig" case xlf = "application/x-xliff+xml" case xpi = "application/x-xpinstall" case xz = "application/x-xz" case z1 = "application/x-zmachine" case xaml = "application/xaml+xml" case xdf = "application/xcap-diff+xml" case xenc = "application/xenc+xml" case xhtml = "application/xhtml+xml" case xml = "application/xml" case dtd = "application/xml-dtd" case xop = "application/xop+xml" case xpl = "application/xproc+xml" case xslt = "application/xslt+xml" case xspf = "application/xspf+xml" case mxml = "application/xv+xml" case yang = "application/yang" case yin = "application/yin+xml" case zip = "application/zip" case adp = "audio/adpcm" case au = "audio/basic" case mid = "audio/midi" case m4a = "audio/mp4" case mpga = "audio/mpeg" case oga = "audio/ogg" case s3m = "audio/s3m" case sil = "audio/silk" case uva = "audio/vnd.dece.audio" case eol = "audio/vnd.digital-winds" case dra = "audio/vnd.dra" case dts = "audio/vnd.dts" case dtshd = "audio/vnd.dts.hd" case lvp = "audio/vnd.lucent.voice" case pya = "audio/vnd.ms-playready.media.pya" case ecelp4800 = "audio/vnd.nuera.ecelp4800" case ecelp7470 = "audio/vnd.nuera.ecelp7470" case ecelp9600 = "audio/vnd.nuera.ecelp9600" case rip = "audio/vnd.rip" case weba = "audio/webm" case aac = "audio/x-aac" case aif = "audio/x-aiff" case caf = "audio/x-caf" case flac = "audio/x-flac" case mka = "audio/x-matroska" case m3u = "audio/x-mpegurl" case wax = "audio/x-ms-wax" case wma = "audio/x-ms-wma" case ram = "audio/x-pn-realaudio" case rmp = "audio/x-pn-realaudio-plugin" case wav = "audio/x-wav" case xm = "audio/xm" case cdx = "chemical/x-cdx" case cif = "chemical/x-cif" case cmdf = "chemical/x-cmdf" case cml = "chemical/x-cml" case csml = "chemical/x-csml" case xyz = "chemical/x-xyz" case ttc = "font/collection" case otf = "font/otf" case ttf = "font/ttf" case woff = "font/woff" case woff2 = "font/woff2" case bmp = "image/bmp" case cgm = "image/cgm" case g3 = "image/g3fax" case gif = "image/gif" case ief = "image/ief" case jpeg = "image/jpeg" case ktx = "image/ktx" case png = "image/png" case btif = "image/prs.btif" case sgi = "image/sgi" case svg = "image/svg+xml" case tiff = "image/tiff" case psd = "image/vnd.adobe.photoshop" case uvi = "image/vnd.dece.graphic" case djvu = "image/vnd.djvu" case sub = "image/vnd.dvb.subtitle" case dwg = "image/vnd.dwg" case dxf = "image/vnd.dxf" case fbs = "image/vnd.fastbidsheet" case fpx = "image/vnd.fpx" case fst = "image/vnd.fst" case mmr = "image/vnd.fujixerox.edmics-mmr" case rlc = "image/vnd.fujixerox.edmics-rlc" case mdi = "image/vnd.ms-modi" case wdp = "image/vnd.ms-photo" case npx = "image/vnd.net-fpx" case wbmp = "image/vnd.wap.wbmp" case xif = "image/vnd.xiff" case webp = "image/webp" case _3ds = "image/x-3ds" case ras = "image/x-cmu-raster" case cmx = "image/x-cmx" case fh = "image/x-freehand" case ico = "image/x-icon" case sid = "image/x-mrsid-image" case pcx = "image/x-pcx" case pic = "image/x-pict" case pnm = "image/x-portable-anymap" case pbm = "image/x-portable-bitmap" case pgm = "image/x-portable-graymap" case ppm = "image/x-portable-pixmap" case rgb = "image/x-rgb" case tga = "image/x-tga" case xbm = "image/x-xbitmap" case xpm = "image/x-xpixmap" case xwd = "image/x-xwindowdump" case eml = "message/rfc822" case igs = "model/iges" case msh = "model/mesh" case dae = "model/vnd.collada+xml" case dwf = "model/vnd.dwf" case gdl = "model/vnd.gdl" case gtw = "model/vnd.gtw" case mts = "model/vnd.mts" case vtu = "model/vnd.vtu" case wrl = "model/vrml" case x3db = "model/x3d+binary" case x3dv = "model/x3d+vrml" case x3d = "model/x3d+xml" case appcache = "text/cache-manifest" case ics = "text/calendar" case css = "text/css" case csv = "text/csv" case html = "text/html" case n3 = "text/n3" case txt = "text/plain" case dsc = "text/prs.lines.tag" case rtx = "text/richtext" case sgml = "text/sgml" case tsv = "text/tab-separated-values" case t = "text/troff" case ttl = "text/turtle" case uri = "text/uri-list" case vcard = "text/vcard" case curl = "text/vnd.curl" case dcurl = "text/vnd.curl.dcurl" case mcurl = "text/vnd.curl.mcurl" case scurl = "text/vnd.curl.scurl" case fly = "text/vnd.fly" case flx = "text/vnd.fmi.flexstor" case gv = "text/vnd.graphviz" case _3dml = "text/vnd.in3d.3dml" case spot = "text/vnd.in3d.spot" case jad = "text/vnd.sun.j2me.app-descriptor" case wml = "text/vnd.wap.wml" case wmls = "text/vnd.wap.wmlscript" case s = "text/x-asm" case c = "text/x-c" case f = "text/x-fortran" case java = "text/x-java-source" case nfo = "text/x-nfo" case opml = "text/x-opml" case p = "text/x-pascal" case etx = "text/x-setext" case sfv = "text/x-sfv" case uu = "text/x-uuencode" case vcs = "text/x-vcalendar" case vcf = "text/x-vcard" case _3gp = "video/3gpp" case _3g2 = "video/3gpp2" case h261 = "video/h261" case h263 = "video/h263" case h264 = "video/h264" case jpgv = "video/jpeg" case jpm = "video/jpm" case mj2 = "video/mj2" case mp4 = "video/mp4" case mpeg = "video/mpeg" case ogv = "video/ogg" case qt = "video/quicktime" case uvh = "video/vnd.dece.hd" case uvm = "video/vnd.dece.mobile" case uvp = "video/vnd.dece.pd" case uvs = "video/vnd.dece.sd" case uvv = "video/vnd.dece.video" case dvb = "video/vnd.dvb.file" case fvt = "video/vnd.fvt" case mxu = "video/vnd.mpegurl" case pyv = "video/vnd.ms-playready.media.pyv" case uvu = "video/vnd.uvvu.mp4" case viv = "video/vnd.vivo" case webm = "video/webm" case f4v = "video/x-f4v" case fli = "video/x-fli" case flv = "video/x-flv" case m4v = "video/x-m4v" case mkv = "video/x-matroska" case mng = "video/x-mng" case asf = "video/x-ms-asf" case vob = "video/x-ms-vob" case wm = "video/x-ms-wm" case wmv = "video/x-ms-wmv" case wmx = "video/x-ms-wmx" case wvx = "video/x-ms-wvx" case avi = "video/x-msvideo" case movie = "video/x-sgi-movie" case smv = "video/x-smv" case ice = "x-conference/x-cooltalk" }
mit
455ee0fbe07e6acac7b5d3e581fa9c18
38.877238
143
0.733797
2.635926
false
false
false
false
codefellows/sea-b23-iOS
Hipstagram/Hipstagram/ViewController.swift
1
5995
// // ViewController.swift // Hipstagram // // Created by Bradley Johnson on 10/15/14. // Copyright (c) 2014 Code Fellows. All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, GalleryDelegate, UICollectionViewDataSource { var managedObjectContext : NSManagedObjectContext! var filters : [Filter]? var thumbnailContainers = [ThumbnailContainer]() var originalThumbnail : UIImage? var gpuContext : CIContext? var imageQueue = NSOperationQueue() @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var collectionViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() //get gpu context var options = [kCIContextWorkingColorSpace : NSNull()] var myEAGLContext = EAGLContext(API: EAGLRenderingAPI.OpenGLES2) self.gpuContext = CIContext(EAGLContext: myEAGLContext, options: options) let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate self.managedObjectContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "Filter") var error : NSError? //first fetch to see if we have anything in the database if let filters = self.managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as? [Filter] { //checking if that fetch produced any items if filters.isEmpty { //its empty, now we gotta seed it self.seedCoreData() self.filters = self.managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as? [Filter] } else { self.filters = filters } } self.collectionView.dataSource = self } func seedCoreData() { //var newFilter = Filter() //this wont work! var sepiaFilter = NSEntityDescription.insertNewObjectForEntityForName("Filter", inManagedObjectContext: self.managedObjectContext) as Filter sepiaFilter.name = "CISepiaTone" sepiaFilter.favorited = true var gaussianBlurFilter = NSEntityDescription.insertNewObjectForEntityForName("Filter", inManagedObjectContext: self.managedObjectContext) as Filter gaussianBlurFilter.name = "CIGaussianBlur" gaussianBlurFilter.favorited = false var error : NSError? //this attempts to save everything in the context into the database self.managedObjectContext.save(&error) if error != nil { println(error!.localizedDescription) } } func resetThumbnails() { //first we generate the thumbnail from the image that was selected var size = CGSize(width: 100, height: 100) UIGraphicsBeginImageContext(size) self.imageView.image?.drawInRect(CGRect(x: 0, y: 0, width: 100, height: 100)) self.originalThumbnail = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() //now we need to setup our thumbnail containers var newThumbnailContainers = [ThumbnailContainer]() for var index = 0; index < self.filters?.count; ++index { let filter = self.filters![index] var thumbnailContainer = ThumbnailContainer(filterName: filter.name, thumbNail: self.originalThumbnail!, queue: self.imageQueue, context: self.gpuContext!) newThumbnailContainers.append(thumbnailContainer) } self.thumbnailContainers = newThumbnailContainers self.collectionView.reloadData() } @IBAction func hipmePressed(sender: AnyObject) { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let galleryAction = UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default) { (action) -> Void in self.performSegueWithIdentifier("SHOW_GALLERY", sender: self) } let photosActions = UIAlertAction(title: "Photos Framework", style: .Default) { (action) -> Void in self.performSegueWithIdentifier("SHOW_PHOTOS_FRAMEWORK", sender: self) } alertController.addAction(galleryAction) alertController.addAction(photosActions) self.presentViewController(alertController, animated: true, completion: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "SHOW_GALLERY" { let galleryVC = segue.destinationViewController as GalleryViewController galleryVC.delegate = self } } func userDidSelectPhoto(image: UIImage) { self.imageView.image = image self.resetThumbnails() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.thumbnailContainers.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("THUMBNAIL_CELL", forIndexPath: indexPath) as ThumbnailCell let thumbnailContainer = self.thumbnailContainers[indexPath.row] if thumbnailContainer.filteredThumbnail != nil { cell.imageView.image = thumbnailContainer.filteredThumbnail } else { cell.imageView.image = thumbnailContainer.originalThumbnail thumbnailContainer.generateFilterThumbnail({ (filteredThumb) -> (Void) in if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ThumbnailCell { cell.imageView.image = filteredThumb } }) } return cell } }
mit
ff6217f98e97cd65856dead2e9e823bd
40.631944
167
0.669725
5.530443
false
false
false
false
zhangzichen/Pontus
Pontus/UIKit+Pontus/UICollectionView+Pontus.swift
1
2154
// // UICollectionView+Halo.swift // Halo // // Created by 王策 on 15/10/24. // Copyright © 2015年 WangCe. All rights reserved. // import UIKit public extension UICollectionView { /// 为 UICollectionView 绑定某种类型的 UITableViewCell @discardableResult func registerCellClass<T: UICollectionViewCell>(_ cellClass: T.Type) -> Self { register(cellClass, forCellWithReuseIdentifier: cellClass.reuseIdentifier) return self } /// 取某种类型的 UICollectionViewCell @discardableResult func dequeueCell<T: UICollectionViewCell>(_ cell: T.Type, indexPath: IndexPath) -> T { return dequeueReusableCell(withReuseIdentifier: cell.reuseIdentifier, for: indexPath) as! T } /// 同时设置 dataSource 和 delegate @discardableResult func dataSourceAndDelegate(_ dataSourceAndDelegate:UICollectionViewDelegate & UICollectionViewDataSource) -> Self { dataSource = dataSourceAndDelegate (self as UICollectionView).delegate = dataSourceAndDelegate return self } var dataSourceAndDelegate : (UICollectionViewDelegate & UICollectionViewDataSource)? { get { guard let dataSource = dataSource else { ccLogWarning("DataSource is nil") return nil } guard let delegate = delegate else { ccLogWarning("Delegate is nil") return nil } if dataSource.isEqual(delegate) { return (dataSource as? UICollectionViewDelegate & UICollectionViewDataSource)! } else { ccLogWarning("DataSource is \(dataSource)\n", "Delegate is \(delegate)\n", "They are different") return nil } } set { self.dataSource = newValue (self as UICollectionView).delegate = newValue } } } extension UICollectionViewCell { /// 返回 "Halo.ReuseIdentifier.YOUR_CLASS_NAME" static var reuseIdentifier: String { return "Pontus.ReuseIdentifier." + String(describing: self) } }
mit
5b3956f7cedceb059aceee4deb6caadb
31.890625
119
0.629454
5.481771
false
false
false
false
royliu1990/EasyAnimationSwift
EasyAnimationSwift/EASKeyValues.swift
1
2327
// // EASKeyValues.swift // MegaBoxDemo // // Created by royliu1990 on 2016/12/28. // Copyright © 2016年 royliu1990. All rights reserved. // import UIKit class EASKeyValues:NSObject { public let popvalue = (type:"transform.scale",values:[1,0.8,1.1,1.0],beginTime:1,duration:0.2,autoreverses:false,repeatCount:0) class func dampingCal(_ _A:Double,_ D:Double) ->(values:[Double],keyTimes:[Double]) { var A = _A var x = [Double]() var t = [Double]() var i = -1 var s:Double = 0.0 x.append(1.0) t.append(0) x.append(1.0.advanced(by:A.multiplied(by: Double(i)))) t.append(Double(A)) s+=Double(A) A = A*(1-D) while(A>D/10) { i = -i x.append(1.0.advanced(by:A.multiplied(by: Double(i)))) t.append(t.last! + A + A/(1-D)) s += A + A/(1-D) A = A*(1-D) } x.append(1.0) s += A/(1-D) t.append(s) t = t.map{return $0/s} return (x,t) } class func fanShaped(center:CGPoint,startRadius:Double,endRadius:Double,startAngle:Double,endAngle:Double,density:Int,fractalRates:[Double]) -> [[CGPoint]]{ let deltaAngle = (endAngle - startAngle).divided(by: Double(density - 1)) let deltaRadius = (endRadius - startRadius).divided(by: Double(density - 1)) var shape = [[CGPoint]]() for i in 0 ..< density { let point = center.polarPosition(angle: CGFloat(startAngle.advanced(by: deltaAngle.multiplied(by: Double(i)))), radius: CGFloat(startRadius.advanced(by: deltaRadius.multiplied(by: Double(i))))) var values = [CGPoint]() for j in 0 ..< fractalRates.count { values.append(point.pointScale(origin: center, scale: CGFloat(fractalRates[j]))) } shape.append(values) } return shape } }
mit
200faa01a31a2d64aa74122d28c909a0
21.784314
205
0.466007
4.013817
false
false
false
false
pikachu987/PKCAlertView
PKCAlertView/Classes/Extension+.swift
1
2131
//Copyright (c) 2017 pikachu987 <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import UIKit extension UIColor{ public static let alertDefault = UIColor(red: 0, green: 0.48, blue: 1, alpha: 1) public static let alertCancel = UIColor(red: 1, green: 0.23, blue: 0.19, alpha: 1) } extension UIEdgeInsets{ static let pkcAlertTopEdge = UIEdgeInsetsMake(16, 16, 2, 16) static let pkcAlertBottomEdge = UIEdgeInsetsMake(2, 16, 16, 16) static let pkcAlertDefaultEdge = UIEdgeInsetsMake(16, 16, 16, 16) } extension UIView{ func horizontalLayout(left: CGFloat = 0, right: CGFloat = 0) -> [NSLayoutConstraint]{ return NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(left)-[view]-\(right)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": self]) } func verticalLayout(top: CGFloat = 0, bottom: CGFloat = 0) -> [NSLayoutConstraint]{ return NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(top)-[view]-\(bottom)-|", options: NSLayoutFormatOptions.alignAllLeading, metrics: nil, views: ["view": self]) } }
mit
081272979e9493a9a646afdf056a24f7
46.355556
181
0.740028
4.236581
false
false
false
false
gemmakbarlow/swiftris
swiftris/swiftris/GameViewController.swift
1
5353
// // GameViewController.swift // swiftris // // Created by Gemma Barlow on 8/20/14. // Copyright (c) 2014 Gemma Barlow. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController, SwiftrisGameDelegate, UIGestureRecognizerDelegate { @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var levelLabel: UILabel! var scene: GameScene! var swiftris:SwiftrisGame! var panPointReference:CGPoint? override func viewDidLoad() { super.viewDidLoad() let currentView = view as! SKView currentView.isMultipleTouchEnabled = false scene = GameScene(size: currentView.bounds.size) scene.scaleMode = .aspectFill scene.tick = didTick swiftris = SwiftrisGame() swiftris.delegate = self swiftris.beginGame() currentView.presentScene(scene) } func didTick() { swiftris.letShapeFall() } override var prefersStatusBarHidden : Bool { return true } // MARK: - SwiftrisGameDelegate func nextShape() { let newShapes = swiftris.newShape() if let fallingShape = newShapes.fallingShape { self.scene.addPreviewShapeToScene(newShapes.nextShape!) {} self.scene.movePreviewShape(fallingShape) { self.view.isUserInteractionEnabled = true self.scene.startTicking() } } } func gameDidBegin(_ swiftris: SwiftrisGame) { levelLabel.text = "\(swiftris.level)" scoreLabel.text = "\(swiftris.score)" scene.tickLengthMillis = TickLengthLevelOne // The following is false when restarting a new game if swiftris.nextShape != nil && swiftris.nextShape!.blocks[0].sprite == nil { scene.addPreviewShapeToScene(swiftris.nextShape!) { self.nextShape() } } else { nextShape() } } func gameDidEnd(_ swiftris: SwiftrisGame) { view.isUserInteractionEnabled = false scene.stopTicking() scene.playSound("gameover.mp3") scene.animateCollapsingLines(swiftris.removeAllBlocks(), fallenBlocks: Array<Array<Block>>()) { swiftris.beginGame() } } func gameDidLevelUp(_ swiftris: SwiftrisGame) { levelLabel.text = "\(swiftris.level)" if scene.tickLengthMillis >= 100 { scene.tickLengthMillis -= 100 } else if scene.tickLengthMillis > 50 { scene.tickLengthMillis -= 50 } scene.playSound("levelup.mp3") } func gameShapeDidDrop(_ swiftris: SwiftrisGame) { scene.stopTicking() scene.redrawShape(swiftris.fallingShape!) { swiftris.letShapeFall() } scene.playSound("drop.mp3") } func gameShapeDidLand(_ swiftris: SwiftrisGame) { scene.stopTicking() self.view.isUserInteractionEnabled = false // #1 let removedLines = swiftris.removeCompletedLines() if removedLines.linesRemoved.count > 0 { self.scoreLabel.text = "\(swiftris.score)" scene.animateCollapsingLines(removedLines.linesRemoved, fallenBlocks:removedLines.fallenBlocks) { // #2 self.gameShapeDidLand(swiftris) } scene.playSound("bomb.mp3") } else { nextShape() } } func gameShapeDidMove(_ swiftris: SwiftrisGame) { scene.redrawShape(swiftris.fallingShape!) {} } // MARK: - Actions @IBAction func didTap(_ sender: AnyObject) { swiftris.rotateShape() } @IBAction func didPan(_ sender: UIPanGestureRecognizer) { let currentPoint = sender.translation(in: self.view) if let originalPoint = panPointReference { if abs(currentPoint.x - originalPoint.x) > (BlockSize * 0.9) { if sender.velocity(in: self.view).x > CGFloat(0) { swiftris.moveShapeRight() panPointReference = currentPoint } else { swiftris.moveShapeLeft() panPointReference = currentPoint } } } else if sender.state == .began { panPointReference = currentPoint } } @IBAction func didSwipeDown(_ sender: AnyObject) { swiftris.dropShape() } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { if let _ = gestureRecognizer as? UISwipeGestureRecognizer { if let _ = otherGestureRecognizer as? UIPanGestureRecognizer { return true } } else if let _ = gestureRecognizer as? UIPanGestureRecognizer { if let _ = otherGestureRecognizer as? UITapGestureRecognizer { return true } } return false } }
mit
653456323ace74932f9d9b0c60da0854
28.738889
157
0.590136
5.01687
false
false
false
false
Sorix/CloudCore
Source/Classes/Fetch/PublicSubscriptions/PublicDatabaseSubscriptions.swift
1
4332
// // PublicDatabaseSubscriptions.swift // CloudCore // // Created by Vasily Ulianov on 13/03/2017. // Copyright © 2017 Vasily Ulianov. All rights reserved. // import CloudKit // TODO: Temporarily disabled, in development /// Use that class to manage subscriptions to public CloudKit database. /// If you want to sync some records with public database you need to subsrcibe for notifications on that changes to enable iCloud -> Local database syncing. //class PublicDatabaseSubscriptions { // // private static var userDefaultsKey: String { return CloudCore.config.userDefaultsKeyTokens } // private static var prefix: String { return CloudCore.config.publicSubscriptionIDPrefix } // // internal(set) static var cachedIDs = UserDefaults.standard.stringArray(forKey: userDefaultsKey) ?? [String]() // // /// Create `CKQuerySubscription` for public database, use it if you want to enable syncing public iCloud -> Core Data // /// // /// - Parameters: // /// - recordType: The string that identifies the type of records to track. You are responsible for naming your app’s record types. This parameter must not be empty string. // /// - predicate: The matching criteria to apply to the records. This parameter must not be nil. For information about the operators that are supported in search predicates, see the discussion in [CKQuery](apple-reference-documentation://hsDjQFvil9). // /// - completion: returns subscriptionID and error upon operation completion // static func subscribe(recordType: String, predicate: NSPredicate, completion: ((_ subscriptionID: String, _ error: Error?) -> Void)?) { // let id = prefix + UUID().uuidString // let subscription = CKQuerySubscription(recordType: recordType, predicate: predicate, subscriptionID: id, options: [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]) // // let notificationInfo = CKNotificationInfo() // notificationInfo.shouldSendContentAvailable = true // subscription.notificationInfo = notificationInfo // // let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: []) // operation.modifySubscriptionsCompletionBlock = { _, _, error in // if error == nil { // self.cachedIDs.append(subscription.subscriptionID) // UserDefaults.standard.set(self.cachedIDs, forKey: self.userDefaultsKey) // UserDefaults.standard.synchronize() // } // // completion?(subscription.subscriptionID, error) // } // // operation.timeoutIntervalForResource = 20 // CKContainer.default().publicCloudDatabase.add(operation) // } // // /// Unsubscribe from public database // /// // /// - Parameters: // /// - subscriptionID: id of subscription to remove // static func unsubscribe(subscriptionID: String, completion: ((Error?) -> Void)?) { // let operation = CKModifySubscriptionsOperation(subscriptionsToSave: [], subscriptionIDsToDelete: [subscriptionID]) // operation.modifySubscriptionsCompletionBlock = { _, _, error in // if error == nil { // if let index = self.cachedIDs.index(of: subscriptionID) { // self.cachedIDs.remove(at: index) // } // UserDefaults.standard.set(self.cachedIDs, forKey: self.userDefaultsKey) // UserDefaults.standard.synchronize() // } // // completion?(error) // } // // operation.timeoutIntervalForResource = 20 // CKContainer.default().publicCloudDatabase.add(operation) // } // // // /// Refresh local `cachedIDs` variable with actual data from CloudKit. // /// Recommended to use after application's UserDefaults reset. // /// // /// - Parameter completion: called upon operation completion, contains list of CloudCore subscriptions and error // static func refreshCache(errorCompletion: ErrorBlock? = nil, successCompletion: (([CKSubscription]) -> Void)? = nil) { // let operation = FetchPublicSubscriptionsOperation() // operation.errorBlock = errorCompletion // operation.fetchCompletionBlock = { subscriptions in // self.setCache(from: subscriptions) // successCompletion?(subscriptions) // } // operation.start() // } // // internal static func setCache(from subscriptions: [CKSubscription]) { // let ids = subscriptions.map { $0.subscriptionID } // self.cachedIDs = ids // // UserDefaults.standard.set(ids, forKey: self.userDefaultsKey) // UserDefaults.standard.synchronize() // } //}
mit
baaebcccd61f9e21625082882fbcbc34
44.09375
254
0.733426
4.008333
false
false
false
false
apple/swift
test/IRGen/objc_protocols.swift
1
11784
// RUN: %empty-directory(%t) // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t %S/Inputs/objc_protocols_Bas.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module > %t/out.ir // RUN: %FileCheck --input-file=%t/out.ir %s --check-prefix=CHECK --check-prefix=CHECK-%target-os // REQUIRES: PTRSIZE=64 // REQUIRES: objc_interop import gizmo import objc_protocols_Bas // -- Protocol "Frungible" inherits only objc protocols and should have no // out-of-line inherited witnesses in its witness table. // CHECK: [[ZIM_FRUNGIBLE_WITNESS:@"\$s14objc_protocols3ZimCAA9FrungibleAAWP"]] = hidden constant [2 x i8*] [ // CHECK: i8* bitcast ({{.*}}* @"$s14objc_protocols3ZimCAA9FrungibleA2aDP6frungeyyFTW{{(\.ptrauth)?}}" to i8*) // CHECK: ] protocol Ansible { func anse() } class Foo : NSRuncing, NSFunging, Ansible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func anse() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Foo = internal constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3FooC5runceyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3FooC5fungeyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3FooC3fooyyFTo{{(\.ptrauth)?}}" to i8*) // CHECK: }] // CHECK: }, section "__DATA, {{.*}}", align 8 class Bar { func bar() {} } // -- Bar does not directly have objc methods... // CHECK-NOT: @_INSTANCE_METHODS_Bar extension Bar : NSRuncing, NSFunging { @objc func runce() {} @objc func funge() {} @objc func foo() {} func notObjC() {} } // -- ...but the ObjC protocol conformances on its extension add some // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC14objc_protocols3Bar_$_objc_protocols" = internal constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3BarC5runceyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3BarC5fungeyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3BarC3fooyyFTo{{(\.ptrauth)?}}" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // -- The runce() implementation comes from the original definition. @objc public func foo() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas3Bas_$_objc_protocols" = internal constant { i32, i32, [1 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 1, // CHECK: [1 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s18objc_protocols_Bas0C0C0a1_B0E3fooyyFTo{{(\.ptrauth)?}}" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // -- Swift protocol refinement of ObjC protocols. protocol Frungible : NSRuncing, NSFunging { func frunge() } class Zim : Frungible { @objc func runce() {} @objc func funge() {} @objc func foo() {} func frunge() {} } // CHECK: @_INSTANCE_METHODS__TtC14objc_protocols3Zim = internal constant { i32, i32, [3 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 3, // CHECK: [3 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3ZimC5runceyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(funge)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3ZimC5fungeyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s14objc_protocols3ZimC3fooyyFTo{{(\.ptrauth)?}}" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 // class Zang from objc_protocols_Bas module extension Zang : Frungible { @objc public func runce() {} // funge() implementation from original definition of Zang @objc public func foo() {} func frunge() {} } // CHECK: @"_CATEGORY_INSTANCE_METHODS__TtC18objc_protocols_Bas4Zang_$_objc_protocols" = internal constant { i32, i32, [2 x { i8*, i8*, i8* }] } { // CHECK: i32 24, i32 2, // CHECK: [2 x { i8*, i8*, i8* }] [ // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(runce)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s18objc_protocols_Bas4ZangC0a1_B0E5runceyyFTo{{(\.ptrauth)?}}" to i8*) }, // CHECK: { i8*, i8*, i8* } { i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(foo)", i64 0, i64 0), i8* getelementptr inbounds ([8 x i8], [8 x i8]* @".str.7.v16@0:8", i64 0, i64 0), i8* bitcast ({{.*}}* @"$s18objc_protocols_Bas4ZangC0a1_B0E3fooyyFTo{{(\.ptrauth)?}}" to i8*) } // CHECK: ] // CHECK: }, section "__DATA, {{.*}}", align 8 @objc protocol BaseProtocol { } protocol InheritingProtocol : BaseProtocol { } // -- Make sure that base protocol conformance is registered // CHECK: @_PROTOCOLS__TtC14objc_protocols17ImplementingClass {{.*}} @_PROTOCOL__TtP14objc_protocols12BaseProtocol_ class ImplementingClass : InheritingProtocol { } // CHECK-linux: @_PROTOCOL_PROTOCOLS_NSDoubleInheritedFunging = weak hidden constant{{.*}}i64 2{{.*}} @_PROTOCOL_NSFungingAndRuncing {{.*}}@_PROTOCOL_NSFunging // CHECK-macosx: @"_OBJC_$_PROTOCOL_REFS_NSDoubleInheritedFunging" = internal global{{.*}}i64 2{{.*}} @"_OBJC_PROTOCOL_$_NSFungingAndRuncing"{{.*}} @"_OBJC_PROTOCOL_$_NSFunging" // -- Force generation of witness for Zim. // CHECK: define hidden swiftcc { %objc_object*, i8** } @"$s14objc_protocols22mixed_heritage_erasure{{[_0-9a-zA-Z]*}}F" func mixed_heritage_erasure(_ x: Zim) -> Frungible { return x // CHECK: [[T0:%.*]] = insertvalue { %objc_object*, i8** } undef, %objc_object* {{%.*}}, 0 // CHECK: insertvalue { %objc_object*, i8** } [[T0]], i8** getelementptr inbounds ([2 x i8*], [2 x i8*]* [[ZIM_FRUNGIBLE_WITNESS]], i32 0, i32 0), 1 } // CHECK-LABEL: define hidden swiftcc void @"$s14objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) {{.*}} { func objc_generic<T : NSRuncing>(_ x: T) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK-LABEL: define hidden swiftcc void @"$s14objc_protocols05call_A8_generic{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) {{.*}} { // CHECK: call swiftcc void @"$s14objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) func call_objc_generic<T : NSRuncing>(_ x: T) { objc_generic(x) } // CHECK-LABEL: define hidden swiftcc void @"$s14objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F"(%objc_object* %0) {{.*}} { func objc_protocol(_ x: NSRuncing) { x.runce() // CHECK: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[SELECTOR]]) } // CHECK: define hidden swiftcc %objc_object* @"$s14objc_protocols0A8_erasure{{[_0-9a-zA-Z]*}}F"(%TSo7NSSpoonC* %0) {{.*}} { func objc_erasure(_ x: NSSpoon) -> NSRuncing { return x // CHECK: [[RES:%.*]] = bitcast %TSo7NSSpoonC* {{%.*}} to %objc_object* // CHECK: ret %objc_object* [[RES]] } // CHECK: define hidden swiftcc void @"$s14objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F"(%objc_object* %0) func objc_protocol_composition(_ x: NSRuncing & NSFunging) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // CHECK: define hidden swiftcc void @"$s14objc_protocols0A27_swift_protocol_composition{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, i8** %1) func objc_swift_protocol_composition (_ x: NSRuncing & Ansible & NSFunging) { x.runce() // CHECK: [[RUNCE:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8 // CHECK: bitcast %objc_object* %0 to [[OBJTYPE:.*]]* // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[RUNCE]]) /* TODO: Abstraction difference from ObjC protocol composition to * opaque protocol x.anse() */ x.funge() // CHECK: [[FUNGE:%.*]] = load i8*, i8** @"\01L_selector(funge)", align 8 // CHECK: call void bitcast (void ()* @objc_msgSend to void ([[OBJTYPE]]*, i8*)*)([[OBJTYPE]]* {{%.*}}, i8* [[FUNGE]]) } // TODO: Mixed class-bounded/fully general protocol compositions. @objc protocol SettableProperty { var reqt: NSRuncing { get set } } func instantiateArchetype<T: SettableProperty>(_ x: T) { let y = x.reqt x.reqt = y } // rdar://problem/21029254 @objc protocol Appaloosa { } protocol Palomino {} protocol Vanner : Palomino, Appaloosa { } struct Stirrup<T : Palomino> { } func canter<T : Palomino>(_ t: Stirrup<T>) {} func gallop<T : Vanner>(_ t: Stirrup<T>) { canter(t) } // https://github.com/apple/swift/issues/49678 func triggerDoubleInheritedFunging() -> AnyObject { return NSDoubleInheritedFunging.self as AnyObject } class TestNonRuntimeProto : RuntimeP { } class TestNonRuntime2Proto : Runtime2P {} public class SomeImpl : DeclarationOnlyUser { public func printIt() { print("hello") } }
apache-2.0
7cc36fb262438f3e3cea19fef6bd65e7
50.234783
306
0.611931
2.919722
false
false
false
false
avito-tech/Marshroute
MarshrouteTests/Sources/TransitionContextsStackClientTests/TransitionContextsStackClient_Tests.swift
1
14904
import XCTest @testable import Marshroute // MARK: - TransitionContextsStackTests final class TransitionContextsStackClientTests: XCTestCase { var __stackClientImpl: TransitionContextsStackClient? var autoZombieContext: CompletedTransitionContext? var neverZombieContext1: CompletedTransitionContext? var neverZombieContext2: CompletedTransitionContext? var oneDayZombieContext: CompletedTransitionContext? private let targetViewController1 = UIViewController() private let targetViewController2 = UIViewController() private var nillableTargetViewController: UIViewController? private let sourceViewController = UIViewController() private var navigationController: UINavigationController? private let dummyTransitionsHandler = DummyAnimatingTransitionsHandler() private let dummyThirdPartyTransitionsHandler = DummyAnimatingTransitionsHandler() override func setUp() { super.setUp() __stackClientImpl = TransitionContextsStackClientImpl() nillableTargetViewController = UIViewController() let autoZombieViewController = UIViewController() navigationController = UINavigationController() autoZombieContext = TransitionContextsCreator.createCompletedTransitionContextFromPresentationTransitionContext( sourceTransitionsHandler: dummyTransitionsHandler, sourceViewController: sourceViewController, targetViewController: autoZombieViewController, navigationController: nil, targetTransitionsHandlerBox: .init(animatingTransitionsHandler: dummyTransitionsHandler)) neverZombieContext1 = TransitionContextsCreator.createCompletedTransitionContextFromPresentationTransitionContext( sourceTransitionsHandler: dummyTransitionsHandler, sourceViewController: sourceViewController, targetViewController: targetViewController1, navigationController: navigationController, targetTransitionsHandlerBox: .init(animatingTransitionsHandler: dummyTransitionsHandler)) neverZombieContext2 = TransitionContextsCreator.createCompletedTransitionContextFromPresentationTransitionContext( sourceTransitionsHandler: dummyTransitionsHandler, sourceViewController: sourceViewController, targetViewController: targetViewController2, navigationController: navigationController, targetTransitionsHandlerBox: .init(animatingTransitionsHandler: dummyTransitionsHandler)) oneDayZombieContext = TransitionContextsCreator.createCompletedTransitionContextFromPresentationTransitionContext( sourceTransitionsHandler: dummyTransitionsHandler, sourceViewController: sourceViewController, targetViewController: nillableTargetViewController!, navigationController: nil, targetTransitionsHandlerBox: .init(animatingTransitionsHandler: dummyTransitionsHandler)) } override func tearDown() { super.tearDown() __stackClientImpl = nil navigationController = nil autoZombieContext = nil neverZombieContext1 = nil neverZombieContext2 = nil oneDayZombieContext = nil nillableTargetViewController = nil } func test_AppendingTransitionContextsWithGoodParameters() { guard let __stackClientImpl = __stackClientImpl else { XCTFail(); return } guard let neverZombieContext1 = neverZombieContext1 else { XCTFail(); return } guard let neverZombieContext2 = neverZombieContext2 else { XCTFail(); return } guard !neverZombieContext1.isZombie else { XCTFail(); return } guard !neverZombieContext2.isZombie else { XCTFail(); return } // adding transitions handler matching the context. must be added to the stack let appended = __stackClientImpl.appendTransition(context: neverZombieContext1, forTransitionsHandler: dummyTransitionsHandler) XCTAssertTrue(appended, "добавили переход, выполненный правильным обработчиком переходов. должен был добавиться") do { // lastTransitionForTransitionsHandler let lastTransition = __stackClientImpl.lastTransitionForTransitionsHandler(dummyTransitionsHandler) XCTAssertNotNil(lastTransition, "добавили переход, выполненный правильным обработчиком переходов. должен был добавиться") XCTAssertEqual(lastTransition!.transitionId, neverZombieContext1.transitionId, "добавили переход, выполненный правильным обработчиком переходов. должен был добавиться") XCTAssertNil(__stackClientImpl.lastTransitionForTransitionsHandler(dummyThirdPartyTransitionsHandler), "переход для этого обработчика не добавляли. его не должно быть в стеке") } do { // chainedTransitionForTransitionsHandler XCTAssertNil(__stackClientImpl.chainedTransitionForTransitionsHandler(dummyTransitionsHandler), "добавили один переход. дочерних переходов не было") XCTAssertNil(__stackClientImpl.chainedTransitionForTransitionsHandler(dummyThirdPartyTransitionsHandler), "переход для этого обработчика не добавляли. для него не должно быть дочерних переходов") } do { // chainedTransitionsHandlerBoxForTransitionsHandler XCTAssertNil(__stackClientImpl.chainedTransitionsHandlerBoxForTransitionsHandler(dummyTransitionsHandler), "добавили один переход. дочерних переходов не было") XCTAssertNil(__stackClientImpl.chainedTransitionsHandlerBoxForTransitionsHandler(dummyThirdPartyTransitionsHandler), "добавили один переход. дочерних переходов не было") } do { // transitionWith let transitionWithId = __stackClientImpl.transitionWith(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyTransitionsHandler) XCTAssertNotNil(transitionWithId, "добавили переход, выполненный правильным обработчиком переходов. должен был добавиться") XCTAssertEqual(transitionWithId!.transitionId, neverZombieContext1.transitionId, "добавили переход, выполненный правильным обработчиком переходов. должен был добавиться") let transitionWithNotAppenededId = __stackClientImpl.transitionWith(transitionId: neverZombieContext2.transitionId, forTransitionsHandler: dummyTransitionsHandler) XCTAssertNil(transitionWithNotAppenededId, "этот переход не добавляли. его не должно быть в стеке") let transitionWithNotAppendedTransitionsHandler = __stackClientImpl.transitionWith(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler) XCTAssertNil(transitionWithNotAppendedTransitionsHandler, "переход для этого обработчика не добавляли. его не должно быть в стеке") } do { // allTransitionsForTransitionsHandler let (chainedTransition, pushTransitions) = __stackClientImpl.allTransitionsForTransitionsHandler(dummyTransitionsHandler) XCTAssertNil(chainedTransition, "добавили один переход. дочерних переходов не было") XCTAssertNotNil(pushTransitions, "сделали один переход. должен был добавиться") XCTAssertEqual(pushTransitions!.count, 1, "сделали один переход. должен был добавиться") XCTAssertEqual(pushTransitions!.first?.transitionId, neverZombieContext1.transitionId, "сделали один переход. должен был добавиться") let allTransitionsForNotAppededTransitionsHandler = __stackClientImpl.allTransitionsForTransitionsHandler(dummyThirdPartyTransitionsHandler) XCTAssertNil(allTransitionsForNotAppededTransitionsHandler.chainedTransition, "переход для этого обработчика не добавляли. для него не должно быть дочерних переходов") XCTAssertNil(allTransitionsForNotAppededTransitionsHandler.pushTransitions, "переход для этого обработчика не добавляли. для него не должно быть push переходов") } do { // transitionsAfter let transitionsAfter = __stackClientImpl.transitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyTransitionsHandler, includingTransitionWithId: false) XCTAssertNil(transitionsAfter.chainedTransition, "добавили один переход. после него переходов не должно быть") XCTAssertNil(transitionsAfter.pushTransitions, "добавили один переход. после него переходов не должно быть") let transitionsAfterIncludingTransitionWithId = __stackClientImpl.transitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyTransitionsHandler, includingTransitionWithId: true) XCTAssertNil(transitionsAfterIncludingTransitionWithId.chainedTransition, "добавили один переход. после него переходов не должно быть") XCTAssertNotNil(transitionsAfterIncludingTransitionWithId.pushTransitions, "добавили один переход. должен был добавиться") XCTAssertEqual(transitionsAfterIncludingTransitionWithId.pushTransitions!.first?.transitionId, neverZombieContext1.transitionId, "сделали один переход. должен был добавиться") let transitionsAfterForNotAppededTransitionsHandler = __stackClientImpl.transitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler, includingTransitionWithId: false) XCTAssertNil(transitionsAfterForNotAppededTransitionsHandler.chainedTransition, "переход для этого обработчика не добавляли. для него не должно быть chained переходов") XCTAssertNil(transitionsAfterForNotAppededTransitionsHandler.pushTransitions, "переход для этого обработчика не добавляли. для него не должно быть chained переходов") let transitionsAfterIncludingTransitionWithIdForNotAppededTransitionsHandler = __stackClientImpl.transitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler, includingTransitionWithId: true) XCTAssertNil(transitionsAfterIncludingTransitionWithIdForNotAppededTransitionsHandler.chainedTransition, "переход для этого обработчика не добавляли. для него не должно быть chained переходов") XCTAssertNil(transitionsAfterIncludingTransitionWithIdForNotAppededTransitionsHandler.pushTransitions, "переход для этого обработчика не добавляли. для него не должно быть chained переходов") } do { // deleteTransitionsAfter XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext2.transitionId, forTransitionsHandler: dummyTransitionsHandler, includingTransitionWithId: false), "этот переход вообще не добавляли. он не должен удалиться") XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext2.transitionId, forTransitionsHandler: dummyTransitionsHandler, includingTransitionWithId: true), "этот переход вообще не добавляли. он не должен удалиться") XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext2.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler, includingTransitionWithId: false), "переход для этого обработчика не добавляли. он не должен удалиться") XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext2.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler, includingTransitionWithId: true), "переход для этого обработчика не добавляли. он не должен удалиться") XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler, includingTransitionWithId: false), "переход для этого обработчика не добавляли. он не должен удалиться") XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyThirdPartyTransitionsHandler, includingTransitionWithId: true), "переход для этого обработчика не добавляли. он не должен удалиться") XCTAssertFalse(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyTransitionsHandler, includingTransitionWithId: false), "добавили один переход. после него переходов не должно быть") XCTAssertTrue(__stackClientImpl.deleteTransitionsAfter(transitionId: neverZombieContext1.transitionId, forTransitionsHandler: dummyTransitionsHandler, includingTransitionWithId: true), "добавили один переход. должен был добавиться. поэтому должен удалиться") } } }
mit
a5856bd10d1f571103073b85f06fc47b
78.060976
278
0.773484
5.100708
false
false
false
false
SuPair/firefox-ios
Client/Frontend/Browser/TabDisplayManager.swift
1
21594
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import Storage @objc protocol TabSelectionDelegate: AnyObject { func didSelectTabAtIndex(_ index: Int) } protocol TopTabCellDelegate: AnyObject { func tabCellDidClose(_ cell: UICollectionViewCell) } protocol TabDisplayer: AnyObject { typealias TabCellIdentifer = String var tabCellIdentifer: TabCellIdentifer { get set } func focusSelectedTab() func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell } class TabDisplayManager: NSObject { fileprivate let tabManager: TabManager var isPrivate = false var isDragging = false fileprivate let collectionView: UICollectionView typealias CompletionBlock = () -> Void private var tabObservers: TabObservers! fileprivate weak var tabDisplayer: TabDisplayer? let tabReuseIdentifer: String var searchedTabs: [Tab] = [] var searchActive: Bool = false var tabStore: [Tab] = [] //the actual datastore fileprivate var pendingUpdatesToTabs: [Tab] = [] //the datastore we are transitioning to fileprivate var needReloads: [Tab?] = [] // Tabs that need to be reloaded fileprivate var completionBlocks: [CompletionBlock] = [] //blocks are performed once animations finish fileprivate var isUpdating = false var pendingReloadData = false fileprivate var oldTabs: [Tab]? // The last state of the tabs before an animation fileprivate weak var oldSelectedTab: Tab? // Used to select the right tab when transitioning between private/normal tabs var tabCount: Int { return self.tabStore.count } private var tabsToDisplay: [Tab] { if searchActive { // tabs can be deleted while a search is active. Make sure the tab still exists in the tabmanager before displaying return searchedTabs.filter({ tabManager.tabs.contains($0) }) } return self.isPrivate ? tabManager.privateTabs : tabManager.normalTabs } init(collectionView: UICollectionView, tabManager: TabManager, tabDisplayer: TabDisplayer, reuseID: String) { self.collectionView = collectionView self.tabDisplayer = tabDisplayer self.tabManager = tabManager self.isPrivate = tabManager.selectedTab?.isPrivate ?? false self.tabReuseIdentifer = reuseID super.init() tabManager.addDelegate(self) self.tabObservers = registerFor(.didLoadFavicon, .didChangeURL, queue: .main) self.tabStore = self.tabsToDisplay } // Once we are done with TabManager we need to call removeObservers to avoid a retain cycle with the observers func removeObservers() { unregister(tabObservers) tabObservers = nil } // Make sure animations don't happen before the view is loaded. fileprivate func shouldAnimate(isRestoringTabs: Bool) -> Bool { return !isRestoringTabs && collectionView.frame != CGRect.zero } private func recordEventAndBreadcrumb(object: UnifiedTelemetry.EventObject, method: UnifiedTelemetry.EventMethod) { let isTabTray = tabDisplayer as? TabTrayController != nil let eventValue = isTabTray ? UnifiedTelemetry.EventValue.tabTray : UnifiedTelemetry.EventValue.topTabs UnifiedTelemetry.recordEvent(category: .action, method: method, object: object, value: eventValue) Sentry.shared.breadcrumb(category: "Tab Action", message: "object: \(object), action: \(method.rawValue), \(eventValue.rawValue), tab count: \(tabStore.count) ") } func togglePBM() { if isUpdating || pendingReloadData { return } let isPrivate = self.isPrivate self.pendingReloadData = true // Stops animations from happening let oldSelectedTab = self.oldSelectedTab self.oldSelectedTab = tabManager.selectedTab //if private tabs is empty and we are transitioning to it add a tab if tabManager.privateTabs.isEmpty && !isPrivate { tabManager.addTab(isPrivate: true) } //get the tabs from which we will select which one to nominate for tribute (selection) //the isPrivate boolean still hasnt been flipped. (It'll be flipped in the BVC didSelectedTabChange method) let tabs = !isPrivate ? tabManager.privateTabs : tabManager.normalTabs if let tab = oldSelectedTab, tabs.index(of: tab) != nil { tabManager.selectTab(tab) } else { tabManager.selectTab(tabs.last) } } } extension TabDisplayManager: UICollectionViewDataSource { @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabStore.count } @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let tab = tabStore[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.tabReuseIdentifer, for: indexPath) if let tabCell = tabDisplayer?.cellFactory(for: cell, using: tab) { return tabCell } else { return cell } } @objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderFooter", for: indexPath) as! TopTabsHeaderFooter view.arrangeLine(kind) return view } } extension TabDisplayManager: TabSelectionDelegate { func didSelectTabAtIndex(_ index: Int) { let tab = tabStore[index] if tabsToDisplay.index(of: tab) != nil { tabManager.selectTab(tab) } } } @available(iOS 11.0, *) extension TabDisplayManager: UIDropInteractionDelegate { func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { // Prevent tabs from being dragged and dropped onto the "New Tab" button. if let localDragSession = session.localDragSession, let item = localDragSession.items.first, let _ = item.localObject as? Tab { return false } return session.canLoadObjects(ofClass: URL.self) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { recordEventAndBreadcrumb(object: .url, method: .drop) _ = session.loadObjects(ofClass: URL.self) { urls in guard let url = urls.first else { return } self.tabManager.addTab(URLRequest(url: url), isPrivate: self.isPrivate) } } } @available(iOS 11.0, *) extension TabDisplayManager: UICollectionViewDragDelegate { func collectionView(_ collectionView: UICollectionView, dragSessionWillBegin session: UIDragSession) { isDragging = true } func collectionView(_ collectionView: UICollectionView, dragSessionDidEnd session: UIDragSession) { isDragging = false reloadData() } func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore let tab = tabStore[indexPath.item] // Get the tab's current URL. If it is `nil`, check the `sessionData` since // it may be a tab that has not been restored yet. var url = tab.url if url == nil, let sessionData = tab.sessionData { let urls = sessionData.urls let index = sessionData.currentPage + urls.count - 1 if index < urls.count { url = urls[index] } } // Ensure we actually have a URL for the tab being dragged and that the URL is not local. // If not, just create an empty `NSItemProvider` so we can create a drag item with the // `Tab` so that it can at still be re-ordered. var itemProvider: NSItemProvider if url != nil, !(url?.isLocal ?? true) { itemProvider = NSItemProvider(contentsOf: url) ?? NSItemProvider() } else { itemProvider = NSItemProvider() } recordEventAndBreadcrumb(object: .tab, method: .drag) let dragItem = UIDragItem(itemProvider: itemProvider) dragItem.localObject = tab return [dragItem] } } @available(iOS 11.0, *) extension TabDisplayManager: UICollectionViewDropDelegate { func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) { guard let destinationIndexPath = coordinator.destinationIndexPath, let dragItem = coordinator.items.first?.dragItem, let tab = dragItem.localObject as? Tab, let sourceIndex = tabStore.index(of: tab) else { return } recordEventAndBreadcrumb(object: .tab, method: .drop) coordinator.drop(dragItem, toItemAt: destinationIndexPath) isDragging = false self.tabManager.moveTab(isPrivate: self.isPrivate, fromIndex: sourceIndex, toIndex: destinationIndexPath.item) self.performTabUpdates() } func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal { guard let localDragSession = session.localDragSession, let item = localDragSession.items.first, let tab = item.localObject as? Tab else { return UICollectionViewDropProposal(operation: .forbidden) } // If the `isDragging` is not `true` by the time we get here, we've had other // add/remove operations happen while the drag was going on. We must return a // `.cancel` operation continuously until `isDragging` can be reset. guard tabStore.index(of: tab) != nil, isDragging else { return UICollectionViewDropProposal(operation: .cancel) } return UICollectionViewDropProposal(operation: .move, intent: .insertAtDestinationIndexPath) } } extension TabDisplayManager: TabEventHandler { func tab(_ tab: Tab, didLoadFavicon favicon: Favicon?, with: Data?) { assertIsMainThread("UICollectionView changes can only be performed from the main thread") if tabStore.index(of: tab) != nil { needReloads.append(tab) performTabUpdates() } } func tab(_ tab: Tab, didChangeURL url: URL) { assertIsMainThread("UICollectionView changes can only be performed from the main thread") if tabStore.index(of: tab) != nil { needReloads.append(tab) performTabUpdates() } } } // Collection Diff (animations) extension TabDisplayManager { struct TopTabMoveChange: Hashable { let from: IndexPath let to: IndexPath var hashValue: Int { return from.hashValue + to.hashValue } // Consider equality when from/to are equal as well as swapped. This is because // moving a tab from index 2 to index 1 will result in TWO changes: 2 -> 1 and 1 -> 2 // We only need to keep *one* of those two changes when dealing with a move. static func ==(lhs: TabDisplayManager.TopTabMoveChange, rhs: TabDisplayManager.TopTabMoveChange) -> Bool { return (lhs.from == rhs.from && lhs.to == rhs.to) || (lhs.from == rhs.to && lhs.to == rhs.from) } } struct TopTabChangeSet { let reloads: Set<IndexPath> let inserts: Set<IndexPath> let deletes: Set<IndexPath> let moves: Set<TopTabMoveChange> init(reloadArr: [IndexPath], insertArr: [IndexPath], deleteArr: [IndexPath], moveArr: [TopTabMoveChange]) { reloads = Set(reloadArr) inserts = Set(insertArr) deletes = Set(deleteArr) moves = Set(moveArr) } var isEmpty: Bool { return reloads.isEmpty && inserts.isEmpty && deletes.isEmpty && moves.isEmpty } } // create a TopTabChangeSet which is a snapshot of updates to perfrom on a collectionView func calculateDiffWith(_ oldTabs: [Tab], to newTabs: [Tab], and reloadTabs: [Tab?]) -> TopTabChangeSet { let inserts: [IndexPath] = newTabs.enumerated().compactMap { index, tab in if oldTabs.index(of: tab) == nil { return IndexPath(row: index, section: 0) } return nil } let deletes: [IndexPath] = oldTabs.enumerated().compactMap { index, tab in if newTabs.index(of: tab) == nil { return IndexPath(row: index, section: 0) } return nil } let moves: [TopTabMoveChange] = newTabs.enumerated().compactMap { newIndex, tab in if let oldIndex = oldTabs.index(of: tab), oldIndex != newIndex { return TopTabMoveChange(from: IndexPath(row: oldIndex, section: 0), to: IndexPath(row: newIndex, section: 0)) } return nil } // Create based on what is visibile but filter out tabs we are about to insert/delete. let reloads: [IndexPath] = reloadTabs.compactMap { tab in guard let tab = tab, newTabs.index(of: tab) != nil else { return nil } return IndexPath(row: newTabs.index(of: tab)!, section: 0) }.filter { return inserts.index(of: $0) == nil && deletes.index(of: $0) == nil } Sentry.shared.breadcrumb(category: "Tab Diff", message: "reloads: \(reloads.count), inserts: \(inserts.count), deletes: \(deletes.count), moves: \(moves.count)") return TopTabChangeSet(reloadArr: reloads, insertArr: inserts, deleteArr: deletes, moveArr: moves) } func updateTabsFrom(_ oldTabs: [Tab]?, to newTabs: [Tab], on completion: (() -> Void)? = nil) { assertIsMainThread("Updates can only be performed from the main thread") guard let oldTabs = oldTabs, !self.isUpdating, !self.pendingReloadData, !self.isDragging else { return } // Lets create our change set let update = self.calculateDiffWith(oldTabs, to: newTabs, and: needReloads) flushPendingChanges() // If there are no changes. We have nothing to do if update.isEmpty { completion?() return } // The actual update block. We update the dataStore right before we do the UI updates. let updateBlock = { self.tabStore = newTabs // Only consider moves if no other operations are pending. if update.deletes.count == 0, update.inserts.count == 0 { for move in update.moves { self.collectionView.moveItem(at: move.from, to: move.to) } } else { self.collectionView.deleteItems(at: Array(update.deletes)) self.collectionView.insertItems(at: Array(update.inserts)) } self.collectionView.reloadItems(at: Array(update.reloads)) } //Lets lock any other updates from happening. self.isUpdating = true self.isDragging = false self.pendingUpdatesToTabs = newTabs // This var helps other mutations that might happen while updating. let onComplete: () -> Void = { completion?() self.isUpdating = false self.pendingUpdatesToTabs = [] // run completion blocks // Sometimes there might be a pending reload. Lets do that. if self.pendingReloadData { return self.reloadData() } // There can be pending animations. Run update again to clear them. let tabs = self.oldTabs ?? self.tabStore self.updateTabsFrom(tabs, to: self.tabsToDisplay, on: { if !update.inserts.isEmpty || !update.reloads.isEmpty { self.tabDisplayer?.focusSelectedTab() } }) } // The actual update. Only animate the changes if no tabs have moved // as a result of drag-and-drop. if update.moves.count == 0, tabDisplayer is TopTabsViewController { UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.performBatchUpdates(updateBlock) }) { (_) in onComplete() } } else { self.collectionView.performBatchUpdates(updateBlock) { _ in onComplete() } } } fileprivate func flushPendingChanges() { oldTabs = nil needReloads.removeAll() } func reloadData(_ completionBlock: CompletionBlock? = nil) { assertIsMainThread("reloadData must only be called from main thread") if let block = completionBlock { completionBlocks.append(block) } if self.isUpdating || self.collectionView.frame == CGRect.zero { self.pendingReloadData = true return } isUpdating = true isDragging = false self.tabStore = self.tabsToDisplay self.flushPendingChanges() UIView.animate(withDuration: TopTabsUX.AnimationSpeed, animations: { self.collectionView.reloadData() self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.layoutIfNeeded() self.tabDisplayer?.focusSelectedTab() }, completion: { (_) in self.isUpdating = false self.pendingReloadData = false self.performTabUpdates() }) } } extension TabDisplayManager: TabManagerDelegate { // Because we don't know when we are about to transition to private mode // check to make sure that the tab we are trying to add is being added to the right tab group fileprivate func tabsMatchDisplayGroup(_ a: Tab?, b: Tab?) -> Bool { if let a = a, let b = b, a.isPrivate == b.isPrivate { return true } return false } func performTabUpdates(_ completionBlock: CompletionBlock? = nil) { if let block = completionBlock { completionBlocks.append(block) } guard !isUpdating else { return } let fromTabs = !self.pendingUpdatesToTabs.isEmpty ? self.pendingUpdatesToTabs : self.oldTabs self.oldTabs = fromTabs ?? self.tabStore if self.pendingReloadData && !isUpdating { self.reloadData() } else { self.updateTabsFrom(self.oldTabs, to: self.tabsToDisplay) { for block in self.completionBlocks { block() } self.completionBlocks.removeAll() } } } func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) { if !shouldAnimate(isRestoringTabs: isRestoring) { return } if !tabsMatchDisplayGroup(selected, b: previous) { self.reloadData() } else { self.needReloads.append(selected) self.needReloads.append(previous) performTabUpdates() } } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, isRestoring: Bool) { if !shouldAnimate(isRestoringTabs: isRestoring) || (tabManager.selectedTab != nil && !tabsMatchDisplayGroup(tab, b: tabManager.selectedTab)) { return } performTabUpdates() } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { // We need to store the earliest oldTabs. So if one already exists use that. self.oldTabs = self.oldTabs ?? tabStore } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) { recordEventAndBreadcrumb(object: .tab, method: .delete) if !shouldAnimate(isRestoringTabs: isRestoring) { return } // If we deleted the last private tab. We'll be switching back to normal browsing. Pause updates till then if self.tabsToDisplay.isEmpty { self.pendingReloadData = true return } // dont want to hold a ref to a deleted tab if tab === oldSelectedTab { oldSelectedTab = nil } performTabUpdates() } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { self.reloadData() } func tabManagerDidAddTabs(_ tabManager: TabManager) { recordEventAndBreadcrumb(object: .tab, method: .add) self.reloadData() } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { recordEventAndBreadcrumb(object: .tab, method: .deleteAll) self.reloadData() } }
mpl-2.0
5279e8fe4f9c86aeca291c47cedd3769
38.622018
213
0.645226
4.965279
false
false
false
false
tardieu/swift
test/Interpreter/protocol_initializers.swift
25
2014
// RUN: %target-run-simple-swift // REQUIRES: executable_test import StdlibUnittest var ProtocolInitTestSuite = TestSuite("ProtocolInit") func mustFail<T>(f: () -> T?) { if f() != nil { preconditionFailure("Didn't fail") } } protocol TriviallyConstructible { init(inner: LifetimeTracked) } enum E : Error { case X } extension TriviallyConstructible { init(middle x: LifetimeTracked) { self.init(inner: x) } init?(failingMiddle x: LifetimeTracked, shouldFail: Bool) { if (shouldFail) { return nil } self.init(inner: x) } init(throwingMiddle x: LifetimeTracked, shouldThrow: Bool) throws { if (shouldThrow) { throw E.X } self.init(inner: x) } } class TrivialClass : TriviallyConstructible { convenience init(outer x: LifetimeTracked) { self.init(middle: x) } convenience init?(failingOuter x: LifetimeTracked, shouldFail: Bool) { self.init(failingMiddle: x, shouldFail: shouldFail) } convenience init(throwingOuter x: LifetimeTracked, shouldThrow: Bool) throws { try self.init(throwingMiddle: x, shouldThrow: shouldThrow) } required init(inner tracker: LifetimeTracked) { self.tracker = tracker } let tracker: LifetimeTracked } ProtocolInitTestSuite.test("ProtocolInit_Trivial") { _ = TrivialClass(outer: LifetimeTracked(0)) } ProtocolInitTestSuite.test("ProtocolInit_Failable") { do { let result = TrivialClass(failingOuter: LifetimeTracked(1), shouldFail: false) assert(result != nil) } do { let result = TrivialClass(failingOuter: LifetimeTracked(2), shouldFail: true) assert(result == nil) } } ProtocolInitTestSuite.test("ProtocolInit_Throwing") { do { let result = try TrivialClass(throwingOuter: LifetimeTracked(4), shouldThrow: false) } catch { preconditionFailure("Expected no error") } do { let result = try TrivialClass(throwingOuter: LifetimeTracked(5), shouldThrow: true) preconditionFailure("Expected error") } catch {} } runAllTests()
apache-2.0
a9f3c7487cb29d55946e688a36764f60
21.629213
88
0.700099
4.093496
false
true
false
false
ProfileCreator/ProfileCreator
ProfileCreator/ProfileCreator/Main Window Profile Preview/MainWindowProfilePreview.swift
1
17426
// // MainWindowProfilePreview.swift // ProfileCreator // // Created by Erik Berglund. // Copyright © 2018 Erik Berglund. All rights reserved. // import Cocoa class MainWindowProfilePreviewController: NSObject { // MARK: - // MARK: Variables let view = NSVisualEffectView() let infoViewController = MainWindowProfilePreviewInfoViewController() let previewViewController = MainWindowProfilePreviewViewController() // MARK: - // MARK: Initialization override init() { super.init() // --------------------------------------------------------------------- // Setup Effect View (Background) // --------------------------------------------------------------------- self.view.translatesAutoresizingMaskIntoConstraints = false if #available(OSX 10.14, *) { self.view.material = .contentBackground } else { self.view.material = .light } // --------------------------------------------------------------------- // Setup Info View // --------------------------------------------------------------------- insert(subview: infoViewController.view) // --------------------------------------------------------------------- // Setup Notification Observers // --------------------------------------------------------------------- NotificationCenter.default.addObserver(self, selector: #selector(didChangeProfileSelection(_:)), name: .didChangeProfileSelection, object: nil) } deinit { NotificationCenter.default.removeObserver(self, name: .didChangeProfileSelection, object: nil) } @objc func didChangeProfileSelection(_ notification: NSNotification?) { if let userInfo = notification?.userInfo, let profileIdentifiers = userInfo[NotificationKey.identifiers] as? [UUID] { if profileIdentifiers.count == 1 { if let profile = ProfileController.sharedInstance.profile(withIdentifier: profileIdentifiers.first!) { self.previewViewController.updateSelection(profile: profile) infoViewController.view.removeFromSuperview() insert(subview: previewViewController.view) self.view.state = .inactive } } else { self.infoViewController.updateSelection(count: profileIdentifiers.count) previewViewController.view.removeFromSuperview() insert(subview: infoViewController.view) self.view.state = .active } } } // MARK: - // MARK: Setup Layout Constraints private func insert(subview: NSView) { // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- var constraints = [NSLayoutConstraint]() // --------------------------------------------------------------------- // Add subview to main view // --------------------------------------------------------------------- self.view.addSubview(subview) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Top constraints.append(NSLayoutConstraint(item: self.view, attribute: .top, relatedBy: .equal, toItem: subview, attribute: .top, multiplier: 1, constant: 0)) // Bottom constraints.append(NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1, constant: 0)) // Leading constraints.append(NSLayoutConstraint(item: self.view, attribute: .leading, relatedBy: .equal, toItem: subview, attribute: .leading, multiplier: 1, constant: 0)) // Trailing constraints.append(NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: subview, attribute: .trailing, multiplier: 1, constant: 0)) // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(constraints) } } class MainWindowProfilePreviewViewController: NSObject { // MARK: - // MARK: Variables let view = NSView() let textFieldTitle = NSTextField() let textFieldDescription = NSTextField() // MARK: - // MARK: Initialization override init() { super.init() // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- var constraints = [NSLayoutConstraint]() // --------------------------------------------------------------------- // Setup View // --------------------------------------------------------------------- self.view.translatesAutoresizingMaskIntoConstraints = false // --------------------------------------------------------------------- // Create and add TextField // --------------------------------------------------------------------- self.setupTextFieldTitle(constraints: &constraints) self.setupTextFieldDescription(constraints: &constraints) // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(constraints) } // MARK: - // MARK: Public Functions public func updateSelection(profile: Profile) { self.textFieldTitle.stringValue = profile.settings.title if profile.versionFormatSupported { self.textFieldDescription.stringValue = "(This will show a preview of the profile settings. Not Implemented.)" } else { self.textFieldDescription.stringValue = "This profile is saved in an older format and cannot be read by this version of ProfileCreator.\n\nTo add this profile to the application again you need to export it as a .mobileconfig using ProfileCreator Beta 4 (0.1-4).\n\nTo learn more, please read the release notes for Beta 5." } } // MARK: - // MARK: Setup Layout Constraints private func setupTextFieldTitle(constraints: inout [NSLayoutConstraint]) { self.textFieldTitle.translatesAutoresizingMaskIntoConstraints = false self.textFieldTitle.lineBreakMode = .byWordWrapping self.textFieldTitle.isBordered = false self.textFieldTitle.isBezeled = false self.textFieldTitle.drawsBackground = false self.textFieldTitle.isEditable = false self.textFieldTitle.font = NSFont.boldSystemFont(ofSize: 30) self.textFieldTitle.textColor = .labelColor self.textFieldTitle.alignment = .center self.textFieldTitle.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) // --------------------------------------------------------------------- // Add subview to main view // --------------------------------------------------------------------- self.view.addSubview(self.textFieldTitle) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Top constraints.append(NSLayoutConstraint(item: self.textFieldTitle, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 60.0)) // Leading constraints.append(NSLayoutConstraint(item: self.textFieldTitle, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 10.0)) // Trailing constraints.append(NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.textFieldTitle, attribute: .trailing, multiplier: 1, constant: 10.0)) } private func setupTextFieldDescription(constraints: inout [NSLayoutConstraint]) { self.textFieldDescription.translatesAutoresizingMaskIntoConstraints = false self.textFieldDescription.lineBreakMode = .byWordWrapping self.textFieldDescription.isBordered = false self.textFieldDescription.isBezeled = false self.textFieldDescription.drawsBackground = false self.textFieldDescription.isEditable = false self.textFieldDescription.font = NSFont.systemFont(ofSize: 19) self.textFieldDescription.textColor = .tertiaryLabelColor self.textFieldDescription.alignment = .center self.textFieldDescription.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) self.textFieldDescription.stringValue = "(This will show a preview of the profile settings. Not Implemented.)" // --------------------------------------------------------------------- // Add subview to main view // --------------------------------------------------------------------- self.view.addSubview(self.textFieldDescription) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Top constraints.append(NSLayoutConstraint(item: self.textFieldDescription, attribute: .top, relatedBy: .equal, toItem: self.textFieldTitle, attribute: .bottom, multiplier: 1, constant: 8)) // Leading constraints.append(NSLayoutConstraint(item: self.textFieldDescription, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 20.0)) // Trailing constraints.append(NSLayoutConstraint(item: self.view, attribute: .trailing, relatedBy: .equal, toItem: self.textFieldDescription, attribute: .trailing, multiplier: 1, constant: 20.0)) } } class MainWindowProfilePreviewInfoViewController: NSObject { // MARK: - // MARK: Variables let view = NSView() let textField = NSTextField() // MARK: - // MARK: Initialization override init() { super.init() // --------------------------------------------------------------------- // Setup Variables // --------------------------------------------------------------------- var constraints = [NSLayoutConstraint]() // --------------------------------------------------------------------- // Setup View // --------------------------------------------------------------------- self.view.translatesAutoresizingMaskIntoConstraints = false // --------------------------------------------------------------------- // Create and add TextField // --------------------------------------------------------------------- self.textField.translatesAutoresizingMaskIntoConstraints = false self.textField.lineBreakMode = .byWordWrapping self.textField.isBordered = false self.textField.isBezeled = false self.textField.drawsBackground = false self.textField.isEditable = false self.textField.font = NSFont.systemFont(ofSize: 19) self.textField.textColor = .tertiaryLabelColor self.textField.alignment = .center setupTextField(constraints: &constraints) // --------------------------------------------------------------------- // Activate Layout Constraints // --------------------------------------------------------------------- NSLayoutConstraint.activate(constraints) // --------------------------------------------------------------------- // Set initial state to no profile selected // --------------------------------------------------------------------- updateSelection(count: 0) } // MARK: - // MARK: Public Functions public func updateSelection(count: Int) { switch count { case 0: self.textField.stringValue = NSLocalizedString("No Profile Selected", comment: "") case 1: self.textField.stringValue = NSLocalizedString("\(count) Profile Selected", comment: "") default: self.textField.stringValue = NSLocalizedString("\(count) Profiles Selected", comment: "") } } // MARK: - // MARK: Setup Layout Constraints private func setupTextField(constraints: inout [NSLayoutConstraint]) { // --------------------------------------------------------------------- // Add subview to main view // --------------------------------------------------------------------- self.view.addSubview(self.textField) // --------------------------------------------------------------------- // Add constraints // --------------------------------------------------------------------- // Center Vertically constraints.append(NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)) // Leading constraints.append(NSLayoutConstraint(item: textField, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)) // Trailing constraints.append(NSLayoutConstraint(item: textField, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)) } }
mit
09db639b364afdc8ec7889d4c7d29b12
43.794344
334
0.399598
7.945736
false
false
false
false
Railsreactor/json-data-sync-swift
JDSKit/Local/BaseDBService.swift
1
13159
// // BaseDBService.swift // JDSKit // // Created by Igor Reshetnikov on 11/27/15. // Copyright © 2015 RailsReactor. All rights reserved. // import Foundation import PromiseKit import CoreData import CocoaLumberjack enum CoreDataError: Error { case storeOutdated } open class BaseDBService: NSObject, ManagedObjectContextProvider { open static var sharedInstance: BaseDBService! var modelURL: URL var storeURL: URL public init(modelURL aModelURL: URL, storeURL aStoreURL: URL) { modelURL = aModelURL storeURL = aStoreURL super.init() if BaseDBService.sharedInstance == nil { BaseDBService.sharedInstance = self } initilizePredefinedGateways() let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(BaseDBService.mergeChangesOnMainThread(_:)), name: NSNotification.Name.NSManagedObjectContextDidSave, object: backgroundManagedObjectContext) } // ****************************************************** fileprivate lazy var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() fileprivate lazy var managedObjectModel: NSManagedObjectModel = { return NSManagedObjectModel(contentsOf: self.modelURL)! }() fileprivate lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { DDLogDebug("Initializing store...") let url = self.storeURL let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) // Clean up DB for debug purpose: // do { // try FileManager.default.removeItem(at: url); // } catch { // } // do { // Cleanup local cache if store going to migrate. Hack to avoid bug when newly added properties not set during sync, because existed entities wasn't updated since last sync. // Options to use with any delta-sync mechanism: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true] let meta = try NSPersistentStoreCoordinator.metadataForPersistentStore(ofType: NSSQLiteStoreType, at: url, options: nil) if !self.managedObjectModel.isConfiguration(withName: nil, compatibleWithStoreMetadata: meta) { throw CoreDataError.storeOutdated } DDLogDebug("Store meta is compatible.") } catch { DDLogError("Failed to init store coordinator with existing database. Trying to reinitialize store...") do { try FileManager.default.removeItem(at: url); } catch {} } do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) DDLogDebug("Store Initialized.") } catch { DDLogError("Failed to initialize sore: \(error)") abort() } return coordinator }() lazy var backgroundManagedObjectContext: NSManagedObjectContext = { var backgroundManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) backgroundManagedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator backgroundManagedObjectContext.mergePolicy = NSOverwriteMergePolicy return backgroundManagedObjectContext }() lazy var mainUIManagedObjectContext: NSManagedObjectContext = { var mainUIManagedObjectContext : NSManagedObjectContext? let initBlock = {() -> Void in mainUIManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) mainUIManagedObjectContext!.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy mainUIManagedObjectContext!.persistentStoreCoordinator = self.persistentStoreCoordinator } if Thread.isMainThread { initBlock() } else { DispatchQueue.main.sync(execute: { () -> Void in initBlock() }) } return mainUIManagedObjectContext! }() //MARK: - Entity Gateways fileprivate var syncObject = NSObject() fileprivate var entityGatewaysByType: [String : GenericEntityGateway] = [:] func initilizePredefinedGateways () { synchronized(syncObject) { () -> () in for gateway in AbstractRegistryService.mainRegistryService._predefinedEntityGateways { self.entityGatewaysByType[String(gateway.managedObjectType.entityName)] = gateway } } } open func entityGatewayByEntityTypeKey(_ typeKey: String) -> GenericEntityGateway? { var gateway = entityGatewaysByType[typeKey] if gateway == nil { synchronized(syncObject) { () -> () in gateway = self.entityGatewaysByType[typeKey] if gateway == nil { if let type = ExtractRep(ExtractModel(typeKey), subclassOf: CDManagedEntity.self) as? CDManagedEntity.Type { gateway = GenericEntityGateway(type) self.entityGatewaysByType[typeKey] = gateway } } } } return gateway } open func entityGatewayByEntityType(_ type: ManagedEntity.Type) -> GenericEntityGateway? { return entityGatewayByEntityTypeKey(String(describing: type)) } open func entityGatewayByMOType(_ type: CDManagedEntity.Type) -> GenericEntityGateway? { return entityGatewayByEntityTypeKey(String(describing: type.entityType)) } //MARK: - Merge @objc internal func mergeChangesOnMainThread(_ didSaveNotification: Notification) { let context = self.mainUIManagedObjectContext context.perform { () -> Void in let timestamp = Date() let inserted = didSaveNotification.userInfo?[NSInsertedObjectsKey] as? NSSet let updated = didSaveNotification.userInfo?[NSUpdatedObjectsKey] as? NSSet let deleted = didSaveNotification.userInfo?[NSDeletedObjectsKey] as? NSSet context.mergeChanges(fromContextDidSave: didSaveNotification) if let updated = didSaveNotification.userInfo?["updated"] as? NSSet { for unasafeMO in updated { if let unasafeMO = unasafeMO as? NSManagedObject { do { let safeMO = try context.existingObject(with: unasafeMO.objectID) context.refresh(safeMO, mergeChanges: true) } catch { DDLogError("Managed Object not found: \(unasafeMO.objectID)") } } } } DDLogDebug("Merged changes: { I: \(inserted?.count ?? 0), U: \(updated?.count ?? 0) D: \(deleted?.count)} in \(abs(timestamp.timeIntervalSinceNow))") } } //MARK: - Save internal func saveUnsafe(_ context: NSManagedObjectContext) { do { try context.save() } catch let error as NSError { DDLogError("Failed to save to data store: \(error.localizedDescription)") if let detailedErrors = error.userInfo[NSDetailedErrorsKey] as? [NSError] { for detailedError in detailedErrors { DDLogError("DetailedError: \(detailedError.userInfo)") } } abort(); } } open func saveContextSyncSafe(_ context: NSManagedObjectContext) { context.performAndWait { () -> Void in self.saveUnsafe(context) } } open func saveContextSafe(_ context: NSManagedObjectContext) { context.perform { () -> Void in self.saveUnsafe(context) } } open func saveSyncSafe() { self.saveContextSyncSafe(self.backgroundManagedObjectContext) } open func saveBackgroundUnsafe() { self.saveUnsafe(self.backgroundManagedObjectContext) } open func performBlockOnBackgroundContext(_ block: @escaping () -> Void) { backgroundManagedObjectContext.perform(block) } open func performPromiseOnBackgroundContext<T>(_ block: @escaping () throws -> T) -> Promise<T> { return Promise<T> { fulfill, reject in self.performBlockOnBackgroundContext({ () -> () in do { fulfill (try block()) } catch { reject(error) } }) } } //MARK: - deinit { NotificationCenter.default.removeObserver(self) } //MARK: - Entities open func contextForCurrentThread() -> NSManagedObjectContext { let context: NSManagedObjectContext = Thread.isMainThread ? mainUIManagedObjectContext : backgroundManagedObjectContext return context } open func fetchEntity(_ managedObjectID: NSManagedObjectID) throws -> NSManagedObject? { let context = contextForCurrentThread() return try context.existingObject(with: managedObjectID) } open func fetchEntities(_ managedObjectIDs: [NSManagedObjectID]) -> [NSManagedObject] { let context = contextForCurrentThread() var array = [NSManagedObject]() for managedObjectID in managedObjectIDs { array.append(context.object(with: managedObjectID)) } return array } //MARK: - Entities open func createEntity(_ type: NSManagedObject.Type, temp: Bool = false) -> NSManagedObject { let context = contextForCurrentThread() let name = String(describing: type) if !temp { return NSEntityDescription.insertNewObject(forEntityName: name, into: context) } else { let entityDesc = NSEntityDescription.entity(forEntityName: name, in: context) return NSManagedObject(entity: entityDesc!, insertInto: nil) } } open func generateFetchRequestForEntity(_ enitityType : NSManagedObject.Type, context: NSManagedObjectContext) -> NSFetchRequest<NSFetchRequestResult> { let fetchRequest = NSFetchRequest<NSFetchRequestResult>() let name = String(describing: enitityType) fetchRequest.entity = NSEntityDescription.entity(forEntityName: name, in: context) return fetchRequest } open func fetchEntity(_ predicate: NSPredicate?, ofType: NSManagedObject.Type) throws -> NSManagedObject? { let context = contextForCurrentThread() let fetchRequest = generateFetchRequestForEntity(ofType, context: context) fetchRequest.fetchLimit = 1 fetchRequest.predicate = predicate var entity: NSManagedObject? = nil if try context.count(for: fetchRequest) > 0 { entity = try context.fetch(fetchRequest).last as? NSManagedObject } return entity } open func fetchEntities(_ predicate: NSPredicate?, ofType: NSManagedObject.Type, sortDescriptors: [NSSortDescriptor]?) throws -> [NSManagedObject] { let context = contextForCurrentThread() let fetchRequest = generateFetchRequestForEntity(ofType, context: context) fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sortDescriptors var entities: [CDManagedEntity] = [] if try context.count(for: fetchRequest) > 0 { entities = try context.fetch(fetchRequest) as! [CDManagedEntity] } return entities } open func countEntities(_ ofType: NSManagedObject.Type) -> Int { let context = contextForCurrentThread() let fetchRequest = generateFetchRequestForEntity(ofType, context: context) let count = (try? context.count(for: fetchRequest)) ?? 0 if(count == NSNotFound) { return 0 } return count } //MARK: - Delete open func deleteEntities(_ predicate: NSPredicate?, ofType: NSManagedObject.Type) throws -> Void { let entities = try fetchEntities(predicate, ofType:ofType, sortDescriptors: nil) for entity in entities { try deleteEntity(entity) } } open func deleteEntity(_ object: NSManagedObject) throws -> Void { let context = contextForCurrentThread() context.delete(object) } } public extension Promise { public func thenInBGContext<U>(_ body: @escaping (T) throws -> U) -> Promise<U> { return firstly { return self }.then(on: .global()) { value in return BaseDBService.sharedInstance.performPromiseOnBackgroundContext{ () -> U in return try body(value) } } } }
mit
0d749ed4e967da26f1447e15e0c2bb7e
36.487179
190
0.623043
5.56599
false
false
false
false
haitran2011/Rocket.Chat.iOS
Rocket.Chat/Extensions/UIViewControllerExtension.swift
2
2918
// // UIViewControllerExtension.swift // Rocket.Chat // // Created by Rafael K. Streit on 14/11/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import UIKit import ObjectiveC private var viewScrollViewAssociatedKey: UInt8 = 0 extension UIViewController { var scrollViewInternal: UIScrollView! { get { return objc_getAssociatedObject(self, &viewScrollViewAssociatedKey) as? UIScrollView } set(newValue) { objc_setAssociatedObject(self, &viewScrollViewAssociatedKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: Keyboard Handling func registerKeyboardHandlers(_ scrollView: UIScrollView) { self.scrollViewInternal = scrollView // Keyboard handler NotificationCenter.default.addObserver( self, selector: #selector(UIViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(UIViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil ) } func unregisterKeyboardNotifications() { NotificationCenter.default.removeObserver(self) } internal func keyboardWillShow(_ notification: Foundation.Notification) { let userInfo = notification.userInfo let value = userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue let rawFrame = value?.cgRectValue ?? CGRect.zero let duration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] ?? 0 let scrollView = self.scrollViewInternal UIView.animate( withDuration: (duration as AnyObject).doubleValue, delay: 0, options: UIViewAnimationOptions(), animations: { guard let insets = scrollView?.contentInset else { return } var newInsets = insets newInsets.bottom = rawFrame.height scrollView?.contentInset = newInsets scrollView?.scrollIndicatorInsets = newInsets }, completion: nil ) } internal func keyboardWillHide(_ notification: Foundation.Notification) { let userInfo = notification.userInfo let duration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] ?? 0 let scrollView = self.scrollViewInternal UIView.animate( withDuration: (duration as AnyObject).doubleValue, delay: 0, options: UIViewAnimationOptions(), animations: { let insets = UIEdgeInsets.zero scrollView?.contentInset = insets scrollView?.scrollIndicatorInsets = insets }, completion: nil ) } }
mit
e773c3c21cffbf89520f37522be77e0f
31.054945
140
0.634556
5.916836
false
false
false
false
garricn/secret
Pods/Cartography/Cartography/ViewUtils.swift
5
937
// // ViewUtils.swift // Cartography // // Created by Garth Snyder on 11/23/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif internal func closestCommonAncestor(a: View, b: View) -> View? { let (aSuper, bSuper) = (a.superview, b.superview) if a === b { return a } if a === bSuper { return a } if b === aSuper { return b } if aSuper === bSuper { return aSuper } let ancestorsOfA = Set(ancestors(a)) for ancestor in ancestors(b) { if ancestorsOfA.contains(ancestor) { return ancestor } } return .None } private func ancestors(v: View) -> AnySequence<View> { return AnySequence { () -> AnyGenerator<View> in var view: View? = v return AnyGenerator { let current = view view = view?.superview return current } } }
mit
d2696530c846ac21815fc70bddedfd2d
19.347826
64
0.583333
3.65625
false
false
false
false
JuweTakeheshi/ajuda
Ajuda/VC/DetailCenter /JUWCollectionCenterViewController.swift
1
3931
// // JUWCollectionCenterViewController.swift // Ajuda // // Created by sp4rt4n_0 on 9/23/17. // Copyright © 2017 Juwe Takeheshi. All rights reserved. // import UIKit import RealmSwift class JUWCollectionCenterViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var twitterLabel: UILabel! @IBOutlet weak var productsLabel: UITableView! @IBOutlet weak var callButton: UIButton! var center:JUWMapCollectionCenter! override func viewDidLoad() { super.viewDidLoad() customizeUserInterface() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func customizeUserInterface() { customizeNavigationBarColors() nameLabel.text = collectionCenter().name addressLabel.text = collectionCenter().address twitterLabel.text = collectionCenter().twitterHandle let phoneNumber = collectionCenter().phoneNumber.isEmpty ? "Sin teléfono registrado" : String.localizedStringWithFormat("%@ (llamar)", collectionCenter().phoneNumber) callButton.isEnabled = !collectionCenter().phoneNumber.isEmpty callButton.alpha = collectionCenter().phoneNumber.isEmpty ? 0.7 : 1 callButton.setTitle(phoneNumber, for: .normal) } @IBAction func backAction(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func call() { let formatedNumber = collectionCenter().phoneNumber.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "") if let url = URL(string: "tel://\(formatedNumber)") { let application:UIApplication = UIApplication.shared if (application.canOpenURL(url)) { if #available(iOS 10.0, *) { application.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } } } 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. if segue.identifier == "goToAddProduct"{ let destinationVC = segue.destination as! JUWAddProductViewController destinationVC.currentCenter = collectionCenter() } } // //MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return collectionCenter().products.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "productCell", for: indexPath) cell.textLabel?.text = collectionCenter().products[indexPath.row].name let dateformatter = DateFormatter() dateformatter.dateFormat = "MM/dd/yy HH:mm a" if let date = collectionCenter().products[indexPath.row].updateDate { let formattedDateString = String.localizedStringWithFormat("Actualizado - %@", dateformatter.string(from: date)) cell.detailTextLabel?.text = formattedDateString } return cell } //MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } func collectionCenter() -> JUWCollectionCenter { let realm = try! Realm() let predicate = NSPredicate(format: "centerIdentifier = %@", center.centerIdentifier) return realm.objects(JUWCollectionCenter.self).filter(predicate).first! } }
mit
b495a5e5f4b800960438732d4aa5a675
37.519608
174
0.674472
5.14941
false
false
false
false
gregomni/swift
test/Generics/unify_superclass_types_4.swift
9
1980
// RUN: %target-typecheck-verify-swift -dump-requirement-machine 2>&1 | %FileCheck %s // Note: The GSB fails this test, because it doesn't implement unification of // superclass type constructor arguments. class Base<T> {} protocol Q { associatedtype T } class Derived<TT : Q> : Base<TT.T> {} protocol P1 { associatedtype X : Base<A1> associatedtype A1 } protocol P2 { associatedtype X : Derived<A2> associatedtype A2 : Q } func sameType<T>(_: T.Type, _: T.Type) {} func takesBase<U>(_: Base<U>.Type, _: U.Type) {} func takesDerived<U : Q>(_: Derived<U>.Type, _: U.Type) {} func unifySuperclassTest<T : P1 & P2>(_: T) { sameType(T.A1.self, T.A2.T.self) takesBase(T.X.self, T.A1.self) takesDerived(T.X.self, T.A2.self) } // CHECK-LABEL: Requirement machine for fresh signature < T > // CHECK-NEXT: Rewrite system: { // CHECK: - [P1:X].[superclass: Base<[P1:A1]>] => [P1:X] [explicit] // CHECK: - [P1:X].[layout: _NativeClass] => [P1:X] // CHECK: - [P2:X].[superclass: Derived<[P2:A2]>] => [P2:X] [explicit] // CHECK: - [P2:X].[layout: _NativeClass] => [P2:X] // CHECK: - τ_0_0.[P2:X] => τ_0_0.[P1:X] // CHECK: - τ_0_0.[P1:X].[superclass: Derived<τ_0_0.[P2:A2]>] => τ_0_0.[P1:X] // CHECK: - τ_0_0.[P1:X].[superclass: Base<τ_0_0.[P2:A2].[Q:T]>] => τ_0_0.[P1:X] // CHECK: - τ_0_0.[P2:A2].[Q:T] => τ_0_0.[P1:A1] // CHECK-NEXT: } // CHECK: Property map: { // CHECK-NEXT: [P1] => { conforms_to: [P1] } // CHECK-NEXT: [P1:X] => { layout: _NativeClass superclass: [superclass: Base<[P1:A1]>] } // CHECK-NEXT: [P2] => { conforms_to: [P2] } // CHECK-NEXT: [P2:X] => { layout: _NativeClass superclass: [superclass: Derived<[P2:A2]>] } // CHECK-NEXT: [P2:A2] => { conforms_to: [Q] } // CHECK-NEXT: [Q] => { conforms_to: [Q] } // CHECK-NEXT: τ_0_0 => { conforms_to: [P1 P2] } // CHECK-NEXT: τ_0_0.[P1:X] => { layout: _NativeClass superclass: [superclass: Derived<τ_0_0.[P2:A2]>] } // CHECK-NEXT: }
apache-2.0
2501c139cdc1835df591cfd0d2470231
34.125
106
0.584647
2.446517
false
false
false
false
ctarda/FountainKit
Sources/TableViewDataSource.swift
1
1787
// // TableViewDataSource.swift // FountainKit // // Created by Cesar Tardaguila on 5/3/2016. // import UIKit /** Minimal implementation of the UITableViewDataSource protocol. This class only implements the ethods required by the protocol. This class can be subclassed to implement more of the UICollectionViewDataSource methods */ open class TableViewDataSource<T, U>: NSObject, UITableViewDataSource where T: DataManager, U: DataSettable, U: UITableViewCell, T.DataType == U.DataType { fileprivate let dataManager: T /** Designated initializer. - parameter dataManager: An implementation of the DataManager protocol. In other words, the data collection that is going to populate this collectionview. - parameter cellType: The type of a UITableViewCell subclass that also implements the DataSettable protocol. This parameter is required to enforce that the generic data type that the first parameter handles is the same as the data type that can be passed to the cell */ public init(dataManager: T, cellType: U.Type) { self.dataManager = dataManager } open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if var cell = tableView.dequeueReusableCell(withIdentifier: U.cellReuseIdentifier()) as? U { let dataItem = dataManager.item(indexPath) cell.data = dataItem; return cell } return U(style: .default, reuseIdentifier: U.cellReuseIdentifier()) } open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let itemCount = dataManager.itemCount(section) else { return 0 } return itemCount } }
mit
beeee54f951557b7a7db2729afd97b34
41.547619
271
0.701175
5.17971
false
false
false
false
nVisium/Swift.nV
Swift.nV/AppDelegate.swift
1
7692
// // AppDelegate.swift // Swift.nV // // Created by Seth Law on 6/23/14. // Copyright (c) 2014 nVisiums. All rights reserved. // import UIKit import CoreData import LocalAuthentication @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var appUser: User? 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) { UserDefaults.standard.synchronize() // Lock force user to reauth via fingerprint or pin //print("User should have to reauth...") } 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. //print("This is where we'll want to require reauth") let defaults : UserDefaults = UserDefaults.standard if let imageView : UIImageView = UIApplication.shared.keyWindow?.subviews.last?.viewWithTag(101) as? UIImageView { imageView.removeFromSuperview() } if ( defaults.bool(forKey: "usePin") ) { let sb : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var rvc : UIViewController = (UIApplication.shared.delegate?.window??.rootViewController)! let pvc = sb.instantiateViewController(withIdentifier: "PinViewController") while (rvc.presentedViewController != nil) { rvc = rvc.presentedViewController! } rvc.present(pvc, animated: true, completion: nil) } } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.nvisium.Swift_nV" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "swift_nV", withExtension: "momd") return NSManagedObjectModel(contentsOf: 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.appendingPathComponent("swift_nV.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error //error = NSError.errorWithDomain("swiftnv", 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 \(String(describing: 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(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType) 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 \(String(describing: error)), \(error!.userInfo)") abort() } } } } /*lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "swift_nV") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error { fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() func saveContext() { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch let error as NSError { fatalError("Unresolved error \(error), \(error.userInfo)") } } }*/ }
gpl-2.0
eed21dcfa9384cbaf741de4808063523
47.683544
290
0.662767
5.748879
false
false
false
false
megavolt605/CNLDataProvider
CNLDataProvider/CNLModelObject.swift
1
3083
// // CNLModelObject.swift // CNLDataProvider // // Created by Igor Smirnov on 22/12/2016. // Copyright © 2016 Complex Numbers. All rights reserved. // import Foundation import CNLFoundationTools /// Common class used for access to resources through class bundle reference, holding the singletone for network provider open class CNLModel { /// Callback type for success network request completion public typealias Success = (_ model: CNLModelObject, _ status: Error) -> Void /// Callback type for failed network request public typealias Failed = (_ model: CNLModelObject, _ error: Error?) -> Void /// Type alias for CNLModelError public typealias Error = CNLModelError /// Type alias for CNLModelErrorKind public typealias ErrorKind = CNLModelErrorKind /// Type alias for CNLModelErrorAlert public typealias ErrorAlert = CNLModelErrorAlert /// Common network provider open static var networkProvider: CNLModelNetwork? } /// Common model object public protocol CNLModelObject: class { /// Creates an API struct instance for the model /// /// - Returns: CNLModelAPI instance func createAPI() -> CNLModelAPI? /// Successfull response status var okStatus: CNLModel.Error { get } /// Default initializer init() } // MARK: - Default implementations public extension CNLModelObject { /// Default implementation. Returns nil /// /// - Returns: Returns CNLModelAPI instance public func createAPI() -> CNLModelAPI? { return nil } /// Default implementation. Just mirror to CNLModel.networkProvider.performRequest /// /// - Parameters: /// - api: CNLModelAPI instance /// - success: Callback when operation was successfull /// - fail: Callback when operation was failed public func defaultAPIPerform(_ api: CNLModelAPI, success: @escaping CNLModel.Success, fail: @escaping CNLModel.Failed) { CNLModel.networkProvider?.performRequest( api: api, success: { apiObject in success(self, apiObject.status) }, fail: { apiObject in fail(self, apiObject.errorStatus) }, networkError: { apiObject, error in fail(self, apiObject.errorStatus(error)) } ) } } /// Model with primary (uniquie) key public protocol CNLModelObjectPrimaryKey: CNLModelObject { /// Primary key type associatedtype KeyType: CNLDictionaryValue /// Primary key value var primaryKey: KeyType { get } /// Initializer with primary key init?(keyValue: KeyType) /// String representation of the primary key var encodedPrimaryKey: String? { get } } // MARK: - Default implementations public extension CNLModelObjectPrimaryKey { /// By default, encodedPrimaryKey equals string reporesentation of primaryKey property public var encodedPrimaryKey: String? { return "\(primaryKey)" } } /// Editable model protocol public protocol CNLModelObjectEditable { var editing: Bool { get set } func updateList() }
mit
4a1524a23d27ad85e9b13af202972149
29.215686
125
0.68462
4.995138
false
false
false
false
glwithu06/ReTodo
ReTodo/View/TaskListViewController.swift
1
4204
// // TaskListViewController.swift // ReTodo // // Created by Nate Kim on 11/07/2017. // Copyright © 2017 NateKim. All rights reserved. // import UIKit import ReSwift class TaskListViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint! override var isEditing: Bool { didSet { tableView.setEditing(isEditing, animated: true) UIView.animate(withDuration: 0.1) { self.toolbarBottomConstraint.constant = self.isEditing ? 0 : -44 self.view.layoutIfNeeded() } updateNavigationBarButtonItems() } } override func viewDidLoad() { super.viewDidLoad() title = "Todo" mainStore.subscribe(self) tableView.register(UINib(nibName: "TaskCell", bundle: nil), forCellReuseIdentifier: TaskCell.identifier()) tableView.allowsMultipleSelectionDuringEditing = true updateNavigationBarButtonItems() } deinit { mainStore.unsubscribe(self) } func addTapped() { let vc = EditTaskViewController(nibName: "EditTaskViewController", bundle: nil) let nvc = UINavigationController(rootViewController: vc) present(nvc, animated: true, completion: nil) } func editTapped() { self.isEditing = true } func cancelTapped() { self.isEditing = false } @IBAction func toggleAllButtonTapped(_ sender: Any) { mainStore.dispatch(ToggleAllTaskAction()) } @IBAction func deleteButtonTapped(_ sender: Any) { guard let indexPaths = tableView.indexPathsForSelectedRows else { return } let deleteIDs = indexPaths.map({ return mainStore.state.taskState.task(at: $0.row)?.id }).flatMap({ $0 }) mainStore.dispatch(DeleteTasksAction(ids: deleteIDs)) } private func updateNavigationBarButtonItems() { if isEditing { navigationItem.rightBarButtonItem = nil navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelTapped)) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTapped)) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editTapped)) } } } extension TaskListViewController: StoreSubscriber { func newState(state: AppState) { tableView.reloadData() } } extension TaskListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mainStore.state.taskState.numberOfTasks() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: TaskCell.identifier()) as? TaskCell else { return UITableViewCell() } cell.task = mainStore.state.taskState.task(at: indexPath.row) cell.delegate = self return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { if let task = mainStore.state.taskState.task(at: indexPath.row) { mainStore.dispatch(DeleteTaskAction(id: task.id)) } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if isEditing == false { tableView.deselectRow(at: indexPath, animated: true) let vc = TaskDetailViewController(nibName: "TaskDetailViewController", bundle: nil) vc.task = mainStore.state.taskState.task(at: indexPath.row) navigationController?.pushViewController(vc, animated: true) } } } extension TaskListViewController: TaskCellDelegate { func cell(cell: TaskCell, toggleTask task: Task) { mainStore.dispatch(ToggleTaskAction(id: task.id)) } }
mit
b89d1246b0261d5f01157c1454e9b07d
35.547826
140
0.66857
5.106926
false
false
false
false
Hamuko/Nullpo
Nullpo/_0x0.swift
1
437
import Foundation class _0x0: UploaderProtocol { static let url = NSURL(string: "https://0x0.st")! static let data = [String: NSData]() static let errorMessages: [String] = [String]() static func daysValid(file: UploadFile) -> Int { let filesize: Double = Double(file.filesize) / 1024 / 1024 let days: Double = 30.0 + (-365.0 + 30.0) * pow(filesize / 256.0 - 1.0, 3.0) return Int(days) } }
apache-2.0
bdc976b7d01f3fd2d98394c449e24b31
30.214286
84
0.608696
3.310606
false
false
false
false
danielpi/NetlistConverter
NetlistConverter/AppDelegate.swift
1
6119
// // AppDelegate.swift // NetlistConverter // // Created by Daniel Pink on 24/06/2014. // Copyright (c) 2014 Electronic Innovations. All rights reserved. // import Cocoa class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet var window: NSWindow! var netlist: Netlist? = nil @IBOutlet var progressIndicator : NSProgressIndicator! @IBOutlet var cancelButton : NSButton! var numericOrder = false func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application self.progressIndicator.hidden = true } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func loadNetlist(sender : AnyObject) { let panel = NSOpenPanel() panel.canChooseDirectories = false panel.allowsMultipleSelection = false panel.message = "Select a Netlist file" panel.allowedFileTypes = ["net", "NET", "repnl", "REPNL"] let completionBlock: (Int) -> Void = { result in if result == NSFileHandlingPanelOKButton { let urls = panel.URLs as NSArray let url = urls.firstObject as! NSURL let fileContents: NSString? do { fileContents = try NSString(contentsOfURL: url, encoding: NSUTF8StringEncoding) } catch _ { fileContents = nil } if let contents = fileContents, let pathExt = url.pathExtension { switch pathExt { case "net", "NET": self.numericOrder = false let fileNetlist = Netlist(fromString: contents as String) self.netlist = Netlist(fromString: contents as String) fileNetlist.prettyPrint() case "repnl", "REPNL": self.numericOrder = true //let fileNetlist = Netlist(REPNLFromString as REPNLString: contents) let fileNetlist = Netlist(REPNLFromString: contents as REPNLString) self.netlist = fileNetlist fileNetlist.prettyPrint() default: print("Tried to use a txt file") } } else { } } } panel.beginSheetModalForWindow(self.window, completionHandler: completionBlock) } @IBAction func exportMatrix(sender : AnyObject) { let panel = NSSavePanel() panel.allowedFileTypes = ["txt"] panel.message = "Where do you want to save the connection matrix to?" panel.nameFieldStringValue = "ConnectionMatrix" let completionBlock: (Int) -> Void = { result in if result == NSFileHandlingPanelOKButton { if let url = panel.URL { if let theNetList = self.netlist { // Set up a progress object self.progressIndicator.hidden = false let progress = NSProgress(totalUnitCount: 2) let options : NSKeyValueObservingOptions = [.New, .Old, .Initial, .Prior] progress.addObserver(self, forKeyPath: "fractionCompleted", options: options, context: nil) let queue: dispatch_queue_t = dispatch_queue_create("My Queue", DISPATCH_QUEUE_SERIAL) dispatch_async(queue) { progress.becomeCurrentWithPendingUnitCount(1) let connectionMatrix = theNetList.exportConnectionMatrix(self.numericOrder) progress.resignCurrent() progress.becomeCurrentWithPendingUnitCount(1) let output = connectionMatrix.description(!(self.numericOrder)) do { //print(output) try output.writeToURL(url, atomically: true, encoding: NSMacOSRomanStringEncoding) } catch _ { } progress.resignCurrent() } } } } } panel.beginSheetModalForWindow(self.window, completionHandler: completionBlock) } @IBAction func cancelOperation(sender : AnyObject) { } //override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafePointer<()>) { override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<()>) { NSOperationQueue.mainQueue().addOperationWithBlock( { let progress = object as! NSProgress self.progressIndicator.doubleValue = ceil(progress.fractionCompleted * 100.0) / 100.0 //println("\(progress.fractionCompleted)") } ) } /* - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (context == ProgressObserverContext) { [[NSOperationQueue mainQueue] addOperationWithBlock:^{ NSProgress *progress = object; self.progressBar.progress = progress.fractionCompleted; self.progressLabel.text = progress.localizedDescription; self.progressAdditionalInfoLabel.text = progress.localizedAdditionalDescription; }]; } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } */ }
mit
394bd00b824b86ab579f40e03c73c760
40.067114
157
0.548129
5.912077
false
false
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/tree/pattern/TagChunk.swift
8
3179
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// /// Represents a placeholder tag in a tree pattern. A tag can have any of the /// following forms. /// /// * `expr`: An unlabeled placeholder for a parser rule `expr`. /// * `ID`: An unlabeled placeholder for a token of type `ID`. /// * `e:expr`: A labeled placeholder for a parser rule `expr`. /// * `id:ID`: A labeled placeholder for a token of type `ID`. /// /// This class does not perform any validation on the tag or label names aside /// from ensuring that the tag is a non-null, non-empty string. /// public class TagChunk: Chunk, CustomStringConvertible { /// /// This is the backing field for _#getTag_. /// private let tag: String /// /// This is the backing field for _#getLabel_. /// private let label: String? /// /// Construct a new instance of _org.antlr.v4.runtime.tree.pattern.TagChunk_ using the specified tag and /// no label. /// /// - Parameter tag: The tag, which should be the name of a parser rule or token /// type. /// /// - Throws: ANTLRError.illegalArgument if `tag` is `null` or /// empty. /// public convenience init(_ tag: String) throws { try self.init(nil, tag) } /// /// Construct a new instance of _org.antlr.v4.runtime.tree.pattern.TagChunk_ using the specified label /// and tag. /// /// - Parameter label: The label for the tag. If this is `null`, the /// _org.antlr.v4.runtime.tree.pattern.TagChunk_ represents an unlabeled tag. /// - Parameter tag: The tag, which should be the name of a parser rule or token /// type. /// /// - Throws: ANTLRError.illegalArgument if `tag` is `null` or /// empty. /// public init(_ label: String?, _ tag: String) throws { self.label = label self.tag = tag super.init() if tag.isEmpty { throw ANTLRError.illegalArgument(msg: "tag cannot be null or empty") } } /// /// Get the tag for this chunk. /// /// - Returns: The tag for the chunk. /// public final func getTag() -> String { return tag } /// /// Get the label, if any, assigned to this chunk. /// /// - Returns: The label assigned to this chunk, or `null` if no label is /// assigned to the chunk. /// public final func getLabel() -> String? { return label } /// /// This method returns a text representation of the tag chunk. Labeled tags /// are returned in the form `label:tag`, and unlabeled tags are /// returned as just the tag name. /// public var description: String { if let label = label { return "\(label):\(tag)" } else { return tag } } override public func isEqual(_ other: Chunk) -> Bool { guard let other = other as? TagChunk else { return false } return tag == other.tag && label == other.label } }
bsd-3-clause
02622170a97d07535067f3eda859a94f
29.27619
108
0.588235
4.14472
false
false
false
false
AnasAlhasani/Metallica
Metallica/Views/AlbumView.swift
1
2004
// // AlbumView.swift // Metallica // // Created by Anas on 9/26/17. // Copyright © 2017 Anas Alhasani. All rights reserved. // import UIKit class AlbumView: UIView { @IBOutlet private weak var imageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var dateLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() imageView.layer.cornerRadius = 10 imageView.layer.masksToBounds = true } var album: Album? { didSet{ if let album = album { imageView.image = album.image titleLabel.text = album.title dateLabel.text = album.date } } } private func prepareForAnimation(viewWidth width: CGFloat) { imageView.center.x += width titleLabel.center.x += width dateLabel.center.x += width } func setViewsHidden(_ isHidden: Bool) { imageView.isHidden = isHidden titleLabel.isHidden = isHidden dateLabel.isHidden = isHidden } func startAnimation(direction: ScrollDirection) { let viewWidth = direction == .right ? bounds.width: -bounds.width setViewsHidden(false) prepareForAnimation(viewWidth: viewWidth) UIView.animate(withDuration: 0.6) { [weak self] in guard let strongSelf = self else { return } strongSelf.imageView.center.x -= viewWidth } UIView.animate(withDuration: 0.6, delay: 0.2, options: [], animations: { [weak self] in guard let strongSelf = self else { return } strongSelf.titleLabel.center.x -= viewWidth }, completion: nil) UIView.animate(withDuration: 0.6, delay: 0.3, options: [], animations: { [weak self] in guard let strongSelf = self else { return } strongSelf.dateLabel.center.x -= viewWidth }, completion: nil) } }
mit
7c23d766f91551b57f32bdd9f479da04
28.028986
95
0.595607
4.712941
false
false
false
false
JanGorman/MapleBacon
MapleBacon/Core/Cache/MemoryCache.swift
2
1491
// // Copyright © 2020 Schnaub. All rights reserved. // import Foundation final class MemoryCache<Key: Hashable, Value> { private let backingCache = NSCache<WrappedKey, Entry>() subscript(key: Key) -> Value? { get { value(forKey: key) } set { guard let value = newValue else { removeValue(forKey: key) return } insert(value, forKey: key) } } init(name: String = "") { backingCache.name = name } func isCached(forKey key: Key) -> Bool { self[key] != nil } func clear() { backingCache.removeAllObjects() } } private extension MemoryCache { func insert(_ value: Value, forKey key: Key) { backingCache.setObject(Entry(value: value), forKey: WrappedKey(key: key)) } func value(forKey key: Key) -> Value? { let entry = backingCache.object(forKey: WrappedKey(key: key)) return entry?.value } func removeValue(forKey key: Key) { backingCache.removeObject(forKey: WrappedKey(key: key)) } } extension MemoryCache { private class WrappedKey: NSObject { private let key: Key override var hash: Int { key.hashValue } init(key: Key) { self.key = key } override func isEqual(_ object: Any?) -> Bool { guard let value = object as? WrappedKey else { return false } return value.key == key } } private class Entry { let value: Value init(value: Value) { self.value = value } } }
mit
6c38ba0f020fca95067dca45dbbf11db
16.529412
77
0.60604
3.820513
false
false
false
false
HackSheffieldTeamImperial/Blockspot
Blockspot/ViewController.swift
1
8050
// // ViewController.swift // Blockspot // // Created by Alessandro Bonardi on 15/10/2016. // Copyright © 2016 Alessandro Bonardi. All rights reserved. // import Cocoa import MapKit var WorkSpaces: [WorkSpace] = [WorkSpace.init(radius: 200.0, location: CLLocationCoordinate2D(latitude: 53.3843472317644, longitude: -1.4787873210134975), name: "Huxley308"), WorkSpace.init(radius: 100.0, location: CLLocationCoordinate2D(latitude: 53.3793472317644, longitude: -1.485873210134975), name: "LibraryMeeting01")] class ViewController: NSViewController, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet var addWorkspaceButton: NSButton! @IBOutlet var changeRadiusSlider: NSSlider! @IBOutlet var doneButton: DoneNSButton! @IBOutlet var nameTextField: NSTextField! @IBOutlet var instructionLabel: NSTextField! @IBOutlet weak var joinButton: NSButton! @IBAction func radiusSliderChanged(_ sender: AnyObject) { mapView.remove(mapView.overlays.last!) let circleOverlay = MKCircle(center: (locationManager.location?.coordinate)!, radius: changeRadiusSlider.doubleValue) mapView.add(circleOverlay) } @IBAction func joinButtonClicked(_ sender: AnyObject) { joinButton.isHidden = true //RUN THE SCRIPT } @IBAction func workspaceButtonClicked(_ sender: AnyObject) { print("yes!") changeRadiusSlider.isHidden = false changeRadiusSlider.isEnabled = true doneButton.isHidden = false doneButton.isEnabled = true nameTextField.isHidden = false nameTextField.isEnabled = true instructionLabel.isHidden = false let circleOverlay = MKCircle(center: (locationManager.location?.coordinate)!, radius: changeRadiusSlider.doubleValue) mapView.add(circleOverlay) } @IBAction func doneButtonClicked(_ sender: AnyObject) { changeRadiusSlider.isHidden = true changeRadiusSlider.isEnabled = false doneButton.isHidden = true doneButton.isEnabled = false nameTextField.isHidden = true nameTextField.isEnabled = false instructionLabel.isHidden = true // ADD NEW WORKSPACE let workspace = WorkSpace(radius: changeRadiusSlider.doubleValue, location: (locationManager.location?.coordinate)!, name: nameTextField.stringValue) WorkSpaces.append(workspace) mapView.removeOverlays(mapView.overlays) drawCircles() } var locationManager = CLLocationManager() let regionRadius: CLLocationDistance = 500 override func viewDidLoad() { let WB : WebsiteBlock = WebsiteBlock(list : ["www.zubair.com", "wwww.java.com"]) WB.rewriteHostFile() super.viewDidLoad() self.locationManager.delegate = self let status = CLLocationManager.authorizationStatus() if status == .restricted || status == .denied { return } self.mapView.delegate = self self.mapView.showsBuildings = true locationManager.startUpdatingLocation() self.mapView.showsUserLocation = true self.locationManager.desiredAccuracy = kCLLocationAccuracyBest centerMapOnLocation(location: locationManager.location!) drawCircles() } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance( location.coordinate, regionRadius * 2.0, regionRadius * 2.0) mapView.setRegion(coordinateRegion, animated: true) } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case .authorized, .authorizedWhenInUse: manager.startUpdatingLocation() self.mapView.showsUserLocation = true centerMapOnLocation(location: manager.location!) default: break } } func drawCircles() { for workSpace in WorkSpaces { print("bubu") let circleOverlay = MKCircle(center: workSpace.location, radius: workSpace.radius) mapView.add(circleOverlay) } } func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let circleRenderer = MKCircleRenderer(overlay: overlay) circleRenderer.fillColor = NSColor.red circleRenderer.alpha = 0.1 return circleRenderer } override func mouseUp(with event: NSEvent) { var clickPoint = event.locationInWindow clickPoint.y = mapView.frame.height - clickPoint.y let clickCoordinate = mapView.convert(clickPoint, toCoordinateFrom: mapView) let clickLocation = CLLocation(latitude: clickCoordinate.latitude, longitude: clickCoordinate.longitude) for circle in mapView.overlays as! [MKCircle] { //print("ok") let centreCoordinate = circle.coordinate let centreLocation = CLLocation(latitude: centreCoordinate.latitude, longitude: centreCoordinate.longitude) //print(centreLocation) //print(clickLocation) //print(centreLocation.distance(from: clickLocation)) if centreLocation.distance(from: clickLocation) < circle.radius { let circleRenderer = MKCircleRenderer(overlay: circle) circleRenderer.fillColor = NSColor.red circleRenderer.alpha = 0.5 mapView.add(circle) print("OLE!!!") for workspace in WorkSpaces { let workspaceLocation = CLLocation(latitude: workspace.location.latitude, longitude: workspace.location.longitude) print(workspaceLocation) print(centreLocation) if workspace.location.latitude == centreCoordinate.latitude && workspace.location.longitude == centreCoordinate.longitude { print("haha") var annotation = MKPointAnnotation() annotation.coordinate = workspace.location annotation.title = workspace.name mapView.addAnnotation(annotation) mapView.selectAnnotation(annotation, animated: true) } } } } } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { //self.mapView.centerCoordinate = (userLocation.location?.coordinate)! //centerMapOnLocation(location: self.mapView.userLocation.location!) } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { print("oleeeee") if !(annotation is MKPointAnnotation) { return nil } let identifier = "annotation" var anView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) if anView == nil { anView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) anView?.isEnabled = true anView?.canShowCallout = true joinButton.isHidden = false joinButton.isEnabled = true //let btn = NSButton() //btn.setButtonType(NSButtonType.momentaryPushIn) //anView?.rightCalloutAccessoryView = btn } else { anView?.annotation = annotation } return anView } }
gpl-3.0
789d1d565ccc6e74793e4ed992fdde7f
35.753425
157
0.612498
5.782328
false
false
false
false
huangboju/Moots
算法学习/LeetCode/LeetCode/LinkList/DetectCycle.swift
1
656
// // DetectCycle.swift // LeetCode // // Created by 黄伯驹 on 2020/4/4. // Copyright © 2020 伯驹 黄. All rights reserved. // import Foundation // https://leetcode.cn/problems/linked-list-cycle-ii/submissions/ func detectCycle(_ head: ListNode?) -> ListNode? { var fast = head, slow = head while fast != nil && fast?.next != nil { slow = slow?.next fast = fast?.next?.next if fast === slow { break } } if fast == nil || fast?.next == nil { return nil } slow = head while slow !== fast { slow = slow?.next fast = fast?.next } return slow }
mit
69e8ae4de84903be4a1683a945d27add
20.433333
65
0.541213
3.674286
false
false
false
false
John-Connolly/Merge
Merge.swift
1
9938
// // Merge.swift // // // Created by John Connolly on 2016-03-20. // // import Foundation import AVKit import AVFoundation final class Merge { fileprivate let configuration: MergeConfiguration init(config: MergeConfiguration) { self.configuration = config } fileprivate var fileUrl: URL { let fullPath = configuration.directory + "/export\(NSUUID().uuidString).mov" return URL(fileURLWithPath: fullPath) } /** Overlays and exports a video with a desired UIImage on top. - Parameter video: AVAsset - Paremeter overlayImage: UIImage - Paremeter completion: Completion Handler - Parameter progressHandler: Returns the progress every 500 milliseconds. */ func overlayVideo(video: AVAsset, overlayImage: UIImage, completion: @escaping (_ URL: URL?) -> Void, progressHandler: @escaping (_ progress: Float) -> Void) { let videoTracks = video.tracks(withMediaType: AVMediaTypeVideo) guard !videoTracks.isEmpty else { return } let videoTrack = videoTracks[0] let audioTracks = video.tracks(withMediaType: AVMediaTypeAudio) let audioTrack = audioTracks.isEmpty ? nil : audioTracks[0] let compositionTry = try? Composition(duration: video.duration, videoAsset: videoTrack, audioAsset: audioTrack) guard let composition = compositionTry else { return } let videoTransform = Transform(videoTrack.preferredTransform) let layerInstruction = LayerInstruction(track: composition.videoTrack, transform: videoTrack.preferredTransform, duration: video.duration) let instruction = Instruction(length: video.duration, layerInstructions: [layerInstruction.instruction]) let size = Size(isPortrait: videoTransform.isPortrait, size: videoTrack.naturalSize) let layer = Layer(overlay: overlayImage, size: size.naturalSize, placement: configuration.placement) let videoComposition = VideoComposition(size: size.naturalSize, instruction: instruction, frameRate: configuration.frameRate, layer: layer ) Exporter(asset: composition.asset, outputUrl: fileUrl, composition: videoComposition.composition, quality: configuration.quality).map { exporter in exporter.render { url in completion(url) } exporter.progress = { progress in progressHandler(progress) } } ?? completion(nil) } } /** Determines overlay placement. - stretchFit: Stretches the ovelay to cover the entire video frame. This is ideal for situations for adding drawing to a video. - custom: Custom coordinates for the ovelay. */ enum Placement { case stretchFit case custom(x: CGFloat, y: CGFloat, size: CGSize) func rect(videoSize: CGSize) -> CGRect { switch self { case .stretchFit: return CGRect(origin: .zero, size: videoSize) case .custom(let x, let y, let size): return CGRect(x: x, y: y, width: size.width, height: size.height) } } } /** Determines export Quality - low - medium - high */ enum Quality: String { case low case medium case high var value: String { switch self { case .low: return AVAssetExportPresetLowQuality case .medium: return AVAssetExportPresetMediumQuality case .high: return AVAssetExportPresetHighestQuality } } } fileprivate final class LayerInstruction { let instruction: AVMutableVideoCompositionLayerInstruction init(track: AVMutableCompositionTrack, transform: CGAffineTransform, duration: CMTime) { instruction = AVMutableVideoCompositionLayerInstruction(assetTrack: track) instruction.setTransform(transform, at: kCMTimeZero) instruction.setOpacity(0.0, at: duration) } } fileprivate final class Composition { let asset = AVMutableComposition() let videoTrack: AVMutableCompositionTrack var audioTrack: AVMutableCompositionTrack? init(duration: CMTime, videoAsset: AVAssetTrack, audioAsset: AVAssetTrack? = nil) throws { videoTrack = asset.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) try videoTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, duration), of: videoAsset, at: kCMTimeZero) if let audioAsset = audioAsset { audioTrack = asset.addMutableTrack(withMediaType: AVMediaTypeAudio, preferredTrackID: Int32(kCMPersistentTrackID_Invalid)) try audioTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, duration), of: audioAsset, at: kCMTimeZero) } } } fileprivate final class Instruction { let videoComposition = AVMutableVideoCompositionInstruction() init(length: CMTime, layerInstructions: [AVVideoCompositionLayerInstruction]) { videoComposition.timeRange = CMTimeRangeMake(kCMTimeZero, length) videoComposition.layerInstructions = layerInstructions } } fileprivate final class VideoComposition { let composition = AVMutableVideoComposition() init(size: CGSize, instruction: Instruction, frameRate: Int32, layer: Layer) { composition.renderSize = size composition.instructions = [instruction.videoComposition] composition.frameDuration = CMTimeMake(1, frameRate) composition.animationTool = AVVideoCompositionCoreAnimationTool( postProcessingAsVideoLayer: layer.videoAndParent.video, in: layer.videoAndParent.parent ) } } fileprivate final class Layer { fileprivate let overlay: UIImage fileprivate let size: CGSize fileprivate let placement: Placement init(overlay: UIImage, size: CGSize, placement: Placement) { self.overlay = overlay self.size = size self.placement = placement } fileprivate var frame: CGRect { return CGRect(origin: .zero, size: size) } fileprivate var overlayFrame: CGRect { return placement.rect(videoSize: size) } lazy var videoAndParent: VideoAndParent = { let overlayLayer = CALayer() overlayLayer.contents = self.overlay.cgImage overlayLayer.frame = self.overlayFrame overlayLayer.masksToBounds = true let videoLayer = CALayer() videoLayer.frame = self.frame let parentLayer = CALayer() parentLayer.frame = self.frame parentLayer.addSublayer(videoLayer) parentLayer.addSublayer(overlayLayer) return VideoAndParent(video: videoLayer, parent: parentLayer) }() final class VideoAndParent { let video: CALayer let parent: CALayer init(video: CALayer, parent: CALayer) { self.video = video self.parent = parent } } } /// A wrapper of AVAssetExportSession. fileprivate final class Exporter { fileprivate let session: AVAssetExportSession var progress: ((_ progress: Float) -> Void)? init?(asset: AVMutableComposition, outputUrl: URL, composition: AVVideoComposition, quality: Quality) { guard let session = AVAssetExportSession(asset: asset, presetName: quality.value) else { return nil } self.session = session self.session.outputURL = outputUrl self.session.outputFileType = AVFileTypeQuickTimeMovie self.session.videoComposition = composition } func render(complete: @escaping (_ url: URL?) -> Void) { let group = DispatchGroup() group.enter() DispatchQueue.global(qos: .utility).async(group: group) { self.session.exportAsynchronously { group.leave() DispatchQueue.main.async { complete(self.session.outputURL) } } self.progress(session: self.session, group: group) } } /** Polls the AVAssetExportSession status every 500 milliseconds. - Parameter session: AVAssetExportSession - Parameter group: DispatchGroup */ private func progress(session: AVAssetExportSession, group: DispatchGroup) { while session.status == .waiting || session.status == .exporting { progress?(session.progress) _ = group.wait(timeout: DispatchTime.now() + .milliseconds(500)) } } } /// Provides an easy way to detemine if the video was taken in landscape or portrait. private struct Transform { fileprivate let transform: CGAffineTransform init(_ transform: CGAffineTransform) { self.transform = transform } var isPortrait: Bool { guard transform.a == 0 && transform.d == 0 else { return false } switch (transform.b, transform.c) { case(1.0, -1.0): return true case(-1.0, 1.0): return true default: return false } } } private struct Size { fileprivate let isPortrait: Bool fileprivate let size: CGSize var naturalSize: CGSize { return isPortrait ? CGSize(width: size.height, height: size.width) : size } } /// Configuration struct. Open for extension. struct MergeConfiguration { let frameRate: Int32 let directory: String let quality: Quality let placement: Placement } extension MergeConfiguration { static var standard: MergeConfiguration { return MergeConfiguration(frameRate: 30, directory: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0], quality: Quality.high, placement: Placement.stretchFit) } }
mit
6080a3e7ed1c134490338f26e99b643c
31.161812
198
0.655263
5.200419
false
false
false
false
yosan/AwsChat
AwsChat/AWSChatMessage.swift
1
708
// // AWSChatMessage.swift // AwsChat // // Created by Takahashi Yosuke on 2016/07/10. // Copyright © 2016年 Yosan. All rights reserved. // import Foundation import AWSDynamoDB /// DynamoDB Object for AWSChatMessages class AWSChatMessage: AWSDynamoDBObjectModel, AWSDynamoDBModeling { var MessageId: NSString = "" var RoomId: NSString = "" var UserId: NSString = "" var Text: NSString = "" var Time: NSNumber = 0 static func dynamoDBTableName() -> String { return "AWSChatMessages" } static func hashKeyAttribute() -> String { return "RoomId" } static func rangeKeyAttribute() -> String { return "MessageId" } }
mit
dded750b13b62fe4dce3c5a0c9dc745f
20.393939
67
0.641135
4.246988
false
false
false
false
cfilipov/TextTable
Sources/TextTable/HtmlFormat.swift
1
1911
// // HTMLFormat.swift // TextTable // // Created by Cristian Filipov on 8/13/16. // // import Foundation public enum Html: TextTableStyle { public static func prepare(_ s: String, for column: Column) -> String { var string = s if let width = column.width { string = string.truncated(column.truncate, length: width) } return escape(string) } public static func escape(_ s: String) -> String { return s .replacingOccurrences(of: "&", with: "&amp;") .replacingOccurrences(of: "<", with: "&lt;") .replacingOccurrences(of: "<", with: "&gt;") } private static func string(for alignment: Alignment) -> String { switch alignment { case .left: return "left" case .right: return "right" case .center: return "center" } } private static func string(header col: Column) -> String { return " <th style=\"text-align:\(string(for: col.align));\">" + col.headerString(for: self) + "</th>\n" } private static func string(row col: Column) -> String { return " <td>" + col.string(for: self) + "</td>\n" } public static func begin(_ table: inout String, index: Int, columns: [Column]) { table += "<table>\n" } public static func end(_ table: inout String, index: Int, columns: [Column]) { table += "</table>\n" } public static func header(_ table: inout String, index: Int, columns: [Column]) { table += " <tr>\n" for col in columns { table += string(header: col) } table += " </tr>\n" } public static func row(_ table: inout String, index: Int, columns: [Column]) { table += " <tr>\n" for col in columns { table += string(row: col) } table += " </tr>\n" } }
mit
7a38e65261f05912fcfd8ea3ded086d1
27.522388
85
0.535322
3.940206
false
false
false
false
nacho4d/Kitura-net
Sources/KituraNet/HttpServer.swift
1
5043
/** * 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 KituraSys import BlueSocket // MARK: HttpServer public class HttpServer { /// /// Queue for listening and establishing new connections /// private static var listenerQueue = Queue(type: .PARALLEL, label: "HttpServer.listenerQueue") /// /// Queue for handling client requests /// private static var clientHandlerQueue = Queue(type: .PARALLEL, label: "HttpServer.clientHAndlerQueue") /// /// HttpServerDelegate /// public weak var delegate: HttpServerDelegate? /// /// Http service provider interface /// private let spi: HttpServerSpi /// /// Port number for listening for new connections /// private var _port: Int? public var port: Int? { get { return _port } } /// /// TCP socket used for listening for new connections /// private var listenSocket: BlueSocket? /// /// Initializes an HttpServer instance /// /// - Returns: an HttpServer instance /// public init() { spi = HttpServerSpi() spi.delegate = self } /// /// Listens for connections on a socket /// /// - Parameter port: port number for new connections (ex. 8090) /// - Parameter notOnMainQueue: whether to have the listener run on the main queue /// public func listen(port: Int, notOnMainQueue: Bool=false) { self._port = port do { self.listenSocket = try BlueSocket.defaultConfigured() } catch let error as BlueSocketError { print("Error reported:\n \(error.description)") } catch { print("Unexpected error...") } let queuedBlock = { self.spi.spiListen(self.listenSocket, port: self._port!) } if notOnMainQueue { HttpServer.listenerQueue.queueAsync(queuedBlock) } else { Queue.queueIfFirstOnMain(HttpServer.listenerQueue, block: queuedBlock) } } /// /// Stop listening for new connections /// public func stop() { if let listenSocket = listenSocket { spi.stopped = true listenSocket.close() } } /// /// Static method to create a new HttpServer and have it listen for conenctions /// /// - Parameter port: port number for accepting new connections /// - Parameter delegate: the delegate handler for Http connections /// - Parameter notOnMainQueue: whether to listen for new connections on the main Queue /// /// - Returns: a new HttpServer instance /// public static func listen(port: Int, delegate: HttpServerDelegate, notOnMainQueue: Bool=false) -> HttpServer { let server = Http.createServer() server.delegate = delegate server.listen(port, notOnMainQueue: notOnMainQueue) return server } } // MARK: HttpServerSpiDelegate extension extension HttpServer : HttpServerSpiDelegate { /// /// Handle a new client Http request /// /// - Parameter clientSocket: the socket used for connecting /// func handleClientRequest(clientSocket: BlueSocket) { if let delegate = delegate { HttpServer.clientHandlerQueue.queueAsync() { let response = ServerResponse(socket: clientSocket) let request = ServerRequest(socket: clientSocket) request.parse() { status in switch status { case .Success: delegate.handleRequest(request, response: response) case .ParsedLessThanRead: print("ParsedLessThanRead") response.statusCode = .BAD_REQUEST do { try response.end() } catch { // handle error in connection } case .UnexpectedEOF: print("UnexpectedEOF") case .InternalError: print("InternalError") } } } } } } /// /// Delegate protocol for an HttpServer /// public protocol HttpServerDelegate: class { func handleRequest(request: ServerRequest, response: ServerResponse) }
apache-2.0
acc0a55064d228ec89226c908c59a07e
26.557377
114
0.580408
5.053106
false
false
false
false
dymx101/Gamers
Gamers/Service/UserBL.swift
1
9566
// // UserBL.swift // Gamers // // Created by 虚空之翼 on 15/7/24. // Copyright (c) 2015年 Freedom. All rights reserved. // import Foundation import Alamofire import Bolts import SwiftyJSON import RealmSwift class UserBL: NSObject { // 单例模式 static let sharedSingleton = UserBL() // 用户登入 func UserLogin(#userName: String, password: String) -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return UserDao.UserLogin(userName: userName, password: password) }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let user = task.result as? User { return BFTask(result: user) } if let response = task.result as? Response { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } // Google用户登入 func GoogleLogin(#userId: String, userName: String?, email: String?, idToken: String?) -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return UserDao.GoogleLogin(userId: userId, userName: userName, email: email, idToken: idToken) }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let user = task.result as? User { return BFTask(result: user) } if let response = task.result as? Response { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } // 获取用户订阅频道的视频列表 func getSubscriptions(#userToken: String?) -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return UserDao.Subscriptions(userToken: userToken) }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let users = task.result as? [User] { return BFTask(result: users) } if let response = task.result as? Response { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } // 用户订阅频道 func setSubscribe(#channelId: String) -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return UserDao.Subscribe(channelId: channelId) }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let response = task.result as? Response { return BFTask(result: response) } if let response = task.result as? Response { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } // 登入,添加用户 func saveUser(user: User) { let realm = Realm() realm.write { realm.add(user, update: true) } } // 追隨 todo:统一使用Router func setFollow(#channelId: String) { let userDefaults = NSUserDefaults.standardUserDefaults() //用户全局登入信息 let isLogin = userDefaults.boolForKey("isLogin") let headers = [ "Auth-token": userDefaults.stringForKey("userToken")! ] if isLogin { Alamofire.request(.POST, "http://beta.gamers.tm:3000/mobile_api/subscribe?userId=\(channelId)", headers: headers).responseJSON { _, _, JSONData, _ in let response = Response.collection(json: JSON(JSONData!)) if response.code == "0" { let alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Subscribe to success", comment: "订阅成功"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } else { let alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Subscribe to fail", comment: "订阅失败"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } } } else { var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Please Login", comment: "请先登入"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } } // 取消追隨 todo:统一使用Router func setUnFollow(#channelId: String) { let userDefaults = NSUserDefaults.standardUserDefaults() //用户全局登入信息 let isLogin = userDefaults.boolForKey("isLogin") let headers = [ "Auth-token": userDefaults.stringForKey("userToken")! ] if isLogin { Alamofire.request(.POST, "http://beta.gamers.tm:3000/mobile_api/unsubscribe?userId=\(channelId)", headers: headers).responseJSON { _, _, JSONData, _ in let response = Response.collection(json: JSON(JSONData!)) // if response.code == "0" { // let alertView: UIAlertView = UIAlertView(title: "", message: "取消成功", delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) // alertView.show() // } else { // let alertView: UIAlertView = UIAlertView(title: "", message: "取消失败", delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) // alertView.show() // } } } else { var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Please Login", comment: "请先登入"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } } // MARK: - 直接调用Youtube Data API // Google 登入(后期统一) func googleLogin(code: String) { var parameters: [String: AnyObject] = [ "code": code, "client_id": "921894916096-i9cuji72d09ut6qo7phcsbpkqsfcmn1a.apps.googleusercontent.com", "client_secret": "282qMxcJSHOZ3DdJM5tVZxyk", "redirect_uri": "http://beta.gamers.tm:3000/back", "grant_type": "authorization_code", ] Alamofire.request(.POST, "https://www.googleapis.com/oauth2/v3/token", parameters: parameters).responseJSON { _, _, JSONData, _ in if let JSONData: AnyObject = JSONData { let googleData = JSON(JSONData) NSUserDefaults.standardUserDefaults().setObject(googleData["access_token"].string, forKey: "googleAccessToken") NSUserDefaults.standardUserDefaults().setObject(googleData["refresh_token"].string, forKey: "googleRefreshToken") NSUserDefaults.standardUserDefaults().setObject(googleData["expires_in"].string, forKey: "googleExpiresIn") NSUserDefaults.standardUserDefaults().setObject(NSDate().dateByAddingTimeInterval(0).timeIntervalSince1970, forKey: "googleTokenBeginTime") } } } //刷新Google的access_token func googleRefreshToken() -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return UserDao.googleRefreshToken() }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let response = task.result as? YTError { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } // 订阅Youtube频道 func Subscriptions(#channelId: String) -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return UserDao.Subscriptions(channelId: channelId) }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let response = task.result as? YTError { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } }
apache-2.0
0cab1e7f476e348d1ff9c9a8a5df98da
34.25
214
0.558887
4.926416
false
false
false
false
austinzheng/swift
stdlib/public/core/StringNormalization.swift
2
15743
//===--- StringNormalization.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims internal enum _Normalization { // ICU's NFC unorm2 instance // // TODO(String performance): Should we cache one on TLS? Is this an expensive // call? internal static var _nfcNormalizer: OpaquePointer = { var err = __swift_stdlib_U_ZERO_ERROR let normalizer = __swift_stdlib_unorm2_getNFCInstance(&err) guard err.isSuccess else { // This shouldn't be possible unless some deep (unrecoverable) system // invariants are violated fatalError("Unable to talk to ICU") } return normalizer }() // When normalized in NFC, some segments may expand in size (e.g. some non-BMP // musical notes). This expansion is capped by the maximum expansion factor of // the normal form. For NFC, that is 3x. internal static let _maxNFCExpansionFactor = 3 internal static let _maxUTF16toUTF8ExpansionFactor = 3 internal typealias _SegmentOutputBuffer = _FixedArray16<UInt16> } // // Pointer casting helpers // @inline(__always) private func _unsafeMutableBufferPointerCast<T, U>( _ ptr: UnsafeMutablePointer<T>, _ count: Int, to: U.Type = U.self ) -> UnsafeMutableBufferPointer<U> { return UnsafeMutableBufferPointer( start: UnsafeMutableRawPointer(ptr).assumingMemoryBound(to: U.self), count: count ) } @inline(__always) private func _unsafeBufferPointerCast<T, U>( _ ptr: UnsafePointer<T>, _ count: Int, to: U.Type = U.self ) -> UnsafeBufferPointer<U> { return UnsafeBufferPointer( start: UnsafeRawPointer(ptr).assumingMemoryBound(to: U.self), count: count ) } internal func _castOutputBuffer( _ ptr: UnsafeMutablePointer<_FixedArray16<UInt8>>, endingAt endIdx: Int = 16 ) -> UnsafeMutableBufferPointer<UInt8> { let bufPtr: UnsafeMutableBufferPointer<UInt8> = _unsafeMutableBufferPointerCast( ptr, 16) return UnsafeMutableBufferPointer<UInt8>(rebasing: bufPtr[..<endIdx]) } internal func _castOutputBuffer( _ ptr: UnsafeMutablePointer<_Normalization._SegmentOutputBuffer>, endingAt endIdx: Int = _Normalization._SegmentOutputBuffer.capacity ) -> UnsafeMutableBufferPointer<UInt16> { let bufPtr: UnsafeMutableBufferPointer<UInt16> = _unsafeMutableBufferPointerCast( ptr, _Normalization._SegmentOutputBuffer.capacity) return UnsafeMutableBufferPointer<UInt16>(rebasing: bufPtr[..<endIdx]) } internal func _castOutputBuffer( _ ptr: UnsafePointer<_Normalization._SegmentOutputBuffer>, endingAt endIdx: Int = _Normalization._SegmentOutputBuffer.capacity ) -> UnsafeBufferPointer<UInt16> { let bufPtr: UnsafeBufferPointer<UInt16> = _unsafeBufferPointerCast( ptr, _Normalization._SegmentOutputBuffer.capacity) return UnsafeBufferPointer<UInt16>(rebasing: bufPtr[..<endIdx]) } extension _StringGuts { internal func foreignHasNormalizationBoundary( before index: String.Index ) -> Bool { let offset = index.encodedOffset if offset == 0 || offset == count { return true } let scalar = foreignErrorCorrectedScalar(startingAt: index).0 return scalar._hasNormalizationBoundaryBefore } } extension UnsafeBufferPointer where Element == UInt8 { internal func hasNormalizationBoundary(before index: Int) -> Bool { if index == 0 || index == count { return true } assert(!_isContinuation(self[_unchecked: index])) // Sub-300 latiny fast-path if self[_unchecked: index] < 0xCC { return true } let cu = _decodeScalar(self, startingAt: index).0 return cu._hasNormalizationBoundaryBefore } } extension Unicode.Scalar { // Normalization boundary - a place in a string where everything left of the // boundary can be normalized independently from everything right of the // boundary. The concatenation of each result is the same as if the entire // string had been normalized as a whole. // // Normalization segment - a sequence of code units between two normalization // boundaries (without any boundaries in the middle). Note that normalization // segments can, as a process of normalization, expand, contract, and even // produce new sub-segments. // Whether this scalar value always has a normalization boundary before it. @inline(__always) // common fast-path internal var _hasNormalizationBoundaryBefore: Bool { // Fast-path: All scalars up through U+02FF are NFC and have boundaries // before them if self.value < 0x300 { return true } _internalInvariant(Int32(exactly: self.value) != nil, "top bit shouldn't be set") let value = Int32(bitPattern: self.value) return 0 != __swift_stdlib_unorm2_hasBoundaryBefore( _Normalization._nfcNormalizer, value) } @inline(__always) // common fast-path internal var _isNFCQCYes: Bool { // Fast-path: All scalars up through U+02FF are NFC and have boundaries // before them if self.value < 0x300 { return true } return __swift_stdlib_u_getIntPropertyValue( Builtin.reinterpretCast(value), __swift_stdlib_UCHAR_NFC_QUICK_CHECK ) == 1 } // Quick check if a scalar is NFC and a segment starter internal var _isNFCStarter: Bool { // Otherwise, consult the properties return self._hasNormalizationBoundaryBefore && self._isNFCQCYes } } extension UnsafeBufferPointer where Element == UInt8 { internal func isOnUnicodeScalarBoundary(_ index: Int) -> Bool { guard index < count else { _internalInvariant(index == count) return true } return !_isContinuation(self[index]) } } //If this returns nil, it means the outputBuffer ran out of space internal func _tryNormalize( _ input: UnsafeBufferPointer<UInt16>, into outputBuffer: UnsafeMutablePointer<_Normalization._SegmentOutputBuffer> ) -> Int? { return _tryNormalize(input, into: _castOutputBuffer(outputBuffer)) } //If this returns nil, it means the outputBuffer ran out of space internal func _tryNormalize( _ input: UnsafeBufferPointer<UInt16>, into outputBuffer: UnsafeMutableBufferPointer<UInt16> ) -> Int? { var err = __swift_stdlib_U_ZERO_ERROR let count = __swift_stdlib_unorm2_normalize( _Normalization._nfcNormalizer, input.baseAddress._unsafelyUnwrappedUnchecked, numericCast(input.count), outputBuffer.baseAddress._unsafelyUnwrappedUnchecked, numericCast(outputBuffer.count), &err ) guard err.isSuccess else { // The output buffer needs to grow return nil } return numericCast(count) } internal struct NormalizationResult { var amountFilled: Int var nextReadPosition: String.Index var allocatedBuffers: Bool } //If this returns nil, it means the outputBuffer ran out of space @_effects(releasenone) private func fastFill( _ sourceBuffer: UnsafeBufferPointer<UInt8>, _ outputBuffer: UnsafeMutableBufferPointer<UInt8> ) -> (read: Int, written: Int)? { let outputBufferThreshold = outputBuffer.count - 4 // TODO: Additional fast-path: All CCC-ascending NFC_QC segments are NFC // TODO: Just freakin do normalization and don't bother with ICU var outputCount = 0 let outputEnd = outputBufferThreshold var inputCount = 0 let inputEnd = sourceBuffer.count while inputCount < inputEnd && outputCount < outputEnd { // TODO: Slightly faster code-unit scan for latiny (<0xCC) // Check scalar-based fast-paths let (scalar, len) = _decodeScalar(sourceBuffer, startingAt: inputCount) _internalInvariant(inputCount &+ len <= inputEnd) if _slowPath( !sourceBuffer.hasNormalizationBoundary(before: inputCount &+ len) || !scalar._isNFCStarter ) { break } inputCount &+= len for cu in UTF8.encode(scalar)._unsafelyUnwrappedUnchecked { outputBuffer[_unchecked: outputCount] = cu outputCount &+= 1 } _internalInvariant(inputCount == outputCount, "non-normalizing UTF-8 fast path should be 1-to-1 in code units") } return outputCount > 0 ? (inputCount, outputCount) : nil } //Transcodes a single segment from the scalars provided by the closure to the outputBuffer as UTF16 //If this returns nil, it means the outputBuffer ran out of space private func copyUTF16Segment( boundedBy range: Range<Int>, into outputBuffer: UnsafeMutableBufferPointer<UInt16>, _ f: (Int) -> (Unicode.Scalar, Int) ) -> (read: Int, written: Int)? { var readIndex = range.lowerBound var outputWriteIndex = 0 let outputCount = outputBuffer.count while readIndex != range.upperBound { let (scalar, length) = f(readIndex) if scalar._hasNormalizationBoundaryBefore && readIndex != range.lowerBound { break } readIndex += length for cu in scalar.utf16 { if outputWriteIndex < outputCount { outputBuffer[outputWriteIndex] = cu outputWriteIndex += 1 } else { return nil } } } return (readIndex - range.lowerBound, outputWriteIndex) } //transcodes the UTF16 segment stored in soureceBuffer into the outputBuffer as UTF8 //If this returns nil, it means the outputBuffer ran out of space private func transcodeValidUTF16ToUTF8( _ sourceBuffer: UnsafeBufferPointer<UInt16>, into outputBuffer: UnsafeMutableBufferPointer<UInt8> ) -> Int? { var readIndex = 0 var writeIndex = 0 let outputCount = outputBuffer.count let sourceCount = sourceBuffer.count while readIndex < sourceCount { let (scalar, length) = _decodeScalar(sourceBuffer, startingAt: readIndex) //we don't need to check for normalization boundaries here because we are only transcoding //a single segment at this point readIndex += length for cu in UTF8.encode(scalar)._unsafelyUnwrappedUnchecked { if writeIndex < outputCount { outputBuffer[writeIndex] = cu writeIndex &+= 1 } else { return nil } } } return writeIndex } internal enum _BufferToCopy { case none, output, icuInput, icuOutput } internal func _allocateBuffers( sourceCount count: Int, preserveDataIn bufferToCopy: _BufferToCopy, outputBuffer: inout UnsafeMutableBufferPointer<UInt8>, icuInputBuffer: inout UnsafeMutableBufferPointer<UInt16>, icuOutputBuffer: inout UnsafeMutableBufferPointer<UInt16> ) { let output = count * _Normalization._maxNFCExpansionFactor * _Normalization._maxUTF16toUTF8ExpansionFactor let icuInput = count let icuOutput = count * _Normalization._maxNFCExpansionFactor let newOutputBuffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: output) let newICUInputBuffer = UnsafeMutableBufferPointer<UInt16>.allocate(capacity: icuInput) let newICUOutputBuffer = UnsafeMutableBufferPointer<UInt16>.allocate(capacity: icuOutput) switch bufferToCopy { case .none: break case .output: let (_, written) = newOutputBuffer.initialize(from: outputBuffer) _internalInvariant(written == 16) case .icuInput: let (_, written) = newICUInputBuffer.initialize(from: icuInputBuffer) _internalInvariant(written == 16) case .icuOutput: let (_, written) = newICUOutputBuffer.initialize(from: icuOutputBuffer) _internalInvariant(written == 16) } outputBuffer = newOutputBuffer icuInputBuffer = newICUInputBuffer icuOutputBuffer = newICUOutputBuffer } internal func _fastNormalize( readIndex: String.Index, sourceBuffer: UnsafeBufferPointer<UInt8>, outputBuffer: inout UnsafeMutableBufferPointer<UInt8>, icuInputBuffer: inout UnsafeMutableBufferPointer<UInt16>, icuOutputBuffer: inout UnsafeMutableBufferPointer<UInt16> ) -> NormalizationResult { let start = readIndex.encodedOffset let rebasedSourceBuffer = UnsafeBufferPointer(rebasing: sourceBuffer[start...]) if let (read, filled) = fastFill(rebasedSourceBuffer, outputBuffer) { let nextIndex = readIndex.encoded(offsetBy: read) _internalInvariant(sourceBuffer.isOnUnicodeScalarBoundary(nextIndex.encodedOffset)) return NormalizationResult( amountFilled: filled, nextReadPosition: nextIndex, allocatedBuffers: false) } var allocatedBuffers = false func performWithAllocationIfNecessary<R>( preserving preserveDataIn: _BufferToCopy, _ f: () -> R? ) -> R { if let result = f() { return result } _allocateBuffers( sourceCount: sourceBuffer.count, preserveDataIn: preserveDataIn, outputBuffer: &outputBuffer, icuInputBuffer: &icuInputBuffer, icuOutputBuffer: &icuOutputBuffer) _internalInvariant(!allocatedBuffers) allocatedBuffers = true return f()! } let (read, filled) = performWithAllocationIfNecessary(preserving: .none) { () -> (Int, Int)? in return copyUTF16Segment(boundedBy: 0..<rebasedSourceBuffer.count, into: icuInputBuffer) { return _decodeScalar(rebasedSourceBuffer, startingAt: $0) } } let nextIndex = readIndex.encoded(offsetBy: read) _internalInvariant(sourceBuffer.isOnUnicodeScalarBoundary(nextIndex.encodedOffset)) let normalized = performWithAllocationIfNecessary(preserving: .icuInput) { () -> Int? in return _tryNormalize( UnsafeBufferPointer(rebasing: icuInputBuffer[..<filled]), into: icuOutputBuffer) } let transcoded = performWithAllocationIfNecessary(preserving: .icuOutput) { () -> Int? in return transcodeValidUTF16ToUTF8( UnsafeBufferPointer<UInt16>(rebasing: icuOutputBuffer[..<normalized]), into: outputBuffer) } return NormalizationResult( amountFilled: transcoded, nextReadPosition: nextIndex, allocatedBuffers: allocatedBuffers) } internal func _foreignNormalize( readIndex: String.Index, endIndex: String.Index, guts: _StringGuts, outputBuffer: inout UnsafeMutableBufferPointer<UInt8>, icuInputBuffer: inout UnsafeMutableBufferPointer<UInt16>, icuOutputBuffer: inout UnsafeMutableBufferPointer<UInt16> ) -> NormalizationResult { var allocatedBuffers = false func performWithAllocationIfNecessary<R>( preserving preserveDataIn: _BufferToCopy, _ f: () -> R? ) -> R { if let result = f() { return result } _allocateBuffers( sourceCount: guts.count, preserveDataIn: preserveDataIn, outputBuffer: &outputBuffer, icuInputBuffer: &icuInputBuffer, icuOutputBuffer: &icuOutputBuffer) _internalInvariant(!allocatedBuffers) allocatedBuffers = true return f()! } let (read, filled) = performWithAllocationIfNecessary(preserving: .none) { () -> (Int, Int)? in let start = readIndex.encodedOffset let end = endIndex.encodedOffset return copyUTF16Segment(boundedBy: start..<end, into: icuInputBuffer) { gutsOffset in return guts.errorCorrectedScalar(startingAt: gutsOffset) } } let nextIndex = readIndex.encoded(offsetBy: read) _internalInvariant(guts.isOnUnicodeScalarBoundary(nextIndex)) let normalized = performWithAllocationIfNecessary(preserving: .icuInput) { () -> Int? in return _tryNormalize( UnsafeBufferPointer(rebasing: icuInputBuffer[..<filled]), into: icuOutputBuffer) } let transcoded = performWithAllocationIfNecessary(preserving: .icuOutput) { () -> Int? in return transcodeValidUTF16ToUTF8( UnsafeBufferPointer<UInt16>(rebasing: icuOutputBuffer[..<normalized]), into: outputBuffer) } return NormalizationResult( amountFilled: transcoded, nextReadPosition: nextIndex, allocatedBuffers: allocatedBuffers) }
apache-2.0
2c6d4527b336e605de5d290b24425202
33.906874
108
0.722035
4.399944
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/RedditLink.swift
1
13322
// // RedditLink.swift // Slide for Reddit // // Created by Carlos Crane on 1/4/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import reddift import SafariServices import UIKit class RedditLink { public static func getViewControllerForURL(urlS: URL) -> UIViewController { var urlString = urlS.absoluteString.replacingOccurrences(of: "slide://", with: "https://") if !urlString.startsWith("http") && !urlString.startsWith("https") { urlString = "https://" + urlString } if urlS.host == "google.com" { urlString = urlString.replacingOccurrences(of: "google.com/amp/s/amp.", with: "") } let oldUrl = URL(string: urlString)! var url = formatRedditUrl(urlS: urlS) var np = false if urlS.absoluteString.startsWith("/m/") { return SingleSubredditViewController.init(subName: urlS.absoluteString, single: true) } if urlS.absoluteString.contains("/r//m/") { if let multiName = urlS.absoluteString.split("/").last, !multiName.isEmpty { return SingleSubredditViewController.init(subName: "/m/" + multiName, single: true) } } if url.isEmpty() { if SettingValues.browser == SettingValues.BROWSER_SAFARI_INTERNAL || SettingValues.browser == SettingValues.BROWSER_SAFARI_INTERNAL_READABILITY { let safariVC = SFHideSafariViewController(url: oldUrl, entersReaderIfAvailable: SettingValues.browser == SettingValues.BROWSER_SAFARI_INTERNAL_READABILITY) if #available(iOS 10.0, *) { safariVC.preferredBarTintColor = ColorUtil.theme.backgroundColor safariVC.preferredControlTintColor = ColorUtil.theme.fontColor } else { // Fallback on earlier versions } return safariVC } return WebsiteViewController.init(url: oldUrl, subreddit: "") } else if url.hasPrefix("np") { np = true url = url.substring(2, length: url.length - 2) } let percentUrl = url.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? url let type = getRedditLinkType(urlBase: URL.init(string: percentUrl)!) var parts = url.split("/") var endParameters = "" if parts[parts.count - 1].startsWith("?") { endParameters = parts[parts.count - 1] parts.remove(at: parts.count - 1) } var safeURL = url.startsWith("/") ? "https://www.reddit.com" + url : url if !safeURL.contains("www.reddit.com") && safeURL.contains("reddit.com") { safeURL = "https://www." + safeURL } switch type { case .SHORTENED: return CommentViewController.init(submission: parts[1], subreddit: nil, np: np) case .MULTI: return SingleSubredditViewController.init(subName: "/u/\(parts[2])/m/\(parts[4])", single: true) case .LIVE: print(parts[1]) return LiveThreadViewController.init(id: parts[2]) case .WIKI: return WebsiteViewController.init(url: URL(string: safeURL)!, subreddit: "") case .SEARCH: let end = parts[parts.count - 1] let sub: String let restrictSub = end.contains("restrict_sr=on") || end.contains("restrict_sr=1") if restrictSub { sub = parts[2] } else { sub = "all" } let query: String if let q = urlS.queryDictionary["q"] { query = q.removingPercentEncoding?.removingPercentEncoding ?? q } else { query = "" } return SearchViewController(subreddit: sub, searchFor: query) case .COMMENT_PERMALINK: var comment = "" var contextNumber = 3 if parts.count >= 7 { var end = parts[6] var endCopy = end if end.contains("?") { end = end.substring(0, length: end.indexOf("?")!) } if end.length >= 3 { comment = end } if endCopy.contains("?context=") { if !endParameters.isEmpty() { endCopy = endParameters } let index = endCopy.indexOf("?context=")! + 9 contextNumber = Int(endCopy.substring(index, length: endCopy.length - index))! } } if contextNumber == 0 { contextNumber = 3 } return CommentViewController.init(submission: parts[4], comment: comment, context: contextNumber, subreddit: parts[2], np: np) case .SUBMISSION: return CommentViewController.init(submission: parts[4], subreddit: parts[2], np: np) case .SUBMISSION_WITHOUT_SUB: return CommentViewController.init(submission: parts[2], subreddit: nil, np: np) case .SUBREDDIT: return SingleSubredditViewController.init(subName: parts[2], single: true) case .MESSAGE: var to = "" var subject = "" var message = "" if let q = urlS.queryDictionary["to"] { to = q.removingPercentEncoding?.removingPercentEncoding ?? q } if let q = urlS.queryDictionary["subject"] { subject = q.removingPercentEncoding?.removingPercentEncoding ?? q } if let q = urlS.queryDictionary["message"] { message = q.removingPercentEncoding?.removingPercentEncoding ?? q } return ReplyViewController.init(name: to, subject: subject, message: message, completion: { (_) in }) case .USER: return ProfileViewController.init(name: parts[2]) case .OTHER: break } if SettingValues.browser == SettingValues.BROWSER_SAFARI_INTERNAL || SettingValues.browser == SettingValues.BROWSER_SAFARI_INTERNAL_READABILITY { let safariVC = SFHideSafariViewController(url: oldUrl, entersReaderIfAvailable: SettingValues.browser == SettingValues.BROWSER_SAFARI_INTERNAL_READABILITY) if #available(iOS 10.0, *) { safariVC.preferredBarTintColor = ColorUtil.theme.backgroundColor safariVC.preferredControlTintColor = ColorUtil.theme.fontColor } else { // Fallback on earlier versions } return safariVC } return WebsiteViewController.init(url: oldUrl, subreddit: "") } /** * Takes an reddit.com url and formats it for easier use * * @param url The url to format * @return Formatted url without subdomains, language tags & other unused prefixes */ static func formatRedditUrl(urlS: URL) -> String { var url = urlS.absoluteString if url.hasPrefix("applewebdata:") { url = urlS.path } // Strip unused prefixes that don't require special handling url.stringByRemovingRegexMatches(pattern: "(?i)^(https?://)?(www\\.)?((ssl|pay|amp)\\.)?") if url.matches(regex: "(?i)[a-z0-9-_]+\\.reddit\\.com.*") { // tests for subdomain let subdomain = urlS.host let domainRegex = "(?i)" + subdomain! + "\\.reddit\\.com" if (subdomain?.hasPrefix("np"))! { // no participation link: https://www.reddit.com/r/NoParticipation/wiki/index url.stringByRemovingRegexMatches(pattern: domainRegex, replaceWith: "reddit.com") url = "np" + url } else if (subdomain?.matches(regex: "beta|blog|code|mod|out|store"))! { return "" } else if (subdomain?.matches(regex: "(?i)([_a-z0-9]{2}-)?[_a-z0-9]{1,2}"))! { /* Either the subdomain is a language tag (with optional region) or a single letter domain, which for simplicity are ignored. */ url.stringByRemovingRegexMatches(pattern: domainRegex, replaceWith: "reddit.com") } else { // subdomain is a subreddit, change subreddit.reddit.com to reddit.com/r/subreddit url.stringByRemovingRegexMatches(pattern: domainRegex, replaceWith: "reddit.com/r/" + subdomain!) } } if url.hasPrefix("/") { url = "reddit.com" + url } if url.hasSuffix("/") { url = url.substring(0, length: url.length - 1) } // Converts links such as reddit.com/help to reddit.com/r/reddit.com/wiki if url.matches(regex: "(?i)[^/]++/(?>w|wiki|help)(?>$|/.*)") { url.stringByRemovingRegexMatches(pattern: "(?i)/(?>w|wiki|help)", replaceWith: "/r/reddit.com/wiki") } url = url.removingPercentEncoding ?? url url = url.removingPercentEncoding ?? url //For some reason, some links are doubly encoded url = url.replacingOccurrences(of: "&amp;", with: "&") return url } /** * Determines the reddit link type * * @param url Reddit.com link * @return LinkType */ static func getRedditLinkType(urlBase: URL) -> RedditLinkType { let url = urlBase.absoluteString if url.matches(regex: "(?i)redd\\.it/\\w+") { // Redd.it link. Format: redd.it/post_id return RedditLinkType.SHORTENED } else if url.matches(regex: "(?i)reddit\\.com/live/[^/]*") { return RedditLinkType.LIVE } else if url.matches(regex: "(?i)reddit\\.com/message/compose.*") { return RedditLinkType.MESSAGE } else if url.matches(regex: "(?i)reddit\\.com(?:/r/[a-z0-9-_.]+)?/(?:wiki|help).*") { // Wiki link. Format: reddit.com/r/$subreddit/wiki/$page [optional] return RedditLinkType.WIKI } else if url.matches(regex: "(?i)reddit\\.com/r/[a-z0-9-_.]+/about.*") { // Unhandled link. Format: reddit.com/r/$subreddit/about/$page [optional] return RedditLinkType.OTHER } else if url.matches(regex: "(?i)reddit\\.com/r/[a-z0-9-_.]+/search.*") { // Wiki link. Format: reddit.com/r/$subreddit/search?q= [optional] return RedditLinkType.SEARCH } else if url.matches(regex: "(?i)reddit\\.com/r/[a-z0-9-_.]+/comments/\\w+/\\w*/.*") { // Permalink to comments. Format: reddit.com/r/$subreddit/comments/$post_id/$post_title [can be empty]/$comment_id return RedditLinkType.COMMENT_PERMALINK } else if url.matches(regex: "(?i)reddit\\.com/r/[a-z0-9-_.]+/comments/\\w+.*") { // Submission. Format: reddit.com/r/$subreddit/comments/$post_id/$post_title [optional] return RedditLinkType.SUBMISSION } else if url.matches(regex: "(?i)reddit\\.com/u(?:ser)?/[a-z0-9-_]+.*/m/[a-z0-9_]+.*") { // Multireddit. Format: reddit.com/u [or user]/$username/m/$multireddit/$sort [optional] return RedditLinkType.MULTI } else if url.matches(regex: "(?i)reddit\\.com/comments/\\w+.*") { // Submission without a given subreddit. Format: reddit.com/comments/$post_id/$post_title [optional] return RedditLinkType.SUBMISSION_WITHOUT_SUB } else if url.matches(regex: "(?i)reddit\\.com/r/[a-z0-9-_.]+.*") { // Subreddit. Format: reddit.com/r/$subreddit/$sort [optional] return RedditLinkType.SUBREDDIT } else if url.matches(regex: "(?i)reddit\\.com/u(?:ser)?/[a-z0-9-_]+.*") { // User. Format: reddit.com/u [or user]/$username/$page [optional] return RedditLinkType.USER } else { //Open all links that we can't open in another app return RedditLinkType.OTHER } } enum RedditLinkType { case SHORTENED case WIKI case COMMENT_PERMALINK case SUBMISSION case SUBMISSION_WITHOUT_SUB case SUBREDDIT case USER case MULTI case SEARCH case MESSAGE case LIVE case OTHER } } extension String { func matches(regex: String) -> Bool { do { let regex = try NSRegularExpression(pattern: regex, options: []) let results = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) return results.count > 0 } catch let error { print("invalid regex: \(error.localizedDescription)") return false } } mutating func stringByRemovingRegexMatches(pattern: String, replaceWith: String = "") { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive) let range = NSRange(location: 0, length: self.length) self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith) } catch { return } } }
apache-2.0
6a9d481812b2432abc4e9b8891a7220d
43.701342
171
0.564747
4.412388
false
false
false
false
domenicosolazzo/practice-swift
CoreLocation/Displaying Pins in MapView/Displaying Pins in MapView/ViewController.swift
1
1819
// // ViewController.swift // Displaying Pins in MapView // // Created by Domenico Solazzo on 18/05/15. // License MIT // import UIKit import CoreLocation import MapKit class ViewController: UIViewController, MKMapViewDelegate { var mapView: MKMapView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) mapView = MKMapView() } /* We have a pin on the map; now zoom into it and make that pin the center of the map */ func setCenterOfMapToLocation(_ location: CLLocationCoordinate2D){ let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01) let region = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) } func addPinToMapView(){ /* This is just a sample location */ let location = CLLocationCoordinate2D(latitude: 58.592737, longitude: 16.185898) /* Create the annotation using the location */ let annotation = MyAnnotation(coordinate: location, title: "My Title", subtitle: "My Sub Title") /* And eventually add it to the map */ mapView.addAnnotation(annotation) /* And now center the map around the point */ setCenterOfMapToLocation(location) } /* Set up the map and add it to our view */ override func viewDidLoad() { super.viewDidLoad() mapView.mapType = .standard mapView.frame = view.frame mapView.delegate = self view.addSubview(mapView) } /* Add the pin to the map and center the map around the pin */ override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) addPinToMapView() } }
mit
0fcbfe6a58ce9726d508c06ed32b28bd
27.421875
78
0.623969
4.76178
false
false
false
false
OEASLAN/LetsEat
IOS/Let's Eat/Let's Eat/RestaurantLocationViewController.swift
1
2100
// // RestaurantLocationViewController.swift // Let's Eat // // Created by Vidal_HARA on 13.04.2015. // Copyright (c) 2015 vidal hara S002866. All rights reserved. // import UIKit import CoreLocation import MapKit class RestaurantLocationViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(3 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in /* let span = MKCoordinateSpanMake(0.01, 0.01) let region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(41.028793, 29.259657) , span) self.mapView.setRegion(region, animated: true)*/ let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(41.026756, 29.219937) annotation.title = "Aras Et" //annotation.subtitle = "Bilim Yuvasi" self.mapView.addAnnotation(annotation) let span = MKCoordinateSpanMake(0.01, 0.01) let region = MKCoordinateRegionMake(annotation.coordinate , span) self.mapView.setRegion(region, animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { NSLog("%@", region) } override func viewDidAppear(animated: Bool) { self.mapView.setUserTrackingMode(MKUserTrackingMode.FollowWithHeading, animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-2.0
ee776490e29e4c8398f7f7a939710700
34
132
0.665714
4.740406
false
false
false
false
Hearst-DD/ObjectMapper
Sources/Mappable.swift
4
4556
// // Mappable.swift // ObjectMapper // // Created by Scott Hoyt on 10/25/15. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // 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 /// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead public protocol BaseMappable { /// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process. mutating func mapping(map: Map) } public protocol Mappable: BaseMappable { /// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point init?(map: Map) } public protocol StaticMappable: BaseMappable { /// This is function that can be used to: /// 1) provide an existing cached object to be used for mapping /// 2) return an object of another class (which conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping static func objectForMapping(map: Map) -> BaseMappable? } public extension Mappable { /// Initializes object from a JSON String init?(JSONString: String, context: MapContext? = nil) { if let obj: Self = Mapper(context: context).map(JSONString: JSONString) { self = obj } else { return nil } } /// Initializes object from a JSON Dictionary init?(JSON: [String: Any], context: MapContext? = nil) { if let obj: Self = Mapper(context: context).map(JSON: JSON) { self = obj } else { return nil } } } public extension BaseMappable { /// Returns the JSON Dictionary for the object func toJSON() -> [String: Any] { return Mapper().toJSON(self) } /// Returns the JSON String for the object func toJSONString(prettyPrint: Bool = false) -> String? { return Mapper().toJSONString(self, prettyPrint: prettyPrint) } } public extension Array where Element: BaseMappable { /// Initialize Array from a JSON String init?(JSONString: String, context: MapContext? = nil) { if let obj: [Element] = Mapper(context: context).mapArray(JSONString: JSONString) { self = obj } else { return nil } } /// Initialize Array from a JSON Array init(JSONArray: [[String: Any]], context: MapContext? = nil) { let obj: [Element] = Mapper(context: context).mapArray(JSONArray: JSONArray) self = obj } /// Returns the JSON Array func toJSON() -> [[String: Any]] { return Mapper().toJSONArray(self) } /// Returns the JSON String for the object func toJSONString(prettyPrint: Bool = false) -> String? { return Mapper().toJSONString(self, prettyPrint: prettyPrint) } } public extension Set where Element: BaseMappable { /// Initializes a set from a JSON String init?(JSONString: String, context: MapContext? = nil) { if let obj: Set<Element> = Mapper(context: context).mapSet(JSONString: JSONString) { self = obj } else { return nil } } /// Initializes a set from JSON init?(JSONArray: [[String: Any]], context: MapContext? = nil) { guard let obj = Mapper(context: context).mapSet(JSONArray: JSONArray) as Set<Element>? else { return nil } self = obj } /// Returns the JSON Set func toJSON() -> [[String: Any]] { return Mapper().toJSONSet(self) } /// Returns the JSON String for the object func toJSONString(prettyPrint: Bool = false) -> String? { return Mapper().toJSONString(self, prettyPrint: prettyPrint) } }
mit
1b101e30527c14f3f7163352119403fb
31.776978
208
0.711589
3.930975
false
false
false
false
garethpaul/TweepTracker
location_tracker/FindTweeps.swift
1
2981
// // FindTweeps.swift // import Foundation import TwitterKit func FindTweeps(completion: (result: [String]) -> Void) { typealias JSON = AnyObject typealias JSONDictionary = Dictionary<String, JSON> typealias JSONArray = Array<JSON> // We must get the memebers of the list. // As a pointer ou can find the members of via :- https://twitter.com/TwitterDev/lists/twitter-dev-advocates // Documentation on this endpoint can be found via :- https://dev.twitter.com/rest/reference/get/lists/members // // Setup endpoint URL let memberListAPI = "https://api.twitter.com/1.1/lists/members.json" // Setup Params to be sent to the endpoint. let params = ["slug": "twitter-dev-advocates", "owner_screen_name": "twitterdev"] // Setup a catch for errors. var clientError : NSError? // initialize Twitter Twitter.initialize() // Create a request to the API notice "GET", "URL" params. let request = Twitter.sharedInstance().APIClient.URLRequestWithMethod("GET", URL: memberListAPI, parameters: params, error:&clientError) // We only want to do things when the request is not nill if request != nil { // The API call is ready to send. Twitter.sharedInstance().APIClient.sendTwitterRequest(request) { (response, data, connectionError) -> Void in // If there are no errors if (connectionError == nil) { var jsonError : NSError? let json : AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) // userArray this is how we store all the users to send back to the ViewController. var userArray = Array<String>() // get the output from the json {"users": [...]} if let users = json!["users"] as? JSONArray { // iterate through the list of users for user in users { // if there is a json object like the following {"screen_name": "gpj"} if let screenName = user["screen_name"] as?String { // Append the user the array userArray.append(screenName) } } } // The list of developer advocates is somewhat limited here are some more to append to our array userArray.append("logicalarthur") userArray.append("laurenschutte") userArray.append("noonisms") userArray.append("jeffseibert") userArray.append("josolennoso") // On completed send the userArray back to the ViewController. completion(result: userArray) } else { println("Error: \(connectionError)") } } } else { println("Error: \(clientError)") } }
apache-2.0
ea13a3382bb2eef87bb5dc54aeff4045
32.122222
141
0.578665
4.815832
false
false
false
false
wess/reddift
reddift/Model/Message.swift
1
3608
// // Message.swift // reddift // // Created by generator.rb via from https://github.com/reddit/reddit/wiki/JSON // Created at 2015-04-15 11:23:32 +0900 // import Foundation /** Message object. */ public struct Message : Thing { /// identifier of Thing like 15bfi0. public var id:String /// name of Thing, that is fullname, like t3_15bfi0. public var name:String /// type of Thing, like t3. public static var kind = "t4" /** the message itself example: Hello! [Hola!](http.... */ public let body:String /** example: false */ public let wasComment:Bool /** example: */ public let firstMessage:String /** either null or the first message's fullname example: */ public let firstMessageName:String /** example: 1427126074 */ public let created:Int /** example: sonson_twit */ public let dest:String /** example: reddit */ public let author:String /** example: 1427122474 */ public let createdUtc:Int /** the message itself with HTML formatting example: &lt;!-- SC_OFF --&gt;&l.... */ public let bodyHtml:String /** null if not a comment. example: */ public let subreddit:String /** null if no parent is attached example: */ public let parentId:String /** if the message is a comment, then the permalink to the comment with ?context=3 appended to the end, otherwise an empty string example: */ public let context:String /** Again, an empty string if there are no replies. example: */ public let replies:String /** unread? not sure example: false */ public let new:Bool /** example: admin */ public let distinguished:String /** subject of message example: Hello, /u/sonson_twit! Welcome to reddit! */ public let subject:String public init(id:String) { self.id = id self.name = "\(Message.kind)_\(self.id)" body = "" wasComment = false firstMessage = "" firstMessageName = "" created = 0 dest = "" author = "" createdUtc = 0 bodyHtml = "" subreddit = "" parentId = "" context = "" replies = "" new = false distinguished = "" subject = "" } /** Parse t4 object. :param: data Dictionary, must be generated parsing "t4". :returns: Message object as Thing. */ public init(data:JSONDictionary) { id = data["id"] as? String ?? "" body = data["body"] as? String ?? "" wasComment = data["was_comment"] as? Bool ?? false firstMessage = data["first_message"] as? String ?? "" name = data["name"] as? String ?? "" firstMessageName = data["first_message_name"] as? String ?? "" created = data["created"] as? Int ?? 0 dest = data["dest"] as? String ?? "" author = data["author"] as? String ?? "" createdUtc = data["created_utc"] as? Int ?? 0 bodyHtml = data["body_html"] as? String ?? "" subreddit = data["subreddit"] as? String ?? "" parentId = data["parent_id"] as? String ?? "" context = data["context"] as? String ?? "" replies = data["replies"] as? String ?? "" new = data["new"] as? Bool ?? false distinguished = data["distinguished"] as? String ?? "" subject = data["subject"] as? String ?? "" } }
mit
dfe6368760836ad95bd9ce49857cc2f4
22.581699
129
0.5449
4.114025
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Me/Account Settings/AccountSettingsViewController.swift
1
17320
import Foundation import UIKit import WordPressShared import WordPressFlux func AccountSettingsViewController(account: WPAccount) -> ImmuTableViewController? { guard let api = account.wordPressComRestApi else { return nil } let service = AccountSettingsService(userID: account.userID.intValue, api: api) return AccountSettingsViewController(accountSettingsService: service) } func AccountSettingsViewController(accountSettingsService: AccountSettingsService) -> ImmuTableViewController { let controller = AccountSettingsController(accountSettingsService: accountSettingsService) let viewController = ImmuTableViewController(controller: controller) viewController.handler.automaticallyDeselectCells = true return viewController } private class AccountSettingsController: SettingsController { let title = NSLocalizedString("Account Settings", comment: "Account Settings Title") var immuTableRows: [ImmuTableRow.Type] { return [ TextRow.self, EditableTextRow.self, DestructiveButtonRow.self ] } // MARK: - Initialization private let accountSettingsService: AccountSettingsService private let accountService: AccountService var settings: AccountSettings? { didSet { NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: ImmuTableViewController.modelChangedNotification), object: nil) } } var noticeMessage: String? { didSet { NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: ImmuTableViewController.modelChangedNotification), object: nil) } } private let alertHelper = DestructiveAlertHelper() init(accountSettingsService: AccountSettingsService, accountService: AccountService = AccountService(managedObjectContext: ContextManager.sharedInstance().mainContext)) { self.accountSettingsService = accountSettingsService self.accountService = accountService let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(AccountSettingsController.loadStatus), name: NSNotification.Name.AccountSettingsServiceRefreshStatusChanged, object: nil) notificationCenter.addObserver(self, selector: #selector(AccountSettingsController.loadSettings), name: NSNotification.Name.AccountSettingsChanged, object: nil) notificationCenter.addObserver(self, selector: #selector(AccountSettingsController.showSettingsChangeErrorMessage), name: NSNotification.Name.AccountSettingsServiceChangeSaveFailed, object: nil) } func refreshModel() { accountSettingsService.refreshSettings() } @objc func loadStatus() { noticeMessage = accountSettingsService.status.errorMessage ?? noticeForAccountSettings(accountSettingsService.settings) } @objc func loadSettings() { settings = accountSettingsService.settings // Status is affected by settings changes (for pending email), so let's load that as well loadStatus() } // MARK: - ImmuTableViewController func tableViewModelWithPresenter(_ presenter: ImmuTablePresenter) -> ImmuTable { return mapViewModel(settings, service: accountSettingsService, presenter: presenter) } // MARK: - Model mapping func mapViewModel(_ settings: AccountSettings?, service: AccountSettingsService, presenter: ImmuTablePresenter) -> ImmuTable { let username = TextRow( title: NSLocalizedString("Username", comment: "Account Settings Username label"), value: settings?.username ?? "" ) let editableUsername = EditableTextRow( title: NSLocalizedString("Username", comment: "Account Settings Username label"), value: settings?.username ?? "", action: presenter.push(changeUsername(with: settings, service: service)) ) let email = EditableTextRow( title: NSLocalizedString("Email", comment: "Account Settings Email label"), value: settings?.emailForDisplay ?? "", accessoryImage: emailAccessoryImage(), action: presenter.push(editEmailAddress(settings, service: service)) ) var primarySiteName = settings.flatMap { service.primarySiteNameForSettings($0) } ?? "" // If the primary site has no Site Title, then show the displayURL. if primarySiteName.isEmpty { let blogService = BlogService(managedObjectContext: ContextManager.sharedInstance().mainContext) primarySiteName = blogService.primaryBlog()?.displayURL as String? ?? "" } let primarySite = EditableTextRow( title: NSLocalizedString("Primary Site", comment: "Primary Web Site"), value: primarySiteName, action: presenter.present(insideNavigationController(editPrimarySite(settings, service: service))) ) let webAddress = EditableTextRow( title: NSLocalizedString("Web Address", comment: "Account Settings Web Address label"), value: settings?.webAddress ?? "", action: presenter.push(editWebAddress(service)) ) let password = EditableTextRow( title: Constants.title, value: "", action: presenter.push(changePassword(with: settings, service: service)) ) let closeAccount = DestructiveButtonRow( title: NSLocalizedString("Close Account", comment: "Close account action label"), action: closeAccountAction, accessibilityIdentifier: "closeAccountButtonRow") return ImmuTable(sections: [ ImmuTableSection( rows: [ (settings?.usernameCanBeChanged ?? false) ? editableUsername : username, email, password, primarySite, webAddress ]), ImmuTableSection( rows: [ closeAccount ]) ]) } // MARK: - Actions func editEmailAddress(_ settings: AccountSettings?, service: AccountSettingsService) -> (ImmuTableRow) -> SettingsTextViewController { return { row in let editableRow = row as! EditableTextRow let hint = NSLocalizedString("Will not be publicly displayed.", comment: "Help text when editing email address") let settingsViewController = self.controllerForEditableText(editableRow, changeType: AccountSettingsChange.email, hint: hint, service: service) settingsViewController.mode = .email settingsViewController.notice = self.noticeForAccountSettings(settings) settingsViewController.displaysActionButton = settings?.emailPendingChange ?? false settingsViewController.actionText = NSLocalizedString("Revert Pending Change", comment: "Cancels a pending Email Change") settingsViewController.onActionPress = { service.saveChange(.emailRevertPendingChange) } return settingsViewController } } func changePassword(with settings: AccountSettings?, service: AccountSettingsService) -> (ImmuTableRow) -> SettingsTextViewController { return { row in return ChangePasswordViewController(username: settings?.username ?? "") { [weak self] value in DispatchQueue.main.async { SVProgressHUD.show(withStatus: Constants.changingPassword) service.updatePassword(value, finished: { (success, error) in if success { self?.refreshAccountDetails { SVProgressHUD.showSuccess(withStatus: Constants.changedPasswordSuccess) } } else { let errorMessage = error?.localizedDescription ?? Constants.changePasswordGenericError SVProgressHUD.showError(withStatus: errorMessage) } }) } } } } func changeUsername(with settings: AccountSettings?, service: AccountSettingsService) -> (ImmuTableRow) -> ChangeUsernameViewController { return { _ in return ChangeUsernameViewController(service: service, settings: settings) { [weak self] username in self?.refreshModel() if let username = username { let notice = Notice(title: String(format: Constants.usernameChanged, username)) ActionDispatcher.dispatch(NoticeAction.post(notice)) } } } } func refreshAccountDetails(finished: @escaping () -> Void) { guard let account = accountService.defaultWordPressComAccount() else { return } accountService.updateUserDetails(for: account, success: { () in finished() }, failure: { _ in finished() }) } func editWebAddress(_ service: AccountSettingsService) -> (ImmuTableRow) -> SettingsTextViewController { let hint = NSLocalizedString("Shown publicly when you comment on blogs.", comment: "Help text when editing web address") return editText(AccountSettingsChange.webAddress, hint: hint, service: service) } func editPrimarySite(_ settings: AccountSettings?, service: AccountSettingsService) -> ImmuTableRowControllerGenerator { return { row in let selectorViewController = BlogSelectorViewController(selectedBlogDotComID: settings?.primarySiteID as NSNumber?, successHandler: { (dotComID: NSNumber?) in if let dotComID = dotComID?.intValue { let change = AccountSettingsChange.primarySite(dotComID) service.saveChange(change) } }, dismissHandler: nil) selectorViewController.title = NSLocalizedString("Primary Site", comment: "Primary Site Picker's Title") selectorViewController.displaysOnlyDefaultAccountSites = true selectorViewController.displaysCancelButton = true selectorViewController.dismissOnCompletion = true selectorViewController.dismissOnCancellation = true return selectorViewController } } private var closeAccountAction: (ImmuTableRow) -> Void { return { [weak self] _ in guard let self = self else { return } switch self.hasAtomicSite { case true: self.showCloseAccountErrorAlert() case false : self.showCloseAccountAlert() } } } private var hasAtomicSite: Bool { return accountService.defaultWordPressComAccount()?.hasAtomicSite() ?? false } private func showCloseAccountAlert() { guard let value = settings?.username else { return } let title = NSLocalizedString("Confirm Close Account", comment: "Close Account alert title") let message = NSLocalizedString("\nTo confirm, please re-enter your username before closing.\n\n", comment: "Message of Close Account confirmation alert") let destructiveActionTitle = NSLocalizedString("Permanently Close Account", comment: "Close Account confirmation action title") let alert = alertHelper.makeAlertWithConfirmation(title: title, message: message, valueToConfirm: value, destructiveActionTitle: destructiveActionTitle, destructiveAction: closeAccount) alert.presentFromRootViewController() } private func closeAccount() { let status = NSLocalizedString("Closing account…", comment: "Overlay message displayed while closing account") SVProgressHUD.setDefaultMaskType(.black) SVProgressHUD.show(withStatus: status) accountSettingsService.closeAccount { [weak self] in switch $0 { case .success: let status = NSLocalizedString("Account closed", comment: "Overlay message displayed when account successfully closed") SVProgressHUD.showDismissibleSuccess(withStatus: status) AccountHelper.logOutDefaultWordPressComAccount() case .failure(let error): SVProgressHUD.dismiss() DDLogError("Error closing account: \(error.localizedDescription)") self?.showCloseAccountErrorAlert() } } } private func showCloseAccountErrorAlert() { let title = NSLocalizedString("Couldn’t close account automatically", comment: "Error title displayed when unable to close user account.") let message = NSLocalizedString("To close this account now, contact our support team.", comment: "Error message displayed when unable to close user account.") let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let contactSupportTitle = NSLocalizedString("Contact Support", comment: "Title for a button displayed when unable to close user account due to having atomic site.") alert.addActionWithTitle(contactSupportTitle, style: .default, handler: contactSupportAction) let cancelAction = NSLocalizedString("Cancel", comment: "Alert dismissal title") alert.addCancelActionWithTitle(cancelAction) alert.presentFromRootViewController() } private var contactSupportAction: ((UIAlertAction) -> Void) { return { action in if ZendeskUtils.zendeskEnabled { guard let leafViewController = UIApplication.shared.leafViewController else { return } ZendeskUtils.sharedInstance.showNewRequestIfPossible(from: leafViewController, with: .closeAccount) { [weak self] identityUpdated in if identityUpdated { self?.refreshModel() } } } else { guard let url = Constants.forumsURL else { return } UIApplication.shared.open(url) } } } @objc fileprivate func showSettingsChangeErrorMessage(notification: NSNotification) { guard let error = notification.userInfo?[NSUnderlyingErrorKey] as? NSError, let errorMessage = error.userInfo[WordPressComRestApi.ErrorKeyErrorMessage] as? String else { return } SVProgressHUD.showError(withStatus: errorMessage) } // MARK: - Private Helpers fileprivate func noticeForAccountSettings(_ settings: AccountSettings?) -> String? { guard settings?.emailPendingChange == true, let pendingAddress = settings?.emailPendingAddress else { return nil } let localizedNotice = NSLocalizedString("There is a pending change of your email to %@. Please check your inbox for a confirmation link.", comment: "Displayed when there's a pending Email Change. The variable is the new email address.") return String(format: localizedNotice, pendingAddress) } fileprivate func emailAccessoryImage() -> UIImage? { guard settings?.emailPendingChange == true else { return nil } return UIImage.gridicon(.noticeOutline).imageWithTintColor(.error) } // MARK: - Constants enum Constants { static let title = NSLocalizedString("Change Password", comment: "Account Settings Change password label") static let changingPassword = NSLocalizedString("Changing password", comment: "Loader title displayed by the loading view while the password is changing") static let changedPasswordSuccess = NSLocalizedString("Password changed successfully", comment: "Loader title displayed by the loading view while the password is changed successfully") static let changePasswordGenericError = NSLocalizedString("There was an error changing the password", comment: "Text displayed when there is a failure loading the history.") static let usernameChanged = NSLocalizedString("Username changed to %@", comment: "Message displayed in a Notice when the username has changed successfully. The placeholder is the new username.") static let forumsURL = URL(string: "https://ios.forums.wordpress.org") } }
gpl-2.0
478719f6f7c8816d6ce2f76916ae089f
45.8
203
0.634442
6.202006
false
false
false
false
siquare/taml
Timetable/Extensions.swift
1
2850
// // Extensions.swift // Timetable // // Created by Cubic on 2015/02/14. // Copyright (c) 2015年 Cubic. All rights reserved. // import Foundation import UIKit infix operator => { associativity left precedence 91 } func => <T>(object: T, initializer: (T) -> ()) -> T { initializer(object) return object } extension UIView { func getParentViewController() -> UIViewController? { var responder : UIResponder? = self while true { responder = responder?.nextResponder() ?? self if responder == nil { return nil } else if responder!.isKindOfClass(UIViewController.self) { return responder as? UIViewController } } } func getFirstResponder() -> UIView? { if self.isFirstResponder() { return self } for subview in self.subviews { if subview.isFirstResponder() { return subview as? UIView } if let ret = subview.getFirstResponder() { return ret } } return nil } func absPoint() -> CGPoint { if self.superview == nil { return CGPointZero } var p = self.superview!.absPoint() return CGPoint(x: self.frame.origin.x + p.x, y: self.frame.origin.y + p.y) } } extension String { var floatValue: Float { return (self as NSString).floatValue } } let CALENDAR = NSCalendar(identifier: NSCalendarIdentifierGregorian)! extension NSDate { func succ(unit : NSCalendarUnit, value : Int) -> NSDate? { return CALENDAR.dateByAddingUnit(unit, value: value, toDate: self, options: nil) } func weekday() -> Int { return CALENDAR.component(.CalendarUnitWeekday, fromDate: self) } func month() -> Int { return CALENDAR.component(.CalendarUnitMonth, fromDate: self) } func day() -> Int { return CALENDAR.component(.CalendarUnitDay, fromDate: self) } func year() -> Int { return CALENDAR.component(.CalendarUnitYear, fromDate: self) } } extension UIColor { class var PrimaryColor : UIColor { return UIColor(red: 85.0/255, green: 172.0/255, blue: 238.0/255, alpha: 1.0) } class var SubColor1 : UIColor { return UIColor(red: 102/255, green: 117/255, blue: 127/255, alpha: 1.0) } class var SubColor2 : UIColor { return UIColor(red: 153/255, green: 170/255, blue: 181/255, alpha: 1.0) } class var SubColor3 : UIColor { return UIColor(red: 204/255, green: 214/255, blue: 221/255, alpha: 1.0) } class var SubColor4 : UIColor { return UIColor(red: 245/255, green: 248/255, blue: 250/255, alpha: 1.0) } } extension NSCalendar { class var Weekdays : [String] { return [ "", "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" ] } //class var Weekdays : [String] { return [ "", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ] } class var Months : [String] { return [ "", "Jan.", "Feb.", "Mar.", "Apr.", "May.", "Jun.", "Jul.", "Aug.", "Sep.", "Oct.", "Nov.", "Dec." ] } }
mit
0b6f1250cdc42161ebcac9ee10719e11
26.242718
142
0.65752
3.266589
false
false
false
false
GuitarPlayer-Ma/Swiftweibo
weibo/weibo/Classes/Home/Model/Status.swift
1
3013
// // Status.swift // weibo // // Created by mada on 15/10/9. // Copyright © 2015年 MD. All rights reserved. // import UIKit class Status: NSObject { // 微博创建时间 var created_at: String? { didSet { let date = NSDate.dateWithStr(created_at!) created_at = date?.dateDescription } } // 微博id var id: Int = 0 // 微博来源 var source: String? { didSet { if let str = source { if str == "" { return } // 拿到起始位置 let startIndex = (str as NSString).rangeOfString(">").location + 1 // 获取截取的长度 let strLength = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startIndex // 截取字符串 source = "来自 " + (str as NSString).substringWithRange(NSMakeRange(startIndex, strLength)) } } } // 微博内容 var text: String? // 配图数组 var pic_urls: [[String: AnyObject]]? { didSet { // 进行安全检查 let count = pic_urls?.count ?? 0 if count == 0 { return } // 生成URL数组 thumbnail_pics = [NSURL]() for dict in pic_urls! { let str = dict["thumbnail_pic"] as! String let url = NSURL(string: str)! thumbnail_pics?.append(url) } } } // 配图的URL数组 var thumbnail_pics: [NSURL]? var pictureURLs: [NSURL]? { return retweeted_status != nil ? retweeted_status?.thumbnail_pics : thumbnail_pics } // 用户模型 var user: User? // 转发微博 var retweeted_status: Status? init(dict: [String: AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) } // setValuesForKeysWithDictionary方法内部会调用setValue方法 override func setValue(value: AnyObject?, forKey key: String) { // 判断是不是user if key == "user" { user = User(dict: value as! [String: AnyObject]) return } // 如果是retweet_status,自己处理 if key == "retweeted_status" { retweeted_status = Status(dict: value as! [String: AnyObject]) return } super.setValue(value, forKey: key) } // 必须重写这个方法,告诉系统不转化的key要怎么做 override func setValue(value: AnyObject?, forUndefinedKey key: String) { } // 属性字典 static let properties = ["id", "name", "profile_image_url", "verified", "verified_type"] // 打印对象 override var description: String{ return "\(self.dictionaryWithValuesForKeys(User.properties))" } }
mit
671de2e605cb6337b374d145e9f1d0c5
24.327273
139
0.508973
4.530081
false
false
false
false
snowpunch/AppLove
App Love/UI/ViewControllers/ReviewListVC.swift
1
2965
// // ReviewListVC.swift // App Love // // Created by Woodie Dovich on 2016-02-24. // Copyright © 2016 Snowpunch. All rights reserved. // // Display reviews for an app, for every territory selected. // import UIKit private extension Selector { static let reloadData = #selector(UITableView.reloadData) static let onReviewOptions = #selector(ReviewListVC.onReviewOptions) } class ReviewListVC: UIViewController { var allReviews = [ReviewModel]() var refreshControl: UIRefreshControl! @IBOutlet var tableView: UITableView! // Territory Loading UICollectionView acting as a visual loader. @IBOutlet weak var appIcon: UIImageView! @IBOutlet weak var appName: UILabel! @IBOutlet weak var aveRating: UILabel! @IBOutlet weak var territoryCollection: UICollectionView! override func viewDidLoad() { super.viewDidLoad() tableSetup() registerNotifications() addRefreshControl() registerTerritoryNotificationsForLoader() if let toolbar = self.navigationController?.toolbar { Theme.toolBar(toolbar) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let _ = AppList.sharedInst.getSelectedModel() { setupCollection() ReviewLoadManager.sharedInst.loadReviews() } else { showEmptyView() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) ReviewLoadManager.sharedInst.cancelLoading() } func onReviewOptions(notification: NSNotification) { guard let dic = notification.userInfo else { return } guard let model = dic["reviewModel"] as? ReviewModel else { return } guard let button = dic["button"] as? UIButton else { return } displayReviewOptions(model, button:button) } func registerNotifications() { NSNotificationCenter.addObserver(self, sel: .reloadData, name: Const.load.reloadData) NSNotificationCenter.addObserver(self,sel: .onReviewOptions, name: Const.reviewOptions.showOptions) } func unregisterNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { NSNotificationCenter.post(Const.load.orientationChange) } @IBAction func onSort(sender: UIBarButtonItem) { displaySortActionSheet(sender) } @IBAction func onAppStore(sender: AnyObject) { // show loading indicator. if let appId = AppList.sharedInst.getSelectedModel()?.appId { showStore(appId) } } @IBAction func onRemoveEmptyTerritories(button: UIBarButtonItem) { removeEmptyTerritories(button) } deinit { unregisterNotifications() } }
mit
c895f7ccf0c2e13b3a2e420052970da4
29.255102
107
0.671053
5.05802
false
false
false
false
wrutkowski/Lucid-Weather-Clock
Pods/Charts/Charts/Classes/Components/ChartYAxis.swift
6
8980
// // ChartYAxis.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif /// Class representing the y-axis labels settings and its entries. /// Be aware that not all features the YLabels class provides are suitable for the RadarChart. /// Customizations that affect the value range of the axis need to be applied before setting data for the chart. open class ChartYAxis: ChartAxisBase { @objc(YAxisLabelPosition) public enum LabelPosition: Int { case outsideChart case insideChart } /// Enum that specifies the axis a DataSet should be plotted against, either Left or Right. @objc public enum AxisDependency: Int { case left case right } open var entries = [Double]() open var entryCount: Int { return entries.count; } /// the number of y-label entries the y-labels should have, default 6 private var _labelCount = Int(6) /// indicates if the top y-label entry is drawn or not open var drawTopYLabelEntryEnabled = true /// if true, the y-labels show only the minimum and maximum value open var showOnlyMinMaxEnabled = false /// flag that indicates if the axis is inverted or not open var inverted = false /// This property is deprecated - Use `axisMinValue` instead. @available(*, deprecated:1.0, message:"Use axisMinValue instead.") open var startAtZeroEnabled: Bool { get { return isAxisMinCustom && _axisMinimum == 0.0 } set { if newValue { axisMinValue = 0.0 } else { resetCustomAxisMin() } } } /// if true, the set number of y-labels will be forced open var forceLabelsEnabled = false /// flag that indicates if the zero-line should be drawn regardless of other grid lines open var drawZeroLineEnabled = false /// Color of the zero line open var zeroLineColor: NSUIColor? = NSUIColor.gray /// Width of the zero line open var zeroLineWidth: CGFloat = 1.0 /// This is how much (in pixels) into the dash pattern are we starting from. open var zeroLineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] open var zeroLineDashLengths: [CGFloat]? /// the formatter used to customly format the y-labels open var valueFormatter: NumberFormatter? /// the formatter used to customly format the y-labels internal var _defaultValueFormatter = NumberFormatter() /// axis space from the largest value to the top in percent of the total axis range open var spaceTop = CGFloat(0.1) /// axis space from the smallest value to the bottom in percent of the total axis range open var spaceBottom = CGFloat(0.1) /// the position of the y-labels relative to the chart open var labelPosition = LabelPosition.outsideChart /// the side this axis object represents private var _axisDependency = AxisDependency.left /// the minimum width that the axis should take /// /// **default**: 0.0 open var minWidth = CGFloat(0) /// the maximum width that the axis can take. /// use Infinity for disabling the maximum. /// /// **default**: CGFloat.infinity open var maxWidth = CGFloat(CGFloat.infinity) /// When true, axis labels are controlled by the `granularity` property. /// When false, axis values could possibly be repeated. /// This could happen if two adjacent axis values are rounded to same value. /// If using granularity this could be avoided by having fewer axis values visible. open var granularityEnabled = false private var _granularity = Double(1.0) /// The minimum interval between axis values. /// This can be used to avoid label duplicating when zooming in. /// /// **default**: 1.0 open var granularity: Double { get { return _granularity } set { _granularity = newValue // set this to true if it was disabled, as it makes no sense to set this property with granularity disabled granularityEnabled = true } } public override init() { super.init() _defaultValueFormatter.minimumIntegerDigits = 1 _defaultValueFormatter.maximumFractionDigits = 1 _defaultValueFormatter.minimumFractionDigits = 1 _defaultValueFormatter.usesGroupingSeparator = true self.yOffset = 0.0 } public init(position: AxisDependency) { super.init() _axisDependency = position _defaultValueFormatter.minimumIntegerDigits = 1 _defaultValueFormatter.maximumFractionDigits = 1 _defaultValueFormatter.minimumFractionDigits = 1 _defaultValueFormatter.usesGroupingSeparator = true self.yOffset = 0.0 } open var axisDependency: AxisDependency { return _axisDependency } open func setLabelCount(_ count: Int, force: Bool) { _labelCount = count if (_labelCount > 25) { _labelCount = 25 } if (_labelCount < 2) { _labelCount = 2 } forceLabelsEnabled = force } /// the number of label entries the y-axis should have /// max = 25, /// min = 2, /// default = 6, /// be aware that this number is not fixed and can only be approximated open var labelCount: Int { get { return _labelCount } set { setLabelCount(newValue, force: false); } } open func requiredSize() -> CGSize { let label = getLongestLabel() as NSString var size = label.size(attributes: [NSFontAttributeName: labelFont]) size.width += xOffset * 2.0 size.height += yOffset * 2.0 size.width = max(minWidth, min(size.width, maxWidth > 0.0 ? maxWidth : size.width)) return size } open func getRequiredHeightSpace() -> CGFloat { return requiredSize().height } open override func getLongestLabel() -> String { var longest = "" for i in 0 ..< entries.count { let text = getFormattedLabel(i) if (longest.characters.count < text.characters.count) { longest = text } } return longest } /// - returns: the formatted y-label at the specified index. This will either use the auto-formatter or the custom formatter (if one is set). open func getFormattedLabel(_ index: Int) -> String { if (index < 0 || index >= entries.count) { return "" } return (valueFormatter ?? _defaultValueFormatter).string(from: entries[index] as NSNumber)! } /// - returns: true if this axis needs horizontal offset, false if no offset is needed. open var needsOffset: Bool { if (enabled && drawLabelsEnabled && labelPosition == .outsideChart) { return true } else { return false } } /// Calculates the minimum, maximum and range values of the YAxis with the given minimum and maximum values from the chart data. /// - parameter dataMin: the y-min value according to chart data /// - parameter dataMax: the y-max value according to chart open func calculate(min dataMin: Double, max dataMax: Double) { // if custom, use value as is, else use data value var min = _customAxisMin ? _axisMinimum : dataMin var max = _customAxisMax ? _axisMaximum : dataMax // temporary range (before calculations) let range = abs(max - min) // in case all values are equal if range == 0.0 { max = max + 1.0 min = min - 1.0 } // bottom-space only effects non-custom min if !_customAxisMin { let bottomSpace = range * Double(spaceBottom) _axisMinimum = min - bottomSpace } // top-space only effects non-custom max if !_customAxisMax { let topSpace = range * Double(spaceTop) _axisMaximum = max + topSpace } // calc actual range axisRange = abs(_axisMaximum - _axisMinimum) } }
mit
697d7c7ce112eedd464f8364130cee0d
27.967742
145
0.594098
4.917853
false
false
false
false
senfi/KSTokenView
KSTokenView/KSTokenField.swift
1
21792
// // KSTokenField.swift // KSTokenView // // Created by Khawar Shahzad on 01/01/2015. // Copyright (c) 2015 Khawar Shahzad. 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 UIKit enum KSTokenFieldState { case Opened case Closed } @objc protocol KSTokenFieldDelegate : UITextFieldDelegate { func tokenFieldShouldChangeHeight(height: CGFloat) optional func tokenFieldDidSelectToken(token: KSToken) optional func tokenFieldDidBeginEditing(tokenField: KSTokenField) optional func tokenFieldDidEndEditing(tokenField: KSTokenField) } class KSTokenField: UITextField { // MARK: - Private Properties private var _cursorColor: UIColor = UIColor.grayColor() { willSet { tintColor = newValue } } private var _setupCompleted: Bool = false private var _selfFrame: CGRect? private var _caretPoint: CGPoint? private var _placeholderValue: String? private var _placeholderLabel: UILabel? private var _state: KSTokenFieldState = .Opened private var _minWidthForInput: CGFloat = 50.0 private var _separatorText: String? private var _font: UIFont? private var _paddingX: CGFloat? private var _paddingY: CGFloat? private var _marginX: CGFloat? private var _marginY: CGFloat? private var _removesTokensOnEndEditing = true private var _scrollView = UIScrollView(frame: .zeroRect) private var _scrollPoint = CGPoint.zeroPoint private var _direction: KSTokenViewScrollDirection = .Vertical { didSet { if (oldValue != _direction) { updateLayout() } } } private var _descriptionText: String = "selections" { didSet { _updateText() } } // MARK: - Public Properties /// default is grayColor() var promptTextColor: UIColor = UIColor.grayColor() /// default is grayColor() var placeHolderColor: UIColor = UIColor.grayColor() /// default is 120.0. After maximum limit is reached, tokens starts scrolling vertically var maximumHeight: CGFloat = 120.0 /// default is nil override var placeholder: String? { get { return _placeholderValue } set { super.placeholder = newValue if (newValue == nil) { return } _placeholderValue = newValue } } weak var parentView: KSTokenView? { willSet (tokenView) { if (tokenView != nil) { _cursorColor = tokenView!.cursorColor _paddingX = tokenView!.paddingX _paddingY = tokenView!.paddingY _marginX = tokenView!.marginX _marginY = tokenView!.marginY _direction = tokenView!.direction _font = tokenView!.font _minWidthForInput = tokenView!.minWidthForInput _separatorText = tokenView!.separatorText _removesTokensOnEndEditing = tokenView!.removesTokensOnEndEditing _descriptionText = tokenView!.descriptionText _setPromptText(tokenView!.promptText) if (_setupCompleted) { updateLayout() } } } } weak var tokenFieldDelegate: KSTokenFieldDelegate? { didSet { delegate = tokenFieldDelegate } } /// returns Array of tokens var tokens = [KSToken]() /// returns selected KSToken object var selectedToken: KSToken? // MARK: - Constructors required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _setupTokenField() } override init(frame: CGRect) { super.init(frame: frame) _setupTokenField() } // MARK: - Methods // MARK: - Setup private func _setupTokenField() { text = "" autocorrectionType = UITextAutocorrectionType.No autocapitalizationType = UITextAutocapitalizationType.None contentVerticalAlignment = UIControlContentVerticalAlignment.Top returnKeyType = UIReturnKeyType.Done text = KSTextEmpty backgroundColor = UIColor.whiteColor() clipsToBounds = true _state = .Closed _setScrollRect() _scrollView.backgroundColor = UIColor.clearColor() _scrollView.autoresizingMask = .FlexibleWidth | .FlexibleHeight let gestureRecognizer = UITapGestureRecognizer(target: self, action: "becomeFirstResponder") gestureRecognizer.cancelsTouchesInView = false _scrollView.addGestureRecognizer(gestureRecognizer) _scrollView.delegate = self addSubview(_scrollView) addTarget(self, action: "tokenFieldTextDidChange:", forControlEvents: UIControlEvents.EditingChanged) } private func _setScrollRect() { _scrollView.frame = CGRect(x: _leftViewRect().width, y: 0, width: frame.width - _leftViewRect().width, height: frame.height) } override func drawRect(rect: CGRect) { _selfFrame = rect _setupCompleted = true _updateText() // Fix the bug which doesn't update the UI when _selfFrame is not set. // https://github.com/khawars/KSTokenView/issues/11 if (count(tokens) > 0) { updateLayout() } } // MARK: - Add Token /** Create and add new token :param: title String value :returns: KSToken object */ func addTokenWithTitle(title: String) -> KSToken? { return addTokenWithTitle(title, tokenObject: nil) } /** Create and add new token with custom object :param: title String value :param: tokenObject Any custom object :returns: KSToken object */ func addTokenWithTitle(title: String, tokenObject: AnyObject?) -> KSToken? { var token = KSToken(title: title, object: tokenObject) return addToken(token) } /** Add new token :param: token KSToken object :returns: KSToken object */ func addToken(token: KSToken) -> KSToken? { if (count(token.title) == 0) { NSException(name: "", reason: "Title is not valid String", userInfo: nil); } if (!contains(tokens, token)) { token.addTarget(self, action: "tokenTouchDown:", forControlEvents: .TouchDown) token.addTarget(self, action: "tokenTouchUpInside:", forControlEvents: .TouchUpInside) tokens.append(token) _insertToken(token) } return token } private func _insertToken(token: KSToken, shouldLayout: Bool = true) { _scrollView.addSubview(token) _scrollView.bringSubviewToFront(token) token.setNeedsDisplay() if shouldLayout == true { updateLayout() } } //MARK: - Delete Token /* **************************** Delete Token **************************** */ /** Deletes a token from view :param: token KSToken object */ func deleteToken(token: KSToken) { removeToken(token) } /** Deletes a token from view, if any token is found for custom object :param: object Custom object */ func deleteTokenWithObject(object: AnyObject?) { if object == nil {return} for token in tokens { if (token.object!.isEqual(object)) { removeToken(token) break } } } /** Deletes all tokens from view */ func forceDeleteAllTokens() { tokens.removeAll(keepCapacity: false) for token in tokens { removeToken(token, removingAll: true) } updateLayout() } /** Deletes token from view :param: token KSToken object :param: removingAll A boolean to describe if removingAll tokens */ func removeToken(token: KSToken, removingAll: Bool = false) { if token.isEqual(selectedToken) { deselectSelectedToken() } token.removeFromSuperview() let index = find(tokens, token) if (index != nil) { tokens.removeAtIndex(index!) } if (!removingAll) { updateLayout() } } //MARK: - Layout /* **************************** Layout **************************** */ /** Untokenzies the layout */ func untokenize() { if (!_removesTokensOnEndEditing) { return } _state = .Closed for subview in _scrollView.subviews { if subview is KSToken { subview.removeFromSuperview() } } updateLayout() } /** Tokenizes the layout */ func tokenize() { _state = .Opened for token: KSToken in tokens { _insertToken(token, shouldLayout: false) } updateLayout() } /** Updates the tokenView layout and calls delegate methods */ func updateLayout(shouldUpdateText: Bool = true) { if (parentView == nil) { return } _caretPoint = _layoutTokens() deselectSelectedToken() if (shouldUpdateText) { _updateText() } if _caretPoint != .zeroPoint { let tokensMaxY = _caretPoint!.y if (frame.size.height != tokensMaxY) { tokenFieldDelegate?.tokenFieldShouldChangeHeight(tokensMaxY) } } } /** Layout tokens :returns: CGPoint maximum position values */ private func _layoutTokens() -> CGPoint { if (_selfFrame == nil) { return .zeroPoint } if (_state == .Closed) { return CGPoint(x: _marginX!, y: _selfFrame!.size.height) } if (_direction == .Horizontal) { return _layoutTokensHorizontally() } var lineNumber = 1 let leftMargin = _leftViewRect().width let rightMargin = _rightViewRect().width let tokenHeight = _font!.lineHeight + _paddingY!; var tokenPosition = CGPoint(x: _marginX!, y: _marginY!) for token: KSToken in tokens { let width = KSUtils.getRect(token.title, width: bounds.size.width, font: _font!).size.width + ceil(_paddingX!*2+1) let tokenWidth = min(width, token.maxWidth) // Add token at specific position if ((token.superview) != nil) { if (tokenPosition.x + tokenWidth + _marginX! + leftMargin > bounds.size.width - rightMargin) { lineNumber++; tokenPosition.x = _marginX! tokenPosition.y += (tokenHeight + _marginY!); } token.frame = CGRect(x: tokenPosition.x, y: tokenPosition.y, width: tokenWidth, height: tokenHeight) tokenPosition.x += tokenWidth + _marginX!; } } // check if next token can be added in same line or new line if ((bounds.size.width) - (tokenPosition.x + _marginX!) - leftMargin < _minWidthForInput) { lineNumber++; tokenPosition.x = _marginX! tokenPosition.y += (tokenHeight + _marginY!); } var positionY = (lineNumber == 1 && tokens.count == 0) ? _selfFrame!.size.height: (tokenPosition.y + tokenHeight + _marginY!) _scrollView.contentSize = CGSize(width: _scrollView.frame.width, height: positionY) if (positionY > maximumHeight) { positionY = maximumHeight } _scrollView.frame.size = CGSize(width: _scrollView.frame.width, height: positionY) scrollViewScrollToEnd() return CGPoint(x: tokenPosition.x + leftMargin, y: positionY) } /** Layout tokens horizontally :returns: CGPoint maximum position values */ private func _layoutTokensHorizontally() -> CGPoint { let leftMargin = _leftViewRect().width let rightMargin = _rightViewRect().width let tokenHeight = _font!.lineHeight + _paddingY!; var tokenPosition = CGPoint(x: _marginX!, y: _marginY!) for token: KSToken in tokens { let width = KSUtils.getRect(token.title, width: bounds.size.width, font: _font!).size.width + ceil(_paddingX!*2+1) let tokenWidth = min(width, token.maxWidth) if ((token.superview) != nil) { token.frame = CGRect(x: tokenPosition.x, y: tokenPosition.y, width: tokenWidth, height: tokenHeight) tokenPosition.x += tokenWidth + _marginX!; } } let offsetWidth = ((tokenPosition.x + _marginX! + _leftViewRect().width) > (frame.width - _minWidthForInput)) ? _minWidthForInput : 0 _scrollView.contentSize = CGSize(width: max(_scrollView.frame.width, tokenPosition.x + offsetWidth), height: frame.height) scrollViewScrollToEnd() return CGPoint(x: min(tokenPosition.x + leftMargin, frame.width - _minWidthForInput), y: frame.height) } /** Scroll the tokens to end */ func scrollViewScrollToEnd() { var bottomOffset: CGPoint switch _direction { case .Vertical: bottomOffset = CGPoint(x: 0, y: _scrollView.contentSize.height - _scrollView.bounds.height) case .Horizontal: bottomOffset = CGPoint(x: _scrollView.contentSize.width - _scrollView.bounds.width, y: 0) } _scrollView.setContentOffset(bottomOffset, animated: true) } //MARK: - Text Rect /* **************************** Text Rect **************************** */ private func _textRectWithBounds(bounds: CGRect) -> CGRect { if (!_setupCompleted) {return .zeroRect} if (tokens.count == 0 || _caretPoint == nil) { return CGRect(x: _leftViewRect().width + _marginX!, y: (bounds.size.height - font.lineHeight)*0.5, width: bounds.size.width-5, height: bounds.size.height) } if (tokens.count != 0 && _state == .Closed) { return CGRect(x: _leftViewRect().maxX + _marginX!, y: (_caretPoint!.y - font.lineHeight - (_marginY!)), width: (frame.size.width - _caretPoint!.x - _marginX!), height: bounds.size.height) } return CGRect(x: _caretPoint!.x, y: (_caretPoint!.y - font.lineHeight - (_marginY!)), width: (frame.size.width - _caretPoint!.x - _marginX!), height: bounds.size.height) } override func leftViewRectForBounds(bounds: CGRect) -> CGRect { return CGRect(x: _marginX!, y: (_selfFrame != nil) ? (_selfFrame!.height - _leftViewRect().height)*0.5: (bounds.height - _leftViewRect().height)*0.5, width: _leftViewRect().width, height: _leftViewRect().height) } override func textRectForBounds(bounds: CGRect) -> CGRect { return _textRectWithBounds(bounds) } override func editingRectForBounds(bounds: CGRect) -> CGRect { return _textRectWithBounds(bounds) } override func placeholderRectForBounds(bounds: CGRect) -> CGRect { return _textRectWithBounds(bounds) } private func _leftViewRect() -> CGRect { if (leftViewMode == .Never || (leftViewMode == .UnlessEditing && editing) || (leftViewMode == .WhileEditing && !editing)) { return .zeroRect } return leftView!.bounds } private func _rightViewRect() -> CGRect { if (rightViewMode == .Never || rightViewMode == .UnlessEditing && editing || rightViewMode == .WhileEditing && !editing) { return .zeroRect } return rightView!.bounds } private func _setPromptText(text: String?) { if (text != nil) { var label = leftView if !(label is UILabel) { label = UILabel(frame: .zeroRect) label?.frame.origin.x += _marginX! (label as! UILabel).textColor = promptTextColor leftViewMode = .Always } (label as! UILabel).text = text (label as! UILabel).font = font (label as! UILabel).sizeToFit() leftView = label } else { leftView = nil } _setScrollRect() } //MARK: - Placeholder /* **************************** Placeholder **************************** */ private func _updateText() { if (!_setupCompleted) {return} _initPlaceholderLabel() switch(_state) { case .Opened: text = KSTextEmpty break case .Closed: if tokens.count == 0 { text = KSTextEmpty } else { var title = KSTextEmpty for token: KSToken in tokens { title += "\(token.title)\(_separatorText!)" } if (count(title) > 0) { title = title.substringWithRange(Range<String.Index>(start: advance(title.startIndex, 0), end: advance(title.endIndex, -count(_separatorText!)))) } var width = KSUtils.widthOfString(title, font: font) if width + _leftViewRect().width > bounds.width { text = "\(tokens.count) \(_descriptionText)" } else { text = title } } break } _updatePlaceHolderVisibility() } private func _updatePlaceHolderVisibility() { if tokens.count == 0 && (text == KSTextEmpty || text.isEmpty) { _placeholderLabel?.text = _placeholderValue! _placeholderLabel?.hidden = false } else { _placeholderLabel?.hidden = true } } private func _initPlaceholderLabel() { let xPos = _marginX! if (_placeholderLabel == nil) { _placeholderLabel = UILabel(frame: CGRect(x: xPos, y: 0, width: _selfFrame!.width - xPos - _leftViewRect().size.width, height: 30)) _placeholderLabel?.textColor = placeHolderColor _scrollView.addSubview(_placeholderLabel!) } else { _placeholderLabel?.frame.origin.x = xPos } } //MARK: - Token Gestures //__________________________________________________________________________________ // func isSelectedToken(token: KSToken) -> Bool { if token.isEqual(selectedToken) { return true } return false } func deselectSelectedToken() { selectedToken?.selected = false selectedToken = nil } func selectToken(token: KSToken) { if (token.sticky) { return } for token: KSToken in tokens { if isSelectedToken(token) { deselectSelectedToken() break } } token.selected = true selectedToken = token tokenFieldDelegate?.tokenFieldDidSelectToken?(token) } func tokenTouchDown(token: KSToken) { if (selectedToken != nil) { selectedToken?.selected = false selectedToken = nil } } func tokenTouchUpInside(token: KSToken) { selectToken(token) } override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { if (touch.view == self) { deselectSelectedToken() } return super.beginTrackingWithTouch(touch, withEvent: event) } func tokenFieldTextDidChange(textField: UITextField) { _updatePlaceHolderVisibility() } // MARK: - Other Methods func paddingX() -> CGFloat? { return _paddingX } func tokenFont() -> UIFont? { return _font } func objects() -> NSArray { var objects = NSMutableArray() for object: AnyObject in tokens { objects.addObject(object) } return objects } override func becomeFirstResponder() -> Bool { super.becomeFirstResponder() tokenFieldDelegate?.tokenFieldDidBeginEditing?(self) return true } override func resignFirstResponder() -> Bool { tokenFieldDelegate?.tokenFieldDidEndEditing?(self) return super.resignFirstResponder() } } //MARK: - UIScrollViewDelegate //__________________________________________________________________________________ // extension KSTokenField : UIScrollViewDelegate { func scrollViewWillBeginDragging(scrollView: UIScrollView) { _scrollPoint = scrollView.contentOffset } func scrollViewDidScroll(aScrollView: UIScrollView) { text = KSTextEmpty updateCaretVisiblity(aScrollView) } func updateCaretVisiblity(aScrollView: UIScrollView) { let scrollViewHeight = aScrollView.frame.size.height; let scrollContentSizeHeight = aScrollView.contentSize.height; let scrollOffset = aScrollView.contentOffset.y; if (scrollOffset + scrollViewHeight < scrollContentSizeHeight - 10) { hideCaret() } else if (scrollOffset + scrollViewHeight >= scrollContentSizeHeight - 10) { showCaret() } } func hideCaret() { tintColor = UIColor.clearColor() } func showCaret() { tintColor = _cursorColor } }
mit
a3ec405cf3e5746dd2c474313cc015dd
29.142462
217
0.599532
4.615971
false
false
false
false
donald-pinckney/Ideal-Gas-Simulator
Thermo/ExSwift/Int.swift
1
4812
// // Int.swift // ExSwift // // Created by pNre on 03/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation public extension Int { /** Calls function self times. :param: function Function to call */ func times <T> (function: Void -> T) { (0..<self).each { _ in function(); return } } /** Calls function self times. :param: function Function to call */ func times (function: Void -> Void) { (0..<self).each { _ in function(); return } } /** Calls function self times passing a value from 0 to self on each call. :param: function Function to call */ func times <T> (function: (Int) -> T) { (0..<self).each { index in function(index); return } } /** Checks if a number is even. :returns: true if self is even */ func isEven () -> Bool { return (self % 2) == 0 } /** Checks if a number is odd. :returns: true if self is odd */ func isOdd () -> Bool { return !isEven() } /** Iterates function, passing in integer values from self up to and including limit. :param: limit Last value to pass :param: function Function to invoke */ func upTo (limit: Int, function: (Int) -> ()) { if limit < self { return } (self...limit).each(function) } /** Iterates function, passing in integer values from self down to and including limit. :param: limit Last value to pass :param: function Function to invoke */ func downTo (limit: Int, function: (Int) -> ()) { if limit > self { return } Array(limit...self).reverse().each(function) } /** Clamps self to a specified range. :param: range Clamping range :returns: Clamped value */ func clamp (range: Range<Int>) -> Int { return clamp(range.startIndex, range.endIndex - 1) } /** Clamps self to a specified range. :param: min Lower bound :param: max Upper bound :returns: Clamped value */ func clamp (min: Int, _ max: Int) -> Int { return Swift.max(min, Swift.min(max, self)) } /** Checks if self is included a specified range. :param: range Range :param: string If true, "<" is used for comparison :returns: true if in range */ func isIn (range: Range<Int>, strict: Bool = false) -> Bool { if strict { return range.startIndex < self && self < range.endIndex - 1 } return range.startIndex <= self && self <= range.endIndex - 1 } /** Checks if self is included in a closed interval. :param: interval Interval to check :returns: true if in the interval */ func isIn (interval: ClosedInterval<Int>) -> Bool { return interval.contains(self) } /** Checks if self is included in an half open interval. :param: interval Interval to check :returns: true if in the interval */ func isIn (interval: HalfOpenInterval<Int>) -> Bool { return interval.contains(self) } /** Returns an [Int] containing the digits in self. :return: Array of digits */ func digits () -> [Int] { var result = [Int]() for char in String(self) { let string = String(char) if let toInt = string.toInt() { result.append(toInt) } } return result } /** Absolute value. :returns: abs(self) */ func abs () -> Int { return Swift.abs(self) } /** Greatest common divisor of self and n. :param: n :returns: GCD */ func gcd (n: Int) -> Int { return n == 0 ? self : n.gcd(self % n) } /** Least common multiple of self and n :param: n :returns: LCM */ func lcm (n: Int) -> Int { return (self * n).abs() / gcd(n) } /** Computes the factorial of self :returns: Factorial */ func factorial () -> Int { return self == 0 ? 1 : self * (self - 1).factorial() } /** Random integer between min and max (inclusive). :param: min Minimum value to return :param: max Maximum value to return :returns: Random integer */ static func random(min: Int = 0, max: Int) -> Int { return Int(arc4random_uniform(UInt32((max - min) + 1))) + min } }
mit
f217581885b5c40eb8e292c9afe19deb
22.023923
91
0.510391
4.311828
false
false
false
false
XWJACK/Music
Music/Universal/ViewControllers/MusicTabBarController.swift
1
1530
// // MusicTabBarController.swift // Music // // Created by Jack on 4/20/17. // Copyright © 2017 Jack. All rights reserved. // import UIKit final class MusicTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() tabBar.tintColor = .white tabBar.backgroundImage = UIImage.image(withColor: .clear) tabBar.barStyle = .black let musicListTabBarItem = UITabBarItem(title: "My Music", image: #imageLiteral(resourceName: "tabBar_music"), selectedImage: #imageLiteral(resourceName: "tabBar_music_selected")) let personalCenterTabBarItem = UITabBarItem(title: "Center", image: #imageLiteral(resourceName: "tabBar_center"), selectedImage: #imageLiteral(resourceName: "tabBar_center_selected")) let musicCollectionListViewController = MusicNavigationController(rootViewController: MusicCollectionListViewController()) let personalCenterViewController = MusicNavigationController(rootViewController: MusicCenterViewController()) musicCollectionListViewController.tabBarItem = musicListTabBarItem personalCenterViewController.tabBarItem = personalCenterTabBarItem viewControllers = [musicCollectionListViewController, personalCenterViewController] } }
mit
f3f3eed7aad42bd809611105a7f48464
40.324324
130
0.635056
6.370833
false
false
false
false
iOSDevLog/iOSDevLog
169. Camera/Camera/FocusViewController.swift
1
1758
// // FocusViewController.swift // Camera // // Created by Matteo Caldari on 06/02/15. // Copyright (c) 2015 Matteo Caldari. All rights reserved. // import UIKit import AVFoundation class FocusViewController: UIViewController, CameraControlsViewControllerProtocol, CameraSettingValueObserver { @IBOutlet var modeSwitch:UISwitch! @IBOutlet var slider:UISlider! var cameraController:CameraController? { willSet { if let cameraController = cameraController { cameraController.unregisterObserver(self, property: CameraControlObservableSettingLensPosition) } } didSet { if let cameraController = cameraController { cameraController.registerObserver(self, property: CameraControlObservableSettingLensPosition) } } } override func viewDidLoad() { setInitialValues() } @IBAction func sliderDidChangeValue(sender:UISlider) { cameraController?.lockFocusAtLensPosition(CGFloat(sender.value)) } @IBAction func modeSwitchValueChanged(sender:UISwitch) { if sender.on { cameraController?.enableContinuousAutoFocus() } else { cameraController?.lockFocusAtLensPosition(CGFloat(self.slider.value)) } slider.enabled = !sender.on } func cameraSetting(setting:String, valueChanged value:AnyObject) { if setting == CameraControlObservableSettingLensPosition { if let lensPosition = value as? Float { slider.value = lensPosition } } } func setInitialValues() { if isViewLoaded() && cameraController != nil { if let autoFocus = cameraController?.isContinuousAutoFocusEnabled() { modeSwitch.on = autoFocus slider.enabled = !autoFocus } if let currentLensPosition = cameraController?.currentLensPosition() { slider.value = currentLensPosition } } } }
mit
3d9a4944558e8f3e27d02eef9c87010a
23.416667
111
0.74744
4.156028
false
false
false
false
NitWitStudios/NWSNewYorkTimesBrowser
CodingExercise/CodingExercise/Controllers/ArticleTableViewController.swift
1
15331
// // ArticleTableViewController.swift // CodingExercise // // Created by James Hickman on 8/19/15. // Copyright (c) 2015 Hotel Tonight. All rights reserved. // import UIKit @objc class ArticleTableViewController: UITableViewController, UISearchBarDelegate, UISearchResultsUpdating, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate, UIScrollViewDelegate { let cellHeight: CGFloat = 150.0 let cellIdentifier = "ArticleTableViewCellIdentifier" var searchController = UISearchController(searchResultsController: nil) var articles = [Article]() var currentPage = 0 var currentTerm = "" var blockOperations = [NSBlockOperation]() var webViewController: WebViewController! var tapGestureRecognizer: UITapGestureRecognizer! // MARK: Overrides override func viewDidLoad() { super.viewDidLoad() // Navigation Bar Init let navImageView = UIImageView(image: UIImage(named: "Logo")) navImageView.frame = CGRectMake(0, 0, 100, 30) navImageView.contentMode = UIViewContentMode.ScaleAspectFit navigationItem.titleView = navImageView // TableView Init tableView.tableFooterView = UIView(frame: CGRectZero) // Hide empty cells tableView.emptyDataSetSource = self tableView.emptyDataSetDelegate = self tableView.registerClass(ArticleTableViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine tableView.separatorColor = UIColor.lightGrayColor() // Pull to load more articles tableView.addInfiniteScrollingWithActionHandler {[weak self] () -> Void in if let weakSelf = self { weakSelf.currentPage++ weakSelf.downloadArticlesForTerm(weakSelf.currentTerm, completion: { (data) -> Void in if let data = data, let articles = weakSelf.parseArticleData(data) { // Append new articles to existing weakSelf.articles += articles weakSelf.reloadData() } else { weakSelf.displayAlert() } }) } } // Search Controller Init definesPresentationContext = true searchController.searchBar.delegate = self searchController.searchResultsUpdater = self searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.sizeToFit() tableView.tableHeaderView = searchController.searchBar // Tap Gesture Recognizer Init tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "didTapView:") tapGestureRecognizer.cancelsTouchesInView = false // Ensure tableView cell can be tapped view.addGestureRecognizer(tapGestureRecognizer) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // Disable the UISearchController (bug when search controller is active and you push new view controller, then rotate pushed view controller and come back, search bar is concealed under navigation bar) searchController.active = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() articles = [] cancelBlockOperations() } // MARK: NY Times API func downloadArticlesForTerm(term: String, completion: (data: NSDictionary?) -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {[weak self] () -> Void in if let weakSelf = self { // Show loading indicator weakSelf.showActivityIndicator() // Build API Query var urlString = Constant.NYTimesApiQueryString() urlString += "q="+term.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! urlString += "&fl="+Constant.NYTimesApiFieldsKey() // Limit API response to only fields we need (i.e. url, headline, thumbnail) to help lighten payload urlString += "&page="+String(weakSelf.currentPage) urlString += "&api-key="+Constant.NYTimesApiKey() if let url = NSURL(string: urlString), let data = NSData(contentsOfURL: url) { var error: NSError? if let json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &error) as? NSDictionary { completion(data: json) } else { completion(data: nil) weakSelf.displayAlert() } weakSelf.hideActivityIndicator() } else { completion(data: nil) weakSelf.hideActivityIndicator() weakSelf.displayAlert() } } }) } func parseArticleData(data: NSDictionary) -> [Article]? { if let response = data[Constant.NYTimesApiResponseKey()] as? [String: AnyObject], let docs = response[Constant.NYTimesApiResponseDocsKey()] as? [AnyObject] { // Check for empty data (i.e. no articles found for search term) if docs.count == 0 { return [] } // Iterate each article's JSON data and build Article objects var articles = [Article]() for articleData in docs as! [[String: AnyObject]] { let title = ((articleData[Constant.NYTimesApiHeadlineKey()] as! [String: AnyObject])[Constant.NYTimesApiHeadlineMainKey()] as! String).decodedHtmlString() let urlString = articleData[Constant.NYTimesApiUrlKey()] as! String // Check for thumbnail image var thumbnailUrlString: String? if let multimedia = articleData[Constant.NYTimesApiMultimediaKey()] as? [[String: AnyObject]] { if multimedia.count > 0 { let urlString = (multimedia[0])[Constant.NYTimesApiMultimediaUrlKey()] as? String thumbnailUrlString = urlString } } let article = Article(title: title, urlString: urlString, thumbnailUrlString: thumbnailUrlString) articles.append(article) } return articles } return nil } func displayAlert() { dispatch_async(dispatch_get_main_queue(), {[weak self] () -> Void in if let weakSelf = self { var alertController = UIAlertController(title: "OOPS!", message: "Looks like there was a problem downloading the articles. Please try again.", preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) alertController.addAction(okAction) weakSelf.presentViewController(alertController, animated: true, completion: nil) } }) } // MARK: UITableViewControllerDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return cellHeight } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: ArticleTableViewCell! if let dequeuedCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as? ArticleTableViewCell { cell = dequeuedCell } else { cell = ArticleTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } // Load article data cell.loadWithArticle(articles[indexPath.row]) return cell } // MARK: UITableViewControllerDelegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! ArticleTableViewCell presentWebViewControllerForArticle(cell.article) } // MARK: UIScrollViewDelegate override func scrollViewWillBeginDragging(scrollView: UIScrollView) { // Hide keyboard once user starts scrolling through results dismissKeyboard() } // MARK: UISearchBarDelegate func searchBarSearchButtonClicked(searchBar: UISearchBar) { // Search searchArticlesForTerm(searchBar.text) } // MARK: UISearchResultsUpdating func updateSearchResultsForSearchController(searchController: UISearchController) { // Search while typing /* DISABLED - Uncomment to enable API calls while typing */ //searchArticlesForTerm(searchController.searchBar.text, withDelay:1.0) } // MARK: DZNEmptyDataSetSource func backgroundColorForEmptyDataSet(scrollView: UIScrollView!) -> UIColor! { return Constant.lightGrayColor() } func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return Constant.newspaperIconImage() } // MARK: DZNEmptyDataSetDelegate func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { return NSAttributedString(string: "No Articles", attributes: [NSForegroundColorAttributeName: UIColor.darkGrayColor()]) } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { var string = "Search for articles above." if currentTerm != "" { string = "Nothing found for \"\(currentTerm)\"" } return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName: UIColor.darkGrayColor()]) } // MARK: WebViewController func presentWebViewControllerForArticle(article: Article) { webViewController = WebViewController() webViewController.article = article // Build navigation bar var backBarButton = UIBarButtonItem(image: Constant.arrowLeftImage(), style: .Plain, target: self, action: "didTapCloseButton") webViewController.navigationItem.leftBarButtonItem = backBarButton webViewController.navigationItem.title = article.title navigationController?.pushViewController(webViewController, animated: true) } func didTapCloseButton() { navigationController?.popViewControllerAnimated(true) } // MARK: Helper functions func didTapView(sender: UITapGestureRecognizer) { dismissKeyboard() } func dismissKeyboard() { searchController.resignFirstResponder() searchController.view.endEditing(true) } func searchArticlesForTerm(term: String, withDelay: Double = 0.0) { // Ignore blank text or same search term if term == "" || term == currentTerm { return } // Use an NSBlockOperation to allow aborting of API calls (i.e. user calls multiple searches rapidly) cancelBlockOperations() var searchBlockOperation = NSBlockOperation() searchBlockOperation.addExecutionBlock {[weak self] () -> Void in if let weakSelf = self { // Check if cancelled if searchBlockOperation.cancelled { return } // Reset weakSelf.currentPage = 0 weakSelf.currentTerm = term weakSelf.downloadArticlesForTerm(weakSelf.currentTerm, completion: { (data) -> Void in if let data = data, let articles = weakSelf.parseArticleData(data) { weakSelf.articles = articles weakSelf.reloadData() } else { weakSelf.displayAlert() } }) } } blockOperations.append(searchBlockOperation) // Delay calling API (i.e. for auto-search while typing) Constant.delay(withDelay, closure: { () -> () in searchBlockOperation.start() }) } func reloadData() { // Update TableView dispatch_async(dispatch_get_main_queue(), {[weak self] () -> Void in if let weakSelf = self { weakSelf.tableView.reloadData() weakSelf.tableView.infiniteScrollingView.stopAnimating() if weakSelf.currentPage == 0 { // Scroll to top if there are new results if weakSelf.articles.count > 0 { weakSelf.searchController.active = false weakSelf.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true) } } weakSelf.hideActivityIndicator() } }) } func cancelBlockOperations() { for blockOperation in blockOperations { blockOperation.cancel() } blockOperations.removeAll() } func showActivityIndicator() { dispatch_async(dispatch_get_main_queue(), {[weak self] () -> Void in if let weakSelf = self { MBProgressHUD.hideHUDForView(weakSelf.view, animated: true) MBProgressHUD.showHUDAddedTo(weakSelf.view, animated: true) } }) } func hideActivityIndicator() { dispatch_async(dispatch_get_main_queue(), {[weak self] () -> Void in if let weakSelf = self { MBProgressHUD.hideHUDForView(weakSelf.view, animated: true) } }) } } @objc class Article: NSObject { var title: String! var url: NSURL! var thumbnailUrl: NSURL? init(title: String, urlString: String, thumbnailUrlString: String?) { super.init() self.title = title self.url = NSURL(string: urlString) if let thumbString = thumbnailUrlString, let thumbUrl = NSURL(string: Constant.NYTimesDomain()+thumbString) { self.thumbnailUrl = thumbUrl } } }
mit
1ac7d8681b2021f53a98057549f1fe65
35.502381
209
0.595982
5.993354
false
false
false
false
keyeMyria/edx-app-ios
Source/Array+Functional.swift
3
1952
// // Array+Functional.swift // edX // // Created by Akiva Leffert on 4/30/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation extension Array { init(count : Int, @noescape generator : Int -> T) { self.init() for i in 0 ..< count { self.append(generator(i)) } } /// Performs a map, but if any of the items return nil, return nil for the overall result. func mapOrFailIfNil<U>(@noescape f : T -> U?) -> [U]? { return reduce([], combine: { (var acc, v) -> [U]? in if let x = f(v) { acc?.append(x) return acc } else { return nil } }) } /// Performs a map, but skips any items that return nil func mapSkippingNils<U>(@noescape f : T -> U?) -> [U] { var result : [U] = [] for v in self { if let t = f(v) { result.append(t) } } return result } /// Returns the index of the first object in the array where the given predicate returns true. /// Returns nil if no object is found. func firstIndexMatching(@noescape predicate : T -> Bool) -> Int? { var i = 0 for object in self { if predicate(object) { return i } i = i + 1 } return nil } func firstObjectMatching(@noescape predicate : T -> Bool) -> T? { for object in self { if predicate(object) { return object } } return nil } func withItemIndexes() -> [(value : T, index : Int)] { var result : [(value : T, index : Int)] = [] var i = 0 for value in self { let next = (value : value, index : i) result.append(next) i++ } return result } }
apache-2.0
66c16032ada51ab4dc7b7d163b57f270
24.038462
98
0.466701
4.234273
false
false
false
false
h3rald/mal
swift/readline.swift
29
1141
//****************************************************************************** // MAL - readline //****************************************************************************** import Foundation private let HISTORY_FILE = "~/.mal-history" private func with_history_file(do_to_history_file: (UnsafePointer<Int8>) -> ()) { HISTORY_FILE.withCString { (c_str) -> () in let abs_path = tilde_expand(UnsafeMutablePointer<Int8>(c_str)) if abs_path != nil { do_to_history_file(abs_path) free(abs_path) } } } func load_history_file() { using_history() with_history_file { let _ = read_history($0) } } func save_history_file() { // Do this? stifle_history(1000) with_history_file { let _ = write_history($0) } } func _readline(prompt: String) -> String? { let line = prompt.withCString { (c_str) -> UnsafeMutablePointer<Int8> in return readline(c_str) } if line != nil { if let result = String(UTF8String: line) { add_history(line) return result } } return nil }
mpl-2.0
d2762c0357cc269b27a9cf46aac88ef4
23.804348
81
0.481157
3.867797
false
false
false
false
dimpiax/FlexibleCollectionViewController
Example/FlexibleCollectionViewController/ViewController.swift
1
5921
// // ViewController.swift // FlexibleCollectionViewController // // Created by Pilipenko Dima on 05/31/2016. // Copyright (c) 2016 Pilipenko Dima. All rights reserved. // import UIKit import FlexibleCollectionViewController class ViewController: UIViewController { fileprivate var _flexibleCollectionVC: FlexibleCollectionViewController<CollectionImageCellData, ListGenerator<CollectionImageCellData>>! override func viewDidLoad() { super.viewDidLoad() // initialisation with configuration _flexibleCollectionVC = FlexibleCollectionViewController(collectionViewLayout: CustomFlowLayout(), configuration: CollectionConfiguration(userInteractionEnabled: true, showsHorizontalScrollIndicator: false, isScrollEnabled: true, multipleTouchEnabled: false, backgroundColor: .clear)) addChildViewController(_flexibleCollectionVC) view.addSubview(_flexibleCollectionVC.view) // cell and supplementary view registering _flexibleCollectionVC.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell") _flexibleCollectionVC.registerSupplementaryView(UIHeaderImageCollectionView.self, kind: .header, reuseIdentifier: UIHeaderImageCollectionView.reuseIdentifier) // requesting indentifier of cell for specific indexPath _flexibleCollectionVC.requestCellIdentifier = { value in return "UICollectionViewCell" } // requesting indentifier of supplementary view for specific indexPath _flexibleCollectionVC.requestSupplementaryIdentifier = { value in return UIHeaderImageCollectionView.reuseIdentifier } // configuration of input cell with related data to indexPath _flexibleCollectionVC.configureCell = { (cell: UICollectionViewCell, data: CollectionImageCellData?, indexPath: IndexPath) in guard let data = data else { return false } cell.backgroundColor = data.color return true } // configuration of supplementary view with related kind and data to indexPath _flexibleCollectionVC.configureSupplementary = { (view: UICollectionReusableView, kind: SupplementaryKind, data: CollectionImageCellData?, indexPath: IndexPath) in if let view = view as? UIHeaderImageCollectionView, let data = data { view.text = data.category return true } return false } // process cell selection to related indexPath _flexibleCollectionVC.cellDidSelect = { value in return (deselect: true, animate: true) } // estimate cell size _flexibleCollectionVC.estimateCellSize = { value in guard let layout = value.1 as? UICollectionViewFlowLayout else { return nil } let col: CGFloat = 3 let width = value.0.bounds.width-(layout.sectionInset.left+layout.sectionInset.right) let side = round(width/col)-layout.minimumInteritemSpacing return CGSize(width: side, height: side) } // put predefined cells in generated order related to ListGenerator _flexibleCollectionVC.setData(getData()) } fileprivate func getData() -> TableData<CollectionImageCellData, ListGenerator<CollectionImageCellData>> { var data = TableData<CollectionImageCellData, ListGenerator<CollectionImageCellData>>(generator: ListGenerator()) var arr = [CollectionImageCellData]() for _ in 0..<100 { arr.append(CollectionImageCellData()) } arr.sort { value in value.0.category! > value.1.category! } arr.forEach { data.addItem($0) } data.generate() return data } } class CustomFlowLayout: UICollectionViewFlowLayout { override init() { super.init() headerReferenceSize = CGSize(width: 0, height: 100) if #available(iOS 9.0, *) { sectionHeadersPinToVisibleBounds = true } else { // Fallback on earlier versions } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class CollectionImageCellData: CellDataProtocol { var title: String { return "B" } var category: String? = nil init() { category = ["Section #1", "Section #2", "Section #N"][Int(arc4random_uniform(3))] } var color: UIColor { return UIColor(red: CGFloat(arc4random_uniform(100))/255, green: CGFloat(arc4random_uniform(100))/255, blue: CGFloat(arc4random_uniform(100))/255, alpha: 1) } } class UIHeaderImageCollectionView: UICollectionReusableView { class var reuseIdentifier: String { return String(describing: self) } var text: String? { get { return _label.text } set { let style = NSMutableParagraphStyle() style.alignment = .center _label.attributedText = NSAttributedString(string: newValue ?? "", attributes: [NSFontAttributeName: UIFont(name: "HelveticaNeue", size: 21)!, NSParagraphStyleAttributeName: style]) _label.sizeToFit() } } fileprivate var _label: UILabel! override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white _label = UILabel() addSubview(_label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() _label.frame = bounds } }
mit
121d06bc18bbb67846683e3bcef89d32
35.325153
292
0.639757
5.43211
false
false
false
false
One-self/ZhihuDaily
ZhihuDaily/ZhihuDaily/Classes/View/ZDStoryViewController.swift
1
3355
// // ZDStoryViewController.swift // ZhihuDaily // // Created by Oneselfly on 2017/5/15. // Copyright © 2017年 Oneself. All rights reserved. // import WebKit private let toolbarHeight: CGFloat = 45 enum ZDStoryLoadDataMethod { case dropDown case pull case normal } class ZDStoryViewController: UIViewController { lazy var detailStoryViewModel = ZDDetailStoryViewModel() fileprivate lazy var storyToolbar = ZDStoryToolbar.storyToolbar() fileprivate lazy var webView = WKWebView() fileprivate lazy var headImageView = ZDDetailStoryHeadImageView.headImageView() fileprivate lazy var dropDownRefreshControl = YLRefreshControl() private var loadDataMethod: ZDStoryLoadDataMethod = .normal override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white setupUI() loadDetailStory() } @objc fileprivate func dropDownReloadData() { loadDataMethod = .dropDown loadDetailStory() } private func loadDetailStory() { detailStoryViewModel.loadDetailStory(loadDataMethod: loadDataMethod) { if $0 == true { self.detailStoryViewModel.isFirstStory ? print("是第一个") : print("不是第一个") self.webView.loadHTMLString(self.detailStoryViewModel.HTMLString ?? "", baseURL: Bundle.main.bundleURL) self.headImageView.detailStory = self.detailStoryViewModel.detailStory } self.dropDownRefreshControl.endRefreshing() self.loadDataMethod = .normal } } } // MARK: - UI extension ZDStoryViewController { fileprivate func setupUI() { view.addSubview(storyToolbar) storyToolbar.snp.makeConstraints { $0.left.bottom.right.equalToSuperview() $0.height.equalTo(toolbarHeight) } storyToolbar.returnButtonClosure = { [weak self] in self?.navigationController?.popViewController(animated: true) } view.addSubview(webView) webView.snp.makeConstraints { $0.top.left.right.equalToSuperview() $0.bottom.equalTo(storyToolbar.snp.top) } let webContentView = webView.scrollView.subviews[0] webContentView.addSubview(headImageView) headImageView.snp.makeConstraints { $0.bottom.equalTo(webContentView.snp.top).offset(200) $0.left.equalTo(webContentView) // 貌似无效,宽度变得很窄 // $0.right.equalTo(webContentView) // 无奈之举... $0.width.equalTo(UIScreen.main.bounds.width) $0.top.equalTo(webView) } webView.scrollView.delegate = self webView.scrollView.addSubview(dropDownRefreshControl) dropDownRefreshControl.addTarget(self, action: #selector(dropDownReloadData), for: .valueChanged) } } extension ZDStoryViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if -scrollView.contentOffset.y > 90 { scrollView.setContentOffset(CGPoint(x: 0, y: -90), animated: false) } } }
mit
c3fcce6656b2bf69d861d359dcb0c815
28.5
119
0.626211
4.931343
false
false
false
false
One-self/ZhihuDaily
ZhihuDaily/ZhihuDaily/Classes/ViewModel/ZDStoriesViewModel.swift
1
1685
// // ZDStoriesViewModel.swift // ZhihuDaily // // Created by Oneselfly on 2017/5/13. // Copyright © 2017年 Oneself. All rights reserved. // class ZDStoriesViewModel { lazy var dayViewModels = [ZDDayViewModel]() lazy var topStories = [ZDStory]() lazy var storyIds = [String]() func loadStories(completion:@escaping (_ isSuccess: Bool) -> Void) { YLNetworkTool.stories(dateString: dayViewModels.last?.day.dateString) { guard let dateString = $0, let storiesJSON = $1 else { completion(false) return } let day = ZDDay() day.dateString = dateString for storyJSON in storiesJSON { let story = ZDStory() story.yy_modelSet(with: storyJSON.dictionaryObject ?? [:]) story.image = storyJSON["images"][0].stringValue day.stories.append(story) self.storyIds.append(story.id ?? "") } let dayViewModel = ZDDayViewModel(day: day) self.dayViewModels.append(dayViewModel) if let topStoriesJSON = $2 { for topStoryJSON in topStoriesJSON { let story = ZDStory() story.yy_modelSet(with: topStoryJSON.dictionaryObject ?? [:]) self.topStories.append(story) } } completion(true) } } }
mit
a84b9025fa7bdb2a3a3aa5e044b605a3
27.508475
81
0.470868
5.272727
false
true
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/RoundedImageView.swift
1
1611
import UIKit /// A `UIImageView` embedded within a `UIView` to allow easier styling class RoundedImageView: SetupView { // MARK: - Properties let imageView = UIImageView() var insets: NSDirectionalEdgeInsets = .zero { didSet { imageViewLeadingAnchor?.constant = insets.leading imageViewTrailingAnchor?.constant = insets.trailing imageViewTopAnchor?.constant = insets.top imageViewBottomAnchor?.constant = insets.bottom } } fileprivate var imageViewLeadingAnchor: NSLayoutConstraint? fileprivate var imageViewTrailingAnchor: NSLayoutConstraint? fileprivate var imageViewTopAnchor: NSLayoutConstraint? fileprivate var imageViewBottomAnchor: NSLayoutConstraint? // MARK: - Lifecycle override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = self.bounds.height / 2 } // MARK: - Setup override func setup() { layer.masksToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false addSubview(imageView) imageViewLeadingAnchor = imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.leading) imageViewTrailingAnchor = imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: insets.trailing) imageViewTopAnchor = imageView.topAnchor.constraint(equalTo: topAnchor, constant: insets.top) imageViewBottomAnchor = imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: insets.bottom) NSLayoutConstraint.activate( [imageViewLeadingAnchor, imageViewTrailingAnchor, imageViewTopAnchor, imageViewBottomAnchor].compactMap { $0 } ) setNeedsLayout() layoutIfNeeded() } }
mit
e0452842dbbf5cdd3c316875fd7eceee
29.980769
115
0.792055
4.696793
false
false
false
false
Daij-Djan/xsd2cocoa
demos/SampleLanguageData/SampleLanguageData-ios/ViewController.swift
3
636
// // ViewController.swift // addressTest_ios // // Created by Dominik Pich on 10/01/15. // Copyright (c) 2015 Dominik Pich. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() let url = NSBundle.mainBundle().URLForResource("SampleLanguageData", withExtension: "xml") if(url != nil) { let addr = LangDefType.LangDefTypeFromURL(url!) if(addr != nil) { textView.text = addr!.dictionary.description } } } }
apache-2.0
b7143a03c8e6dd3e82064b778357e8ac
21.714286
98
0.606918
4.24
false
false
false
false
CKOTech/checkoutkit-ios
CheckoutKit/CheckoutKit/CardToken.swift
1
2648
// // CardToken.swift // CheckoutKit // // Created by Manon Henrioux on 17/08/2015. // Copyright (c) 2015 Checkout.com. All rights reserved. // import Foundation /** Class instantiated when the createCardToken method of CheckoutKit is called, it contains all the information returned by Checkout */ open class CardToken: Serializable { open var expMonth: String! open var expYear: String! open var billDetails: CustomerDetails? open var last4: String! open var paymentMethod: String! open var name: String! open var id: String! open var logging: Bool = false /** Default constructor for a CardToken @param expMonth String containing the expiring month of the card @param expYear String containing the expiring year of the card @param billDetails Object containing the billing details of the customer @param last4 String containing the last 4 digits of the card's number @param paymentMethod String containing the payment method corresponding to the card @param name String corresponding the the card's owner name @param cardToken String containing the card token */ public init(expMonth: String, expYear: String, billDetails: CustomerDetails, last4: String, paymentMethod: String, name: String, cardToken: String) { self.expYear = expYear self.expMonth = expMonth self.billDetails = billDetails self.last4 = last4 self.paymentMethod = paymentMethod self.name = name self.id = cardToken } /** Convenience constructor @param data Dictionary [String: AnyObject] containing a JSON representation of a CardToken instance */ public required init?(data: [String: AnyObject]) { if let year = data["expiryYear"] as? String, let month = data["expiryMonth"] as? String, let id = data["id"] as? String, let last4 = data["last4"] as? String, let paymentMethod = data["paymentMethod"] as? String { self.expMonth = month self.expYear = year self.id = id self.last4 = last4 self.paymentMethod = paymentMethod if let name = data["name"] as? String { self.name = name } if let billDetails = data["billingDetails"] as? [String: AnyObject] { self.billDetails = CustomerDetails(data: billDetails) } } else { return nil } } }
mit
5ceda5172f0e231d9bde485125ff14fa
29.790698
153
0.611027
4.958801
false
false
false
false
BigZhanghan/DouYuLive
DouYuLive/DouYuLive/Classes/Tools/NetworkTools.swift
1
797
// // NetworkTools.swift // DouYuLive // // Created by zhanghan on 2017/10/9. // Copyright © 2017年 zhanghan. All rights reserved. // import UIKit import Alamofire enum MethodType { case post case get } class NetworkTools { class func requestData(type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishCallBack : @escaping(_ result : Any) -> ()) { let method = type == .get ? HTTPMethod.get : HTTPMethod.post Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in guard let result = response.result.value else { print(response.result.error!) return } finishCallBack(result : result) } } }
mit
c00972673fd5a5050f7aa25f3c8c209e
25.466667
153
0.604534
4.411111
false
false
false
false
HappyHourApp/ios-app
HappyHour/HappyHour/GroupMainViewController.swift
1
2502
import UIKit import MapKit class GroupMainViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! var locationManager = CLLocationManager() let regionRadius: CLLocationDistance = 1000 override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.requestLocation() } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 2.0, regionRadius * 2.0) mapView.setRegion(coordinateRegion, animated: true) let myAnnotation: MKPointAnnotation = MKPointAnnotation() myAnnotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude); myAnnotation.title = "Me" mapView.addAnnotation(myAnnotation) let near1: MKPointAnnotation = MKPointAnnotation() let near2: MKPointAnnotation = MKPointAnnotation() let near3: MKPointAnnotation = MKPointAnnotation() near1.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude - 0.02, location.coordinate.longitude); near1.title = "Drinking Buddy 1" near2.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude + 0.002, location.coordinate.longitude + 0.002); near2.title = "Drinking Buddy 2" near3.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude - 0.001, location.coordinate.longitude - 0.00001); mapView.addAnnotation(near1) mapView.addAnnotation(near2) mapView.addAnnotation(near3) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { for location in locations { print("**********************") print("Long \(location.coordinate.longitude)") print("Lati \(location.coordinate.latitude)") print("Alt \(location.altitude)") print("Sped \(location.speed)") print("Accu \(location.horizontalAccuracy)") print("**********************") centerMapOnLocation(location: location) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("error:: (error)") } }
apache-2.0
1fbde4b989b621ed4f3f13c5d36529af
36.924242
133
0.682654
5.597315
false
false
false
false
JGiola/swift-package-manager
Sources/Utility/ArgumentParserShellCompletion.swift
2
9764
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Foundation import Basic fileprivate let removeDefaultRegex = try! NSRegularExpression(pattern: "\\[default: .+?\\]", options: []) extension ArgumentParser { /// Generates part of a completion script for the given shell. /// /// These aren't complete scripts, as some setup code is required. See /// `Utilities/bash/completions` and `Utilities/zsh/_swift` for example /// usage. public func generateCompletionScript(for shell: Shell, on stream: OutputByteStream) { guard let commandName = commandName else { abort() } let name = "_\(commandName.replacingOccurrences(of: " ", with: "_"))" switch shell { case .bash: // Information about how to include this function in a completion script. stream <<< """ # Generates completions for \(commandName) # # Parameters # - the start position of this parser; set to 1 if unknown """ generateBashSwiftTool(name: name, on: stream) case .zsh: // Information about how to include this function in a completion script. stream <<< """ # Generates completions for \(commandName) # # In the final compdef file, set the following file header: # # #compdef \(name) # local context state state_descr line # typeset -A opt_args """ generateZshSwiftTool(name: name, on: stream) } stream.flush() } // MARK: - BASH fileprivate func generateBashSwiftTool(name: String, on stream: OutputByteStream) { stream <<< """ function \(name) { """ // Suggest positional arguments. Beware that this forces positional arguments // before options. For example [swift package pin <TAB>] expects a name as the // first argument. So no options (like --all) will be suggested. However after // the positional argument; [swift package pin MyPackage <TAB>] will list them // just fine. for (index, argument) in positionalArguments.enumerated() { stream <<< " if [[ $COMP_CWORD == $(($1+\(index))) ]]; then\n" generateBashCompletion(argument, on: stream) stream <<< " fi\n" } // Suggest subparsers in addition to other arguments. stream <<< " if [[ $COMP_CWORD == $1 ]]; then\n" var completions = [String]() for (subName, _) in subparsers { completions.append(subName) } for option in optionArguments { completions.append(option.name) if let shortName = option.shortName { completions.append(shortName) } } stream <<< """ COMPREPLY=( $(compgen -W "\(completions.joined(separator: " "))" -- $cur) ) return fi """ // Suggest completions based on previous word. generateBashCasePrev(on: stream) // Forward completions to subparsers. stream <<< " case ${COMP_WORDS[$1]} in\n" for (subName, _) in subparsers { stream <<< """ (\(subName)) \(name)_\(subName) $(($1+1)) return ;; """ } stream <<< " esac\n" // In all other cases (no positional / previous / subparser), suggest // this parsers completions. stream <<< """ COMPREPLY=( $(compgen -W "\(completions.joined(separator: " "))" -- $cur) ) } """ for (subName, subParser) in subparsers { subParser.generateBashSwiftTool(name: "\(name)_\(subName)", on: stream) } } fileprivate func generateBashCasePrev(on stream: OutputByteStream) { stream <<< " case $prev in\n" for argument in optionArguments { let flags = [argument.name] + (argument.shortName.map({ [$0] }) ?? []) stream <<< " (\(flags.joined(separator: "|")))\n" generateBashCompletion(argument, on: stream) stream <<< " ;;\n" } stream <<< " esac\n" } fileprivate func generateBashCompletion(_ argument: AnyArgument, on stream: OutputByteStream) { switch argument.completion { case .none: // return; no value to complete stream <<< " return\n" case .unspecified: break case .values(let values): let x = values.map({ $0.value }).joined(separator: " ") stream <<< """ COMPREPLY=( $(compgen -W "\(x)" -- $cur) ) return """ case .filename: stream <<< """ _filedir return """ case .function(let name): stream <<< """ \(name) return """ } } // MARK: - ZSH private func generateZshSwiftTool(name: String, on stream: OutputByteStream) { // Completions are provided by zsh's _arguments builtin. stream <<< """ \(name)() { arguments=( """ for argument in positionalArguments { stream <<< " \"" generateZshCompletion(argument, on: stream) stream <<< "\"\n" } for argument in optionArguments { generateZshArgument(argument, on: stream) } // Use a simple state-machine when dealing with sub parsers. if subparsers.count > 0 { stream <<< """ '(-): :->command' '(-)*:: :->arg' """ } stream <<< """ ) _arguments $arguments && return """ // Handle the state set by the state machine. if subparsers.count > 0 { stream <<< """ case $state in (command) local modes modes=( """ for (subName, subParser) in subparsers { stream <<< """ '\(subName):\(subParser.overview)' """ } stream <<< """ ) _describe "mode" modes ;; (arg) case ${words[1]} in """ for (subName, _) in subparsers { stream <<< """ (\(subName)) \(name)_\(subName) ;; """ } stream <<< """ esac ;; esac """ } stream <<< "}\n\n" for (subName, subParser) in subparsers { subParser.generateZshSwiftTool(name: "\(name)_\(subName)", on: stream) } } /// Generates an option argument for `_arguments`, complete with description and completion values. fileprivate func generateZshArgument(_ argument: AnyArgument, on stream: OutputByteStream) { stream <<< " \"" switch argument.shortName { case .none: stream <<< "\(argument.name)" case let shortName?: stream <<< "(\(argument.name) \(shortName))\"{\(argument.name),\(shortName)}\"" } let description = removeDefaultRegex .replace(in: argument.usage ?? "", with: "") .replacingOccurrences(of: "\"", with: "\\\"") .replacingOccurrences(of: "[", with: "\\[") .replacingOccurrences(of: "]", with: "\\]") stream <<< "[\(description)]" generateZshCompletion(argument, on: stream) stream <<< "\"\n" } /// Generates completion values, as part of an item for `_arguments`. fileprivate func generateZshCompletion(_ argument: AnyArgument, on stream: OutputByteStream) { let message = removeDefaultRegex .replace(in: argument.usage ?? " ", with: "") .replacingOccurrences(of: "\"", with: "\\\"") switch argument.completion { case .none: stream <<< ":\(message): " case .unspecified: break case .filename: stream <<< ":\(message):_files" case let .values(values): stream <<< ": :{_values ''" for (value, description) in values { stream <<< " '\(value)[\(description)]'" } stream <<< "}" case .function(let name): stream <<< ":\(message):\(name)" } } } fileprivate extension NSRegularExpression { func replace(`in` original: String, with replacement: String) -> String { return stringByReplacingMatches( in: original, options: [], range: NSRange(location: 0, length: original.count), withTemplate: replacement) } }
apache-2.0
6b8255cc331bd1afef10cc5642a64617
32.438356
108
0.480746
5.190856
false
false
false
false
s9998373/PHP-SRePS
PHP-SRePS/PHP-SRePS/AddTransactionTableViewController.swift
1
7440
// // AddTransactionTableViewController.swift // PHP-SRePS // // Created by Terry Lewis on 16/08/2016. // Copyright © 2016 swindp2. All rights reserved. // import UIKit protocol AddTransactionTableViewControllerDelegate: class { func didAddTransaction(sender: AddTransactionTableViewController, transaction: Transaction?) func didModifyTransaction(sender: AddTransactionTableViewController, transaction: Transaction?) } class AddTransactionTableViewController: UITableViewController { weak var delegate: AddTransactionTableViewControllerDelegate!; var currentTransaction : Transaction!; var newTransaction:Bool = false let kCellIdentifier = "SalesEntryCellIdentifier"; override func viewDidLoad() { super.viewDidLoad() let cancelButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: #selector(AddTransactionTableViewController.dismiss)); let doneButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: #selector(AddTransactionTableViewController.doneAction)); let flexibleSpaceItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil); let addProductButton = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: #selector(AddTransactionTableViewController.addProduct)); self.navigationItem.rightBarButtonItem = doneButton; self.navigationItem.leftBarButtonItem = cancelButton; self.navigationController?.setToolbarHidden(false, animated: false) let buttons = [flexibleSpaceItem, addProductButton, flexibleSpaceItem]; self.setToolbarItems(buttons, animated: true); self.toolbarItems = buttons; } /// Reload the table view. func reloadData(){ self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Fade) } /// Display the new product view controller. func addProduct(){ let controller = ProductsListTableViewController.init(); controller.storyboardReference = self.storyboard; controller.delegate = self; let nav = UINavigationController.init(rootViewController: controller); self.presentViewController(nav, animated: true, completion: nil); } /// Generic method to dismiss the view controller. func dismiss(){ self.dismissViewControllerAnimated(true, completion: nil) } /// Handle when the use taps done. func doneAction(){ if newTransaction { self.delegate.didAddTransaction(self, transaction: currentTransaction) }else{ self.delegate.didModifyTransaction(self, transaction: currentTransaction) } } /// Handles the user selecting a product in the product selection controller. /// /// - parameter selectedProduct: The product that was selected. /// - parameter selectedQuantity: The quantity of the selected product. func handleSelectedProduct(selectedProduct: Product, selectedQuantity: Int){ print("Selected ", selectedQuantity, " of ", selectedProduct.name, "."); if (currentTransaction == nil) { currentTransaction = Transaction(date: NSDate()); newTransaction = true }else{ newTransaction = false } let salesEntry = SalesEntry(product: selectedProduct, quanity: selectedQuantity); if (currentTransaction.doesProductExistInTransaction(selectedProduct)){ handleDuplicateSalesEntry(salesEntry) }else{ handleAdditionalSalesEntry(salesEntry) } } /// If the product already exists, allow the user to summate the total of products or input a new amount. /// /// - parameter salesEntry: The sales entry that is affected/already exists for a given product type. func handleDuplicateSalesEntry(salesEntry : SalesEntry){ let alert = UIAlertController.init(title: "Information", message: "A sales entry for this product already exists. Do you wish to summate the existing and new quantities?", preferredStyle: UIAlertControllerStyle.Alert); alert.addAction(UIAlertAction.init(title: "Summate", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) in self.currentTransaction.mergeSalesEntry(salesEntry); self.reloadData() })); alert.addAction(UIAlertAction.init(title: "Replace", style: UIAlertActionStyle.Cancel, handler: { (action: UIAlertAction) in self.currentTransaction.removeSalesEntry(salesEntry) self.handleAdditionalSalesEntry(salesEntry) })); self.presentViewController(alert, animated: true, completion: nil); } /// Handles the case where a given SalesEntry to be added is unique. /// /// - parameter salesEntry: The SalesEntry to be added. func handleAdditionalSalesEntry(salesEntry : SalesEntry){ currentTransaction.addSalesEntry(salesEntry) self.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if (currentTransaction == nil) { return 0 } return currentTransaction.numberOfItems() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell? if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: kCellIdentifier) // cell = UITableViewCell.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier: kCellIdentifier) } // Configure the cell... let currentItem = currentTransaction.salesEntryAtIndex(indexPath.row) cell!.textLabel?.text = currentItem.product!.name cell!.detailTextLabel!.text = String(currentItem.quantity!) return cell! } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { let salesEntry = currentTransaction.salesEntryAtIndex(indexPath.row) print("Remove entry: \(currentTransaction.removeSalesEntry(salesEntry))") reloadData() } } } extension AddTransactionTableViewController : ProductsListTableViewControllerDelegate{ func didSelectProduct(sender: ProductsListTableViewController, product: Product, selectedQuantity: Int) { sender.dismissViewControllerAnimated(true, completion: nil); handleSelectedProduct(product, selectedQuantity: selectedQuantity); } }
mit
da16731a93023374334e9d6f576edff2
43.017751
226
0.706278
5.506292
false
false
false
false
thanegill/RxSwift
RxTests/Any+Equatable.swift
11
909
// // Any+Equatable.swift // Rx // // Created by Krunoslav Zaher on 12/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** A way to use built in XCTest methods with objects that are partially equatable. If this can be done simpler, PRs are welcome :) */ struct AnyEquatable<Target> : Equatable , CustomDebugStringConvertible , CustomStringConvertible { typealias Comparer = (Target, Target) -> Bool let _target: Target let _comparer: Comparer init(target: Target, comparer: Comparer) { _target = target _comparer = comparer } } func == <T>(lhs: AnyEquatable<T>, rhs: AnyEquatable<T>) -> Bool { return lhs._comparer(lhs._target, rhs._target) } extension AnyEquatable { var description: String { return "\(_target)" } var debugDescription: String { return "\(_target)" } }
mit
22b59bdeea36ea49587123052ac63e04
20.139535
80
0.646476
4.035556
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/App Lock/AppLockModule.swift
1
3186
// // Wire // Copyright (C) 2020 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 Foundation import WireDataModel import WireSyncEngine /// This module is responsible for displaying the app lock and requesting /// authentication from the user. enum AppLockModule: ModuleInterface { typealias Session = UserSessionAppLockInterface & UserSessionEncryptionAtRestInterface typealias PasscodePreference = AppLockPasscodePreference typealias AuthenticationResult = AppLockAuthenticationResult typealias Strings = L10n.Localizable.AppLockModule static func build(session: Session) -> View { let router = Router() let interactor = Interactor(session: session) let presenter = Presenter() let view = View() assemble(interactor: interactor, presenter: presenter, view: view, router: router) return view } } extension AppLockModule { enum Event: Equatable { case viewDidAppear case applicationWillEnterForeground case unlockButtonTapped case openDeviceSettingsButtonTapped case passcodeSetupCompleted case customPasscodeVerified case configChangeAcknowledged } enum Request: Equatable { case initiateAuthentication(requireActiveApp: Bool) case evaluateAuthentication case openAppLock } enum Result: Equatable { case customPasscodeCreationNeeded(shouldInform: Bool) case readyForAuthentication(shouldInform: Bool) case authenticationDenied(AuthenticationType) case authenticationUnavailable case customPasscodeNeeded } enum Action: Equatable { case createPasscode(shouldInform: Bool) case inputPasscode case informUserOfConfigChange case openDeviceSettings } } // MARK: - Interactor protocol AppLockInteractorPresenterInterface: InteractorPresenterInterface { func executeRequest(_ request: AppLockModule.Request) } // MARK: - Presenter protocol AppLockPresenterInteractorInterface: PresenterInteractorInterface { func handleResult(_ result: AppLockModule.Result) } protocol AppLockPresenterViewInterface: PresenterViewInterface { func processEvent(_ event: AppLockModule.Event) } // MARK: - View protocol AppLockViewPresenterInterface: ViewPresenterInterface { func refresh(withModel model: AppLockModule.ViewModel) } // MARK: - Router protocol AppLockRouterPresenterInterface: RouterPresenterInterface { func performAction(_ action: AppLockModule.Action) }
gpl-3.0
8bdd043a1196d65260618d8b42df09ce
24.488
90
0.73823
5.163695
false
false
false
false
Eveets/cryptick
cryptick/View/TickerCollectionViewCell.swift
1
4982
// // TickerCollectionViewCell.swift // cryptick // // Created by Steeve Monniere on 22-07-2017. // Copyright © 2017 Steeve Monniere. All rights reserved. // import UIKit class TickerCollectionViewCell: UICollectionViewCell { var quoteLabel: UILabel! var priceLabel: UILabel! var lowLabel: UILabel! var highLabel: UILabel! var percentLabel: UILabel! var trendLabel: UILabel! var ticker:Ticker? //**** private var hLabel: UILabel! private var pLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) //First Column quoteLabel = UILabel(frame: CGRect(x: 5, y: frame.size.height/2-18, width: frame.size.width/3-20, height: frame.size.height/2)) quoteLabel.font = UIFont.boldSystemFont(ofSize: 16.0) quoteLabel.textAlignment = .left contentView.addSubview(quoteLabel) //2nd column hLabel = UILabel(frame: CGRect(x:frame.size.width/3+10 , y:5, width: frame.size.width/3-20, height:14.0)) hLabel.font = UIFont.boldSystemFont(ofSize: 14.0) hLabel.textAlignment = .center hLabel.text = "24h" contentView.addSubview(hLabel) lowLabel = UILabel(frame: CGRect(x: frame.size.width/3+10, y:24 , width: frame.size.width/3-20, height: 14)) lowLabel.font = UIFont.systemFont(ofSize:12.0) lowLabel.textAlignment = .center contentView.addSubview(lowLabel) highLabel = UILabel(frame: CGRect(x: frame.size.width/3+10, y:24+16 , width: frame.size.width/3-20, height: 14)) highLabel.font = UIFont.systemFont(ofSize: 12.0) highLabel.textAlignment = .center contentView.addSubview(highLabel) percentLabel = UILabel(frame: CGRect(x: frame.size.width/3+10, y: 24+2*(16), width: frame.size.width/3-20, height: 14)) percentLabel.font = UIFont.systemFont(ofSize: 12.0) percentLabel.textAlignment = .center contentView.addSubview(percentLabel) //3rd Column pLabel = UILabel(frame: CGRect(x:2*(frame.size.width/3)+10 , y:frame.size.height/2-18, width: frame.size.width/3-20, height:14.0)) pLabel.font = UIFont.boldSystemFont(ofSize: 14.0) pLabel.textAlignment = .center pLabel.text = "Last" contentView.addSubview(pLabel) priceLabel = UILabel(frame: CGRect(x: 2*frame.size.width/3+10, y:frame.size.height/2 , width: frame.size.width/3-20, height:14.0)) priceLabel.font = UIFont.systemFont(ofSize: 18) priceLabel.textAlignment = .center contentView.addSubview(priceLabel) trendLabel = UILabel(frame: CGRect(x: 2*frame.size.width/3+10, y:frame.size.height/2+16 , width: frame.size.width/3-20, height:12.0)) trendLabel.font = UIFont.systemFont(ofSize: 12) trendLabel.textAlignment = .center contentView.addSubview(trendLabel) } func updateTicker(ticker:Ticker) { self.ticker = ticker let precision:String = getCurrencyPrecision(currency: ticker.quote!) let trend:Double = (ticker.price!/ticker.vwap!-1)*100 self.quoteLabel.text = String.localizedStringWithFormat("%@/%@", ticker.base!.uppercased(), ticker.quote!.uppercased()) self.priceLabel.text = String.localizedStringWithFormat(precision, ticker.price!) self.lowLabel.text = String.localizedStringWithFormat("Low: "+precision, ticker.low!) self.highLabel.text = String.localizedStringWithFormat("High: "+precision, ticker.high!) self.percentLabel.text = String.localizedStringWithFormat("Avg : "+precision, ticker.vwap!) self.trendLabel.text = String.localizedStringWithFormat("(%0.2f%%)", trend) if(trend < 0) { self.trendLabel.textColor = UIColor.red } else { self.trendLabel.textColor = UIColor(red:35.0/255, green:160.0/255, blue:35.0/255, alpha: 1.0) } if(!ticker.unchanged) { self.animate(up: ticker.up) } } func animate(up:Bool) { if(up){ self.backgroundColor = UIColor(red: 35/255, green: 160/255, blue: 35/255, alpha: 0.5) } else { self.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5) } UIView.animate(withDuration: 1.0, delay: 0.0, options:[UIViewAnimationOptions.curveEaseOut], animations: { if(up){ self.backgroundColor = UIColor(red: 35/255, green: 160/255, blue: 35/255, alpha: 0.0) } else { self.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.0) } }, completion:nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
e3093b5443d923ff2869f156b36c1061
36.734848
141
0.614134
3.864236
false
false
false
false
kingka/SwiftWeiBo
SwiftWeiBo/SwiftWeiBo/Classes/Home/HomeTableViewController.swift
1
8825
// // HomeTableViewController.swift // SwiftWeiBo // // Created by Imanol on 1/11/16. // Copyright © 2016 imanol. All rights reserved. // import UIKit let HomeReuseIdentifier = "HomeReuseIdentifier" class HomeTableViewController: BaseViewController { //设置 中间的 view let btn = TitleView() var pullupRefreshFlag = false var models : [Statuses]?{ didSet{ tableView.reloadData() } } //缓存行高 var cacheRowHeight : [Int : CGFloat] = [Int : CGFloat]() override func didReceiveMemoryWarning() { // 清空缓存 cacheRowHeight.removeAll() } override func viewDidLoad() { super.viewDidLoad() // 判断登陆状态 if isLogin{ setupNavigationBarBtn() }else{ visitView?.setupVisitInfo("关注一些人,回这里看看有什么惊喜", imgName: "visitordiscover_feed_image_house", homePage: true) return } //监听 NSNotificationCenter.defaultCenter().addObserver(self, selector: "change", name: PopoverAnimatorWillShow, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "change", name: PopoverAnimatorWilldismiss, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "popPhotoBrowser:", name: KKPopPhotoBrowser, object: nil) // 注册2个cell tableView.registerClass(StatusesNormalCell.self, forCellReuseIdentifier: statusType.normalCell.rawValue) tableView.registerClass(StatusesForwordCell.self, forCellReuseIdentifier: statusType.forwordCell.rawValue) //已经通过计算的方式得到了rowHeight,并且缓存了,就不需要预估 //tableView.estimatedRowHeight = 200 //tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = UITableViewCellSeparatorStyle.None refreshControl = HomeRefreshControl() refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged) newStatusLabel.hidden = true //加载数据 loadData() } func popPhotoBrowser(userinfo : NSNotification) { guard let indexPath = userinfo.userInfo![KKPhotoBrowserIndexKey] as? NSIndexPath else{ print("no indexPath") return } guard let urls = userinfo.userInfo![KKPhotoBrowserURLKey] as? [NSURL] else{ print("no urls") return } let photoBrowser = PhotoBrowserController(index: indexPath.item, urls: urls) presentViewController(photoBrowser, animated: true) { () -> Void in } } func showNewStatusLabel(count : Int){ newStatusLabel.hidden = false newStatusLabel.text = (count == 0) ? "没有刷新到新的微博数据" : "刷新到\(count)条微博数据" UIView.animateWithDuration(2, animations: { () -> Void in self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height) }) { (_) -> Void in UIView.animateWithDuration(2, animations: { () -> Void in self.newStatusLabel.transform = CGAffineTransformIdentity }, completion: { (_) -> Void in self.newStatusLabel.hidden = true }) } } func loadData(){ //默认当作是下拉来处理,因为since_id 和 max_id , 必须有一个为0 var since_id = models?.first?.id ?? 0 var max_id = 0 if pullupRefreshFlag{ max_id = models?.last?.id ?? 0 since_id = 0 pullupRefreshFlag = false } //2 load statues Statuses.loadStatuses (since_id,max_id: max_id){ (list, error) -> () in // 接收刷新 self.refreshControl?.endRefreshing() if error != nil { print(error) return } // 下拉刷新 if since_id > 0 { self.models = list! + self.models! self.showNewStatusLabel(list?.count ?? 0) }else if max_id > 0{ self.models = self.models! + list! } else { self.models = list! } } } func setupNavigationBarBtn(){ // 1.添加左右按钮 navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButton("navigationbar_friendattention", target: self, action: "letBtnClick") navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButton("navigationbar_pop", target: self, action: "rightBtnClick") btn.setTitle("Imanol", forState: UIControlState.Normal) btn.addTarget(self, action: "titleViewClick:", forControlEvents: UIControlEvents.TouchUpInside) btn.sizeToFit() navigationItem.titleView = btn } func titleViewClick(btn:UIButton){ // //1 弹出菜单 let sb = UIStoryboard(name: "PopoverViewController", bundle: nil) let vc = sb.instantiateInitialViewController() //2 设置转场代理 vc?.transitioningDelegate = poperAnimator //设置转场样式 vc?.modalPresentationStyle = UIModalPresentationStyle.Custom; presentViewController(vc!, animated: true, completion: nil) print(__FUNCTION__) } func letBtnClick(){ print(__FUNCTION__) } func rightBtnClick(){ let sb = UIStoryboard(name: "QRCodeController", bundle: nil) let vc = sb.instantiateInitialViewController()! presentViewController(vc, animated: true, completion: nil) } deinit { // 移除通知 NSNotificationCenter.defaultCenter().removeObserver(self) } //MARK: - Lazy private lazy var poperAnimator:PoperAnimator = { let p = PoperAnimator() p.presentFrame = CGRect(x: 100, y: 56, width: 200, height: 350) return p }() /// 刷新提醒控件 private lazy var newStatusLabel: UILabel = { let label = UILabel() let height: CGFloat = 44 label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: height) label.backgroundColor = UIColor.orangeColor() label.textColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center // 加载 navBar 上面,不会随着 tableView 一起滚动 self.navigationController?.navigationBar.insertSubview(label, atIndex: 0) label.hidden = true return label }() //MARK: - 通知事件 /** 修改标题按钮的状态 */ func change(){ btn.selected = !btn.selected } } extension HomeTableViewController { // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let status = models![indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(statusType.cellID(status), forIndexPath: indexPath) as! StatusesCell cell.statuses = status let count = models?.count ?? 0 if indexPath.row == count - 1{ print("上啦加载") pullupRefreshFlag = true loadData() } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { //是否已经存储过对应微博id 的行高.有的话直接返回 let status = models![indexPath.row] if let rowHeight = cacheRowHeight[status.id] { //print("from cache:\(rowHeight)") return rowHeight } //没有的话,先取出cell, 然后计算,存储,再返回 let cell = tableView.dequeueReusableCellWithIdentifier(statusType.cellID(status)) as! StatusesCell let rowHeight = cell.rowHeight(status) cacheRowHeight[status.id] = rowHeight //print("caculate rowHeight:\(rowHeight)") return rowHeight } }
mit
02495226bfd378671e9b03667e34c697
30.066667
144
0.586791
5.127139
false
false
false
false
cbatch/fruit-ninja-ios
FruitNinjaiOS/FruitNinjaiOS/TargetEntity.swift
1
1070
// // TargetEntity.swift // FruitNinjaiOS // // Created by Connor Batch on 11/12/16. // Copyright © 2016 Connor Batch. All rights reserved. // import SpriteKit class TargetEntity : SwitchEntity { var hit : Bool = false var hitOnce : Bool = false init() { super.init(imageNamed: "target_down") self.physicsBody = SKPhysicsBody(rectangleOf: size) self.physicsBody?.categoryBitMask = PhysicsCategory.Target self.physicsBody?.contactTestBitMask = PhysicsCategory.Ninja | PhysicsCategory.Arrow self.physicsBody?.collisionBitMask = PhysicsCategory.Target } required init?(coder aDecoder: NSCoder) { // Decoding length here would be nice... super.init(coder: aDecoder) } override func update() { if (hit && !hitOnce) { levelManager.switchCounter -= 1 if (levelManager.switchCounter == 0) { levelManager.switchAction() } hitOnce = true } } }
mit
561eb7d1cb8c35b5ff90cb8f506749c7
23.860465
92
0.590271
4.668122
false
false
false
false
AvdLee/Moya
Demo/DemoMultiTarget/ViewController.swift
2
5738
import UIKit import Moya let provider = MoyaProvider<MultiTarget>(plugins: [NetworkLoggerPlugin(verbose: true)]) class ViewController: UITableViewController { var progressView = UIView() var repos = NSArray() override func viewDidLoad() { super.viewDidLoad() progressView.frame = CGRect(origin: .zero, size: CGSize(width: 0, height: 2)) progressView.backgroundColor = .blue navigationController?.navigationBar.addSubview(progressView) downloadRepositories("ashfurrow") } fileprivate func showAlert(_ title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(ok) present(alertController, animated: true, completion: nil) } // MARK: - API Stuff func downloadRepositories(_ username: String) { provider.request(MultiTarget(GitHub.userRepositories(username))) { result in switch result { case let .success(response): do { if let json = try response.mapJSON() as? NSArray { // Presumably, you'd parse the JSON into a model object. This is just a demo, so we'll keep it as-is. self.repos = json } else { self.showAlert("GitHub Fetch", message: "Unable to fetch from GitHub") } } catch { self.showAlert("GitHub Fetch", message: "Unable to fetch from GitHub") } self.tableView.reloadData() case let .failure(error): guard let error = error as? CustomStringConvertible else { break } self.showAlert("GitHub Fetch", message: error.description) } } } func downloadZen() { provider.request(MultiTarget(GitHub.zen)) { result in var message = "Couldn't access API" if case let .success(response) = result { let jsonString = try? response.mapString() message = jsonString ?? message } self.showAlert("Zen", message: message) } } func uploadGiphy() { let data = animatedBirdData() provider.request(MultiTarget(Giphy.upload(gif: data)), queue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } func downloadMoyaLogo() { provider.request(MultiTarget(GitHubUserContent.downloadMoyaWebContent("logo_github.png")), queue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } // MARK: - Progress Helpers lazy var progressClosure: ProgressBlock = { response in UIView.animate(withDuration: 0.3) { self.progressView.frame.size.width = self.view.frame.size.width * CGFloat(response.progress) } } lazy var progressCompletionClosure: Completion = { result in let color: UIColor switch result { case .success: color = .green case .failure: color = .red } UIView.animate(withDuration: 0.3) { self.progressView.backgroundColor = color self.progressView.frame.size.width = self.view.frame.size.width } UIView.animate(withDuration: 0.3, delay: 1, options: [], animations: { self.progressView.alpha = 0 }, completion: { _ in self.progressView.backgroundColor = .blue self.progressView.frame.size.width = 0 self.progressView.alpha = 1 } ) } // MARK: - User Interaction @IBAction func giphyWasPressed(_ sender: UIBarButtonItem) { uploadGiphy() } @IBAction func searchWasPressed(_ sender: UIBarButtonItem) { var usernameTextField: UITextField? let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { action in if let username = usernameTextField?.text { self.downloadRepositories(username) } } promptController.addAction(ok) promptController.addTextField { textField in usernameTextField = textField } present(promptController, animated: true, completion: nil) } @IBAction func zenWasPressed(_ sender: UIBarButtonItem) { downloadZen() } @IBAction func downloadWasPressed(_ sender: UIBarButtonItem) { downloadMoyaLogo() } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let repo = repos[indexPath.row] as? NSDictionary cell.textLabel?.text = repo?["name"] as? String return cell } }
mit
4ae70397601ea1340e2260397af332bf
35.547771
125
0.56274
5.517308
false
false
false
false
LDlalala/LDZBLiving
LDZBLiving/LDZBLiving/Classes/Main/LDPageView/LDPageView.swift
1
1800
// // LDPageView.swift // LDPageView // // Created by 李丹 on 17/8/2. // Copyright © 2017年 LD. All rights reserved. // import UIKit class LDPageView: UIView { private var titles : [String] private var childVcs : [UIViewController] private var parent : UIViewController private var style : LDPageStyle init(frame : CGRect ,titles : [String] ,style : LDPageStyle , childVcs : [UIViewController], parent : UIViewController) { // 在super前初始化变量 assert(titles.count == childVcs.count,"标题&控制器个数不相同,请检测") self.titles = titles self.childVcs = childVcs; self.parent = parent self.style = style self.parent.automaticallyAdjustsScrollViewInsets = false super.init(frame: frame) setupUI() } private func setupUI() { // 添加标题视图 let titleFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: style.titleHeight) let titleView = LDTitleView(titles: titles, frame: titleFrame, style: style) titleView.backgroundColor = UIColor.black addSubview(titleView) // 添加内容视图 let contentFrame = CGRect(x: 0, y: style.titleHeight, width: self.bounds.width, height: self.bounds.height - style.titleHeight) let contentView = LDContentView(frame: contentFrame, childVcs: childVcs, parent: parent) contentView.backgroundColor = UIColor.randomColor() addSubview(contentView) // 设置contentView&titleView关系 titleView.delegate = contentView contentView.delegate = titleView } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
cc111bffada3a8c17845583c3e1d735a
30.87037
135
0.642069
4.505236
false
false
false
false
iceman201/NZAirQuality
Pods/ScrollableGraphView/Classes/Plots/LinePlot.swift
3
4929
import UIKit open class LinePlot : Plot { // Public settings for the LinePlot // ################################ /// Specifies how thick the graph of the line is. In points. open var lineWidth: CGFloat = 2 /// The color of the graph line. UIColor. open var lineColor: UIColor = UIColor.black /// Whether the line is straight or curved. open var lineStyle_: Int { get { return lineStyle.rawValue } set { if let enumValue = ScrollableGraphViewLineStyle(rawValue: newValue) { lineStyle = enumValue } } } /// Whether or not the line should be rendered using bezier curves are straight lines. open var lineStyle = ScrollableGraphViewLineStyle.straight /// How each segment in the line should connect. Takes any of the Core Animation LineJoin values. open var lineJoin: String = convertFromCAShapeLayerLineJoin(CAShapeLayerLineJoin.round) /// The line caps. Takes any of the Core Animation LineCap values. open var lineCap: String = convertFromCAShapeLayerLineCap(CAShapeLayerLineCap.round) open var lineCurviness: CGFloat = 0.5 // Fill Settings // ############# /// Specifies whether or not the plotted graph should be filled with a colour or gradient. open var shouldFill: Bool = false var fillType_: Int { get { return fillType.rawValue } set { if let enumValue = ScrollableGraphViewFillType(rawValue: newValue) { fillType = enumValue } } } /// Specifies whether to fill the graph with a solid colour or gradient. open var fillType = ScrollableGraphViewFillType.solid /// If fillType is set to .Solid then this colour will be used to fill the graph. open var fillColor: UIColor = UIColor.black /// If fillType is set to .Gradient then this will be the starting colour for the gradient. open var fillGradientStartColor: UIColor = UIColor.white /// If fillType is set to .Gradient, then this will be the ending colour for the gradient. open var fillGradientEndColor: UIColor = UIColor.black open var fillGradientType_: Int { get { return fillGradientType.rawValue } set { if let enumValue = ScrollableGraphViewGradientType(rawValue: newValue) { fillGradientType = enumValue } } } /// If fillType is set to .Gradient, then this defines whether the gradient is rendered as a linear gradient or radial gradient. open var fillGradientType = ScrollableGraphViewGradientType.linear // Private State // ############# private var lineLayer: LineDrawingLayer? private var fillLayer: FillDrawingLayer? private var gradientLayer: GradientDrawingLayer? public init(identifier: String) { super.init() self.identifier = identifier } override func layers(forViewport viewport: CGRect) -> [ScrollableGraphViewDrawingLayer?] { createLayers(viewport: viewport) return [lineLayer, fillLayer, gradientLayer] } private func createLayers(viewport: CGRect) { // Create the line drawing layer. lineLayer = LineDrawingLayer(frame: viewport, lineWidth: lineWidth, lineColor: lineColor, lineStyle: lineStyle, lineJoin: lineJoin, lineCap: lineCap, shouldFill: shouldFill, lineCurviness: lineCurviness) // Depending on whether we want to fill with solid or gradient, create the layer accordingly. // Gradient and Fills switch (self.fillType) { case .solid: if(shouldFill) { // Setup fill fillLayer = FillDrawingLayer(frame: viewport, fillColor: fillColor, lineDrawingLayer: lineLayer!) } case .gradient: if(shouldFill) { gradientLayer = GradientDrawingLayer(frame: viewport, startColor: fillGradientStartColor, endColor: fillGradientEndColor, gradientType: fillGradientType, lineDrawingLayer: lineLayer!) } } lineLayer?.owner = self fillLayer?.owner = self gradientLayer?.owner = self } } @objc public enum ScrollableGraphViewLineStyle : Int { case straight case smooth } @objc public enum ScrollableGraphViewFillType : Int { case solid case gradient } @objc public enum ScrollableGraphViewGradientType : Int { case linear case radial } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromCAShapeLayerLineJoin(_ input: CAShapeLayerLineJoin) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromCAShapeLayerLineCap(_ input: CAShapeLayerLineCap) -> String { return input.rawValue }
mit
c72642b87c02b0b46b0f278c85eba9cf
33.468531
211
0.653074
5.172088
false
false
false
false
wuzzapcom/Fluffy-Book
FluffyBook/WordPreviewModel.swift
1
510
// // WordPreviewModel.swift // FluffyBook // // Created by Владимир Лапатин on 01.04.17. // Copyright © 2017 wuzzapcom. All rights reserved. // import Foundation import RealmSwift class WordPreviewModel : Object{ dynamic var word : String = "" dynamic var translation : String = "" dynamic var transcription : String = "" public func setFields(word w : String, translation tr : String) { word = w translation = tr } }
mit
a5a9e2af350ed5c0372caaaab2c8102c
18.76
69
0.615385
4.01626
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/OAuthSwift/OAuthSwiftTests/ServicesTests.swift
2
13463
// // ServicesTests.swift // OAuthSwift // // Created by phimage on 25/11/15. // Copyright © 2015 Dongri Jin. All rights reserved. // import XCTest import OAuthSwift import Erik class ServicesTests: XCTestCase { let services = Services() let FileManager: Foundation.FileManager = Foundation.FileManager.default let DocumentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] var confPath: String { let appPath = "\(DocumentDirectory)/.oauth/" if !FileManager.fileExists(atPath: appPath) { do { try FileManager.createDirectory(atPath: appPath, withIntermediateDirectories: false, attributes: nil) }catch { print("Failed to create \(appPath)") } } return "\(appPath)Services.plist" } override func setUp() { super.setUp() if let path = Bundle(for: type(of: self)).path(forResource: "Services", ofType: "plist") { services.loadFromFile(path) if !FileManager.fileExists(atPath: confPath) { do { try FileManager.copyItem(atPath: path, toPath: confPath) }catch { print("Failed to copy empty conf to\(confPath)") } } } services.loadFromFile(confPath) if let path = Bundle(for: type(of: self)).path(forResource: "ServicesTest", ofType: "plist") { services.loadFromFile(path) } } override func tearDown() { super.tearDown() } func _testAllServices() { for (service, parameters) in services.parameters { testService(service, serviceParameters: parameters) } } func testDropBox() { testService("Dropbox") } func testBitBucket() { testService("BitBucket") } func testService(_ service: String) { if let param = services[service] { self.testService(service, serviceParameters: param) } else { XCTFail("No parameters for \(service). Test ignored") } } func testService(_ service: String, serviceParameters: [String: String]) { if !Services.parametersEmpty(serviceParameters) { if let versionString = serviceParameters["version"] , let version = Int(versionString) { if version == 1 { testServiceOAuth1(service, serviceParameters: serviceParameters) } else if version == 2 { testServiceOAuth2(service, serviceParameters: serviceParameters) } else { XCTFail("Wrong version \(version) for \(service)") } } } } func testServiceOAuth1(_ service: String, serviceParameters: [String: String]) { guard let oauthswift = OAuth1Swift(parameters: serviceParameters) else { print("\(service) not well configured for test [consumerKey, consumerSecret, requestTokenUrl, authorizeUrl, accessTokenUrl]") return } print("\(service) testing") let callbackURL = serviceParameters["callbackURL"] ?? "oauth-swift://oauth-callback/\(service)" guard let handler = ServicesURLHandlerType( service: service, serviceParameters: serviceParameters, callbackURL: callbackURL ) else { return } oauthswift.authorizeURLHandler = handler if let allowMissingOAuthVerifier = serviceParameters["allowMissingOAuthVerifier"] { oauthswift.allowMissingOAuthVerifier = allowMissingOAuthVerifier == "1" || allowMissingOAuthVerifier == "true" } let expectation = self.expectation(description: service) let _ = oauthswift.authorize(withCallbackURL: URL(string: callbackURL)!, success: { credential, response, parameters in expectation.fulfill() print("\(service) token ok") }, failure: { error in print(error.localizedDescription) } ) self.waitForExpectations(timeout: 20) { (error) -> Void in if let e = error { print("\(service): \(e.localizedDescription)") } } } func testServiceOAuth2(_ service: String, serviceParameters: [String: String]) { guard let oauthswift = OAuth2Swift(parameters: serviceParameters) else { print("\(service) not well configured for test [consumerKey, consumerSecret, responseType, authorizeUrl, accessTokenUrl]") return } print("\(service) testing") let callbackURL = serviceParameters["callbackURL"] ?? "oauth-swift://oauth-callback/\(service)" let scope = serviceParameters["scope"] ?? "all" guard let handler = ServicesURLHandlerType( service: service, serviceParameters: serviceParameters, callbackURL: callbackURL ) else { return } oauthswift.authorizeURLHandler = handler let expectation = self.expectation(description: service) let state = generateState(withLength: 20) let _ = oauthswift.authorize(withCallbackURL: URL(string: callbackURL)!, scope: scope, state: state, success: { credential, response, parameters in expectation.fulfill() print("\(service) token ok") }, failure: { error in print(error.localizedDescription) } ) self.waitForExpectations(timeout: 20) { (error) -> Void in if let e = error { print("\(service): \(e.localizedDescription)") } } } } import WebKit class ServicesURLHandlerType: LayoutEngineNavigationDelegate, OAuthSwiftURLHandlerType { let browser: Erik var service: String var serviceParameters: [String: String] var callbackURL: String var handled: Bool = false init?(service: String, serviceParameters: [String: String], callbackURL: String) { self.service = service self.serviceParameters = serviceParameters self.callbackURL = callbackURL let webView = WKWebView() browser = Erik(webView: webView) super.init() webView.navigationDelegate = self guard let _ = self.serviceParameters["form_username_selector"], let _ = self.serviceParameters["form_password_selector"], let _ = self.serviceParameters["form_selector"] else { print("\(service): No selector defined for form [form_username_selector, form_password_selector, form_selector]") return nil } guard let _ = self.serviceParameters["form_username_value"], let _ = self.serviceParameters["form_password_value"] else { print("\(self.service): No value defined to fill form [form_username_value, form_password_value]") return nil } } internal func handle(_ url: URL) { guard let form_username_selector = serviceParameters["form_username_selector"], let form_password_selector = serviceParameters["form_password_selector"], let form_selector = serviceParameters["form_selector"] else { XCTFail("\(service): Cannot handle \(url), no selector defined for form [form_username_selector, form_password_selector, form_selector]") return } browser.visit(url: url) {[unowned self] (document, error) in if self.handled { return // already handled (many already connected) } if let doc = document { // Fill form if let usernameInput = doc.querySelector(form_username_selector), let passwordInput = doc.querySelector(form_password_selector), let _ = doc.querySelector(form_selector) as? Form { guard let username = self.serviceParameters["form_username_value"], let password = self.serviceParameters["form_password_value"] else { print("\(self.service): Cannot handle \(url), no value defined to fill form [form_username_value, form_password_value]") return } usernameInput["value"] = username passwordInput["value"] = password // check form affectation self.browser.currentContent {[unowned self] (document, error) in if let doc = document { guard let usernameInput = doc.querySelector(form_username_selector), let passwordInput = doc.querySelector(form_password_selector) else { print("\(self.service): Unable to get form element ") return } XCTAssertEqual(usernameInput["value"], username) XCTAssertEqual(passwordInput["value"], password) } guard let form = doc.querySelector(form_selector) as? Form else { print("\(self.service): Unable to get the form") return } let authorizeButtonBlock = { // Wait redirection self.browser.currentContent {[unowned self] (document, error) in if let e = error { print("\(e)") } if let currentURL = self.browser.url { print("\(currentURL)") } if let doc = document { self.authorizeButton(doc) } } } // Submit form if let formButton = self.serviceParameters["form_button_selector"], let button = form.querySelector(formButton) { button.click { obj, err in if let error = err { print("\(error)") } else { authorizeButtonBlock() } } } else { form.submit{ obj, err in if let error = err { print("\(error)") } else { authorizeButtonBlock() } } } } } else { self.authorizeButton(doc) } } else { XCTFail("\(self.service): Cannot handle \(url) \(String(describing: error))") } } } func authorizeButton(_ doc: Document) { // Submit authorization if let autorizeButton = self.serviceParameters["authorize_button_selector"] { if let button = doc.querySelector(autorizeButton) { button.click() } else { print(doc.toHTML ?? "ERROR: no HTML doc") XCTFail("\(self.service): \(autorizeButton) not found to valid authentification]. \(String(describing: self.browser.url))") } } else if !self.handled { XCTFail("\(self.service): No [authorize_button_selector) to valid authentification]. \(String(describing: self.browser.url))") } } override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler) if let url = navigationAction.request.url { let urlString = "\(url)" if urlString.hasPrefix(self.callbackURL) { self.handled = true OAuthSwift.handle(url: url) decisionHandler(.cancel) } else { decisionHandler(.allow) } } } }
mit
e8c936e1b42ac6f4dd7e6a8c3e5e6bf1
38.02029
166
0.503714
5.914763
false
true
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/VoiceRecordingContainerView.swift
1
3624
// // VoiceRecordingContainerView.swift // Pigeon-project // // Created by Roman Mizin on 11/25/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit class VoiceRecordingContainerView: UIView { var recordButton: UIButton = { var recordButton = UIButton() recordButton.translatesAutoresizingMaskIntoConstraints = false recordButton.setTitle("Record", for: .normal) return recordButton }() var stopButton: UIButton = { var stopButton = UIButton() stopButton.translatesAutoresizingMaskIntoConstraints = false stopButton.setTitleColor(UIColor.red, for: .normal) stopButton.setTitle("Stop", for: .normal) return stopButton }() var statusLabel: UILabel = { var statusLabel = UILabel() statusLabel.text = "00:00:00" statusLabel.textColor = ThemeManager.currentTheme().generalTitleColor statusLabel.translatesAutoresizingMaskIntoConstraints = false return statusLabel }() var waveForm: WaveformView = { var waveForm = WaveformView() waveForm.translatesAutoresizingMaskIntoConstraints = false waveForm.amplitude = 0.0 waveForm.backgroundColor = .clear return waveForm }() override init(frame: CGRect) { super.init(frame: frame) recordButton.setTitleColor(ThemeManager.currentTheme().tintColor, for: .normal) addSubview(recordButton) addSubview(stopButton) addSubview(statusLabel) addSubview(waveForm) recordButton.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true recordButton.widthAnchor.constraint(equalToConstant: 80).isActive = true recordButton.heightAnchor.constraint(equalToConstant: 50).isActive = true stopButton.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true stopButton.leftAnchor.constraint(equalTo: recordButton.rightAnchor, constant: 10).isActive = true stopButton.widthAnchor.constraint(equalToConstant: 70).isActive = true stopButton.heightAnchor.constraint(equalToConstant: 50).isActive = true statusLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10).isActive = true // statusLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true statusLabel.widthAnchor.constraint(equalToConstant: 75).isActive = true statusLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true waveForm.topAnchor.constraint(equalTo: recordButton.bottomAnchor).isActive = true if #available(iOS 11.0, *) { recordButton.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true statusLabel.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true waveForm.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true waveForm.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true waveForm.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -10).isActive = true } else { recordButton.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true statusLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true waveForm.rightAnchor.constraint(equalTo: rightAnchor).isActive = true waveForm.leftAnchor.constraint(equalTo: leftAnchor).isActive = true waveForm.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
e737b15c12f9c5561b363f2b81167de6
38.380435
113
0.747723
4.990358
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/00193-swift-typebase-gettypevariables.swift
11
963
// 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 // RUN: not %target-swift-frontend %s -parse [] } protocol p { } protocol g : p { } n j } } protocol k { class func q() } class n: k{ class func q {} func r<e: t, s where j<s> == e.m { func g k q<n : t> { q g: n } func p<n>() ->(b: T) { } f(true as Boolean) f> { c(d ()) } func b(e)-> <d>(() -> d) d "" e} class d { func b((Any, d)typealias b = b d> Bool { e !(f) [] } f m) return "" } } class C: B, A { over } } func e<T where T: A, T: B>(t: T) { t.c() } func a<T>() -> (T -> T) -> T { T, T -> T) ->)func typealias F = Int func g<T where T.E == F>(f: B<T>) { } }
apache-2.0
19a26a398fd8fddc6e76edf6411ed4a4
16.509091
78
0.554517
2.623978
false
false
false
false
emilstahl/swift
stdlib/public/core/Prespecialized.swift
8
2565
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// // Pre-specializaiton of some popular generic classes and functions. //===----------------------------------------------------------------------===// struct _Prespecialize { // Create specializations for the arrays of most // popular builtin integer and floating point types. static internal func _specializeArrays() { func _createArrayUser<Element : Comparable>(sampleValue: Element) { // Initializers. let _: [Element] = [ sampleValue ] var a = [Element](count: 1, repeatedValue: sampleValue) // Read array element let _ = a[0] // Set array elements for j in 0..<a.count { a[0] = a[j] } for var i1 = 0; i1 < a.count; ++i1 { for var i2 = 0; i2 < a.count; ++i2 { a[i1] = a[i2] } } a[0] = sampleValue // Get length and capacity let _ = a.count + a.capacity // Iterate over array for e in a { print(e) print("Value: \(e)") } print(a) // Reserve capacity a.removeAll() a.reserveCapacity(100) // Sort array let _ = a.sort { (a:Element, b:Element) in a < b } a.sortInPlace { (a:Element, b:Element) in a < b } // force specialization of print<Element> print(sampleValue) print("Element:\(sampleValue)") } _createArrayUser(1 as Int) _createArrayUser(1 as Int8) _createArrayUser(1 as Int16) _createArrayUser(1 as Int32) _createArrayUser(1 as Int64) _createArrayUser(1 as UInt) _createArrayUser(1 as UInt8) _createArrayUser(1 as UInt16) _createArrayUser(1 as UInt32) _createArrayUser(1 as UInt64) _createArrayUser("a" as String) _createArrayUser(1.5 as Float) _createArrayUser(1.5 as Double) } // Force pre-specialization of Range<Int> static internal func _specializeRanges() -> Int { let a = [Int](count: 10, repeatedValue: 1) var count = 0 // Specialize Range for integers for i in 0..<a.count { count += a[i] } return count } }
apache-2.0
07e1ad41f5973369b7f4b91f91b25793
27.5
80
0.556335
4.184339
false
false
false
false