hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
092856f16184caf5b5079d5837e1c9657aa1f81d | 3,532 | //
// FGDoodlingPathPlayView.swift
// FGDoodlingBoardExample
//
// Created by xgf on 2019/3/15.
// Copyright © 2019年 mrpyq. All rights reserved.
//
import UIKit
private struct FGDoodlingPathPoint {
var point : CGPoint
var head : Bool = false
var color : UIColor?
}
public class FGDoodlingPathPlayView: UIView {
private var points = [FGDoodlingPathPoint]()
private var currentPlayingPoints = [FGDoodlingPathPoint]()
private var currentPlayingPointCount = 0
private var isPlaying = false
private var timer : DispatchSourceTimer?
public override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = hexcolor(0xf4f4f4)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = hexcolor(0xf4f4f4)
}
}
public extension FGDoodlingPathPlayView {
public func setContents(contents : [[String : Any]]) {
if isPlaying {
timer?.cancel()
currentPlayingPoints = [FGDoodlingPathPoint].init(points)
setNeedsDisplay()
isPlaying = false
return
}
var pathPoints = [FGDoodlingPathPoint]()
for dict in contents {
let hex = dict["color"] as? UInt ?? 0x000000
let color = hexcolor(hex)
let linePoints = dict["points"] as? [[String : CGFloat]] ?? []
for i in 0 ..< linePoints.count {
let linePoint = linePoints[i]
let x = linePoint["x"] ?? 0
let y = linePoint["y"] ?? 0
let p = FGDoodlingPathPoint.init(point: .init(x: x, y: y), head: (i == 0), color: (i == 0) ? color : nil)
pathPoints.append(p)
}
}
points = [FGDoodlingPathPoint].init(pathPoints)
currentPlayingPoints.removeAll()
currentPlayingPointCount = 0
timerStart()
isPlaying = true
}
private func timerStart() {
if timer != nil {
timer?.cancel()
}
timer = DispatchSource.makeTimerSource(flags: [], queue: .main)
weak var wkself = self
timer?.setEventHandler {
wkself?.playPoints()
}
timer?.schedule(deadline: .now(), repeating: .microseconds(10), leeway: .seconds(0))
timer?.resume()
}
private func playPoints() {
currentPlayingPointCount += 1
if currentPlayingPointCount > points.count {
timer?.cancel()
isPlaying = false
return
}
let seq = points[..<points.index(points.startIndex, offsetBy: currentPlayingPointCount)]
currentPlayingPoints = [FGDoodlingPathPoint].init(seq)
setNeedsDisplay()
}
}
public extension FGDoodlingPathPlayView {
override public func draw(_ rect: CGRect) {
var path = UIBezierPath.init()
path.lineWidth = 4.0
var color : UIColor? = nil
for pt in currentPlayingPoints {
if pt.head {
if color != nil {
color?.set()
path.stroke()
path.close()
}
color = pt.color
path = UIBezierPath.init()
path.lineWidth = 4.0
path.move(to: pt.point)
} else {
path.addLine(to: pt.point)
}
}
if color != nil {
color?.set()
}
path.stroke()
path.close()
}
}
| 30.188034 | 121 | 0.552095 |
382deda7399f0e2031f75c0ac74b3a491ae6c1c2 | 1,000 | //
// NewGameMenuScene.swift
// sudoku
//
// Created by Дмитрий Папков on 05.05.2021.
//
import SwiftUI
struct NewGameMenuScene: View {
@State var game: GameModel? = nil
var body: some View {
VStack(alignment: .trailing, spacing: 16) {
HStack { Spacer() }
Spacer()
ButtonMenuItemView("Простой") { self.game = .init(.flash) }
ButtonMenuItemView("Легкий") { self.game = .init(.easy) }
ButtonMenuItemView("Средний") { self.game = .init(.medium) }
ButtonMenuItemView("Сложний") { self.game = .init(.hard) }
ButtonMenuItemView("Невообразимый") { self.game = .init(.insane) }
}
.padding()
.navigationBarTitle(Text("Новая игра"), displayMode: .large)
.fullScreenCover(item: $game) { GameScene(model: $0) }
}
}
struct NewGameMenuScene_Previews: PreviewProvider {
static var previews: some View {
NewGameMenuScene()
}
}
| 27.777778 | 78 | 0.581 |
1a93f13afa23653287fef12cf63288bc0b8fe6e1 | 2,296 | import Foundation
import TSCBasic
import TuistCore
import TuistGraph
import TuistGraphTesting
import TuistSupport
import XCTest
@testable import ProjectDescription
@testable import TuistLoader
@testable import TuistLoaderTesting
@testable import TuistSupportTesting
final class DependenciesModelLoaderTests: TuistUnitTestCase {
private var manifestLoader: MockManifestLoader!
private var subject: DependenciesModelLoader!
override func setUp() {
super.setUp()
manifestLoader = MockManifestLoader()
subject = DependenciesModelLoader(manifestLoader: manifestLoader)
}
override func tearDown() {
subject = nil
manifestLoader = nil
super.tearDown()
}
func test_loadDependencies() throws {
// Given
let temporaryPath = try self.temporaryPath()
let localSwiftPackagePath = temporaryPath.appending(component: "LocalPackage")
manifestLoader.loadDependenciesStub = { _ in
Dependencies(
carthage: [
.github(path: "Dependency1", requirement: .exact("1.1.1")),
.git(path: "Dependency1", requirement: .exact("2.3.4")),
],
swiftPackageManager: .init(
[
.local(path: Path(localSwiftPackagePath.pathString)),
.remote(url: "RemoteUrl.com", requirement: .exact("1.2.3")),
]
),
platforms: [.iOS, .macOS]
)
}
// When
let got = try subject.loadDependencies(at: temporaryPath)
// Then
let expected: TuistGraph.Dependencies = .init(
carthage: .init(
[
.github(path: "Dependency1", requirement: .exact("1.1.1")),
.git(path: "Dependency1", requirement: .exact("2.3.4")),
]
),
swiftPackageManager: .init(
[
.local(path: localSwiftPackagePath),
.remote(url: "RemoteUrl.com", requirement: .exact("1.2.3")),
],
productTypes: [:]
),
platforms: [.iOS, .macOS]
)
XCTAssertEqual(got, expected)
}
}
| 29.818182 | 86 | 0.555314 |
185fbd8f08a6d0ee5eda5bdd7f110339a3157d19 | 130,427 | //
// SingleSubredditViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 12/22/16.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import Anchorage
import Embassy
import MaterialComponents.MDCActivityIndicator
import MKColorPicker
import RealmSwift
import reddift
import RLBAlertsPickers
import SDWebImage
import SloppySwiper
import YYText
import UIKit
import SDCAlertView
// MARK: - Base
class SingleSubredditViewController: MediaViewController, UINavigationControllerDelegate {
override var prefersStatusBarHidden: Bool {
return SettingValues.fullyHideNavbar
}
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: " ", modifierFlags: [], action: #selector(spacePressed)),
UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(spacePressed)),
UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(spacePressedUp)),
UIKeyCommand(input: "s", modifierFlags: .command, action: #selector(search), discoverabilityTitle: "Search"),
UIKeyCommand(input: "p", modifierFlags: .command, action: #selector(hideReadPosts), discoverabilityTitle: "Hide read posts"),
UIKeyCommand(input: "r", modifierFlags: .command, action: #selector(refresh(_:)), discoverabilityTitle: "Reload"),
]
}
var navbarEnabled: Bool {
return true
}
var toolbarEnabled: Bool {
return true
}
let maxHeaderHeight: CGFloat = 120
let minHeaderHeight: CGFloat = 56
public var inHeadView: UIView?
var lastTopItem: Int = 0
let margin: CGFloat = 10
let cellsPerRow = 3
var readLaterCount: Int {
return ReadLater.readLaterIDs.allValues.filter { (value) -> Bool in
if sub == "all" || sub == "frontpage" { return true }
guard let valueStr = value as? String else { return false }
return valueStr.lowercased() == sub.lowercased()
}.count
}
var panGesture: UIPanGestureRecognizer!
var translatingCell: LinkCellView?
var times = 0
var startTime = Date()
var parentController: MainViewController?
var accentChosen: UIColor?
var primaryChosen: UIColor?
var isModal = false
var offline = false
var isAccent = false
var isCollapsed = false
var isHiding = false
var isToolbarHidden = false
var oldY = CGFloat(0)
var links: [RSubmission] = []
var paginator = Paginator()
var sub: String
var session: Session?
var tableView: UICollectionView!
var single: Bool = false
var loaded = false
var sideView: UIView = UIView()
var subb: UIButton = UIButton()
var subInfo: Subreddit?
var flowLayout: WrappingFlowLayout = WrappingFlowLayout.init()
static var firstPresented = true
static var cellVersion = 0 {
didSet {
PagingCommentViewController.savedComment = nil
}
}
var swiper: SloppySwiper?
var more = UIButton()
var lastY: CGFloat = CGFloat(0)
var lastYUsed = CGFloat(0)
var listingId: String = "" //a random id for use in Realm
var fab: UIButton?
var first = true
var indicator: MDCActivityIndicator?
var searchText: String?
var loading = false
var nomore = false
var showing = false
var sort = SettingValues.defaultSorting
var time = SettingValues.defaultTimePeriod
var refreshControl: UIRefreshControl!
var realmListing: RListing?
var hasHeader = false
var subLinks = [SubLinkItem]()
var oldsize = CGFloat(0)
init(subName: String, parent: MainViewController) {
sub = subName
self.parentController = parent
super.init(nibName: nil, bundle: nil)
self.sort = SettingValues.getLinkSorting(forSubreddit: self.sub)
self.time = SettingValues.getTimePeriod(forSubreddit: self.sub)
}
init(subName: String, single: Bool) {
sub = subName
self.single = true
super.init(nibName: nil, bundle: nil)
self.sort = SettingValues.getLinkSorting(forSubreddit: self.sub)
self.time = SettingValues.getTimePeriod(forSubreddit: self.sub)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func becomeFirstResponder() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
CachedTitle.titles.removeAll()
flowLayout.delegate = self
self.tableView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
self.view = UIView.init(frame: CGRect.zero)
self.view.addSubview(tableView)
tableView.verticalAnchors == view.verticalAnchors
tableView.horizontalAnchors == view.safeHorizontalAnchors
panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panCell))
panGesture.direction = .horizontal
panGesture.delegate = self
self.tableView.addGestureRecognizer(panGesture)
if single && navigationController != nil {
panGesture.require(toFail: navigationController!.interactivePopGestureRecognizer!)
}
if single {
self.edgesForExtendedLayout = UIRectEdge.all
} else {
self.edgesForExtendedLayout = []
}
self.extendedLayoutIncludesOpaqueBars = true
self.tableView.delegate = self
self.tableView.dataSource = self
refreshControl = UIRefreshControl()
if !(navigationController is TapBehindModalViewController) {
inHeadView = UIView().then {
$0.backgroundColor = ColorUtil.getColorForSub(sub: sub, true)
if SettingValues.fullyHideNavbar {
$0.backgroundColor = .clear
}
}
self.view.addSubview(inHeadView!)
inHeadView!.isHidden = UIDevice.current.orientation.isLandscape
inHeadView!.topAnchor == view.topAnchor
inHeadView!.horizontalAnchors == view.horizontalAnchors
inHeadView!.heightAnchor == (UIApplication.shared.statusBarView?.frame.size.height ?? 0)
}
reloadNeedingColor()
self.flowLayout.reset(modal: self.presentingViewController != nil)
tableView.reloadData()
self.automaticallyAdjustsScrollViewInsets = false
if #available(iOS 11.0, *) {
self.tableView.contentInsetAdjustmentBehavior = .never
}
}
func reTheme() {
self.reloadNeedingColor()
flowLayout.reset(modal: presentingViewController != nil)
CachedTitle.titles.removeAll()
LinkCellImageCache.initialize()
self.tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if single && !isModal && !(self.navigationController!.delegate is SloppySwiper) {
swiper = SloppySwiper.init(navigationController: self.navigationController!)
self.navigationController!.delegate = swiper!
for view in view.subviews {
if view is UIScrollView {
let scrollView = view as! UIScrollView
swiper!.panRecognizer.require(toFail: scrollView.panGestureRecognizer)
break
}
}
}
server?.stop()
loop?.stop()
first = false
tableView.delegate = self
if single {
setupBaseBarColors()
}
if !loaded {
showUI()
}
self.view.backgroundColor = ColorUtil.theme.backgroundColor
self.navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = false
splitViewController?.navigationController?.navigationBar.isTranslucent = false
splitViewController?.navigationController?.setNavigationBarHidden(true, animated: false)
if let bar = splitViewController?.navigationController?.navigationBar {
bar.heightAnchor == 0
}
if single {
navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: sub, true)
if let interactiveGesture = self.navigationController?.interactivePopGestureRecognizer {
self.tableView.panGestureRecognizer.require(toFail: interactiveGesture)
}
}
navigationController?.navigationBar.tintColor = SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white
self.navigationController?.navigationBar.shadowImage = UIImage()
self.splitViewController?.navigationController?.navigationBar.shadowImage = UIImage()
if single {
navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: sub, true)
}
navigationController?.toolbar.barTintColor = ColorUtil.theme.backgroundColor
navigationController?.toolbar.tintColor = ColorUtil.theme.fontColor
inHeadView?.isHidden = UIDevice.current.orientation.isLandscape
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if toolbarEnabled && !MainViewController.isOffline {
if single {
navigationController?.setToolbarHidden(false, animated: false)
} else {
parentController?.menuNav?.view.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - (parentController?.menuNav?.bottomOffset ?? 64), width: parentController?.menuNav?.view.frame.width ?? 0, height: parentController?.menuNav?.view.frame.height ?? 0)
}
self.isToolbarHidden = false
if fab == nil {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.setupFab(self.view.bounds.size)
}
} else {
show(true)
}
} else {
if single {
navigationController?.setToolbarHidden(true, animated: false)
}
}
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if cell is AutoplayBannerLinkCellView {
(cell as! AutoplayBannerLinkCellView).doLoadVideo()
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if self.view.bounds.width != oldsize {
oldsize = self.view.bounds.width
flowLayout.reset(modal: presentingViewController != nil)
tableView.reloadData()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
for index in tableView.indexPathsForVisibleItems {
if let cell = tableView.cellForItem(at: index) as? LinkCellView {
cell.endVideos()
}
}
if single {
UIApplication.shared.statusBarView?.backgroundColor = .clear
}
if fab != nil {
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
}, completion: { _ in
self.fab?.removeFromSuperview()
self.fab = nil
})
}
if let session = (UIApplication.shared.delegate as? AppDelegate)?.session {
if AccountController.isLoggedIn && AccountController.isGold && !History.currentSeen.isEmpty {
do {
try session.setVisited(names: History.currentSeen) { (result) in
print(result)
History.currentSeen.removeAll()
}
} catch let error {
print(error)
}
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.fab?.removeFromSuperview()
self.fab = nil
self.setupFab(size)
inHeadView?.isHidden = UIDevice.current.orientation.isLandscape
coordinator.animate(
alongsideTransition: { [unowned self] _ in
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
self.view.setNeedsLayout()
//todo content offset
}, completion: nil
)
// if self.viewIfLoaded?.window != nil {
// tableView.reloadData()
// }
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight && SettingValues.reduceColor {
return .default
} else {
return .lightContent
}
}
static func getHeightFromAspectRatio(imageHeight: CGFloat, imageWidth: CGFloat, viewWidth: CGFloat) -> CGFloat {
let ratio = imageHeight / imageWidth
return viewWidth * ratio
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if fab != nil {
fab?.removeFromSuperview()
fab = nil
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let currentY = scrollView.contentOffset.y
if !SettingValues.pinToolbar {
if currentY > lastYUsed && currentY > 60 {
if navigationController != nil && !isHiding && !isToolbarHidden && !(scrollView.contentOffset.y >= (scrollView.contentSize.height - scrollView.frame.size.height)) {
hideUI(inHeader: true)
} else if fab != nil && !fab!.isHidden && !isHiding {
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
}, completion: { _ in
self.fab?.isHidden = true
self.isHiding = false
})
}
} else if (currentY < lastYUsed - 15 || currentY < 100) && !isHiding && navigationController != nil && (isToolbarHidden) {
showUI()
}
}
lastYUsed = currentY
lastY = currentY
}
func hideUI(inHeader: Bool) {
isHiding = true
if navbarEnabled {
(navigationController)?.setNavigationBarHidden(true, animated: true)
}
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
}, completion: { _ in
self.fab?.isHidden = true
self.isHiding = false
})
if single {
navigationController?.setToolbarHidden(true, animated: true)
} else {
if let parent = self.parentController, parent.menu.superview != nil, let topView = parent.menuNav?.topView {
parent.menu.deactivateImmediateConstraints()
parent.menu.topAnchor == topView.topAnchor - 10
parent.menu.widthAnchor == 56
parent.menu.heightAnchor == 56
parent.menu.leftAnchor == topView.leftAnchor
parent.more.deactivateImmediateConstraints()
parent.more.topAnchor == topView.topAnchor - 10
parent.more.widthAnchor == 56
parent.more.heightAnchor == 56
parent.more.rightAnchor == topView.rightAnchor
}
UIView.animate(withDuration: 0.25) {
self.parentController?.menuNav?.view.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - (SettingValues.totallyCollapse ? 0 : ((self.parentController?.menuNav?.bottomOffset ?? 56) / 2)), width: self.parentController?.menuNav?.view.frame.width ?? 0, height: self.parentController?.menuNav?.view.frame.height ?? 0)
self.parentController?.menu.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
self.parentController?.more.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}
// if !single && parentController != nil {
// parentController!.drawerButton.isHidden = false
// }
}
self.isToolbarHidden = true
}
func showUI(_ disableBottom: Bool = false) {
if navbarEnabled {
(navigationController)?.setNavigationBarHidden(false, animated: true)
}
if self.fab?.superview != nil {
self.fab?.isHidden = false
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity
})
}
if single && !MainViewController.isOffline {
navigationController?.setToolbarHidden(false, animated: true)
} else if !disableBottom {
UIView.animate(withDuration: 0.25) {
if let parent = self.parentController {
if parent.menu.superview != nil, let topView = parent.menuNav?.topView {
parent.menu.deactivateImmediateConstraints()
parent.menu.topAnchor == topView.topAnchor
parent.menu.widthAnchor == 56
parent.menu.heightAnchor == 56
parent.menu.leftAnchor == topView.leftAnchor
parent.more.deactivateImmediateConstraints()
parent.more.topAnchor == topView.topAnchor
parent.more.widthAnchor == 56
parent.more.heightAnchor == 56
parent.more.rightAnchor == topView.rightAnchor
}
parent.menuNav?.view.frame = CGRect(x: 0, y: (UIScreen.main.bounds.height - (parent.menuNav?.bottomOffset ?? 0)), width: parent.menuNav?.view.frame.width ?? 0, height: parent.menuNav?.view.frame.height ?? 0)
parent.menu.transform = CGAffineTransform(scaleX: 1, y: 1)
parent.more.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
}
self.isToolbarHidden = false
}
func show(_ animated: Bool = true) {
if fab != nil && (fab!.isHidden || fab!.superview == nil) {
if animated {
if fab!.superview == nil {
if single {
self.navigationController?.toolbar.addSubview(fab!)
} else {
parentController?.toolbar?.addSubview(fab!)
}
}
self.fab!.isHidden = false
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.fab?.transform = CGAffineTransform.identity
})
} else {
self.fab!.isHidden = false
}
}
}
func hideFab(_ animated: Bool = true) {
if self.fab != nil {
if animated {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.fab!.alpha = 0
}, completion: { _ in
self.fab!.isHidden = true
})
} else {
self.fab!.isHidden = true
}
}
}
func setupFab(_ size: CGSize) {
addNewFab(size)
}
func addNewFab(_ size: CGSize) {
if self.fab != nil {
self.fab!.removeFromSuperview()
self.fab = nil
}
if !MainViewController.isOffline && !SettingValues.hiddenFAB {
self.fab = UIButton(frame: CGRect.init(x: (size.width / 2) - 70, y: -20, width: 140, height: 45))
self.fab!.backgroundColor = ColorUtil.accentColorForSub(sub: sub)
self.fab!.accessibilityHint = sub
self.fab!.layer.cornerRadius = 22.5
self.fab!.clipsToBounds = true
let title = " " + SettingValues.fabType.getTitleShort()
self.fab!.setTitle(title, for: .normal)
self.fab!.leftImage(image: (UIImage.init(named: SettingValues.fabType.getPhoto())?.navIcon(true))!, renderMode: UIImage.RenderingMode.alwaysOriginal)
self.fab!.elevate(elevation: 2)
self.fab!.titleLabel?.textAlignment = .center
self.fab!.titleLabel?.font = UIFont.systemFont(ofSize: 14)
let width = title.size(with: self.fab!.titleLabel!.font).width + CGFloat(65)
self.fab!.frame = CGRect.init(x: (size.width / 2) - (width / 2), y: -20, width: width, height: CGFloat(45))
self.fab!.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 20, bottom: 0, right: 20)
if single {
self.navigationController?.toolbar.addSubview(self.fab!)
} else {
self.parentController?.toolbar?.addSubview(self.fab!)
self.parentController?.menuNav?.callbacks.didBeginPanning = {
if !(self.fab?.isHidden ?? true) && !self.isHiding {
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
}, completion: { _ in
self.fab?.isHidden = true
self.isHiding = false
})
}
}
self.parentController?.menuNav?.callbacks.didCollapse = {
self.fab?.isHidden = false
self.fab?.transform = CGAffineTransform.identity.scaledBy(x: 0.001, y: 0.001)
UIView.animate(withDuration: 0.25, delay: 0.25, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity
}, completion: { _ in
})
}
}
self.fab?.transform = CGAffineTransform.init(scaleX: 0.001, y: 0.001)
UIView.animate(withDuration: 0.25, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.2, options: .curveEaseInOut, animations: {
self.fab?.transform = CGAffineTransform.identity
}, completion: { (_) in
self.fab?.addTarget(self, action: #selector(self.doFabActions), for: .touchUpInside)
self.fab?.addLongTapGestureRecognizer {
self.changeFab()
}
})
}
}
@objc func doFabActions() {
if UserDefaults.standard.bool(forKey: "FAB_SHOWN") == false {
let a = UIAlertController(title: "Subreddit Action Button", message: "This is the subreddit action button!\n\nThis button's actions can be customized by long pressing on it at any time, and this button can be removed completely in Settings > General.", preferredStyle: .alert)
a.addAction(UIAlertAction(title: "Change action", style: .default, handler: { (_) in
UserDefaults.standard.set(true, forKey: "FAB_SHOWN")
UserDefaults.standard.synchronize()
self.changeFab()
}))
a.addAction(UIAlertAction(title: "Hide button", style: .default, handler: { (_) in
SettingValues.hiddenFAB = true
UserDefaults.standard.set(true, forKey: SettingValues.pref_hiddenFAB)
UserDefaults.standard.set(true, forKey: "FAB_SHOWN")
UserDefaults.standard.synchronize()
self.setupFab(self.view.bounds.size)
}))
a.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (_) in
UserDefaults.standard.set(true, forKey: "FAB_SHOWN")
UserDefaults.standard.synchronize()
self.doFabActions()
}))
self.present(a, animated: true, completion: nil)
} else {
switch SettingValues.fabType {
case .SIDEBAR:
self.doDisplaySidebar()
case .NEW_POST:
self.newPost(self.fab!)
case .SHADOWBOX:
self.shadowboxMode()
case .RELOAD:
self.refresh()
case .HIDE_READ:
self.hideReadPosts()
case .HIDE_PERMANENTLY:
self.hideReadPostsPermanently()
case .GALLERY:
self.galleryMode()
case .SEARCH:
self.search()
}
}
}
var headerImage: URL?
func loadBubbles() {
self.subLinks.removeAll()
if self.sub == ("all") || self.sub == ("frontpage") || self.sub == ("popular") || self.sub == ("friends") || self.sub.lowercased() == ("myrandom") || self.sub.lowercased() == ("random") || self.sub.lowercased() == ("randnsfw") || self.sub.hasPrefix("/m/") || self.sub.contains("+") {
return
}
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.getStyles(sub, completion: { (result) in
switch result {
case .failure(let error):
print(error)
return
case .success(let r):
if let baseData = r as? JSONDictionary, let data = baseData["data"] as? [String: Any] {
if let content = data["content"] as? [String: Any],
let widgets = content["widgets"] as? [String: Any],
let items = widgets["items"] as? [String: Any] {
for item in items.values {
if let body = item as? [String: Any] {
if let kind = body["kind"] as? String, kind == "menu" {
if let data = body["data"] as? JSONArray {
for link in data {
if let children = link["children"] as? JSONArray {
for subItem in children {
if let content = subItem as? JSONDictionary {
self.subLinks.append(SubLinkItem(content["text"] as? String, link: URL(string: (content["url"] as! String).decodeHTML())))
}
}
} else {
self.subLinks.append(SubLinkItem(link["text"] as? String, link: URL(string: (link["url"] as! String).decodeHTML())))
}
}
}
}
}
}
}
if let styles = data["style"] as? [String: Any] {
if let headerUrl = styles["bannerBackgroundImage"] as? String {
self.headerImage = URL(string: headerUrl.unescapeHTML)
}
}
}
DispatchQueue.main.async {
self.hasHeader = true
if self.loaded && !self.loading {
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
if UIDevice.current.userInterfaceIdiom != .pad {
var newOffset = self.tableView.contentOffset
newOffset.y -= self.headerHeight(false)
self.tableView.setContentOffset(newOffset, animated: false)
}
}
}
}
})
} catch {
}
}
func changeFab() {
if !UserDefaults.standard.bool(forKey: "FAB_SHOWN") {
UserDefaults.standard.set(true, forKey: "FAB_SHOWN")
UserDefaults.standard.synchronize()
}
let actionSheetController: UIAlertController = UIAlertController(title: "Change button type", message: "", preferredStyle: .alert)
actionSheetController.addCancelButton()
for t in SettingValues.FabType.cases {
let saveActionButton: UIAlertAction = UIAlertAction(title: t.getTitle(), style: .default) { _ -> Void in
UserDefaults.standard.set(t.rawValue, forKey: SettingValues.pref_fabType)
SettingValues.fabType = t
self.setupFab(self.view.bounds.size)
}
actionSheetController.addAction(saveActionButton)
}
self.present(actionSheetController, animated: true, completion: nil)
}
var lastVersion = 0
func reloadNeedingColor() {
tableView.backgroundColor = ColorUtil.theme.backgroundColor
inHeadView?.backgroundColor = ColorUtil.getColorForSub(sub: sub, true)
if SettingValues.fullyHideNavbar {
inHeadView?.backgroundColor = .clear
}
refreshControl.tintColor = ColorUtil.theme.fontColor
refreshControl.attributedTitle = NSAttributedString(string: "")
refreshControl.addTarget(self, action: #selector(self.drefresh(_:)), for: UIControl.Event.valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
tableView.alwaysBounceVertical = true
self.automaticallyAdjustsScrollViewInsets = false
// TODO: Can just use .self instead of .classForCoder()
self.tableView.register(BannerLinkCellView.classForCoder(), forCellWithReuseIdentifier: "banner\(SingleSubredditViewController.cellVersion)")
self.tableView.register(AutoplayBannerLinkCellView.classForCoder(), forCellWithReuseIdentifier: "autoplay\(SingleSubredditViewController.cellVersion)")
self.tableView.register(ThumbnailLinkCellView.classForCoder(), forCellWithReuseIdentifier: "thumb\(SingleSubredditViewController.cellVersion)")
self.tableView.register(TextLinkCellView.classForCoder(), forCellWithReuseIdentifier: "text\(SingleSubredditViewController.cellVersion)")
self.tableView.register(LoadingCell.classForCoder(), forCellWithReuseIdentifier: "loading")
self.tableView.register(ReadLaterCell.classForCoder(), forCellWithReuseIdentifier: "readlater")
self.tableView.register(PageCell.classForCoder(), forCellWithReuseIdentifier: "page")
self.tableView.register(LinksHeaderCellView.classForCoder(), forCellWithReuseIdentifier: "header")
lastVersion = SingleSubredditViewController.cellVersion
var top = 68
if #available(iOS 11.0, *) {
top += 20
}
self.tableView.contentInset = UIEdgeInsets.init(top: CGFloat(top), left: 0, bottom: 65, right: 0)
session = (UIApplication.shared.delegate as! AppDelegate).session
if (SingleSubredditViewController.firstPresented && !single && self.links.count == 0) || (self.links.count == 0 && !single && !SettingValues.subredditBar) {
load(reset: true)
SingleSubredditViewController.firstPresented = false
}
self.sort = SettingValues.getLinkSorting(forSubreddit: self.sub)
self.time = SettingValues.getTimePeriod(forSubreddit: self.sub)
let offline = MainViewController.isOffline
if single && !offline {
let sort = UIButton.init(type: .custom)
sort.setImage(UIImage.init(named: "ic_sort_white")?.navIcon(), for: UIControl.State.normal)
sort.addTarget(self, action: #selector(self.showSortMenu(_:)), for: UIControl.Event.touchUpInside)
sort.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let sortB = UIBarButtonItem.init(customView: sort)
subb = UIButton.init(type: .custom)
subb.setImage(UIImage.init(named: Subscriptions.subreddits.contains(sub) ? "subbed" : "addcircle")?.navIcon(), for: UIControl.State.normal)
subb.addTarget(self, action: #selector(self.subscribeSingle(_:)), for: UIControl.Event.touchUpInside)
subb.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let subbB = UIBarButtonItem.init(customView: subb)
let info = UIButton.init(type: .custom)
info.setImage(UIImage.init(named: "info")?.toolbarIcon(), for: UIControl.State.normal)
info.addTarget(self, action: #selector(self.doDisplaySidebar), for: UIControl.Event.touchUpInside)
info.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let infoB = UIBarButtonItem.init(customView: info)
more = UIButton.init(type: .custom)
more.setImage(UIImage.init(named: "moreh")?.menuIcon(), for: UIControl.State.normal)
more.addTarget(self, action: #selector(self.showMoreNone(_:)), for: UIControl.Event.touchUpInside)
more.frame = CGRect.init(x: 0, y: 0, width: 25, height: 25)
let moreB = UIBarButtonItem.init(customView: more)
navigationItem.rightBarButtonItems = [sortB]
let flexButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
toolbarItems = [infoB, flexButton, moreB]
title = sub
if !loaded {
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.about(sub, completion: { (result) in
switch result {
case .failure:
print(result.error!.description)
DispatchQueue.main.async {
if self.sub == ("all") || self.sub == ("frontpage") || self.sub == ("popular") || self.sub == ("friends") || self.sub.lowercased() == ("myrandom") || self.sub.lowercased() == ("random") || self.sub.lowercased() == ("randnsfw") || self.sub.hasPrefix("/m/") || self.sub.contains("+") {
self.load(reset: true)
self.loadBubbles()
} else {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
let alert = UIAlertController.init(title: "Subreddit not found", message: "r/\(self.sub) could not be found, is it spelled correctly?", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .default, handler: { (_) in
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
case .success(let r):
self.subInfo = r
DispatchQueue.main.async {
if self.subInfo!.over18 && !SettingValues.nsfwEnabled {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
let alert = UIAlertController.init(title: "r/\(self.sub) is NSFW", message: "You must log into Reddit and enable NSFW content at Reddit.com to view this subreddit", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .default, handler: { (_) in
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
} else {
if self.sub != ("all") && self.sub != ("frontpage") && !self.sub.hasPrefix("/m/") {
if SettingValues.saveHistory {
if SettingValues.saveNSFWHistory && self.subInfo!.over18 {
Subscriptions.addHistorySub(name: AccountController.currentName, sub: self.subInfo!.displayName)
} else if !self.subInfo!.over18 {
Subscriptions.addHistorySub(name: AccountController.currentName, sub: self.subInfo!.displayName)
}
}
}
self.load(reset: true)
self.loadBubbles()
}
}
}
})
} catch {
}
}
} else if offline && single && !loaded {
title = sub
self.navigationController?.setToolbarHidden(true, animated: false)
self.load(reset: true)
}
}
func exit() {
self.navigationController?.popViewController(animated: true)
if self.navigationController!.modalPresentationStyle == .pageSheet {
self.navigationController!.dismiss(animated: true, completion: nil)
}
}
func doDisplayMultiSidebar(_ sub: Multireddit) {
VCPresenter.presentModally(viewController: ManageMultireddit(multi: sub, reloadCallback: {
self.refresh()
}), self)
}
@objc func subscribeSingle(_ selector: AnyObject) {
if subChanged && !Subscriptions.isSubscriber(sub) || Subscriptions.isSubscriber(sub) {
//was not subscriber, changed, and unsubscribing again
Subscriptions.unsubscribe(sub, session: session!)
subChanged = false
BannerUtil.makeBanner(text: "Unsubscribed", color: ColorUtil.accentColorForSub(sub: sub), seconds: 3, context: self, top: true)
subb.setImage(UIImage.init(named: "addcircle")?.navIcon(), for: UIControl.State.normal)
} else {
let alrController = UIAlertController.init(title: "Follow r/\(sub)", message: nil, preferredStyle: .alert)
if AccountController.isLoggedIn {
let somethingAction = UIAlertAction(title: "Subscribe", style: UIAlertAction.Style.default, handler: { (_: UIAlertAction!) in
Subscriptions.subscribe(self.sub, true, session: self.session!)
self.subChanged = true
BannerUtil.makeBanner(text: "Subscribed to r/\(self.sub)", color: ColorUtil.accentColorForSub(sub: self.sub), seconds: 3, context: self, top: true)
self.subb.setImage(UIImage.init(named: "subbed")?.navIcon(), for: UIControl.State.normal)
})
alrController.addAction(somethingAction)
}
let somethingAction = UIAlertAction(title: "Casually subscribe", style: UIAlertAction.Style.default, handler: { (_: UIAlertAction!) in
Subscriptions.subscribe(self.sub, false, session: self.session!)
self.subChanged = true
BannerUtil.makeBanner(text: "r/\(self.sub) added to your subreddit list", color: ColorUtil.accentColorForSub(sub: self.sub), seconds: 3, context: self, top: true)
self.subb.setImage(UIImage.init(named: "subbed")?.navIcon(), for: UIControl.State.normal)
})
alrController.addAction(somethingAction)
alrController.addCancelButton()
self.present(alrController, animated: true, completion: {})
}
}
func displayMultiredditSidebar() {
do {
try (UIApplication.shared.delegate as! AppDelegate).session?.getMultireddit(Multireddit.init(name: sub.substring(3, length: sub.length - 3), user: AccountController.currentName), completion: { (result) in
switch result {
case .success(let r):
DispatchQueue.main.async {
self.doDisplayMultiSidebar(r)
}
default:
DispatchQueue.main.async {
BannerUtil.makeBanner(text: "Multireddit information not found", color: GMColor.red500Color(), seconds: 3, context: self)
}
}
})
} catch {
}
}
@objc func hideReadPosts() {
var indexPaths: [IndexPath] = []
var index = 0
var count = 0
self.lastTopItem = 0
for submission in links {
if History.getSeen(s: submission) {
indexPaths.append(IndexPath(row: count, section: 0))
links.remove(at: index)
} else {
index += 1
}
count += 1
}
//todo save realm
DispatchQueue.main.async {
if !indexPaths.isEmpty {
self.tableView.performBatchUpdates({
self.tableView.deleteItems(at: indexPaths)
}, completion: { (_) in
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
})
}
}
}
func hideReadPostsPermanently() {
var indexPaths: [IndexPath] = []
var toRemove: [RSubmission] = []
var index = 0
var count = 0
for submission in links {
if History.getSeen(s: submission) {
indexPaths.append(IndexPath(row: count, section: 0))
toRemove.append(submission)
links.remove(at: index)
} else {
index += 1
}
count += 1
}
//todo save realm
DispatchQueue.main.async {
if !indexPaths.isEmpty {
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.performBatchUpdates({
self.tableView.deleteItems(at: indexPaths)
}, completion: { (_) in
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
})
}
}
if let session = (UIApplication.shared.delegate as? AppDelegate)?.session {
if !indexPaths.isEmpty {
var hideString = ""
for item in toRemove {
hideString.append(item.getId() + ",")
}
hideString = hideString.substring(0, length: hideString.length - 1)
do {
try session.setHide(true, name: hideString) { (result) in
print(result)
}
} catch {
}
}
}
}
func resetColors() {
if single {
navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: sub, true)
}
setupFab(UIScreen.main.bounds.size)
if parentController != nil {
parentController?.colorChanged(ColorUtil.getColorForSub(sub: sub))
}
}
func reloadDataReset() {
self.flowLayout.reset(modal: self.presentingViewController != nil)
tableView.reloadData()
tableView.layoutIfNeeded()
setupFab(UIScreen.main.bounds.size)
}
var oldPosition: CGPoint = CGPoint.zero
@objc func search() {
let alert = DragDownAlertMenu(title: "Search", subtitle: sub, icon: nil, full: true)
let searchAction = {
if !AccountController.isLoggedIn {
let alert = UIAlertController(title: "Log in to search!", message: "You must be logged into Reddit to search", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .default, handler: nil))
VCPresenter.presentAlert(alert, parentVC: self)
} else {
let search = SearchViewController.init(subreddit: self.sub, searchFor: alert.getText() ?? "")
VCPresenter.showVC(viewController: search, popupIfPossible: true, parentNavigationController: self.navigationController, parentViewController: self)
}
}
let searchAllAction = {
if !AccountController.isLoggedIn {
let alert = UIAlertController(title: "Log in to search!", message: "You must be logged into Reddit to search", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Close", style: .default, handler: nil))
VCPresenter.presentAlert(alert, parentVC: self)
} else {
let search = SearchViewController.init(subreddit: "all", searchFor: alert.getText() ?? "")
VCPresenter.showVC(viewController: search, popupIfPossible: true, parentNavigationController: self.navigationController, parentViewController: self)
}
}
if sub != "all" && sub != "frontpage" && sub != "popular" && sub != "random" && sub != "randnsfw" && sub != "friends" && !sub.startsWith("/m/") {
alert.addTextInput(title: "Search in \(sub)", icon: nil, enabled: false, action: searchAction, inputPlaceholder: "What are you looking for?", inputIcon: UIImage(named: "search")!, textRequired: true, exitOnAction: true)
alert.addAction(title: "Search all of Reddit", icon: nil, enabled: true, action: searchAllAction)
} else {
alert.addTextInput(title: "Search all of Reddit", icon: nil, enabled: false, action: searchAllAction, inputPlaceholder: "What are you looking for?", inputIcon: UIImage(named: "search")!, textRequired: true, exitOnAction: true)
}
alert.show(self)
}
@objc func doDisplaySidebar() {
Sidebar.init(parent: self, subname: self.sub).displaySidebar()
}
func filterContent() {
let alert = AlertController(title: "Content to hide on", message: "r/\(sub)", preferredStyle: .alert)
let settings = Filter(subreddit: sub, parent: self)
alert.addChild(settings)
let filterView = settings.view!
settings.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
alert.setupTheme()
alert.attributedTitle = NSAttributedString(string: "Content to hide on", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 17), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor])
alert.attributedMessage = NSAttributedString(string: "r/\(sub)", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor])
alert.contentView.addSubview(filterView)
settings.didMove(toParent: alert)
filterView.verticalAnchors == alert.contentView.verticalAnchors
filterView.horizontalAnchors == alert.contentView.horizontalAnchors + 8
filterView.heightAnchor == CGFloat(50 * settings.tableView(settings.tableView, numberOfRowsInSection: 0))
alert.addCancelButton()
alert.addBlurView()
alert.addCancelButton()
present(alert, animated: true, completion: nil)
}
func galleryMode() {
if !VCPresenter.proDialogShown(feature: true, self) {
let controller = GalleryTableViewController()
var gLinks: [RSubmission] = []
for l in links {
if l.banner {
gLinks.append(l)
}
}
controller.setLinks(links: gLinks)
controller.modalPresentationStyle = .overFullScreen
present(controller, animated: true, completion: nil)
}
}
func shadowboxMode() {
if !VCPresenter.proDialogShown(feature: true, self) && !links.isEmpty && !self.loading && self.loaded {
let visibleRect = CGRect(origin: tableView.contentOffset, size: tableView.bounds.size)
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
let visibleIndexPath = tableView.indexPathForItem(at: visiblePoint)
let controller = ShadowboxViewController.init(submissions: links, subreddit: sub, index: visibleIndexPath?.row ?? 0, paginator: paginator, sort: sort, time: time)
controller.modalPresentationStyle = .overFullScreen
present(controller, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadMore() {
if !showing {
showLoader()
}
load(reset: false)
}
func showLoader() {
showing = true
//todo maybe?
}
@objc func showSortMenu(_ selector: UIView?) {
let actionSheetController = DragDownAlertMenu(title: "Sorting", subtitle: "", icon: nil, themeColor: ColorUtil.accentColorForSub(sub: sub), full: true)
let selected = UIImage.init(named: "selected")!.getCopy(withSize: .square(size: 20), withColor: .blue)
for link in LinkSortType.cases {
actionSheetController.addAction(title: link.description, icon: sort == link ? selected : nil) {
self.showTimeMenu(s: link, selector: selector)
}
}
actionSheetController.show(self)
}
func showTimeMenu(s: LinkSortType, selector: UIView?) {
if s == .hot || s == .new || s == .rising || s == .best {
sort = s
refresh()
return
} else {
let actionSheetController = DragDownAlertMenu(title: "Select a time period", subtitle: "", icon: nil, themeColor: ColorUtil.accentColorForSub(sub: sub), full: true)
for t in TimeFilterWithin.cases {
actionSheetController.addAction(title: t.param, icon: nil) {
self.sort = s
self.time = t
self.refresh()
}
}
actionSheetController.show(self)
}
}
@objc func refresh(_ indicator: Bool = true) {
if indicator {
self.tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.contentOffset.y - (self.refreshControl!.frame.size.height)), animated: true)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
self.refreshControl?.beginRefreshing()
})
}
links = []
self.flowLayout.reset(modal: self.presentingViewController != nil)
flowLayout.invalidateLayout()
UIView.transition(with: self.tableView, duration: 0.10, options: .transitionCrossDissolve, animations: {
self.tableView.reloadData()
}, completion: nil)
load(reset: true)
}
func deleteSelf(_ cell: LinkCellView) {
do {
try session?.deleteCommentOrLink(cell.link!.getId(), completion: { (_) in
DispatchQueue.main.async {
if self.navigationController!.modalPresentationStyle == .formSheet {
self.navigationController!.dismiss(animated: true)
} else {
self.navigationController!.popViewController(animated: true)
}
}
})
} catch {
}
}
var page = 0
var reset = false
var tries = 0
func load(reset: Bool) {
self.reset = reset
PagingCommentViewController.savedComment = nil
LinkCellView.checkedWifi = false
if sub.lowercased() == "randnsfw" && !SettingValues.nsfwEnabled {
DispatchQueue.main.async {
let alert = UIAlertController.init(title: "r/\(self.sub) is NSFW", message: "You must log into Reddit and enable NSFW content at Reddit.com to view this subreddit", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .default, handler: { (_) in
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
self.refreshControl.endRefreshing()
return
} else if sub.lowercased() == "myrandom" && !AccountController.isGold {
DispatchQueue.main.async {
let alert = UIAlertController.init(title: "r/\(self.sub) requires gold", message: "See reddit.com/gold/about for more details", preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Close", style: .default, handler: { (_) in
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
self.refreshControl.endRefreshing()
return
}
if !loading {
if !loaded {
if indicator == nil {
indicator = MDCActivityIndicator.init(frame: CGRect.init(x: CGFloat(0), y: CGFloat(0), width: CGFloat(80), height: CGFloat(80)))
indicator?.strokeWidth = 5
indicator?.radius = 15
indicator?.indicatorMode = .indeterminate
indicator?.cycleColors = [ColorUtil.getColorForSub(sub: sub), ColorUtil.accentColorForSub(sub: sub)]
self.view.addSubview(indicator!)
indicator!.centerAnchors == self.view.centerAnchors
indicator?.startAnimating()
}
}
do {
loading = true
if reset {
paginator = Paginator()
self.page = 0
self.lastTopItem = 0
}
if reset || !loaded {
self.startTime = Date()
}
var subreddit: SubredditURLPath = Subreddit.init(subreddit: sub)
if sub.hasPrefix("/m/") {
subreddit = Multireddit.init(name: sub.substring(3, length: sub.length - 3), user: AccountController.currentName)
}
if sub.contains("/u/") {
subreddit = Multireddit.init(name: sub.split("/")[3], user: sub.split("/")[1])
}
try session?.getList(paginator, subreddit: subreddit, sort: sort, timeFilterWithin: time, completion: { (result) in
self.loaded = true
self.reset = false
switch result {
case .failure:
print(result.error!)
//test if realm exists and show that
print("Getting realm data")
DispatchQueue.main.async {
do {
let realm = try Realm()
var updated = NSDate()
if let listing = realm.objects(RListing.self).filter({ (item) -> Bool in
return item.subreddit == self.sub
}).first {
self.links = []
for i in listing.links {
self.links.append(i)
}
updated = listing.updated
}
var paths = [IndexPath]()
for i in 0..<self.links.count {
paths.append(IndexPath.init(item: i, section: 0))
}
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.indicator?.stopAnimating()
self.indicator?.isHidden = true
self.loading = false
self.loading = false
self.nomore = true
self.offline = true
var top = CGFloat(0)
if #available(iOS 11, *) {
top += 26
if UIDevice.current.userInterfaceIdiom == .pad || !self.hasTopNotch {
top -= 18
}
}
let navoffset = (-1 * ( (self.navigationController?.navigationBar.frame.size.height ?? 64)))
self.tableView.contentOffset = CGPoint.init(x: 0, y: -18 + navoffset - top)
if self.tries < 1 {
self.tries += 1
self.load(reset: true)
} else {
if self.links.isEmpty {
BannerUtil.makeBanner(text: "No offline content found! You can set up subreddit caching in Settings > Auto Cache", color: ColorUtil.accentColorForSub(sub: self.sub), seconds: 5, context: self)
} else {
self.navigationItem.titleView = self.setTitle(title: self.sub, subtitle: "Content \(DateFormatter().timeSince(from: updated, numericDates: true)) old")
}
}
UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: self.tableView)
} catch {
}
}
case .success(let listing):
self.tries = 0
if reset {
self.links = []
self.page = 0
}
self.offline = false
let before = self.links.count
if self.realmListing == nil {
self.realmListing = RListing()
self.realmListing!.subreddit = self.sub
self.realmListing!.updated = NSDate()
}
if reset && self.realmListing!.links.count > 0 {
self.realmListing!.links.removeAll()
}
let newLinks = listing.children.compactMap({ $0 as? Link })
var converted: [RSubmission] = []
for link in newLinks {
let newRS = RealmDataWrapper.linkToRSubmission(submission: link)
converted.append(newRS)
CachedTitle.addTitle(s: newRS)
}
var values = PostFilter.filter(converted, previous: self.links, baseSubreddit: self.sub).map { $0 as! RSubmission }
if self.page > 0 && !values.isEmpty && SettingValues.showPages {
let pageItem = RSubmission()
pageItem.subreddit = DateFormatter().timeSince(from: self.startTime as NSDate, numericDates: true)
pageItem.author = "PAGE_SEPARATOR"
pageItem.title = "Page \(self.page + 1)\n\(self.links.count + values.count - self.page) posts"
values.insert(pageItem, at: 0)
}
self.page += 1
self.links += values
self.paginator = listing.paginator
self.nomore = !listing.paginator.hasMore() || values.isEmpty
do {
let realm = try Realm()
//todo insert
try realm.beginWrite()
for submission in self.links {
if submission.author != "PAGE_SEPARATOR" {
realm.create(type(of: submission), value: submission, update: true)
if let listing = self.realmListing {
listing.links.append(submission)
}
}
}
realm.create(type(of: self.realmListing!), value: self.realmListing!, update: true)
try realm.commitWrite()
} catch {
}
self.preloadImages(values)
DispatchQueue.main.async {
if self.links.isEmpty {
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.indicator?.stopAnimating()
self.indicator?.isHidden = true
self.loading = false
if MainViewController.first {
MainViewController.first = false
self.parentController?.checkForMail()
}
if listing.children.isEmpty {
BannerUtil.makeBanner(text: "No posts found!\nMake sure this sub exists and you have permission to view it", color: GMColor.red500Color(), seconds: 5, context: self)
} else {
BannerUtil.makeBanner(text: "No posts found!\nCheck your filter settings, or tap here to reload.", color: GMColor.red500Color(), seconds: 5, context: self) {
self.refresh()
}
}
} else {
self.oldPosition = CGPoint.zero
var paths = [IndexPath]()
for i in before..<self.links.count {
paths.append(IndexPath.init(item: i + self.headerOffset(), section: 0))
}
if before == 0 {
self.flowLayout.invalidateLayout()
UIView.transition(with: self.tableView, duration: 0.15, options: .transitionCrossDissolve, animations: {
self.tableView.reloadData()
}, completion: nil)
var top = CGFloat(0)
if #available(iOS 11, *) {
top += 26
if UIDevice.current.userInterfaceIdiom == .pad || !self.hasTopNotch {
top -= 18
}
}
let navoffset = (-1 * ( (self.navigationController?.navigationBar.frame.size.height ?? 64)))
let headerHeight = (UIDevice.current.userInterfaceIdiom == .pad ? 0 : self.headerHeight(false))
self.tableView.contentOffset = CGPoint.init(x: 0, y: -18 + navoffset - top + headerHeight)
} else {
self.flowLayout.invalidateLayout()
self.tableView.insertItems(at: paths)
}
self.tableView.isUserInteractionEnabled = true
self.indicator?.stopAnimating()
self.indicator?.isHidden = true
self.refreshControl.endRefreshing()
self.loading = false
if MainViewController.first {
MainViewController.first = false
self.parentController?.checkForMail()
}
}
// UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: self.tableView)
}
}
})
} catch {
print(error)
}
}
}
var hasTopNotch: Bool {
if #available(iOS 11.0, *) {
return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 20
}
return false
}
func preloadImages(_ values: [RSubmission]) {
var urls: [URL] = []
if !SettingValues.noImages && !(SettingValues.dataSavingDisableWiFi && LinkCellView.checkWiFi()) && SettingValues.dataSavingEnabled {
for submission in values {
var thumb = submission.thumbnail
var big = submission.banner
var height = submission.height
if submission.url != nil {
var type = ContentType.getContentType(baseUrl: submission.url)
if submission.isSelf {
type = .SELF
}
if thumb && type == .SELF {
thumb = false
}
let fullImage = ContentType.fullImage(t: type)
if !fullImage && height < 75 {
big = false
thumb = true
} else if big && (SettingValues.postImageMode == .CROPPED_IMAGE) {
height = 200
}
if type == .SELF && SettingValues.hideImageSelftext || SettingValues.hideImageSelftext && !big || type == .SELF {
big = false
thumb = false
}
if height < 75 {
thumb = true
big = false
}
let shouldShowLq = SettingValues.dataSavingEnabled && submission.lQ && !(SettingValues.dataSavingDisableWiFi && LinkCellView.checkWiFi())
if type == ContentType.CType.SELF && SettingValues.hideImageSelftext
|| SettingValues.noImages && submission.isSelf {
big = false
thumb = false
}
if big || !submission.thumbnail {
thumb = false
}
if !big && !thumb && submission.type != .SELF && submission.type != .NONE {
thumb = true
}
if thumb && !big {
if submission.thumbnailUrl == "nsfw" {
} else if submission.thumbnailUrl == "web" || submission.thumbnailUrl.isEmpty {
} else {
if let url = URL.init(string: submission.thumbnailUrl) {
urls.append(url)
}
}
}
if big {
if shouldShowLq {
if let url = URL.init(string: submission.lqUrl) {
urls.append(url)
}
} else {
if let url = URL.init(string: submission.bannerUrl) {
urls.append(url)
}
}
}
}
}
SDWebImagePrefetcher.shared.prefetchURLs(urls)
}
}
static func sizeWith(_ submission: RSubmission, _ width: CGFloat, _ isCollection: Bool) -> CGSize {
let itemWidth = width
var thumb = submission.thumbnail
var big = submission.banner
var submissionHeight = CGFloat(submission.height)
var type = ContentType.getContentType(baseUrl: submission.url)
if submission.isSelf {
type = .SELF
}
if SettingValues.postImageMode == .THUMBNAIL {
big = false
thumb = true
}
let fullImage = ContentType.fullImage(t: type)
if !fullImage && submissionHeight < 75 {
big = false
thumb = true
} else if big && (( SettingValues.postImageMode == .CROPPED_IMAGE)) && !(SettingValues.shouldAutoPlay() && (ContentType.displayVideo(t: type) && type != .VIDEO)) {
submissionHeight = 200
} else if big {
let h = getHeightFromAspectRatio(imageHeight: submissionHeight, imageWidth: CGFloat(submission.width), viewWidth: itemWidth - ((SettingValues.postViewMode != .CARD) ? CGFloat(5) : CGFloat(0)))
if h == 0 {
submissionHeight = 200
} else {
submissionHeight = h
}
}
if type == .SELF && SettingValues.hideImageSelftext || SettingValues.hideImageSelftext && !big {
big = false
thumb = false
}
if submissionHeight < 75 {
thumb = true
big = false
}
if type == ContentType.CType.SELF && SettingValues.hideImageSelftext
|| SettingValues.noImages && submission.isSelf {
big = false
thumb = false
}
if big || !submission.thumbnail {
thumb = false
}
if (thumb || big) && submission.nsfw && (!SettingValues.nsfwPreviews || SettingValues.hideNSFWCollection && isCollection) {
big = false
thumb = true
}
if SettingValues.noImages && !(SettingValues.dataSavingDisableWiFi && LinkCellView.checkWiFi()) && SettingValues.dataSavingEnabled {
big = false
thumb = false
}
if thumb && type == .SELF {
thumb = false
}
if !big && !thumb && submission.type != .SELF && submission.type != .NONE { //If a submission has a link but no images, still show the web thumbnail
thumb = true
}
if type == .LINK && SettingValues.linkAlwaysThumbnail {
thumb = true
big = false
}
if (thumb || big) && submission.spoiler {
thumb = true
big = false
}
if big {
let imageSize = CGSize.init(width: submission.width, height: ((SettingValues.postImageMode == .CROPPED_IMAGE) && !(SettingValues.shouldAutoPlay() && (ContentType.displayVideo(t: type) && type != .VIDEO)) ? 200 : submission.height))
var aspect = imageSize.width / imageSize.height
if aspect == 0 || aspect > 10000 || aspect.isNaN {
aspect = 1
}
if SettingValues.postImageMode == .CROPPED_IMAGE && !(SettingValues.shouldAutoPlay() && (ContentType.displayVideo(t: type) && type != .VIDEO)) {
aspect = width / 200
if aspect == 0 || aspect > 10000 || aspect.isNaN {
aspect = 1
}
submissionHeight = 200
}
}
var paddingTop = CGFloat(0)
var paddingBottom = CGFloat(2)
var paddingLeft = CGFloat(0)
var paddingRight = CGFloat(0)
var innerPadding = CGFloat(0)
if SettingValues.postViewMode == .CARD || SettingValues.postViewMode == .CENTER {
paddingTop = 5
paddingBottom = 5
paddingLeft = 5
paddingRight = 5
}
let actionbar = CGFloat(!SettingValues.actionBarMode.isFull() ? 0 : 24)
let thumbheight = (SettingValues.largerThumbnail ? CGFloat(75) : CGFloat(50)) - (SettingValues.postViewMode == .COMPACT ? 15 : 0)
let textHeight = CGFloat(submission.isSelf ? 5 : 0)
if thumb {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between top and thumbnail
if SettingValues.actionBarMode.isFull() {
innerPadding += 18 - (SettingValues.postViewMode == .COMPACT ? 4 : 0) //between label and bottom box
innerPadding += (SettingValues.postViewMode == .COMPACT ? 4 : 8) //between box and end
} else {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between thumbnail and bottom
}
} else if big {
if SettingValues.postViewMode == .CENTER {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 16) //between label
if SettingValues.actionBarMode.isFull() {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between banner and box
} else {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between buttons and bottom
}
} else {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 4 : 8) //between banner and label
if SettingValues.actionBarMode.isFull() {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between label and box
} else {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between buttons and bottom
}
}
if SettingValues.actionBarMode.isFull() {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 4 : 8) //between box and end
}
} else {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between top and title
if SettingValues.actionBarMode.isFull() {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between body and box
innerPadding += (SettingValues.postViewMode == .COMPACT ? 4 : 8) //between box and end
} else {
innerPadding += (SettingValues.postViewMode == .COMPACT ? 4 : 8) //between title and bottom
}
}
var estimatedUsableWidth = itemWidth - paddingLeft - paddingRight
if thumb {
estimatedUsableWidth -= thumbheight //is the same as the width
estimatedUsableWidth -= (SettingValues.postViewMode == .COMPACT ? 16 : 24) //between edge and thumb
estimatedUsableWidth -= (SettingValues.postViewMode == .COMPACT ? 8 : 12) //between thumb and label
} else if SettingValues.actionBarMode.isFull() || SettingValues.actionBarMode == .NONE {
estimatedUsableWidth -= (SettingValues.postViewMode == .COMPACT ? 16 : 24) //title label padding
}
if SettingValues.postImageMode == .CROPPED_IMAGE && !(SettingValues.shouldAutoPlay() && (ContentType.displayVideo(t: type) && type != .VIDEO)) {
submissionHeight = 200
} else {
let bannerPadding = (SettingValues.postViewMode != .CARD) ? CGFloat(5) : CGFloat(0)
submissionHeight = getHeightFromAspectRatio(imageHeight: submissionHeight == 200 ? CGFloat(200) : CGFloat(submission.height), imageWidth: CGFloat(submission.width), viewWidth: width - paddingLeft - paddingRight - (bannerPadding * 2))
}
var imageHeight = big && !thumb ? CGFloat(submissionHeight) : CGFloat(0)
if thumb {
imageHeight = thumbheight
}
if SettingValues.actionBarMode.isSide() {
estimatedUsableWidth -= 40
estimatedUsableWidth -= (SettingValues.postViewMode == .COMPACT ? 8 : 16) //buttons horizontal margins
if thumb {
estimatedUsableWidth += (SettingValues.postViewMode == .COMPACT ? 16 : 24) //between edge and thumb no longer exists
estimatedUsableWidth -= (SettingValues.postViewMode == .COMPACT ? 4 : 8) //buttons buttons and thumb
}
}
let size = CGSize(width: estimatedUsableWidth, height: CGFloat.greatestFiniteMagnitude)
let layout = YYTextLayout(containerSize: size, text: CachedTitle.getTitle(submission: submission, full: false, false))!
let textSize = layout.textBoundingSize
let totalHeight = paddingTop + paddingBottom + (thumb ? max(SettingValues.actionBarMode.isSide() ? 72 : 0, ceil(textSize.height), imageHeight) : max(SettingValues.actionBarMode.isSide() ? 72 : 0, ceil(textSize.height)) + imageHeight) + innerPadding + actionbar + textHeight + CGFloat(5)
return CGSize(width: itemWidth, height: totalHeight)
}
// TODO: This is mostly replicated by `RSubmission.getLinkView()`. Can we consolidate?
static func cellType(forSubmission submission: RSubmission, _ isCollection: Bool, cellWidth: CGFloat) -> CurrentType {
var target: CurrentType = .none
var thumb = submission.thumbnail
var big = submission.banner
let height = CGFloat(submission.height)
var type = ContentType.getContentType(baseUrl: submission.url)
if submission.isSelf {
type = .SELF
}
if SettingValues.postImageMode == .THUMBNAIL {
big = false
thumb = true
}
let fullImage = ContentType.fullImage(t: type)
var submissionHeight = height
if !fullImage && submissionHeight < 75 {
big = false
thumb = true
} else if big && SettingValues.postImageMode == .CROPPED_IMAGE {
submissionHeight = 200
} else if big {
let h = getHeightFromAspectRatio(imageHeight: submissionHeight, imageWidth: CGFloat(submission.width), viewWidth: cellWidth)
if h == 0 {
submissionHeight = 200
} else {
submissionHeight = h
}
}
if type == .SELF && SettingValues.hideImageSelftext || SettingValues.hideImageSelftext && !big {
big = false
thumb = false
}
if submissionHeight < 75 {
thumb = true
big = false
}
if type == ContentType.CType.SELF && SettingValues.hideImageSelftext
|| SettingValues.noImages && submission.isSelf {
big = false
thumb = false
}
if big || !submission.thumbnail {
thumb = false
}
if SettingValues.noImages && !(SettingValues.dataSavingDisableWiFi && LinkCellView.checkWiFi()) && SettingValues.dataSavingEnabled {
big = false
thumb = false
}
if thumb && type == .SELF {
thumb = false
}
if !big && !thumb && submission.type != .SELF && submission.type != .NONE { //If a submission has a link but no images, still show the web thumbnail
thumb = true
}
if (thumb || big) && submission.nsfw && (!SettingValues.nsfwPreviews || (SettingValues.hideNSFWCollection && isCollection)) {
big = false
thumb = true
}
if (thumb || big) && submission.spoiler {
thumb = true
big = false
}
if thumb && !big {
target = .thumb
} else if big {
if SettingValues.autoPlayMode != .NEVER && (ContentType.displayVideo(t: type) && type != .VIDEO) {
target = .autoplay
} else {
target = .banner
}
} else {
target = .text
}
if big && submissionHeight < 75 {
target = .thumb
}
if type == .LINK && SettingValues.linkAlwaysThumbnail {
target = .thumb
}
return target
}
var loop: SelectorEventLoop?
var server: DefaultHTTPServer?
func addToHomescreen() {
DispatchQueue.global(qos: .background).async { () -> Void in
self.loop = try! SelectorEventLoop(selector: try! KqueueSelector())
self.server = DefaultHTTPServer(eventLoop: self.loop!, port: 8080) { (_, startResponse: ((String, [(String, String)]) -> Void), sendBody: ((Data) -> Void)
) in
// Start HTTP response
startResponse("200 OK", [])
let sub = ColorUtil.getColorForSub(sub: self.sub)
let lighterSub = sub.add(overlay: UIColor.white.withAlphaComponent(0.4))
var coloredIcon = UIImage.convertGradientToImage(colors: [lighterSub, sub], frame: CGSize.square(size: 150))
coloredIcon = coloredIcon.overlayWith(image: UIImage(named: "slideoverlay")!.getCopy(withSize: CGSize.square(size: 150)), posX: 0, posY: 0)
let imageData: Data = coloredIcon.pngData()!
let base64String = imageData.base64EncodedString()
// send EOF
let baseHTML = Bundle.main.url(forResource: "html", withExtension: nil)!
var htmlString = try! String.init(contentsOf: baseHTML, encoding: String.Encoding.utf8)
htmlString = htmlString.replacingOccurrences(of: "{{subname}}", with: self.sub)
htmlString = htmlString.replacingOccurrences(of: "{{subcolor}}", with: ColorUtil.getColorForSub(sub: self.sub).toHexString())
htmlString = htmlString.replacingOccurrences(of: "{{subicon}}", with: base64String)
print(htmlString)
let bodyString = htmlString.toBase64()
sendBody(Data.init(base64Encoded: bodyString!)!)
sendBody(Data())
}
// Start HTTP server to listen on the port
do {
try self.server?.start()
} catch let error {
print(error)
self.server?.stop()
do {
try self.server?.start()
} catch {
}
}
// Run event loop
self.loop?.runForever()
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(URL.init(string: "http://[::1]:8080/foo-bar")!)
} else {
// Fallback on earlier versions
UIApplication.shared.openURL(URL.init(string: "http://[::1]:8080/foo-bar")!)
}
}
}
// MARK: - Actions
extension SingleSubredditViewController {
@objc func spacePressed() {
UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.tableView.contentOffset.y = min(self.tableView.contentOffset.y + 350, self.tableView.contentSize.height - self.tableView.frame.size.height)
}, completion: nil)
}
@objc func spacePressedUp() {
UIView.animate(withDuration: 0.2, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
self.tableView.contentOffset.y = max(self.tableView.contentOffset.y - 350, -64)
}, completion: nil)
}
@objc func drefresh(_ sender: AnyObject) {
refresh()
}
@objc func showMoreNone(_ sender: AnyObject) {
showMore(sender, parentVC: nil)
}
@objc func hideAll(_ sender: AnyObject) {
for submission in links {
if History.getSeen(s: submission) {
let index = links.index(of: submission)!
links.remove(at: index)
}
}
self.flowLayout.reset(modal: self.presentingViewController != nil)
tableView.reloadData()
}
@objc func pickTheme(sender: AnyObject?, parent: MainViewController?) {
parentController = parent
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
isAccent = false
let margin: CGFloat = 10.0
let rect = CGRect(x: margin, y: margin, width: UIScreen.main.traitCollection.userInterfaceIdiom == .pad ? 314 - margin * 4.0: alertController.view.bounds.size.width - margin * 4.0, height: 150)
let MKColorPicker = ColorPickerView.init(frame: rect)
MKColorPicker.scrollToPreselectedIndex = true
MKColorPicker.delegate = self
MKColorPicker.colors = GMPalette.allColor()
MKColorPicker.selectionStyle = .check
MKColorPicker.scrollDirection = .vertical
MKColorPicker.style = .circle
let baseColor = ColorUtil.getColorForSub(sub: sub).toHexString()
var index = 0
for color in GMPalette.allColor() {
if color.toHexString() == baseColor {
break
}
index += 1
}
MKColorPicker.preselectedIndex = index
alertController.view.addSubview(MKColorPicker)
/*todo maybe ?alertController.addAction(image: UIImage.init(named: "accent"), title: "Custom color", color: ColorUtil.accentColorForSub(sub: sub), style: .default, isEnabled: true) { (action) in
if(!VCPresenter.proDialogShown(feature: false, self)){
let alert = UIAlertController.init(title: "Choose a color", message: nil, preferredStyle: .actionSheet)
alert.addColorPicker(color: (self.navigationController?.navigationBar.barTintColor)!, selection: { (c) in
ColorUtil.setColorForSub(sub: self.sub, color: (self.navigationController?.navigationBar.barTintColor)!)
self.reloadDataReset()
self.navigationController?.navigationBar.barTintColor = c
UIApplication.shared.statusBarView?.backgroundColor = c
self.sideView.backgroundColor = c
self.add.backgroundColor = c
self.sideView.backgroundColor = c
if (self.parentController != nil) {
self.parentController?.colorChanged()
}
})
alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: { (action) in
self.pickTheme(sender: sender, parent: parent)
}))
self.present(alert, animated: true)
}
}*/
alertController.addAction(image: UIImage(named: "colors"), title: "Accent color", color: ColorUtil.accentColorForSub(sub: sub), style: .default) { _ in
ColorUtil.setColorForSub(sub: self.sub, color: self.primaryChosen ?? ColorUtil.baseColor)
self.pickAccent(sender: sender, parent: parent)
if self.parentController != nil {
self.parentController?.colorChanged(ColorUtil.getColorForSub(sub: self.sub))
}
self.reloadDataReset()
}
alertController.addAction(image: nil, title: "Save", color: ColorUtil.accentColorForSub(sub: sub), style: .default) { _ in
ColorUtil.setColorForSub(sub: self.sub, color: self.primaryChosen ?? ColorUtil.baseColor)
self.reloadDataReset()
if self.parentController != nil {
self.parentController?.colorChanged(ColorUtil.getColorForSub(sub: self.sub))
}
}
alertController.addCancelButton()
alertController.modalPresentationStyle = .popover
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = sender as! UIButton
presenter.sourceRect = (sender as! UIButton).bounds
}
present(alertController, animated: true, completion: nil)
}
func pickAccent(sender: AnyObject?, parent: MainViewController?) {
parentController = parent
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
isAccent = true
let margin: CGFloat = 10.0
let rect = CGRect(x: margin, y: margin, width: UIScreen.main.traitCollection.userInterfaceIdiom == .pad ? 314 - margin * 4.0: alertController.view.bounds.size.width - margin * 4.0, height: 150)
let MKColorPicker = ColorPickerView.init(frame: rect)
MKColorPicker.scrollToPreselectedIndex = true
MKColorPicker.delegate = self
MKColorPicker.colors = GMPalette.allColorAccent()
MKColorPicker.selectionStyle = .check
MKColorPicker.scrollDirection = .vertical
MKColorPicker.style = .circle
let baseColor = ColorUtil.accentColorForSub(sub: sub).toHexString()
var index = 0
for color in GMPalette.allColorAccent() {
if color.toHexString() == baseColor {
break
}
index += 1
}
MKColorPicker.preselectedIndex = index
alertController.view.addSubview(MKColorPicker)
alertController.addAction(image: UIImage(named: "palette"), title: "Primary color", color: ColorUtil.accentColorForSub(sub: sub), style: .default) { _ in
ColorUtil.setAccentColorForSub(sub: self.sub, color: self.accentChosen ?? ColorUtil.accentColorForSub(sub: self.sub))
self.pickTheme(sender: sender, parent: parent)
self.reloadDataReset()
}
alertController.addAction(image: nil, title: "Save", color: ColorUtil.accentColorForSub(sub: sub), style: .default) { _ in
ColorUtil.setAccentColorForSub(sub: self.sub, color: self.accentChosen!)
self.reloadDataReset()
if self.parentController != nil {
self.parentController?.colorChanged(ColorUtil.getColorForSub(sub: self.sub))
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (_: UIAlertAction!) in
self.resetColors()
})
alertController.addAction(cancelAction)
alertController.modalPresentationStyle = .popover
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = sender as! UIButton
presenter.sourceRect = (sender as! UIButton).bounds
}
present(alertController, animated: true, completion: nil)
}
@objc func newPost(_ sender: AnyObject) {
PostActions.showPostMenu(self, sub: self.sub)
}
@objc func showMore(_ sender: AnyObject, parentVC: MainViewController? = nil) {
let alertController = DragDownAlertMenu(title: "Subreddit options", subtitle: sub, icon: nil)
let special = !(sub != "all" && sub != "frontpage" && sub != "popular" && sub != "random" && sub != "randnsfw" && sub != "friends" && !sub.startsWith("/m/"))
alertController.addAction(title: "Search", icon: UIImage(named: "search")!.menuIcon()) {
self.search()
}
if single && !special {
alertController.addAction(title: Subscriptions.isSubscriber(self.sub) ? "Un-subscribe" : "Subscribe", icon: UIImage(named: Subscriptions.isSubscriber(self.sub) ? "subbed" : "addcircle")!.menuIcon()) {
self.subscribeSingle(sender)
}
}
alertController.addAction(title: "Sort (currently \(sort.path))", icon: UIImage(named: "filter")!.menuIcon()) {
self.showSortMenu(self.more)
}
if sub.contains("/m/") {
alertController.addAction(title: "Manage multireddit", icon: UIImage(named: "info")!.menuIcon()) {
self.displayMultiredditSidebar()
}
} else if !special {
alertController.addAction(title: "Show sidebar", icon: UIImage(named: "info")!.menuIcon()) {
self.doDisplaySidebar()
}
}
alertController.addAction(title: "Cache for offline viewing", icon: UIImage(named: "save-1")!.menuIcon()) {
_ = AutoCache.init(baseController: self, subs: [self.sub])
}
alertController.addAction(title: "Shadowbox", icon: UIImage(named: "shadowbox")!.menuIcon()) {
self.shadowboxMode()
}
alertController.addAction(title: "Hide read posts", icon: UIImage(named: "hide")!.menuIcon()) {
self.hideReadPosts()
}
alertController.addAction(title: "Refresh posts", icon: UIImage(named: "sync")!.menuIcon()) {
self.refresh()
}
alertController.addAction(title: "Gallery view", icon: UIImage(named: "image")!.menuIcon()) {
self.galleryMode()
}
alertController.addAction(title: "Custom theme for \(sub)", icon: UIImage(named: "colors")!.menuIcon()) {
if parentVC != nil {
let p = (parentVC!)
self.pickTheme(sender: sender, parent: p)
} else {
self.pickTheme(sender: sender, parent: nil)
}
}
if !special {
alertController.addAction(title: "Submit new post", icon: UIImage(named: "edit")!.menuIcon()) {
self.newPost(sender)
}
}
alertController.addAction(title: "Filter content from \(sub)", icon: UIImage(named: "filter")!.menuIcon()) {
if !self.links.isEmpty || self.loaded {
self.filterContent()
}
}
alertController.addAction(title: "Add homescreen shortcut", icon: UIImage(named: "add_homescreen")!.menuIcon()) {
self.addToHomescreen()
}
alertController.show(self)
}
}
// MARK: - Collection View Delegate
extension SingleSubredditViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if cell is AutoplayBannerLinkCellView && (cell as! AutoplayBannerLinkCellView).videoView != nil {
(cell as! AutoplayBannerLinkCellView).endVideos()
}
}
}
extension SingleSubredditViewController: UIScrollViewDelegate {
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
if scrollView.contentOffset.y > oldPosition.y {
oldPosition = scrollView.contentOffset
return true
} else {
tableView.setContentOffset(oldPosition, animated: true)
oldPosition = CGPoint.zero
}
return false
}
func markReadScroll() {
if SettingValues.markReadOnScroll {
let top = tableView.indexPathsForVisibleItems
print(top)
print(lastTopItem)
if !top.isEmpty {
let topItem = top[0].row - 1
if topItem > lastTopItem && topItem < links.count {
for item in lastTopItem..<topItem {
History.addSeen(s: links[item], skipDuplicates: true)
}
lastTopItem = topItem
}
}
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
markReadScroll()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
markReadScroll()
}
}
// MARK: - Collection View Data Source
extension SingleSubredditViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (loaded && (!loading || self.links.count > 0) ? headerOffset() : 0) + links.count + (loaded && !reset ? 1 : 0)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var row = indexPath.row
if row == 0 && hasHeader {
let cell = tableView.dequeueReusableCell(withReuseIdentifier: "header", for: indexPath) as! LinksHeaderCellView
cell.setLinks(links: self.subLinks, sub: self.sub, delegate: self)
return cell
}
if hasHeader {
row -= 1
}
if row >= self.links.count {
let cell = tableView.dequeueReusableCell(withReuseIdentifier: "loading", for: indexPath) as! LoadingCell
cell.loader.color = ColorUtil.theme.fontColor
cell.loader.startAnimating()
if !loading && !nomore {
self.loadMore()
}
return cell
}
let submission = self.links[row]
if submission.author == "PAGE_SEPARATOR" {
let cell = tableView.dequeueReusableCell(withReuseIdentifier: "page", for: indexPath) as! PageCell
let textParts = submission.title.components(separatedBy: "\n")
let finalText: NSMutableAttributedString!
if textParts.count > 1 {
let firstPart = NSMutableAttributedString.init(string: textParts[0], attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.boldSystemFont(ofSize: 16)]))
let secondPart = NSMutableAttributedString.init(string: "\n" + textParts[1], attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.systemFont(ofSize: 13)]))
firstPart.append(secondPart)
finalText = firstPart
} else {
finalText = NSMutableAttributedString.init(string: submission.title, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.boldSystemFont(ofSize: 14)]))
}
cell.time.font = UIFont.systemFont(ofSize: 12)
cell.time.textColor = ColorUtil.theme.fontColor
cell.time.alpha = 0.7
cell.time.text = submission.subreddit
cell.title.attributedText = finalText
return cell
}
var cell: LinkCellView!
if lastVersion != SingleSubredditViewController.cellVersion {
self.tableView.register(BannerLinkCellView.classForCoder(), forCellWithReuseIdentifier: "banner\(SingleSubredditViewController.cellVersion)")
self.tableView.register(AutoplayBannerLinkCellView.classForCoder(), forCellWithReuseIdentifier: "autoplay\(SingleSubredditViewController.cellVersion)")
self.tableView.register(ThumbnailLinkCellView.classForCoder(), forCellWithReuseIdentifier: "thumb\(SingleSubredditViewController.cellVersion)")
self.tableView.register(TextLinkCellView.classForCoder(), forCellWithReuseIdentifier: "text\(SingleSubredditViewController.cellVersion)")
}
var numberOfColumns = CGFloat.zero
var portraitCount = CGFloat(SettingValues.multiColumnCount / 2)
if portraitCount == 0 {
portraitCount = 1
}
let pad = UIScreen.main.traitCollection.userInterfaceIdiom == .pad
if portraitCount == 1 && pad {
portraitCount = 2
}
if SettingValues.appMode == .MULTI_COLUMN {
if UIApplication.shared.statusBarOrientation.isPortrait {
if UIScreen.main.traitCollection.userInterfaceIdiom != .pad {
numberOfColumns = 1
} else {
numberOfColumns = portraitCount
}
} else {
numberOfColumns = CGFloat(SettingValues.multiColumnCount)
}
} else {
numberOfColumns = 1
}
if pad && UIApplication.shared.keyWindow?.frame != UIScreen.main.bounds {
numberOfColumns = 1
}
var tableWidth = self.tableView.frame.size.width
switch SingleSubredditViewController.cellType(forSubmission: submission, Subscriptions.isCollection(sub), cellWidth: (tableWidth == 0 ? UIScreen.main.bounds.size.width : tableWidth) / numberOfColumns ) {
case .thumb:
cell = tableView.dequeueReusableCell(withReuseIdentifier: "thumb\(SingleSubredditViewController.cellVersion)", for: indexPath) as! ThumbnailLinkCellView
case .autoplay:
cell = tableView.dequeueReusableCell(withReuseIdentifier: "autoplay\(SingleSubredditViewController.cellVersion)", for: indexPath) as! AutoplayBannerLinkCellView
case .banner:
cell = tableView.dequeueReusableCell(withReuseIdentifier: "banner\(SingleSubredditViewController.cellVersion)", for: indexPath) as! BannerLinkCellView
default:
cell = tableView.dequeueReusableCell(withReuseIdentifier: "text\(SingleSubredditViewController.cellVersion)", for: indexPath) as! TextLinkCellView
}
cell.preservesSuperviewLayoutMargins = false
cell.del = self
cell.layer.shouldRasterize = true
cell.layer.rasterizationScale = UIScreen.main.scale
//cell.panGestureRecognizer?.require(toFail: self.tableView.panGestureRecognizer)
//ecell.panGestureRecognizer2?.require(toFail: self.tableView.panGestureRecognizer)
cell.configure(submission: submission, parent: self, nav: self.navigationController, baseSub: self.sub, np: false)
return cell
}
}
// MARK: - Collection View Prefetching Data Source
//extension SingleSubredditViewController: UICollectionViewDataSourcePrefetching {
// func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
// // TODO: Implement
// }
//}
// MARK: - Link Cell View Delegate
extension SingleSubredditViewController: LinkCellViewDelegate {
func openComments(id: String, subreddit: String?) {
if let nav = ((self.splitViewController?.viewControllers.count ?? 0 > 1) ? self.splitViewController?.viewControllers[1] : nil) as? UINavigationController, let detail = nav.viewControllers[0] as? PagingCommentViewController {
if detail.submissions[0].getId() == id {
return
}
}
var index = 0
for s in links {
if s.getId() == id {
break
}
index += 1
}
var newLinks: [RSubmission] = []
for i in index ..< links.count {
newLinks.append(links[i])
}
let comment = PagingCommentViewController.init(submissions: newLinks, offline: self.offline, reloadCallback: { [weak self] in
if let strongSelf = self {
strongSelf.tableView.reloadData()
}
return true
})
VCPresenter.showVC(viewController: comment, popupIfPossible: true, parentNavigationController: self.navigationController, parentViewController: self)
}
}
// MARK: - Color Picker View Delegate
extension SingleSubredditViewController: ColorPickerViewDelegate {
public func colorPickerView(_ colorPickerView: ColorPickerView, didSelectItemAt indexPath: IndexPath) {
if isAccent {
accentChosen = colorPickerView.colors[indexPath.row]
self.fab?.backgroundColor = accentChosen
} else {
let c = colorPickerView.colors[indexPath.row]
primaryChosen = c
self.navigationController?.navigationBar.barTintColor = SettingValues.reduceColor ? ColorUtil.theme.backgroundColor : c
sideView.backgroundColor = c
sideView.backgroundColor = c
inHeadView?.backgroundColor = SettingValues.reduceColor ? ColorUtil.theme.backgroundColor : c
if SettingValues.fullyHideNavbar {
inHeadView?.backgroundColor = .clear
}
if parentController != nil {
parentController?.colorChanged(c)
}
}
}
}
// MARK: - Wrapping Flow Layout Delegate
extension SingleSubredditViewController: WrappingFlowLayoutDelegate {
func headerOffset() -> Int {
return hasHeader ? 1 : 0
}
func headerHeight(_ estimate: Bool = true) -> CGFloat {
if !estimate && SettingValues.alwaysShowHeader {
return CGFloat(0)
}
return CGFloat(hasHeader ? (headerImage != nil ? 180 : 38) : 0)
}
func collectionView(_ collectionView: UICollectionView, width: CGFloat, indexPath: IndexPath) -> CGSize {
var row = indexPath.row
if row == 0 && hasHeader {
return CGSize(width: width, height: headerHeight())
}
row -= self.headerOffset()
if row < links.count {
let submission = links[row]
if submission.author == "PAGE_SEPARATOR" {
return CGSize(width: width, height: 80)
}
return SingleSubredditViewController.sizeWith(submission, width, Subscriptions.isCollection(sub))
}
return CGSize(width: width, height: 80)
}
}
// MARK: - Submission More Delegate
extension SingleSubredditViewController: SubmissionMoreDelegate {
func hide(index: Int) {
links.remove(at: index)
self.flowLayout.reset(modal: self.presentingViewController != nil)
tableView.reloadData()
}
func subscribe(link: RSubmission) {
let sub = link.subreddit
let alrController = UIAlertController.init(title: "Follow r/\(sub)", message: nil, preferredStyle: .alert)
if AccountController.isLoggedIn {
let somethingAction = UIAlertAction(title: "Subscribe", style: UIAlertAction.Style.default, handler: { (_: UIAlertAction!) in
Subscriptions.subscribe(sub, true, session: self.session!)
self.subChanged = true
BannerUtil.makeBanner(text: "Subscribed to r/\(sub)", color: ColorUtil.accentColorForSub(sub: sub), seconds: 3, context: self, top: true)
})
alrController.addAction(somethingAction)
}
let somethingAction = UIAlertAction(title: "Casually subscribe", style: UIAlertAction.Style.default, handler: { (_: UIAlertAction!) in
Subscriptions.subscribe(sub, false, session: self.session!)
self.subChanged = true
BannerUtil.makeBanner(text: "r/\(sub) added to your subreddit list", color: ColorUtil.accentColorForSub(sub: sub), seconds: 3, context: self, top: true)
})
alrController.addAction(somethingAction)
alrController.addCancelButton()
alrController.modalPresentationStyle = .fullScreen
self.present(alrController, animated: true, completion: {})
}
func reply(_ cell: LinkCellView) {
}
func save(_ cell: LinkCellView) {
do {
try session?.setSave(!ActionStates.isSaved(s: cell.link!), name: (cell.link?.getId())!, completion: { (_) in
})
ActionStates.setSaved(s: cell.link!, saved: !ActionStates.isSaved(s: cell.link!))
cell.refresh()
} catch {
}
}
func upvote(_ cell: LinkCellView) {
do {
try session?.setVote(ActionStates.getVoteDirection(s: cell.link!) == .up ? .none : .up, name: (cell.link?.getId())!, completion: { (_) in
})
ActionStates.setVoteDirection(s: cell.link!, direction: ActionStates.getVoteDirection(s: cell.link!) == .up ? .none : .up)
History.addSeen(s: cell.link!)
cell.refresh()
cell.refreshTitle(force: true)
} catch {
}
}
func downvote(_ cell: LinkCellView) {
do {
try session?.setVote(ActionStates.getVoteDirection(s: cell.link!) == .down ? .none : .down, name: (cell.link?.getId())!, completion: { (_) in
})
ActionStates.setVoteDirection(s: cell.link!, direction: ActionStates.getVoteDirection(s: cell.link!) == .down ? .none : .down)
History.addSeen(s: cell.link!)
cell.refresh()
cell.refreshTitle(force: true)
} catch {
}
}
func hide(_ cell: LinkCellView) {
do {
try session?.setHide(true, name: cell.link!.getId(), completion: { (_) in })
let id = cell.link!.getId()
var location = 0
var item = links[0]
for submission in links {
if submission.getId() == id {
item = links[location]
links.remove(at: location)
break
}
location += 1
}
self.tableView.isUserInteractionEnabled = false
if !loading {
tableView.performBatchUpdates({
self.tableView.deleteItems(at: [IndexPath.init(item: location, section: 0)])
}, completion: { (_) in
self.tableView.isUserInteractionEnabled = true
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
})
} else {
self.flowLayout.reset(modal: self.presentingViewController != nil)
tableView.reloadData()
}
BannerUtil.makeBanner(text: "Hidden forever!\nTap to undo", color: GMColor.red500Color(), seconds: 4, context: self, top: false, callback: {
self.links.insert(item, at: location)
self.tableView.insertItems(at: [IndexPath.init(item: location + self.headerOffset(), section: 0)])
self.flowLayout.reset(modal: self.presentingViewController != nil)
self.tableView.reloadData()
do {
try self.session?.setHide(false, name: cell.link!.getId(), completion: { (_) in })
} catch {
}
})
} catch {
}
}
func more(_ cell: LinkCellView) {
PostActions.showMoreMenu(cell: cell, parent: self, nav: self.navigationController!, mutableList: true, delegate: self, index: tableView.indexPath(for: cell)?.row ?? 0)
}
func readLater(_ cell: LinkCellView) {
guard let link = cell.link else {
return
}
ReadLater.toggleReadLater(link: link)
if #available(iOS 10.0, *) {
HapticUtility.hapticActionComplete()
}
cell.refresh()
}
func mod(_ cell: LinkCellView) {
PostActions.showModMenu(cell, parent: self)
}
func applyFilters() {
self.links = PostFilter.filter(self.links, previous: nil, baseSubreddit: self.sub).map { $0 as! RSubmission }
self.reloadDataReset()
}
func showFilterMenu(_ cell: LinkCellView) {
let link = cell.link!
let actionSheetController: UIAlertController = UIAlertController(title: "What would you like to filter?", message: "", preferredStyle: .alert)
actionSheetController.addCancelButton()
var cancelActionButton = UIAlertAction()
cancelActionButton = UIAlertAction(title: "Posts by u/\(link.author)", style: .default) { _ -> Void in
PostFilter.profiles.append(link.author as NSString)
PostFilter.saveAndUpdate()
self.links = PostFilter.filter(self.links, previous: nil, baseSubreddit: self.sub).map { $0 as! RSubmission }
self.reloadDataReset()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Posts from r/\(link.subreddit)", style: .default) { _ -> Void in
PostFilter.subreddits.append(link.subreddit as NSString)
PostFilter.saveAndUpdate()
self.links = PostFilter.filter(self.links, previous: nil, baseSubreddit: self.sub).map { $0 as! RSubmission }
self.reloadDataReset()
}
actionSheetController.addAction(cancelActionButton)
cancelActionButton = UIAlertAction(title: "Posts linking to \(link.domain)", style: .default) { _ -> Void in
PostFilter.domains.append(link.domain as NSString)
PostFilter.saveAndUpdate()
self.links = PostFilter.filter(self.links, previous: nil, baseSubreddit: self.sub).map { $0 as! RSubmission }
self.reloadDataReset()
}
actionSheetController.addAction(cancelActionButton)
//todo make this work on ipad
self.present(actionSheetController, animated: true, completion: nil)
}
}
extension SingleSubredditViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if gestureRecognizer == panGesture {
if !SettingValues.submissionGesturesEnabled {
return false
}
if SettingValues.submissionActionLeft == .NONE && SettingValues.submissionActionRight == .NONE {
return false
}
}
return true
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer.numberOfTouches == 2 {
return true
}
return false
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// Limit angle of pan gesture recognizer to avoid interfering with scrolling
if gestureRecognizer == panGesture {
if !SettingValues.submissionGesturesEnabled {
return false
}
if SettingValues.submissionActionLeft == .NONE && SettingValues.submissionActionRight == .NONE {
return false
}
}
if let recognizer = gestureRecognizer as? UIPanGestureRecognizer, recognizer == panGesture {
return recognizer.shouldRecognizeForAxis(.horizontal, withAngleToleranceInDegrees: 45)
}
return true
}
@objc func panCell(_ recognizer: UIPanGestureRecognizer) {
if recognizer.view != nil && recognizer.state == .began {
let velocity = recognizer.velocity(in: recognizer.view!).x
if (velocity > 0 && SettingValues.submissionActionRight == .NONE) || (velocity < 0 && SettingValues.submissionActionLeft == .NONE) {
return
}
}
if recognizer.state == .began || translatingCell == nil {
let point = recognizer.location(in: self.tableView)
let indexpath = self.tableView.indexPathForItem(at: point)
if indexpath == nil {
return
}
guard let cell = self.tableView.cellForItem(at: indexpath!) as? LinkCellView else {
return
}
translatingCell = cell
}
translatingCell?.handlePan(recognizer)
if recognizer.state == .ended {
translatingCell = nil
}
}
}
public class LoadingCell: UICollectionViewCell {
var loader = UIActivityIndicatorView()
override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
loader.startAnimating()
self.contentView.addSubview(loader)
loader.topAnchor == self.contentView.topAnchor + 10
loader.bottomAnchor == self.contentView.bottomAnchor - 10
loader.centerXAnchor == self.contentView.centerXAnchor
}
}
public class ReadLaterCell: UICollectionViewCell {
let title = UILabel()
override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setArticles(articles: Int) {
let text = "Read Later "
let numberText = "(\(articles))"
let number = NSMutableAttributedString.init(string: numberText, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.boldSystemFont(ofSize: 15)]))
let readLater = NSMutableAttributedString.init(string: text, attributes: convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor): ColorUtil.theme.fontColor, convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.systemFont(ofSize: 15)]))
let finalText = readLater
finalText.append(number)
title.attributedText = finalText
}
func setupView() {
title.backgroundColor = ColorUtil.theme.foregroundColor
title.textAlignment = .center
title.numberOfLines = 0
let titleView: UIView
if SettingValues.postViewMode == .CARD || SettingValues.postViewMode == .CENTER {
if !SettingValues.flatMode {
title.layer.cornerRadius = 15
}
titleView = title.withPadding(padding: UIEdgeInsets(top: 8, left: 5, bottom: 0, right: 5))
} else {
titleView = title.withPadding(padding: UIEdgeInsets(top: 8, left: 0, bottom: 0, right: 0))
}
title.clipsToBounds = true
self.contentView.addSubview(titleView)
titleView.heightAnchor == 60
titleView.horizontalAnchors == self.contentView.horizontalAnchors
titleView.topAnchor == self.contentView.topAnchor
}
}
public class PageCell: UICollectionViewCell {
var title = UILabel()
var time = UILabel()
override public init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
self.contentView.addSubviews(title, time)
title.heightAnchor == 60
title.horizontalAnchors == self.contentView.horizontalAnchors
title.topAnchor == self.contentView.topAnchor + 10
title.bottomAnchor == self.contentView.bottomAnchor - 10
title.numberOfLines = 0
title.lineBreakMode = .byWordWrapping
title.textAlignment = .center
title.textColor = ColorUtil.theme.fontColor
time.heightAnchor == 60
time.leftAnchor == self.contentView.leftAnchor
time.topAnchor == self.contentView.topAnchor + 10
time.bottomAnchor == self.contentView.bottomAnchor - 10
time.numberOfLines = 0
time.widthAnchor == 70
time.lineBreakMode = .byWordWrapping
time.textAlignment = .center
}
}
// Helper function inserted by Swift 4.2 migrator.
private func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value) })
}
// Helper function inserted by Swift 4.2 migrator.
private func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
public class LinksHeaderCellView: UICollectionViewCell {
var scroll: TouchUIScrollView!
var links = [SubLinkItem]()
var sub = ""
var header = UIView()
var hasHeader = false
weak var del: SingleSubredditViewController?
func setLinks(links: [SubLinkItem], sub: String, delegate: SingleSubredditViewController) {
self.links = links
self.sub = sub
self.del = delegate
self.hasHeader = delegate.headerImage != nil
setupViews()
}
func addSubscribe(_ stack: UIStackView, _ scroll: UIScrollView) -> CGFloat {
let view = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45)).then {
$0.clipsToBounds = true
$0.layer.cornerRadius = 15
$0.setImage(UIImage(named: "add")?.menuIcon().getCopy(withColor: .white), for: .normal)
$0.backgroundColor = ColorUtil.accentColorForSub(sub: sub)
$0.imageView?.contentMode = .center
}
view.addTapGestureRecognizer(action: {
self.del?.subscribeSingle(view)
stack.removeArrangedSubview(view)
var oldSize = scroll.contentSize
oldSize.width -= 38
stack.widthAnchor == oldSize.width
scroll.contentSize = oldSize
view.removeFromSuperview()
})
let widthS = CGFloat(30)
view.heightAnchor == CGFloat(30)
view.widthAnchor == widthS
stack.addArrangedSubview(view)
return 30
}
func addSubmit(_ stack: UIStackView) -> CGFloat {
let view = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45)).then {
$0.clipsToBounds = true
$0.layer.cornerRadius = 15
$0.setImage(UIImage(named: "edit")?.menuIcon().getCopy(withColor: .white), for: .normal)
$0.backgroundColor = ColorUtil.accentColorForSub(sub: sub)
$0.imageView?.contentMode = .center
$0.addTapGestureRecognizer(action: {
PostActions.showPostMenu(self.del!, sub: self.sub)
})
}
let widthS = CGFloat(30)
view.heightAnchor == CGFloat(30)
view.widthAnchor == widthS
stack.addArrangedSubview(view)
return 30
}
func addSidebar(_ stack: UIStackView) -> CGFloat {
let view = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45)).then {
$0.clipsToBounds = true
$0.layer.cornerRadius = 15
$0.setImage(UIImage(named: "info")?.menuIcon().getCopy(withColor: .white), for: .normal)
$0.backgroundColor = ColorUtil.accentColorForSub(sub: sub)
$0.imageView?.contentMode = .center
$0.addTapGestureRecognizer(action: {
self.del?.doDisplaySidebar()
})
}
let widthS = CGFloat(30)
view.heightAnchor == CGFloat(30)
view.widthAnchor == widthS
stack.addArrangedSubview(view)
return 30
}
func setupViews() {
if scroll == nil {
scroll = TouchUIScrollView()
let buttonBase = UIStackView().then {
$0.accessibilityIdentifier = "Subreddit links"
$0.axis = .horizontal
$0.spacing = 8
}
var finalWidth = CGFloat(8)
var spacerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 10))
buttonBase.addArrangedSubview(spacerView)
if Subscriptions.subreddits.contains(sub) {
finalWidth += self.addSubmit(buttonBase) + 8
} else {
finalWidth += self.addSubscribe(buttonBase, scroll) + 8
}
finalWidth += self.addSidebar(buttonBase) + 8
for link in self.links {
let view = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 45)).then {
$0.layer.cornerRadius = 15
$0.clipsToBounds = true
$0.setTitle(link.title, for: .normal)
$0.setTitleColor(UIColor.white, for: .normal)
$0.setTitleColor(.white, for: .selected)
$0.titleLabel?.textAlignment = .center
$0.titleLabel?.font = UIFont.systemFont(ofSize: 12)
$0.backgroundColor = ColorUtil.accentColorForSub(sub: sub)
$0.addTapGestureRecognizer(action: {
self.del?.doShow(url: link.link!, heroView: nil, heroVC: nil)
})
}
let widthS = view.currentTitle!.size(with: view.titleLabel!.font).width + CGFloat(45)
view.heightAnchor == CGFloat(30)
view.widthAnchor == widthS
finalWidth += widthS
finalWidth += 8
buttonBase.addArrangedSubview(view)
}
spacerView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 10))
buttonBase.addArrangedSubview(spacerView)
self.contentView.addSubview(scroll)
self.scroll.isUserInteractionEnabled = true
self.contentView.isUserInteractionEnabled = true
buttonBase.isUserInteractionEnabled = true
scroll.heightAnchor == CGFloat(30)
scroll.horizontalAnchors == self.contentView.horizontalAnchors
scroll.addSubview(buttonBase)
buttonBase.heightAnchor == CGFloat(30)
buttonBase.edgeAnchors == scroll.edgeAnchors
buttonBase.centerYAnchor == scroll.centerYAnchor
buttonBase.widthAnchor == finalWidth
scroll.alwaysBounceHorizontal = true
scroll.showsHorizontalScrollIndicator = false
if hasHeader && del != nil {
self.contentView.addSubview(header)
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
header.addSubview(imageView)
imageView.clipsToBounds = true
if UIDevice.current.userInterfaceIdiom == .pad {
imageView.verticalAnchors == header.verticalAnchors
imageView.horizontalAnchors == header.horizontalAnchors + 4
imageView.layer.cornerRadius = 15
} else {
imageView.edgeAnchors == header.edgeAnchors
}
header.heightAnchor == 180
header.horizontalAnchors == self.contentView.horizontalAnchors
header.topAnchor == self.contentView.topAnchor + 4
scroll.topAnchor == self.header.bottomAnchor + 4
imageView.sd_setImage(with: del!.headerImage!)
header.heightAnchor == 140
} else {
scroll.topAnchor == self.contentView.topAnchor + 4
}
scroll.contentSize = CGSize.init(width: finalWidth + 30, height: CGFloat(30))
}
}
}
public class SubLinkItem {
var title = ""
var link: URL?
init(_ title: String?, link: URL?) {
self.title = title ?? "LINK"
self.link = link
}
}
| 43.811555 | 351 | 0.563028 |
dbbc586077f54803dd3e42a8e975c8f2a0df0e2d | 1,141 | import Vapor
extension Droplet {
func setupRoutes() throws {
// get("view") { req in
// return try self.view.make("myview")
// }
//
// get("bonus") { req in
// return try self.view.make("mydataview", ["name": "Sai Omkaram"])
// }
//
// get("user") { req in
// let list = try User.all()
// return try self.view.make(
// "userview", ["userlist": list.makeNode(in: nil)]
// )
// }
//
// post("user") { req in
// guard let username = req.data["username"]?.string else {
//
// return Response(status: .badRequest)
// }
//
// let user = User(username: username)
// try user.save()
//
// return Response(redirect: "/user")
// }
let userController = UserController(drop: self)
get("user", handler:userController.list)
post("user", handler:userController.create)
post("user", ":id", "update", handler: userController.update)
post("user", ":id", "delete", handler: userController.delete)
}
}
| 28.525 | 78 | 0.497809 |
5b06044b9e133bb23554c73349af1f4a6d2488cd | 929 | //
// BencodeKey.swift
// Bencode
//
// Created by Daniel Tombor on 2017. 09. 16..
//
import Foundation
/** For ordered encoding. */
public struct BencodeKey {
public let key: String
public let order: Int
public init(_ key: String, order: Int = Int.max) {
self.key = key
self.order = order
}
}
extension BencodeKey: Hashable {
public static func ==(lhs: BencodeKey, rhs: BencodeKey) -> Bool {
return lhs.key == rhs.key
}
}
extension BencodeKey: Comparable {
public static func <(lhs: BencodeKey, rhs: BencodeKey) -> Bool {
if lhs.order != rhs.order {
return lhs.order < rhs.order
} else {
return lhs.key < rhs.key
}
}
}
// MARK: - String helper extension
extension String {
/** Convert string to BencodeKey */
var bKey: BencodeKey {
return BencodeKey(self)
}
}
| 18.215686 | 69 | 0.572659 |
efaf5fc9e514031a3cb6e5b496ed0b810847dcc6 | 1,428 | //
// Floyd-2D.swift
// Dijkstra & Floyd
//
// Created by 诸葛俊伟 on 10/1/16.
// Copyright © 2016 University of Pittsburgh. All rights reserved.
//
import Foundation
func floyd2D(_ graph: [[Int]])
{
let n = graph.count
var dist = Array(repeating: Array(repeatElement(0, count: n)), count: n)
var path = Array(repeating: Array(repeatElement(0, count: n)), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dist[i][j] = 0
} else if graph[i][j] == 0 {
dist[i][j] = Int(Int32.max)
} else {
dist[i][j] = graph[i][j]
}
}
}
for k in 0..<n {
for i in 0..<n {
for j in 0..<n {
if dist[i][k] + dist[k][j] < dist[i][j] {
path[i][j] = k
dist[i][j] = dist[i][k] + dist[k][j]
}
}
}
}
// return path
}
//var p = [[Int]]()
//
//func path(_ q: Int, _ r: Int) {
// if p[q][r] != 0 {
// path(q, p[q][r])
// print("v\(p[q][r])", terminator: " ")
// path(p[q][r], r)
// }
//}
//
//func printPath(_ n: Int) {
// for i in 0..<n {
// for j in 0..<n {
// if i != j {
// print("The path from \(i) -> \(j):", terminator: " ")
// path(i, j)
// print("\n")
// }
// }
// }
//}
| 23.032258 | 76 | 0.384454 |
46bb5f565193bea8ee44006416c9aa9b947fd5a3 | 4,827 | //
// ColorThemeSettings.swift
//
//
// Copyright 2017 Amazon.com, Inc. or its affiliates (Amazon). All Rights Reserved.
//
// Code generated by AWS Mobile Hub. Amazon gives unlimited permission to
// copy, distribute and modify it.
//
// Source code generated from template: aws-my-sample-app-ios-swift v0.19
//
import Foundation
import UIKit
import AWSCore
import AWSCognito
let ColorThemeSettingsTitleTextColorKey = "title_text_color"
let ColorThemeSettingsTitleBarColorKey = "title_bar_color"
let ColorThemeSettingsBackgroundColorKey = "background_color"
let ColorThemeSettingsDefaultTitleTextColor: Int32 = Int32(bitPattern: 0xFFFFFFFF)
let ColorThemeSettingsDefaultTitleBarColor: Int32 = Int32(bitPattern: 0xFFF58535)
let ColorThemeSettingsDefaultBackgroundColor: Int32 = Int32(bitPattern: 0xFFFFFFFF)
class ColorThemeSettings {
var theme: Theme
static let sharedInstance: ColorThemeSettings = ColorThemeSettings()
fileprivate init() {
theme = Theme()
}
// MARK: - User Settings Functions
func loadSettings(_ completionBlock: @escaping (ColorThemeSettings?, Error?) -> Void) {
let syncClient: AWSCognito = AWSCognito.default()
let userSettings: AWSCognitoDataset = syncClient.openOrCreateDataset("user_settings")
userSettings.synchronize().continueWith { (task: AWSTask<AnyObject>) -> Any? in
if let error = task.error as? NSError {
print("loadSettings error: \(error)")
completionBlock(nil, error)
return nil
}
let titleTextColorString: String? = userSettings.string(forKey: ColorThemeSettingsTitleTextColorKey)
let titleBarColorString: String? = userSettings.string(forKey: ColorThemeSettingsTitleBarColorKey)
let backgroundColorString: String? = userSettings.string(forKey: ColorThemeSettingsBackgroundColorKey)
if let titleTextColorString = titleTextColorString,
let titleBarColorString = titleBarColorString,
let backgroundColorString = backgroundColorString {
self.theme = Theme(titleTextColor: titleTextColorString.toInt32(),
withTitleBarColor: titleBarColorString.toInt32(),
withBackgroundColor: backgroundColorString.toInt32())
} else {
self.theme = Theme()
}
completionBlock(self, nil)
return nil
}
}
func saveSettings(_ completionBlock: ((ColorThemeSettings?, Error?) -> Void)?) {
let syncClient: AWSCognito = AWSCognito.default()
let userSettings: AWSCognitoDataset = syncClient.openOrCreateDataset("user_settings")
userSettings.setString("\(theme.titleTextColor)", forKey: ColorThemeSettingsTitleTextColorKey)
userSettings.setString("\(theme.titleBarColor)", forKey: ColorThemeSettingsTitleBarColorKey)
userSettings.setString("\(theme.backgroundColor)", forKey: ColorThemeSettingsBackgroundColorKey)
userSettings.synchronize().continueWith { (task: AWSTask<AnyObject>) -> Any? in
if let error = task.error {
print("saveSettings AWS task error: \(error)")
completionBlock?(nil, error)
return nil
}
completionBlock?(self, nil)
return nil
}
}
func wipe() {
AWSCognito.default().wipe()
}
}
class Theme: NSObject {
fileprivate(set) var titleTextColor: Int32
fileprivate(set) var titleBarColor: Int32
fileprivate(set) var backgroundColor: Int32
override init() {
titleTextColor = ColorThemeSettingsDefaultTitleTextColor
titleBarColor = ColorThemeSettingsDefaultTitleBarColor
backgroundColor = ColorThemeSettingsDefaultBackgroundColor
super.init()
}
init(titleTextColor: Int32, withTitleBarColor titleBarColor: Int32, withBackgroundColor backgroundColor: Int32) {
self.titleTextColor = titleTextColor
self.titleBarColor = titleBarColor
self.backgroundColor = backgroundColor
super.init()
}
}
// MARK: - Utility
extension Int32 {
public func UIColorFromARGB() -> UIColor {
let argbValue: Int64 = Int64(self)
let divider: Float = 255.0
return UIColor(red: CGFloat((Float((argbValue & 0x00FF0000) >> 16)) / divider),
green: CGFloat((Float((argbValue & 0x0000FF00) >> 8)) / divider),
blue: CGFloat((Float((argbValue & 0x000000FF) >> 0)) / divider),
alpha: CGFloat((Float((argbValue & 0xFF000000) >> 24)) / divider))
}
}
extension String {
public func toInt32() -> Int32 {
return Int32(self)!
}
}
| 37.130769 | 117 | 0.661487 |
1847dfdd14980ab033ba3a802a4769b803ad68cc | 2,351 | //
// FSFindCircleCell.swift
// fitsky
// 发现社圈
// Created by gouyz on 2020/2/24.
// Copyright © 2020 gyz. All rights reserved.
//
import UIKit
class FSFindCircleCell: UITableViewCell {
/// 填充数据
var dataModel : FSIMCircleModel?{
didSet{
if let model = dataModel {
tagImgView.kf.setImage(with: URL.init(string: model.thumb!), placeholder: UIImage.init(named: "app_img_avatar_def"))
nameLab.text = model.name
typeLab.text = model.category_id_text
}
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = kWhiteColor
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI(){
contentView.addSubview(tagImgView)
contentView.addSubview(nameLab)
contentView.addSubview(typeLab)
tagImgView.snp.makeConstraints { (make) in
make.left.equalTo(kMargin)
make.centerY.equalTo(contentView)
make.size.equalTo(CGSize.init(width: 48, height: 48))
}
typeLab.snp.makeConstraints { (make) in
make.left.equalTo(tagImgView.snp.right).offset(kMargin)
make.centerY.equalTo(tagImgView)
make.height.equalTo(30)
}
nameLab.snp.makeConstraints { (make) in
make.left.equalTo(typeLab.snp.right).offset(kMargin)
make.centerY.height.equalTo(typeLab)
}
}
/// 社圈图片
lazy var tagImgView : UIImageView = {
let imgView = UIImageView()
imgView.backgroundColor = kGrayBackGroundColor
imgView.cornerRadius = 24
return imgView
}()
/// 名称
lazy var nameLab : UILabel = {
let lab = UILabel()
lab.textColor = kGaryFontColor
lab.font = k14Font
lab.text = "湖塘健身一圈1"
return lab
}()
///
lazy var typeLab : UILabel = {
let lab = UILabel()
lab.textColor = kHeightGaryFontColor
lab.font = k12Font
lab.text = "学员"
return lab
}()
}
| 26.715909 | 132 | 0.569545 |
761287793ed33c3c8dca9ae9a30cff0468b590d6 | 968 | //
// MainView.swift
// APLayoutKit_Example
//
// Created by Vladislav Sosiuk on 30.10.2020.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import APLayoutKit
class MasterView: APBaseView {
var tableView: UITableView?
override func setup() {
backgroundColor = .systemBackground
tableView = addSubview(UITableView(), pin: [.pinToHorizontalEdges(),
.safeArea(.top()),
.bottom()]) {
$0.register(MasterTableViewCell.self, forCellReuseIdentifier: String(describing: MasterTableViewCell.self))
}
}
}
#if targetEnvironment(simulator)
import SwiftUI
@available (iOS 13.0, *)
struct MainView_Previews: PreviewProvider {
static var previews: some View {
Group {
Preview {
MasterView()
}
.previewLayout(.device)
}
}
}
#endif
| 24.2 | 119 | 0.56405 |
33641ef9f36e1580cdca803e318803688b2ab33b | 1,393 | import UIKit
public class AspectRatioConstrainedImageView: UIImageView {
private var aspectRatioConstraint: NSLayoutConstraint?
override public init(frame: CGRect) {
super.init(frame: frame)
contentMode = .scaleAspectFit
}
required init?(coder: NSCoder) {
super.init(coder: coder)
contentMode = .scaleAspectFit
}
override public var image: UIImage? {
didSet {
aspectRatioConstraint.map(removeConstraint)
aspectRatioConstraint = nil
if let image = image {
let size = image.size
let constraint = NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: size.height / size.width,
constant: 0
)
constraint.identifier = "Image Aspect Ratio"
constraint.priority = .defaultHigh
aspectRatioConstraint = constraint
constraint.isActive = true
}
}
}
override public var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
}
| 29.020833 | 81 | 0.529792 |
8af2bcc568e4731e72a0d8b91c78f3bd8ae252a0 | 743 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "SessionTools",
platforms: [
.macOS("10.12"),
.iOS("10.0"),
.tvOS("10.0"),
.watchOS("4.2")
],
products: [
.library(
name: "SessionTools",
targets: ["SessionTools"])
],
dependencies: [
.package(url: "https://github.com/kishikawakatsumi/KeychainAccess.git", from: "4.2.0"),
],
targets: [
.target(
name: "SessionTools",
dependencies: ["KeychainAccess"],
path: "Sources"),
.testTarget(
name: "SessionTools-iOSTests",
dependencies: ["SessionTools"],
path: "Tests")
]
)
| 23.967742 | 95 | 0.504711 |
2fcd7f5560f301f3950082364b595e64416326cb | 3,754 | //
// DropdownMenuView.swift
// Daybar
//
// Created by Jay Stakelon on 9/7/20.
// Copyright © 2020 Jay Stakelon. All rights reserved.
//
import SwiftUI
struct DropdownMenuView: NSViewRepresentable {
var profile: Profile?
var eventListViewModel: EventListViewModel?
func makeNSView(context: Context) -> NSPopUpButton {
let dropdown = NSPopUpButton(frame: CGRect(x: 0, y: 0, width: 48, height: 24), pullsDown: true)
dropdown.menu!.autoenablesItems = false
return dropdown
}
func updateNSView(_ nsView: NSPopUpButton, context: Context) {
nsView.removeAllItems()
var img: NSImage = NSImage(named: "avatar-placeholder")!
if let p = profile {
if let url = URL(string: p.picture) {
if let data = try? Data(contentsOf: url) {
if let image = NSImage(data: data) {
img = image
}
}
}
}
let avatarItem = NSMenuItem()
let avatarImage = img
avatarImage.size = NSSize(width: 24, height: 24)
avatarItem.image = avatarImage.oval()
let emailItem = NSMenuItem()
var emailStr = ""
if let e = profile?.email {
emailStr = e
}
emailItem.attributedTitle = NSAttributedString(string: emailStr, attributes: [NSAttributedString.Key.foregroundColor: NSColor.lightGray])
let signOutItem = NSMenuItem(title: "Sign out", action: #selector(GoogleLoader.signOutFromMenu(_:)), keyEquivalent: "")
signOutItem.target = GoogleLoader.shared
let calendarModeItem = NSMenuItem(title: "Calendar mode", action: #selector(Coordinator.toggleCalendarModeAction), keyEquivalent: "")
calendarModeItem.state = UserDefaultsStore().isCalendarMode ? .on : .off
calendarModeItem.representedObject = eventListViewModel
calendarModeItem.target = context.coordinator
let quitItem = NSMenuItem(title: "Quit", action: #selector(Coordinator.quitAction), keyEquivalent: "q")
quitItem.target = context.coordinator
nsView.menu?.insertItem(avatarItem, at: 0)
nsView.menu?.insertItem(emailItem, at: 1)
nsView.menu?.insertItem(signOutItem, at: 2)
nsView.menu?.insertItem(NSMenuItem.separator(), at: 3)
nsView.menu?.insertItem(calendarModeItem, at: 4)
nsView.menu?.insertItem(NSMenuItem.separator(), at: 5)
nsView.menu?.insertItem(quitItem, at: 6)
let cell = nsView.cell as? NSButtonCell
cell?.imagePosition = .imageOnly
cell?.bezelStyle = .texturedRounded
nsView.wantsLayer = true
nsView.layer?.backgroundColor = NSColor.clear.cgColor
nsView.isBordered = false
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator: NSObject {
@objc func fetchAction(_ sender: NSMenuItem) {
let vm = sender.representedObject as! EventListViewModel
vm.fetch()
}
@objc func quitAction(_ sender: NSMenuItem) {
NSApplication.shared.terminate(self)
}
@objc func toggleCalendarModeAction(_ sender: NSMenuItem) {
let userDefaultsStore = UserDefaultsStore()
userDefaultsStore.isCalendarMode = !userDefaultsStore.isCalendarMode
sender.state = userDefaultsStore.isCalendarMode ? .on : .off
let vm = sender.representedObject as! EventListViewModel
vm.fetch()
}
}
}
//struct DropdownMenuView_Previews: PreviewProvider {
// static var previews: some View {
// DropdownMenuView()
// }
//}
| 35.415094 | 145 | 0.62147 |
ab4305161331a8171326c7174acc34a853244a96 | 1,356 | //
// SearchAPI.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import Alamofire
public class SearchAPI: APIBase {
/**
- parameter completion: completion handler to receive the data and the error objects
*/
public class func search(completion: ((data: [AnyObject]?, error: ErrorType?) -> Void)) {
searchWithRequestBuilder().execute { (response, error) -> Void in
completion(data: response?.body, error: error);
}
}
/**
- GET /search
- Search - BASIC:
- type: http
- name: bearerAuth
- examples: [{contentType=application/json, example="{}", statusCode=200}]
- returns: RequestBuilder<[AnyObject]>
*/
public class func searchWithRequestBuilder() -> RequestBuilder<[AnyObject]> {
let path = "/search"
let URLString = OpenAPIClientAPI.basePath + path
let nillableParameters: [String:AnyObject?] = [:]
let parameters = APIHelper.rejectNil(nillableParameters)
let convertedParameters = APIHelper.convertBoolToString(parameters)
let requestBuilder: RequestBuilder<[AnyObject]>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder()
return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true)
}
}
| 27.673469 | 118 | 0.658555 |
e26da9bffd8693590d18e8301beed5b54d233b5c | 1,318 | //
// ViewModel.swift
// MvvmArchitecture-Swift
//
// Created by James on 2019/6/19.
// Copyright © 2019 geekdroid. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import NSObject_Rx //it must import this that can found out disposeBag
import ObjectMapper
class ViewModel: NSObject {
var page = 1
let error = ErrorTracker()
let parsedError = PublishSubject<ApiError>()
// let loading = ActivityIndicator()
override init() {
super.init()
error.asObservable().map { (error) -> ApiError? in
do {
let errorResponse = error as? MoyaError
if let body = try errorResponse?.response?.mapJSON() as? [String: Any],
let errorResponse = Mapper<ErrorResponse>().map(JSON: body) {
return ApiError.serverError(response: errorResponse)
}
} catch {
print(error)
}
return nil
}.filterNil().bind(to: parsedError).disposed(by: rx.disposeBag)
error.asDriver().drive(onNext: { (error) in
logError("\(error)")
}).disposed(by: rx.disposeBag)
}
deinit {
logDebug("\(type(of: self)): Deinited")
logResourcesCount()
}
}
| 26.897959 | 87 | 0.567527 |
50b7f5ff732fae81f340de8ffc768ba89f05a90a | 684 | //
// UITableView+Bela.swift
// BlokZaBelu
//
// Created by Dominik Cubelic on 10/08/2019.
// Copyright © 2019 Dominik Cubelic. All rights reserved.
//
import UIKit
extension UICollectionView {
func dequeueReusableCell<T: UICollectionViewCell>(ofType: T.Type, withIdentifier: String? = nil, for indexPath: IndexPath) -> T {
let identifier = withIdentifier ?? String(describing: ofType)
guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? T else {
fatalError("Table view \(self) can't dequeue a cell of type \(ofType) for identifier \(identifier)")
}
return cell
}
}
| 31.090909 | 133 | 0.665205 |
6a549e57aa6e91d88985f0c46f4d7809b7141fbd | 1,415 | /*:
## Replacing Items
You’ve seen how to add and remove items from a mutable array. What if you need to replace one item with another?
Earlier, you saw how to access an item in an array by using its index:
*/
var flavors = ["Chocolate", "Vanilla", "Strawberry", "Pistachio", "Rocky Road"]
let firstFlavor = flavors[0] // Remember, the first item is at index 0
/*:
In Swift, the part of the statement `[0]` is called a _subscript_.
With a mutable array, you can use the subscript to set the value at an existing index, replacing the value that is already there:
*/
flavors[0] = "Fudge Ripple"
let newFirstFlavor = flavors[0]
/*:
- experiment: Change the value of "Pistachio" to a flavor of ice cream that’s not already used in the array, like “Mint Chocolate Chip.” Check the results sidebar to make sure you’ve made the change.
*/
// Change "Pistachio" to another flavor.
flavors[3] = "Tres Leches"
/*:
If you try to use an index that is not contained in the array, you will get an error. You can only replace values in a mutable array using subscripts, you can’t add or remove things.
- experiment: In the statement below, what’s the highest number you can set the subscript to without receiving an error. Why is that the highest number you can use?
*/
flavors[1] = "Maple Walnut"
//: Next, review what you’ve learned.\
//: [Previous](@previous) | page 11 of 17 | [Next: Wrapup](@next)
| 40.428571 | 200 | 0.718728 |
1abc9de1e8d0ac4b841f912e1eb5127ac71de3a6 | 681 | //
// FinkelhorCell.swift
// MFL-Common
//
// Created by Alex Miculescu on 27/11/2017.
//
import UIKit
class FinkelhorCell: UITableViewCell, Reusable {
@IBOutlet fileprivate weak var button: RoundedButton!
var style : Style? { didSet { updateStyle() } }
var action : (() -> Void)?
var name : String? { didSet { updateName() } }
private func updateStyle() {
button.backgroundColor = style?.textColor4
button.setTitleColor(style?.primary, for: .normal)
}
private func updateName() {
button.setTitle(name, for: .normal)
}
@IBAction func didTapButton(_ sender: Any) {
action?()
}
}
| 21.28125 | 58 | 0.60793 |
e5b525767708c942d690c789cf1105fed321b7cd | 7,865 | //
// MediaOverlays.swift
// r2-shared-swift
//
// Created by Alexandre Camilleri on 4/11/17.
//
// Copyright 2018 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
import ObjectMapper
/// Errors related to MediaOverlays.
///
/// - nodeNotFound: Couldn't find any node for the given `forFragmentId`.
public enum MediaOverlaysError: Error {
case nodeNotFound(forFragmentId: String?)
}
// The functionnal wrapper around mediaOverlayNodes.
/// The object representing the MediaOverlays for a Link.
/// Two ways of using it, using the `Clip`s or `MediaOverlayNode`s.
/// Clips or a functionnal representation of a `MediaOverlayNode` (while the
/// MediaOverlayNode is more of an XML->Object representation.
public class MediaOverlays {
public var nodes: [MediaOverlayNode]!
public init(withNodes nodes: [MediaOverlayNode] = [MediaOverlayNode]()) {
self.nodes = nodes
}
public func append(_ newNode: MediaOverlayNode) {
nodes.append(newNode)
}
/// Get the audio `Clip` associated to an audio Fragment id.
/// The fragment id can be found in the HTML document in <p> & <span> tags,
/// it refer to a element of one of the SMIL files, providing informations
/// about the synchronized audio.
/// This function returns the clip representing this element from SMIL.
///
/// - Parameter id: The audio fragment id.
/// - Returns: The `Clip`, representation of the associated SMIL element.
/// - Throws: `MediaOverlayNodeError.audio`,
/// `MediaOverlayNodeError.timersParsing`.
public func clip(forFragmentId id: String) throws -> Clip? {
let clip: Clip?
do {
let fragmentNode = try node(forFragmentId: id)
clip = fragmentNode.clip
}
return clip
}
/// Get the audio `Clip` for the node right after the one designated by
/// `id`.
/// The fragment id can be found in the HTML document in <p> & <span> tags,
/// it refer to a element of one of the SMIL files, providing informations
/// about the synchronized audio.
/// This function returns the `Clip representing the element following this
/// element from SMIL.
///
/// - Parameter id: The audio fragment id.
/// - Returns: The `Clip` for the node element positioned right after the
/// one designated by `id`.
/// - Throws: `MediaOverlayNodeError.audio`,
/// `MediaOverlayNodeError.timersParsing`.
public func clip(nextAfterFragmentId id: String) throws -> Clip? {
let clip: Clip?
do {
let fragmentNextNode = try node(nextAfterFragmentId: id)
clip = fragmentNextNode.clip
}
return clip
}
/// Return the `MediaOverlayNode` found for the given 'fragment id'.
///
/// - Parameter forFragment: The SMIL fragment identifier.
/// - Returns: The node associated to the fragment.
public func node(forFragmentId id: String?) throws -> MediaOverlayNode {
guard let node = _findNode(forFragment: id, inNodes: self.nodes) else {
throw MediaOverlaysError.nodeNotFound(forFragmentId: id)
}
return node
}
/// Return the `MediaOverlayNode` right after the node found for the given
/// 'fragment id'.
///
/// - Parameter forFragment: The SMIL fragment identifier.
/// - Returns: The node right after the node associated to the fragment.
public func node(nextAfterFragmentId id: String?) throws -> MediaOverlayNode {
let ret = _findNextNode(forFragment: id, inNodes: self.nodes)
guard let node = ret.found else {
throw MediaOverlaysError.nodeNotFound(forFragmentId: id)
}
return node
}
// Mark: - Fileprivate Methods.
/// [RECURISVE]
/// Find the node (<par>) corresponding to "fragment" ?? nil.
///
/// - Parameters:
/// - fragment: The current fragment name for which we are looking the
/// associated media overlay node.
/// - nodes: The set of MediaOverlayNodes where to search. Default to
/// self children.
/// - Returns: The node we found ?? nil.
fileprivate func _findNode(forFragment fragment: String?,
inNodes nodes: [MediaOverlayNode]) -> MediaOverlayNode?
{
// For each node of the current scope..
for node in nodes {
// If the node is a "section" (<seq> sequence element)..
// FIXME: ask if really usefull?
if node.role.contains("section") {
// Try to find par nodes inside.
if let found = _findNode(forFragment: fragment, inNodes: node.children)
{
return found
}
}
// If the node text refer to filename or that filename is nil,
// return node.
if fragment == nil || node.text?.contains(fragment!) ?? false {
return node
}
}
// If nothing found, return nil.
return nil
}
/// [RECURISVE]
/// Find the node (<par>) corresponding to the next one after the given
/// "fragment" ?? nil.
///
/// - Parameters:
/// - fragment: The fragment name corresponding to the node previous to
/// the one we want.
/// - nodes: The set of MediaOverlayNodes where to search. Default to
/// self children.
/// - Returns: The node we found ?? nil.
fileprivate func _findNextNode(forFragment fragment: String?,
inNodes nodes: [MediaOverlayNode]) -> (found: MediaOverlayNode?, prevFound: Bool)
{
var previousNodeFoundFlag = false
// For each node of the current scope..
for node in nodes {
guard !previousNodeFoundFlag else {
/// If the node is a section, we get the first non section child.
if node.role.contains("section") {
if let validChild = getFirstNonSectionChild(of: node) {
return (validChild, false)
} else {
// Try next nodes.
continue
}
}
/// Else we just return it.
return (node, false)
}
// If the node is a "section" (<seq> sequence element)..
if node.role.contains("section") {
let ret = _findNextNode(forFragment: fragment, inNodes: node.children)
if let foundNode = ret.found {
return (foundNode, false)
}
previousNodeFoundFlag = ret.prevFound
}
// If the node text refer to filename or that filename is nil,
// return node.
if fragment == nil || node.text?.contains(fragment!) ?? false {
previousNodeFoundFlag = true
}
}
// If nothing found, return nil.
return (nil, previousNodeFoundFlag)
}
/// Returns the closest non section children node found.
///
/// - Parameter node: The section node
/// - Returns: The closest non section node or nil.
fileprivate func getFirstNonSectionChild(of node: MediaOverlayNode) -> MediaOverlayNode? {
for node in node.children {
if node.role.contains("section") {
if let found = getFirstNonSectionChild(of: node) {
return found
}
} else {
return node
}
}
return nil
}
}
| 36.752336 | 116 | 0.588811 |
297b4fc1cc26d0d564f1bdb7164b7f38b19baa4e | 518 | //: [Previous](@previous)
/*:
## Internal and External Names
*/
func addValues(value1 x: Int, value2 y: Int) -> Int {
// interally, use `x` and `y`
return x + y
}
// externally, use `value1` and `value2`
addValues(value1: 5, value2: 10)
/*:
## Ignore External Names
*/
func addExcitementToString(_ string: String) -> String {
return string + "!"
}
addExcitementToString("Swift")
func combineStrings(_ s1: String, _ s2: String) -> String {
return s1 + s2
}
combineStrings("We love", " Swift!") | 19.185185 | 59 | 0.638996 |
1874f8bbf7b7a8887fdb1b904921e050215653cf | 2,729 | import Foundation
import SourceKittenFramework
public struct QuickDiscouragedPendingTestRule: OptInRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "quick_discouraged_pending_test",
name: "Quick Discouraged Pending Test",
description: "Discouraged pending test. This test won't run while it's marked as pending.",
kind: .lint,
nonTriggeringExamples: QuickDiscouragedPendingTestRuleExamples.nonTriggeringExamples,
triggeringExamples: QuickDiscouragedPendingTestRuleExamples.triggeringExamples
)
public func validate(file: File) -> [StyleViolation] {
let testClasses = file.structure.dictionary.substructure.filter {
return $0.inheritedTypes.contains("QuickSpec") &&
$0.kind.flatMap(SwiftDeclarationKind.init) == .class
}
let specDeclarations = testClasses.flatMap { classDict in
return classDict.substructure.filter {
return $0.name == "spec()" && $0.enclosedVarParameters.isEmpty &&
$0.kind.flatMap(SwiftDeclarationKind.init) == .functionMethodInstance &&
$0.enclosedSwiftAttributes.contains(.override)
}
}
return specDeclarations.flatMap {
validate(file: file, dictionary: $0)
}
}
private func validate(file: File, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
return dictionary.substructure.flatMap { subDict -> [StyleViolation] in
var violations = validate(file: file, dictionary: subDict)
if let kindString = subDict.kind,
let kind = SwiftExpressionKind(rawValue: kindString) {
violations += validate(file: file, kind: kind, dictionary: subDict)
}
return violations
}
}
private func validate(file: File,
kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard
kind == .call,
let name = dictionary.name,
let offset = dictionary.offset,
QuickPendingCallKind(rawValue: name) != nil else { return [] }
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))]
}
}
private enum QuickPendingCallKind: String {
case pending
case xdescribe
case xcontext
case xit
case xitBehavesLike
}
| 37.902778 | 105 | 0.633565 |
1eb6bf65937f5da2b2a84ba42f3ea33dfe17fbfe | 267 | //
// Data.swift
// Vmee
//
// Created by Micha Volin on 2017-02-15.
// Copyright © 2017 Vmee. All rights reserved.
//
extension Data{
func lenght() -> Int{
let data = NSData(data: self)
let lenght = data.length
return lenght
}
}
| 14.833333 | 47 | 0.576779 |
e81a1c67f5748ad842641f62d365cc5b653397f7 | 1,262 | // Copyright (c) 2019 Spotify AB.
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 Commandant
#if !swift(>=5.0)
import Result
#endif
let registry = CommandRegistry<CommandantError<Swift.Error>>()
registry.register(ParseCommand())
registry.register(ManifestCommand())
registry.register(DumpCommand())
registry.register(VersionCommand())
registry.register(HelpCommand(registry: registry))
registry.main(defaultVerb: HelpCommand(registry: registry).verb) { error in
print(error)
}
| 36.057143 | 75 | 0.767829 |
611be034c981ed03996f8a3831c71b88ccdc5b67 | 7,235 | //
// DPAGApplicationFacade.swift
// ginlo
//
// Created by RBU on 04/11/15.
// Copyright © 2020 ginlo.net GmbH. All rights reserved.
//
import MagicalRecord
public class DPAGApplicationFacade: NSObject {
public static var isResetingAccount = false
private static var _couplingWorker: DPAGCouplingWorkerProtocol = DPAGCouplingWorker.sharedInstance
private static var _backupWorker: DPAGBackupWorkerProtocol = DPAGBackupWorker.sharedInstance
private static var _persistance: DPAGPersistanceProtocol = DPAGPersistance()
private static var _server: DPAGServerWorkerProtocol = DPAGServerWorker()
private static var _service: DPAGHttpServiceProtocol = DPAGHttpService()
private static var _model: DPAGSimsMeModelProtocol = DPAGSimsMeModel()
private static var _contactFactory: DPAGContactModelFactoryProtocol = DPAGContactModelFactory()
private static var _messageFactory: DPAGMessageModelFactoryProtocol = DPAGMessageModelFactory()
private static var _preferences = DPAGMDMPreferences()
private static var _cache = DPAGCache()
private static var _sharedContainer = DPAGSharedContainer()
private static var _sharedContainerSending = DPAGSharedContainerSending()
private static var _statusWorker: DPAGStatusWorkerProtocol = DPAGStatusWorker()
private static var _sendMessageWorker: DPAGSendMessageWorkerProtocol = DPAGSendMessageWorker()
private static var _companyAdressbook: DPAGCompanyAdressbookWorkerProtocol = DPAGCompanyAdressbookWorker()
private static var _contactsWorker: DPAGContactsWorkerProtocol = DPAGContactsWorker()
private static var _migrationWorker: DPAGMigrationWorkerProtocol = DPAGMigrationWorker()
private static var _updateKnownContactsWorker: DPAGUpdateKnownContactsWorkerProtocol = DPAGUpdateKnownContactsWorker()
private static var _devicesWorker: DPAGDevicesWorkerProtocol = DPAGDevicesWorker()
private static var _chatRoomWorker: DPAGChatRoomWorkerProtocol = DPAGChatRoomWorker()
private static var _feedWorker: DPAGFeedWorkerProtocol = DPAGFeedWorker()
private static var _accountManager: DPAGAccountManagerProtocol = DPAGAccountManager()
private static var _messageWorker: DPAGMessageWorkerProtocol = DPAGMessageWorker()
private static var _messageCryptoWorker: DPAGMessageCryptoWorkerProtocol = DPAGMessageCryptoWorker()
private static var _receiveMessagesWorker: DPAGReceiveMessagesWorkerProtocol = DPAGReceiveMessagesWorker()
private static var _automaticRegistrationWorker: DPAGAutomaticRegistrationWorkerProtocol = DPAGAutomaticRegistrationWorker()
private static var _requestWorker: DPAGRequestWorkerProtocol = DPAGRequestWorker()
private static var _profileWorker: DPAGProfileWorkerProtocol = DPAGProfileWorker()
private static var _mediaWorker: DPAGMediaWorkerProtocol = DPAGMediaWorker()
public static var runtimeConfig = DPAGRuntimeConfig()
public class func reset() {
_couplingWorker = DPAGCouplingWorker.sharedInstance
_backupWorker = DPAGBackupWorker.sharedInstance
// _preferences = DPAGMDMPreferences()
_preferences.reset()
_preferences.setDefaults()
_persistance = DPAGPersistance()
_service = DPAGHttpService()
_server = DPAGServerWorker()
_model = DPAGSimsMeModel()
_contactFactory = DPAGContactModelFactory()
_messageFactory = DPAGMessageModelFactory()
_cache = DPAGCache()
_sharedContainer = DPAGSharedContainer()
_sharedContainerSending = DPAGSharedContainerSending()
_cache.initFetchedResultsController()
_statusWorker = DPAGStatusWorker()
_sendMessageWorker = DPAGSendMessageWorker()
_companyAdressbook = DPAGCompanyAdressbookWorker()
_contactsWorker = DPAGContactsWorker()
_migrationWorker = DPAGMigrationWorker()
_updateKnownContactsWorker = DPAGUpdateKnownContactsWorker()
_devicesWorker = DPAGDevicesWorker()
_chatRoomWorker = DPAGChatRoomWorker()
_feedWorker = DPAGFeedWorker()
_accountManager = DPAGAccountManager()
_messageWorker = DPAGMessageWorker()
_messageCryptoWorker = DPAGMessageCryptoWorker()
_receiveMessagesWorker = DPAGReceiveMessagesWorker()
_automaticRegistrationWorker = DPAGAutomaticRegistrationWorker()
_requestWorker = DPAGRequestWorker()
_profileWorker = DPAGProfileWorker()
_mediaWorker = DPAGMediaWorker()
DPAGCryptoHelper.resetAccountCrypto()
}
class var persistance: DPAGPersistanceProtocol { _persistance }
class var server: DPAGServerWorkerProtocol { _server }
class var service: DPAGHttpServiceProtocol { _service }
public class var model: DPAGSimsMeModelProtocol { _model }
class var contactFactory: DPAGContactModelFactoryProtocol { _contactFactory }
class var messageFactory: DPAGMessageModelFactoryProtocol { _messageFactory }
public class var preferences: DPAGMDMPreferences { _preferences }
public class var cache: DPAGCache { _cache }
public class var sharedContainer: DPAGSharedContainer { _sharedContainer }
public class var sharedContainerSending: DPAGSharedContainerSending { _sharedContainerSending }
public class var statusWorker: DPAGStatusWorkerProtocol { _statusWorker }
public class var sendMessageWorker: DPAGSendMessageWorkerProtocol { _sendMessageWorker }
public class var backupWorker: DPAGBackupWorkerProtocol { _backupWorker }
public class var companyAdressbook: DPAGCompanyAdressbookWorkerProtocol { _companyAdressbook }
public class var contactsWorker: DPAGContactsWorkerProtocol { _contactsWorker }
public class var couplingWorker: DPAGCouplingWorkerProtocol { _couplingWorker }
public class var migrationWorker: DPAGMigrationWorkerProtocol { _migrationWorker }
public class var updateKnownContactsWorker: DPAGUpdateKnownContactsWorkerProtocol { _updateKnownContactsWorker }
public class var devicesWorker: DPAGDevicesWorkerProtocol { _devicesWorker }
public class var chatRoomWorker: DPAGChatRoomWorkerProtocol { _chatRoomWorker }
public class var feedWorker: DPAGFeedWorkerProtocol { _feedWorker }
public class var accountManager: DPAGAccountManagerProtocol { _accountManager }
public class var messageWorker: DPAGMessageWorkerProtocol { _messageWorker }
class var messageCryptoWorker: DPAGMessageCryptoWorkerProtocol { _messageCryptoWorker }
public class var receiveMessagesWorker: DPAGReceiveMessagesWorkerProtocol { _receiveMessagesWorker }
public class var automaticRegistrationWorker: DPAGAutomaticRegistrationWorkerProtocol { _automaticRegistrationWorker }
public class var requestWorker: DPAGRequestWorkerProtocol { _requestWorker }
public class var profileWorker: DPAGProfileWorkerProtocol { _profileWorker }
public class var mediaWorker: DPAGMediaWorkerProtocol { _mediaWorker }
public class func setupModel() {
MagicalRecord.setupCoreDataStack(withAutoMigratingSqliteStoreNamed: FILEHELPER_FILE_NAME_DATABASE)
DPAGApplicationFacade.messageWorker.migrateIllegalMessageSendingStates()
}
public class func cleanupModel() {
MagicalRecord.cleanUp()
}
}
| 56.523438 | 128 | 0.792813 |
28c256a691bc4e709ca52f408d32cad878410c0b | 5,034 | //
// SetGame.swift
// Set
//
// Created by Plamen on 7.11.18.
// Copyright © 2018 Plamen. All rights reserved.
//
import Foundation
struct SetGame
{
private(set) var allCards = [SetCard]()
private(set) var activeCards = [SetCard]()
private(set) var matchedCards = [SetCard]()
var currentlySelectedCards = [SetCard]()
private(set) var points = 0
private var removedPointsForDifficulty = 0
init(numberOfCards: Int) {
generateCards()
activeCards.append(contentsOf: allCards.takeFromStart(numberOfElementsToTake: numberOfCards))
allCards.removeFromStart(numberOfElementsToRemove: numberOfCards)
}
mutating private func generateCards(){
for number in SetNumber.allCases {
for shape in SetShape.allCases {
for color in SetColor.allCases {
for fill in SetFill.allCases {
allCards.append(SetCard(number: number, color: color, shape: shape, fill: fill))
}
}
}
}
allCards.shuffle()
}
mutating func replaceCards(indicesOfCardsToReplace array: [Int]) {
for index in array {
let newCard = allCards.removeFirst()
activeCards.replace(newElement: newCard, at: index)
}
}
mutating func addThreeMoreCards(){
activeCards.append(contentsOf: allCards.takeFromStart(numberOfElementsToTake: 3))
allCards.removeFromStart(numberOfElementsToRemove: 3)
removedPointsForDifficulty += 1
}
mutating func selectCard(indexOfCard: Int){
currentlySelectedCards.append(activeCards[indexOfCard])
}
mutating func deselectCard(indexOfCard: Int) {
currentlySelectedCards.remove(at: indexOfCard)
}
mutating func deselectAllCards(){
currentlySelectedCards.removeAll()
}
mutating func scoreGame() {
if checkIfItIsASet() {
points += (5-removedPointsForDifficulty)
} else {
points -= 2
}
}
func checkIfItIsASet() -> Bool {
var isMatch = false
if currentlySelectedCards.count == 3 {
let cardOne = currentlySelectedCards[0]
let cardTwo = currentlySelectedCards[1]
let cardThree = currentlySelectedCards[2]
isMatch = checkNumbers(of: cardOne, of: cardTwo, of: cardThree)
if !isMatch {
return false
}
isMatch = checkShapes(of: cardOne, of: cardTwo, of: cardThree)
if !isMatch {
return false
}
isMatch = checkColors(of: cardOne, of: cardTwo, of: cardThree)
if !isMatch {
return false
}
isMatch = checkFills(of: cardOne, of: cardTwo, of: cardThree)
}
return isMatch
}
private func checkNumbers(of cardOne: SetCard, of cardTwo: SetCard, of cardThree: SetCard) -> Bool {
if cardOne.number == cardTwo.number && cardTwo.number == cardThree.number {
return true
}
if cardOne.number != cardTwo.number &&
cardOne.number != cardThree.number &&
cardTwo.number != cardThree.number {
return true
}
return false
}
private func checkShapes(of cardOne: SetCard, of cardTwo: SetCard, of cardThree: SetCard) -> Bool {
if cardOne.shape == cardTwo.shape && cardTwo.shape == cardThree.shape {
return true
}
if cardOne.shape != cardTwo.shape &&
cardOne.shape != cardThree.shape &&
cardTwo.shape != cardThree.shape {
return true
}
return false
}
private func checkColors(of cardOne: SetCard, of cardTwo: SetCard, of cardThree: SetCard) -> Bool {
if cardOne.color == cardTwo.color && cardTwo.color == cardThree.color {
return true
}
if cardOne.color != cardTwo.color &&
cardOne.color != cardThree.color &&
cardTwo.color != cardThree.color {
return true
}
return false
}
private func checkFills(of cardOne: SetCard, of cardTwo: SetCard, of cardThree: SetCard) -> Bool {
if cardOne.fill == cardTwo.fill && cardTwo.fill == cardThree.fill {
return true
}
if cardOne.fill != cardTwo.fill &&
cardOne.fill != cardThree.fill &&
cardTwo.fill != cardThree.fill {
return true
}
return false
}
}
//protocol SetGameProtocol {
// var allCards: [Card] {get}
// var gameCards: [Card] {get}
// var currentlySelectedCards: [Card] {get}
// var matchedCards: [Card] {get}
//
// mutating func selectCard(card: Card) -> Card
//}
| 29.438596 | 104 | 0.559793 |
1d634d245dd41c1045e641f92be43e4a5f90ec3e | 6,643 | // =========================================================================================
// Copyright 2017 Gal Orlanczyk
//
// 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
/// `TagParamsKeys` holds the param keys for the tags extra params info.
/// This param keys are used to get information like the attributes seperator,
/// extras to remove required count and keys and more.
enum TagParamsKeys {
/// the attributes seperator key.
static let attributesSeperator = "attributeSeperator"
/// the extras to remove from the text key.
static let attributesExtrasToRemove = "attributesExtrasToRemove"
/// The required attributes count key (can have more that are not required).
static let attributesCount = "attributesCount"
/// The required attributes keys key (can have more that are not required).
/// Used also for validating the integrity of the tag when parsing.
static let attributesKeys = "attributesKeys"
}
/* ***********************************************************/
// MARK: - PlaylistLine
/* ***********************************************************/
/// `PlaylistLine` protocol represents a general line in the playlist text
public protocol PlaylistLine {
/// The text string of the line (the actual original data for each line)
var text: String { get }
init(text: String, tagType: Tag.Type, extraParams: [String: Any]?) throws
}
/* ***********************************************************/
// MARK: - Tag
/* ***********************************************************/
/// `Tag` protocol represents a tag line in the playlist
public protocol Tag: PlaylistLine {
/// The tag itself, for example: '#EXTM3U'
static var tag: String { get }
/// The tag text data - all of the text after the tag.
/// For example: '#EXTINF:4.458667,' tagDataText = '4.458667,'
var tagDataText: String { get }
/// The tag type, used to help subclass of base tags to identify the real type of the object.
var tagType: Tag.Type { get }
func toText(replacingTagValueWith newValue: String) -> String
}
extension Tag {
public func toText(replacingTagValueWith newValue: String) -> String {
return self.tagType.tag + tagDataText
}
}
enum TagError: LocalizedError {
case invalidData(tag: String, received: String, expected: String)
case missingAttributes
var errorDescription: String? {
switch self {
case .invalidData(let tag, let received, let expected):
return "Failed to create tag (\(tag)) invalid data, \(received), \(expected).\nMake sure the playlist is valid."
case .missingAttributes:
return "Required attributes are missing, can not parse invalid playlist"
}
}
}
public protocol AttributedTag: Tag {
var attributes: [String: String] { get }
}
public protocol MultilineTag {
/// gets the line count for the text
static func linesCount(for text: String) -> Int
}
extension AttributedTag {
/// Gets the line attributes providing the tag, seperator and extras to remove before spliting.
/// This action get the attributes by:
/// - Removing extra strings provided
/// - Spliting the remaining string using the provided seperator
/// - Fetching key value by substring to the first "=" to get the key and from it get the value.
/// For example: URI="http..." key is URI and value is "http...".
///
/// - Parameters:
/// - tagDataText: The tag data text we need to extract the attributes from.
/// - seperator: The seperator between each attribute (usually ',').
/// - extrasToRemove: extra strings to remove from the line(" or ' etc) default is nil.
/// - Returns: The attributes of playlist line. if no attributes found returns nil.
static func getAttributes(from tagDataText: String, seperatedBy seperator: String, extrasToRemove: [String]? = nil) -> [String: String] {
var attributes = [String: String]()
// a mutable copy of the line tag text value so we can extract data from it.
var mutableText = tagDataText
// remove extras
if let extrasToRemove = extrasToRemove {
for extraToRemove in extrasToRemove {
mutableText = mutableText.replacingOccurrences(of: extraToRemove, with: "")
}
}
// get the raw attributes that are seperated by the seperator.
let rawAttributes = mutableText.components(separatedBy: seperator)
for rawAttribute in rawAttributes {
guard let equationRange = rawAttribute.range(of: "=") else { continue }
let attributeKey = String(rawAttribute[..<equationRange.lowerBound])
let attributeValue = String(rawAttribute[equationRange.upperBound...])
attributes[attributeKey] = attributeValue
}
return attributes
}
func validateIntegrity(requiredAttributes: [String]) throws {
for requiredAttribute in requiredAttributes {
if self.attributes[requiredAttribute] == nil {
throw TagError.missingAttributes
}
}
}
}
extension String {
func isMatch(tagType: Tag.Type) -> Bool {
return self.hasPrefix(tagType.tag)
}
func getTagValue(forType tagType: Tag.Type) -> String {
guard let tagRange = self.range(of: tagType.tag) else { return "" }
var tagValue = self
tagValue.removeSubrange(tagRange)
return tagValue
}
}
| 43.703947 | 157 | 0.640674 |
4a1e049e1e9d711ba63aa5d37b8bbda488411b3a | 313 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
import<d
class B{
class a
class B<T where B:a{
{
}
let b=a
a{
}
struct S{
var a{
class B{
protocol A{
{
}
enum b{
func f{{
}
class B<where T{
a
| 12.52 | 87 | 0.699681 |
4bc131aedf5c4be397ab3bd64246807889708bb8 | 2,663 | //
// LoginView.swift
// Bankey
//
// Created by hashmi on 22/02/22.
//
import Foundation
import UIKit
class LoginView: UIView {
let stackView = UIStackView()
let usernameTextField = UITextField()
let passwordTextField = UITextField()
let dividerView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
style()
layout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LoginView {
func style() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .secondarySystemBackground
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
stackView.spacing = 8
usernameTextField.translatesAutoresizingMaskIntoConstraints = false
usernameTextField.placeholder = "Username"
usernameTextField.delegate = self
passwordTextField.translatesAutoresizingMaskIntoConstraints = false
passwordTextField.placeholder = "Password"
passwordTextField.isSecureTextEntry = true
passwordTextField.delegate = self
dividerView.translatesAutoresizingMaskIntoConstraints = false
dividerView.backgroundColor = .secondarySystemFill
layer.cornerRadius = 5
clipsToBounds = true
}
func layout() {
stackView.addArrangedSubview(usernameTextField)
stackView.addArrangedSubview(dividerView)
stackView.addArrangedSubview(passwordTextField)
addSubview(stackView)
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalToSystemSpacingBelow: topAnchor, multiplier: 1),
stackView.leadingAnchor.constraint(equalToSystemSpacingAfter: leadingAnchor, multiplier: 1),
trailingAnchor.constraint(equalToSystemSpacingAfter: stackView.trailingAnchor, multiplier: 1),
bottomAnchor.constraint(equalToSystemSpacingBelow: stackView.bottomAnchor, multiplier: 1)
])
dividerView.heightAnchor.constraint(equalToConstant: 1).isActive = true
}
}
// UITextFieldDelegate
extension LoginView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
usernameTextField.endEditing(true)
passwordTextField.endEditing(true)
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
}
}
| 28.945652 | 106 | 0.674427 |
38f2d4180640e82295742b7a7191ca099e875744 | 8,662 | //
// GPSTracker.swift
// Loggy
//
// Created by Peter Strand on 2017-06-19.
// Copyright © 2017 Peter Strand. All rights reserved.
//
import Foundation
import CoreLocation
public class GPSTracker {
public typealias TrackPointLogger = (TrackPoint, Bool) -> Void
public typealias StateMonitor = (Bool) -> Void
var loggers : [(Int,TrackPointLogger)] = []
var locationTrackers: [Int] = []
var loggerId = 0
let loc_mgr : CLLocationManager
var pendingTracking = false
var pendingOneshotTracking : [((TrackPoint) -> Void)] = []
var loc_delegate : LocDelegate! = nil
private var isActive = false
var state_callback : StateMonitor?
struct Config {
var timeThreshold: Double
var distThreshold: Double
func isSignificant(_ pt1: TrackPoint, _ pt2: TrackPoint) -> Bool {
var time_diff = Double.greatestFiniteMagnitude
let tm1 = pt1.timestamp
let tm2 = pt2.timestamp
time_diff = tm1.timeIntervalSince(tm2)
let dist_diff = GPSTracker.greatCircleDist(pt1.location, pt2.location)
return dist_diff > distThreshold || time_diff > timeThreshold
}
}
var config : Config = Config(timeThreshold: 10, distThreshold: 1)
var last_point : TrackPoint?
var last_minor_point : TrackPoint?
public init() {
loc_mgr = CLLocationManager()
let delegate = LocDelegate(self)
loc_mgr.delegate = delegate
loc_delegate = delegate
}
public func monitorState(callback : @escaping StateMonitor) {
self.state_callback = callback
self.state_callback?(isActive)
}
func startPendingTracking() {
if pendingTracking || pendingOneshotTracking.count > 0{
loc_mgr.startUpdatingLocation()
print("GPS.startUpdatingLocation()")
isActive = true
pendingTracking = false
self.state_callback?(isActive)
}
}
public func requestLocationTracking() -> Token {
loggerId += 1
let removeId = loggerId
self.locationTrackers.append(removeId)
if !isActive {
start()
}
assert((isActive || pendingTracking) == (self.locationTrackers.count > 0))
return TokenImpl {
if let ix = self.locationTrackers.index(of: removeId) {
self.locationTrackers.remove(at: ix)
if self.locationTrackers.isEmpty {
self.stop()
}
}
}
}
public func addTrackPointLogger(_ logger : @escaping TrackPointLogger) -> Token {
loggerId += 1
let removeId = loggerId
self.loggers.append((removeId,logger))
return TokenImpl {
for ix in self.loggers.indices {
if self.loggers[ix].0 == removeId {
self.loggers.remove(at: ix)
break
}
}
}
}
private func start() {
pendingTracking = true
internalStart()
assert(isActive != pendingTracking);
assert((isActive || pendingTracking) == (self.locationTrackers.count > 0))
}
private func internalStart() {
let status = CLLocationManager.authorizationStatus()
print("start: gps status: \(status.rawValue)")
switch status {
case .notDetermined:
// loc_mgr?.requestWhenInUseAuthorization()
loc_mgr.requestAlwaysAuthorization()
break
case .authorizedAlways, .authorizedWhenInUse:
startPendingTracking()
default:
break
}
}
private func stop() {
pendingTracking = false
internalStop()
assert(isActive == (self.locationTrackers.count > 0))
}
fileprivate func internalStop() {
print("GPS.stopUpdatingLocation()")
loc_mgr.stopUpdatingLocation()
isActive = false
self.state_callback?(isActive)
}
public func currentLocation() -> TrackPoint? {
if let pt = last_minor_point, isActive {
return pt
} else {
return nil
}
}
public func withCurrentLocation(callback: @escaping (TrackPoint) -> Void) {
if let pt = last_minor_point, isActive {
callback(pt)
} else {
pendingOneshotTracking.append(callback)
internalStart()
}
}
public func isGpsActive() -> Bool {
return isActive
}
func handleNewLocation(_ tp : TrackPoint) {
last_minor_point = tp
let significant = last_point == nil || config.isSignificant(last_point!, tp)
for (_,logger) in loggers {
logger(tp, significant)
}
last_point = tp
}
class LocDelegate : NSObject, CLLocationManagerDelegate {
let parent : GPSTracker
init(_ gps : GPSTracker) {
parent = gps
}
func locationManager(_ : CLLocationManager, didUpdateLocations locs: [CLLocation]) {
// print("Tells the delegate that new location data is available: [\(locs)]")
var last_pt : TrackPoint?
for loc in locs {
let pt = TrackPoint(location: loc)
parent.handleNewLocation(pt)
last_pt = pt
}
if parent.pendingOneshotTracking.count > 0 {
if let pt = last_pt {
for cb in parent.pendingOneshotTracking {
cb(pt)
}
parent.pendingOneshotTracking.removeAll()
}
if !parent.pendingTracking {
parent.internalStop()
}
}
}
func locationManager(_ : CLLocationManager, didFailWithError error: Error) {
print("Tells the delegate that the location manager was unable to retrieve a location value.\n\(error)")
}
func locationManager(_ : CLLocationManager, didFinishDeferredUpdatesWithError: Error?) {
print("Tells the delegate that updates will no longer be deferred.")
}
func locationManagerDidPauseLocationUpdates(_ : CLLocationManager) {
print("Tells the delegate that location updates were paused.")
}
func locationManagerDidResumeLocationUpdates(_ _ : CLLocationManager) {
print("Tells the delegate that the delivery of location updates has resumed.\nResponding to Heading Events")
}
func locationManager(_ : CLLocationManager, didUpdateHeading: CLHeading) {
print("Tells the delegate that the location manager received updated heading information.")
}
func locationManagerShouldDisplayHeadingCalibration(_ : CLLocationManager) -> Bool {
print("Asks the delegate whether the heading calibration alert should be displayed.\nResponding to Region Events")
return false
}
func locationManager(_ : CLLocationManager, didEnterRegion: CLRegion) {
print("Tells the delegate that the user entered the specified region.")
}
func locationManager(_ : CLLocationManager, didExitRegion: CLRegion) {
print("Tells the delegate that the user left the specified region.")
}
func locationManager(_ : CLLocationManager, didDetermineState: CLRegionState, for: CLRegion) {
print("Tells the delegate about the state of the specified region.")
}
func locationManager(_ : CLLocationManager, monitoringDidFailFor: CLRegion?, withError: Error) {
print("Tells the delegate that a region monitoring error occurred.")
}
func locationManager(_ : CLLocationManager, didStartMonitoringFor: CLRegion) {
print("Tells the delegate that a new region is being monitored.\nResponding to Ranging Events")
}
func locationManager(_ : CLLocationManager, didRangeBeacons: [CLBeacon], in: CLBeaconRegion) {
print("Tells the delegate that one or more beacons are in range.")
}
func locationManager(_ : CLLocationManager, rangingBeaconsDidFailFor: CLBeaconRegion, withError: Error) {
print("Tells the delegate that an error occurred while gathering ranging information for a set of beacons.\nResponding to Visit Events")
}
func locationManager(_ : CLLocationManager, didVisit: CLVisit) {
print("Tells the delegate that a new visit-related event was received.\nResponding to Authorization Changes")
}
func locationManager(_ : CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("didChangeAuthorization: gps status: \(status.rawValue)")
switch status {
case .authorizedAlways, .authorizedWhenInUse:
parent.startPendingTracking()
break
default:
break
}
}
}
public static func greatCircleDist(_ loc1: CLLocationCoordinate2D, _ loc2: CLLocationCoordinate2D) -> Double {
// Equirectangular approximation
// see: http://www.movable-type.co.uk/scripts/latlong.html
let lat1 = loc1.latitude
let lon1 = loc1.longitude
let lat2 = loc2.latitude
let lon2 = loc2.longitude
let R = 6371000.0
let x = (lon2-lon1) * cos((lat1+lat2)/2);
let y = (lat2-lat1);
let d = sqrt(x*x + y*y) * R;
return d
}
}
| 31.046595 | 142 | 0.671208 |
4bdb29026eba2ce2c92e0b6c11efcbd0bcf5e85b | 1,843 | import KsApi
import Prelude
public struct SelectableRow {
public let isSelected: Bool
public let params: DiscoveryParams
// swiftlint:disable type_name
public enum lens {
public static let isSelected = Lens<SelectableRow, Bool>(
view: { $0.isSelected },
set: { SelectableRow(isSelected: $0, params: $1.params) }
)
public static let params = Lens<SelectableRow, DiscoveryParams>(
view: { $0.params },
set: { SelectableRow(isSelected: $1.isSelected, params: $0) }
)
}
// swiftlint:enable type_name
}
public extension LensType where Whole == SelectableRow, Part == DiscoveryParams {
public var social: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.social
}
public var staffPicks: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.staffPicks
}
public var starred: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.starred
}
public var category: Lens<SelectableRow, KsApi.Category?> {
return SelectableRow.lens.params • DiscoveryParams.lens.category
}
public var hasLiveStreams: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.hasLiveStreams
}
public var includePOTD: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.includePOTD
}
public var recommended: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.recommended
}
public var backed: Lens<SelectableRow, Bool?> {
return SelectableRow.lens.params • DiscoveryParams.lens.backed
}
}
extension SelectableRow: Equatable {}
public func == (lhs: SelectableRow, rhs: SelectableRow) -> Bool {
return lhs.isSelected == rhs.isSelected && lhs.params == rhs.params
}
| 34.12963 | 81 | 0.729788 |
29f74b4ebbb24726067dc5552f613cec2d0f23b7 | 3,769 | import Foundation
import JavaScriptCore
import PromiseKit
@objc protocol ClientsExports: JSExport {
func get(_: String) -> JSValue?
func matchAll(_: [String: Any]?) -> JSValue?
func openWindow(_: String) -> JSValue?
func claim() -> JSValue?
}
/// Implementation of Clients: https://developer.mozilla.org/en-US/docs/Web/API/Clients to allow
/// Service Workers to get/take control of/open clients under their scope. This is really just
/// a bridge to whatever ServiceWorkerClientDelegate is set.
@objc class Clients: NSObject, ClientsExports {
unowned let worker: ServiceWorker
init(for worker: ServiceWorker) {
self.worker = worker
}
func get(_ id: String) -> JSValue? {
return Promise<Client?> { seal in
if self.worker.clientsDelegate?.clients?(self.worker, getById: id, { err, clientProtocol in
if let error = err {
seal.reject(error)
} else if let clientExists = clientProtocol {
seal.fulfill(Client.getOrCreate(from: clientExists))
} else {
seal.fulfill(nil)
}
}) == nil {
seal.reject(ErrorMessage("ServiceWorkerDelegate does not implement get()"))
}
}.toJSPromiseInCurrentContext()
}
func matchAll(_ options: [String: Any]?) -> JSValue? {
return Promise<[Client]> { seal in
// Two options provided here: https://developer.mozilla.org/en-US/docs/Web/API/Clients/matchAll
let type = options?["type"] as? String ?? "all"
let includeUncontrolled = options?["includeUncontrolled"] as? Bool ?? false
let options = ClientMatchAllOptions(includeUncontrolled: includeUncontrolled, type: type)
if self.worker.clientsDelegate?.clients?(self.worker, matchAll: options, { err, clientProtocols in
if let error = err {
seal.reject(error)
} else if let clientProtocolsExist = clientProtocols {
let mapped = clientProtocolsExist.map({ Client.getOrCreate(from: $0) })
seal.fulfill(mapped)
} else {
seal.reject(ErrorMessage("Callback did not error but did not send a response either"))
}
}) == nil {
seal.reject(ErrorMessage("ServiceWorkerDelegate does not implement matchAll()"))
}
}
.toJSPromiseInCurrentContext()
}
func openWindow(_ url: String) -> JSValue? {
return Promise<ClientProtocol> { seal in
guard let parsedURL = URL(string: url, relativeTo: self.worker.url) else {
return seal.reject(ErrorMessage("Could not parse URL given"))
}
if self.worker.clientsDelegate?.clients?(self.worker, openWindow: parsedURL, { err, resp in
if let error = err {
seal.reject(error)
} else if let response = resp {
seal.fulfill(response)
}
}) == nil {
seal.reject(ErrorMessage("ServiceWorkerDelegate does not implement openWindow()"))
}
}.toJSPromiseInCurrentContext()
}
func claim() -> JSValue? {
return Promise<Void> { seal in
if self.worker.clientsDelegate?.clientsClaim?(self.worker, { err in
if let error = err {
seal.reject(error)
} else {
seal.fulfill(())
}
}) == nil {
seal.reject(ErrorMessage("ServiceWorkerDelegate does not implement claim()"))
}
}.toJSPromiseInCurrentContext()
}
}
| 37.316832 | 110 | 0.57177 |
3800e50aeebdb2d372ff6fd80264ba3a0af4d2eb | 967 | // Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Foundation
public class Stellar: Blockchain {
public override var coinType: CoinType {
return .stellar
}
public override func address(data: Data) -> Address? {
return StellarAddress(data: data)
}
public override func address(string: String) -> Address? {
return StellarAddress(string: string)
}
public override func address(for publicKey: PublicKey) -> Address {
return StellarAddress(publicKey: publicKey.compressed)
}
}
extension StellarAddress: Address {
public static func isValid(data: Data) -> Bool {
return data.count == 32
}
public var data: Data {
return keyHash
}
}
| 26.135135 | 77 | 0.667011 |
16bc683bd1b196af8c2a178a39d8e28b74b67797 | 1,080 | // Copyright © 2018 Stormbird PTE. LTD.
import Foundation
import UIKit
struct RequestViewModel {
private let account: Wallet
init(account: Wallet) {
self.account = account
}
var myAddressText: String {
return account.address.eip55String
}
var myAddress: AlphaWallet.Address {
return account.address
}
var copyWalletText: String {
return R.string.localizable.requestCopyWalletButtonTitle()
}
var addressCopiedText: String {
return R.string.localizable.requestAddressCopiedTitle()
}
var backgroundColor: UIColor {
return Colors.appBackground
}
var addressLabelColor: UIColor {
return Colors.appText
}
var copyButtonsFont: UIFont {
return Fonts.semibold(size: 17)
}
var labelColor: UIColor? {
return Colors.appText
}
var addressFont: UIFont {
return Fonts.semibold(size: 17)
}
var addressBackgroundColor: UIColor {
return Colors.appBackground
}
var instructionFont: UIFont {
return Fonts.regular(size: 17)
}
var instructionText: String {
return R.string.localizable.aWalletAddressScanInstructions()
}
}
| 17.704918 | 62 | 0.740741 |
d63a209e688f2dcbe7fdd8a01d8258b5ff548b63 | 1,039 | // UInt4Tests+BinaryIntegerTests.swift
// ExtensionsTests
//
// Copyright © 2021 Alexandre H. Saad
// Licensed under Apache License v2.0 with Runtime Library Exception
//
import XCTest
@testable import Extensions
extension UInt4Tests {
func test_initializedClampingSucceeds() {
// Given
let min: TestSubject = .init(clamping: -1)
let max: TestSubject = .init(clamping: 16)
// Then
XCTAssertEqual(min, 0)
XCTAssertEqual(max, 15)
}
func test_trailingZeroBitCountSucceeds() {
// Given
let zero: TestSubject = .init(0b0000)
let fifteen: TestSubject = .init(0b1111)
// Then
XCTAssertEqual(zero.trailingZeroBitCount, 4)
XCTAssertEqual(fifteen.trailingZeroBitCount, 0)
}
func test_signumSucceeds() {
// Given
let zero: TestSubject = 0
let four: TestSubject = 4
// Then
XCTAssertEqual(zero.signum(), 0)
XCTAssertEqual(four.signum(), 1)
}
}
| 24.738095 | 68 | 0.611165 |
4a48d64116b6a997c72b9cc1a5ee398d216f9a56 | 2,761 | //
// SceneDelegate.swift
// Flux
//
// Created by Matsushita Kohei on 2020/05/28.
// Copyright © 2020 Stanfit Inc. All rights reserved.
//
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 42.476923 | 147 | 0.705904 |
ef0511a47f6063f99b3cf89d686e24a56a082212 | 2,193 | //
// UrlRequester.swift
// OnTheMap
//
// Created by Fabrício Silva Carvalhal on 05/06/21.
//
import Foundation
protocol URLRequesterProtocol {
func makeRequest(with request: URLRequest, completion: ((Result<Data>) -> Void)?)
}
enum URLRequesterError: LocalizedError {
case emptyResponse
case emptyData
case unauthorized
case serverError
case urlSessionError(Error)
var errorDescription: String? {
switch self {
case .emptyData, .emptyResponse:
return "Server returned no data"
case .serverError:
return "An error occurred on the server"
case .unauthorized:
return "User not authorized, check your credentials and try again"
case .urlSessionError:
return "Error communication with the server"
}
}
}
final class URLRequester: URLRequesterProtocol {
func makeRequest(with request: URLRequest, completion: ((Result<Data>) -> Void)?) {
URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in
if let error = error {
completion?(.failure(URLRequesterError.urlSessionError(error)))
return
}
guard let data = data else {
completion?(.failure(URLRequesterError.emptyData))
return
}
if let urlResponse = response as? HTTPURLResponse {
do {
try self?.handleResponseCode(urlResponse.statusCode)
completion?(.success(data))
} catch let error {
completion?(.failure(error))
}
} else {
completion?(.failure(URLRequesterError.emptyResponse))
}
}.resume()
}
func handleResponseCode(_ statusCode: Int) throws {
switch statusCode {
case 200..<300:
return
case 400..<500:
throw URLRequesterError.unauthorized
case 500..<600:
throw URLRequesterError.serverError
default:
throw URLRequesterError.serverError
}
}
}
| 28.855263 | 90 | 0.574099 |
6a355eae82b5b05aa465cceaad1099ded18bafd4 | 2,844 | //
// RuntimeInfo.swift
// mcCore
//
// Created by Vlad Gorlov on 02.04.18.
// Copyright © 2018 WaveLabs. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
public struct RuntimeInfo {
public struct Constants {
public static let isPlaygroundTestingMode = "app.runtime.isPlaygroundTestingMode"
public static let isUITestingMode = "app.runtime.isUITestingMode"
public static let isNetworkingTraceEnabled = "app.runtime.isNetworkingTraceEnabled"
public static let isInMemoryStore = "app.runtime.isInMemoryStore"
public static let isStubsDisabled = "app.runtime.isStubsDisabled"
public static let shouldAssertOnAmbiguousLayout = "app.runtime.shouldAssertOnAmbiguousLayout"
}
/**
The raw system info string, e.g. "iPhone7,2".
- SeeAlso: http://stackoverflow.com/a/30075200/1418981
*/
public static var rawSystemInfo: String? {
var systemInfo = utsname()
uname(&systemInfo)
return String(bytes: Data(bytes: &systemInfo.machine,
count: Int(_SYS_NAMELEN)), encoding: .ascii)?.trimmingCharacters(in: .controlCharacters)
}
public static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
public static let isInsidePlayground = (Bundle.main.bundleIdentifier ?? "").hasPrefix("com.apple.dt")
public static var isUnderTesting: Bool {
return isUnderLogicTesting || isUnderUITesting || isPlaygroundTesting
}
public static var isUnderLogicTesting: Bool = {
NSClassFromString("XCTestCase") != nil
}()
public static let isUnderUITesting: Bool = {
ProcessInfo.processInfo.environment[Constants.isUITestingMode] != nil
}()
public static let isInMemoryStore: Bool = {
ProcessInfo.processInfo.environment[Constants.isInMemoryStore] != nil
}()
public static let isPlaygroundTesting: Bool = {
ProcessInfo.processInfo.environment[Constants.isPlaygroundTestingMode] != nil
}()
public static let isNetworkingTraceEnabled: Bool = {
ProcessInfo.processInfo.environment[Constants.isNetworkingTraceEnabled] != nil
}()
public static let isStubsDisabled: Bool = {
ProcessInfo.processInfo.environment[Constants.isStubsDisabled] != nil
}()
public static let shouldAssertOnAmbiguousLayout: Bool = {
ProcessInfo.processInfo.environment[Constants.shouldAssertOnAmbiguousLayout] != nil
}()
#if os(iOS)
public static let deviceName = UIDevice.current.name
#elseif os(OSX)
// This method executes synchronously. The execution time of this method can be highly variable,
// depending on the local network configuration, and may block for several seconds if the network is unreachable.
public static let serviceName = Host.current().name ?? "localhost"
#endif
}
| 33.458824 | 120 | 0.719761 |
0a444b4d02b4fd4a61cddb68a33a254d0b8de27c | 9,124 | //
// FidoPositions.swift
//
//
// Input: for use with Portfolio_Positions_Mmm-DD-YYYY.csv from Fidelity Brokerage Services
//
// Output: supports openalloc/holding, /security, /account, and /meta schemas
//
// Copyright 2021 FlowAllocator LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import SwiftCSV
import AllocData
import FINporter
public class FidoPositions: FINporter {
public override var name: String { "Fido Positions" }
public override var id: String { "fido_positions" }
public override var description: String { "Detect and decode position export files from Fidelity." }
public override var sourceFormats: [AllocFormat] { [.CSV] }
public override var outputSchemas: [AllocSchema] { [.allocMetaSource, .allocAccount, .allocHolding, .allocSecurity] }
private let trimFromTicker = CharacterSet(charactersIn: "*")
internal static let headerRE = #"""
Account Number,Account Name,Symbol,Description,Quantity,Last Price,Last Price Change,Current Value,Today's Gain/Loss Dollar,Today's Gain/Loss Percent,Total Gain/Loss Dollar,Total Gain/Loss Percent,Percent Of Account,Cost Basis,Cost Basis Per Share,Type
"""#
// should match all lines, until a blank line or end of block/file
internal static let csvRE = #"Account Number,Account Name,Symbol,Description,Quantity,(?:.+(\n|\Z))+"#
public override func detect(dataPrefix: Data) throws -> DetectResult {
guard let str = FINporter.normalizeDecode(dataPrefix),
str.range(of: FidoPositions.headerRE,
options: .regularExpression) != nil
else {
return [:]
}
return outputSchemas.reduce(into: [:]) { map, schema in
map[schema, default: []].append(.CSV)
}
}
override open func decode<T: AllocRowed>(_ type: T.Type,
_ data: Data,
rejectedRows: inout [T.RawRow],
inputFormat _: AllocFormat? = nil,
outputSchema: AllocSchema? = nil,
url: URL? = nil,
defTimeOfDay _: String? = nil,
timeZone _: TimeZone = TimeZone.current,
timestamp: Date? = nil) throws -> [T.DecodedRow] {
guard let str = FINporter.normalizeDecode(data) else {
throw FINporterError.decodingError("unable to parse data")
}
guard let outputSchema_ = outputSchema else {
throw FINporterError.needExplicitOutputSchema(outputSchemas)
}
var items = [T.DecodedRow]()
if outputSchema_ == .allocMetaSource {
var exportedAt: Date? = nil
// extract exportedAt from "Date downloaded 07/30/2021 2:26 PM ET" (with quotes)
let ddRE = #"(?<=\"Date downloaded ).+(?=\")"#
if let dd = str.range(of: ddRE, options: .regularExpression) {
exportedAt = fidoDateFormatter.date(from: String(str[dd]))
}
let sourceMetaID = UUID().uuidString
items.append([
MSourceMeta.CodingKeys.sourceMetaID.rawValue: sourceMetaID,
MSourceMeta.CodingKeys.url.rawValue: url,
MSourceMeta.CodingKeys.importerID.rawValue: self.id,
MSourceMeta.CodingKeys.exportedAt.rawValue: exportedAt,
])
} else {
if let csvRange = str.range(of: FidoPositions.csvRE, options: .regularExpression) {
let csvStr = str[csvRange]
let delimitedRows = try CSV(string: String(csvStr)).namedRows
let nuItems = decodeDelimitedRows(delimitedRows: delimitedRows,
outputSchema_: outputSchema_,
rejectedRows: &rejectedRows,
timestamp: timestamp)
items.append(contentsOf: nuItems)
}
}
return items
}
internal func decodeDelimitedRows(delimitedRows: [AllocRowed.RawRow],
outputSchema_: AllocSchema,
rejectedRows: inout [AllocRowed.RawRow],
timestamp: Date?) -> [AllocRowed.DecodedRow] {
delimitedRows.reduce(into: []) { decodedRows, delimitedRow in
switch outputSchema_ {
case .allocAccount:
guard let item = account(delimitedRow, rejectedRows: &rejectedRows) else { return }
decodedRows.append(item)
case .allocHolding:
guard let item = holding(delimitedRow, rejectedRows: &rejectedRows) else { return }
decodedRows.append(item)
case .allocSecurity:
guard let item = security(delimitedRow, rejectedRows: &rejectedRows, timestamp: timestamp) else { return }
decodedRows.append(item)
default:
rejectedRows.append(delimitedRow)
//throw FINporterError.targetSchemaNotSupported(outputSchemas)
}
}
}
internal func holding(_ row: AllocRowed.RawRow, rejectedRows: inout [AllocRowed.RawRow]) -> AllocRowed.DecodedRow? {
// required values
guard let accountID = MHolding.parseString(row["Account Number"]),
accountID.count > 0,
let securityID = MHolding.parseString(row["Symbol"], trimCharacters: trimFromTicker),
securityID.count > 0,
securityID != "Pending Activity",
let shareCount = MHolding.parseDouble(row["Quantity"]),
shareCount != 0
else {
rejectedRows.append(row)
return nil
}
var decodedRow: AllocRowed.DecodedRow = [
MHolding.CodingKeys.accountID.rawValue: accountID,
MHolding.CodingKeys.securityID.rawValue: securityID,
MHolding.CodingKeys.shareCount.rawValue: shareCount,
]
// holding may have "n/a" for share basis
var shareBasis: Double? = nil
shareBasis = MHolding.parseDouble(row["Cost Basis Per Share"])
if (shareBasis == nil || shareBasis == 0),
row["Cost Basis Per Share"] == "n/a" {
if let sharePrice = MHolding.parseDouble(row["Last Price"]),
sharePrice == 1.0 {
// assume it's cash, where the share basis is 1.00
shareBasis = 1.0
} else if let costBasis = MHolding.parseDouble(row["Cost Basis"]),
costBasis > 0 {
// reconstruct the shareBasis
shareBasis = costBasis / shareCount
}
}
if let _shareBasis = shareBasis {
decodedRow[MHolding.CodingKeys.shareBasis.rawValue] = _shareBasis
}
return decodedRow
}
internal func security(_ row: AllocRowed.RawRow, rejectedRows: inout [AllocRowed.RawRow], timestamp: Date?) -> AllocRowed.DecodedRow? {
guard let securityID = MHolding.parseString(row["Symbol"], trimCharacters: trimFromTicker),
securityID.count > 0,
securityID != "Pending Activity",
let sharePrice = MHolding.parseDouble(row["Last Price"])
else {
rejectedRows.append(row)
return nil
}
var decodedRow: AllocRowed.DecodedRow = [
MSecurity.CodingKeys.securityID.rawValue: securityID,
MSecurity.CodingKeys.sharePrice.rawValue: sharePrice,
]
if let updatedAt = timestamp {
decodedRow[MSecurity.CodingKeys.updatedAt.rawValue] = updatedAt
}
return decodedRow
}
internal func account(_ row: AllocRowed.RawRow, rejectedRows: inout [AllocRowed.RawRow]) -> AllocRowed.DecodedRow? {
guard let accountID = MHolding.parseString(row["Account Number"]),
accountID.count > 0,
let title = MHolding.parseString(row["Account Name"])
else {
rejectedRows.append(row)
return nil
}
return [
MAccount.CodingKeys.accountID.rawValue: accountID,
MAccount.CodingKeys.title.rawValue: title
]
}
}
| 41.853211 | 256 | 0.578803 |
e5bad80e7eebff14844a7e3ad79bce10f9518566 | 589 | import Foundation
extension SendPaymentAmount {
struct Routing {
let onShowProgress: () -> Void
let onHideProgress: () -> Void
let onShowError: (_ erroMessage: String) -> Void
let onPresentPicker: (
_ options: [String],
_ onSelect: @escaping (_ balanceId: String) -> Void
) -> Void
let onSendAction: ((_ sendModel: Model.SendPaymentModel) -> Void)?
let onShowWithdrawDestination: ((_ sendModel: Model.SendWithdrawModel) -> Void)?
let showFeesOverview: (_ asset: String, _ feeType: Int32) -> Void
}
}
| 34.647059 | 88 | 0.624788 |
0395af821b8bdb9e04e6dcb00c51921fd09bf1d1 | 590 | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "sql-kit",
products: [
.library(name: "SQLKit", targets: ["SQLKit"]),
.library(name: "SQLKitBenchmark", targets: ["SQLKitBenchmark"]),
],
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.0.0"),
],
targets: [
.target(name: "SQLKit", dependencies: ["NIO"]),
.target(name: "SQLKitBenchmark", dependencies: ["SQLKit"]),
.testTarget(name: "SQLKitTests", dependencies: ["SQLKit", "SQLKitBenchmark"]),
]
)
| 31.052632 | 86 | 0.6 |
69745bca8e472c525a8ac8339b5b046709e4a1e2 | 906 | //
// DGCAWalletTests.swift
// DGCAWalletTests
//
// Created by Yannick Spreen on 4/8/21.
//
import XCTest
@testable import DGCAWallet
class DGCAWalletTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
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.
}
}
}
| 26.647059 | 111 | 0.666667 |
ac7be171e1fcfb460283696df8dffe953779315b | 224 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
return {
let start = compose ( [ {
init {
class
case ,
| 22.4 | 87 | 0.736607 |
ed941d76e24f2afbc12c58ed9d28e71b94688327 | 1,604 | //
// MapInfo.swift
// Moop
//
// Created by kor45cw on 31/07/2019.
// Copyright © 2019 kor45cw. All rights reserved.
//
import Foundation
import MapKit
struct MapInfo: Decodable {
let cgv: [AreaGroup]
let lotte: [AreaGroup]
let megabox: [AreaGroup]
var items: [TheaterMapInfo] {
let cgvList = cgv.flatMap({ $0.theaterList })
let lotteList = lotte.flatMap({ $0.theaterList })
let megaboxList = megabox.flatMap({ $0.theaterList })
return cgvList + lotteList + megaboxList
}
}
struct AreaGroup: Decodable {
let area: Area
let theaterList: [TheaterMapInfo]
}
struct Area: Decodable {
let code: String
let name: String
}
class TheaterMapInfo: NSObject, Decodable, MKAnnotation {
let type: String
let code: String
let name: String
let lng: Double
let lat: Double
var theaterType: TheaterType {
return TheaterType(type: type)
}
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: lat, longitude: lng)
}
var title: String? {
return "\(name) \(theaterType.title)"
}
var destinationName: String {
let dname = "도착지".localized.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
return title?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? dname
}
var mapItem: MKMapItem {
let placemark = MKPlacemark(coordinate: coordinate)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}
}
| 24.30303 | 104 | 0.648379 |
26b4028465f6b45b064346218baf89a47eb2b298 | 13,222 | //
// DroidClockSelector.swift
// DroidTimeSelection
//
// Created by Dan Draiman on 7/22/20.
// Copyright © 2020 Nexxmark Studio. All rights reserved.
//
import UIKit
/// A time selector showing a time indicator along with a physical clock to
/// give user the ability to manually select the time using an intuitive way.
///
/// Set the callback `onSelectionChanged` to get updates from this component.
///
/// This is the same UI presented in Android phones.
/// - Change `timeFormat` to change the selection mode for the selector.
/// - Change `style` to change the style of the selectors and the menu. See `ClockStyle` for more details about possible styling.
@available(iOS 10.0, *)
@IBDesignable
public class DroidClockSelector: UIView, ClockTimeSelector {
// MARK: - Storyboard Properties
@IBInspectable
var outerCircleTextColor: UIColor = .white {
didSet {
style.outerCircleTextColor = outerCircleTextColor
}
}
@IBInspectable
var outerCircleBackgroundColor: UIColor = .clear {
didSet {
style.outerCircleBackgroundColor = outerCircleBackgroundColor
}
}
@IBInspectable
var innerCircleTextColor: UIColor = .gray {
didSet {
style.innerCircleTextColor = innerCircleTextColor
}
}
@IBInspectable
var innerCircleBackgroundColor: UIColor = .clear {
didSet {
style.innerCircleBackgroundColor = innerCircleBackgroundColor
}
}
@IBInspectable
var selectedColor: UIColor = .white {
didSet {
style.selectedColor = selectedColor
}
}
@IBInspectable
var deselectedColor: UIColor = .gray {
didSet {
style.deselectedColor = deselectedColor
}
}
@IBInspectable
var indicatorColor: UIColor = .blue {
didSet {
style.indicatorColor = indicatorColor
}
}
@IBInspectable
var selectionFont: UIFont = .systemFont(ofSize: 18) {
didSet {
style.selectionFont = selectionFont
}
}
@IBInspectable
var numbersFont: UIFont = .systemFont(ofSize: 18) {
didSet {
style.numbersFont = numbersFont
}
}
// MARK: - Public Properties
/// Styling for Hybrid menu and for the inner selectors.
public var style: ClockStyle = .init() {
didSet {
if oldValue != style {
onStyleChanged()
}
}
}
/// Time format for the selector.
public var timeFormat: DroidTimeFormat = .twelve {
didSet {
onTimeFormatChanged()
}
}
/// The current time value of the selector. See `Time` object for more info.
public var time: Time {
return currentTime
}
/// Will be called for every change in Time value.
public var onSelectionChanged: ((Time) -> Void)?
/// Will be called once both hours and minutes are chosen and interaction ends.
public var onSelectionEnded: ((Time) -> Void)?
// MARK: - Private Properties
private var currentTime: Time = .init() {
didSet {
onSelectionChanged?(currentTime)
onCurrentTimeChanged()
}
}
private var currentMode: ClockSelectionMode = .hour
// MARK: - UI Components
private let timeIndicator = DroidTimeIndicatorView()
private let clockCollection = DroidClockCollectionView()
// MARK: - Lifecycle
public override init(frame: CGRect) {
super.init(frame: .zero)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
addSubview(clockCollection)
addSubview(timeIndicator)
timeIndicator.anchor(height: 80)
timeIndicator.anchor(
in: self,
to: [.top()],
padding: .init(top: 28, left: 28, bottom: 28, right: 28))
timeIndicator
.widthAnchor
.constraint(lessThanOrEqualTo: widthAnchor,
multiplier: 0.8)
.isActive = true
timeIndicator.centerX(in: self)
clockCollection
.topAnchor
.constraint(equalTo: timeIndicator.bottomAnchor)
.isActive = true
clockCollection.anchor(
in: self,
to: [.bottom(), .left(), .right()],
padding: .init(top: 12, left: 12, bottom: 12, right: 12))
clockCollection
.widthAnchor
.constraint(equalTo: clockCollection.heightAnchor,
multiplier: 1.0)
.isActive = true
bindTimeIndicator()
bindClockCollection()
onStyleChanged()
reset()
}
// MARK: - Setup
private func bindTimeIndicator() {
timeIndicator.onPmTapped = { [weak self] in
self?.onPmLabelTapped()
}
timeIndicator.onAmTapped = { [weak self] in
self?.onAmLabelTapped()
}
timeIndicator.onHoursTapped = { [weak self] in
self?.onHourLabelTapped()
}
timeIndicator.onMinutesTapped = { [weak self] in
self?.onMinutesLabelTapped()
}
}
private func bindClockCollection() {
clockCollection.onHourSelected = { [weak self] hour in
self?.onHourSelected(hour)
}
clockCollection.onMinuteSelected = { [weak self] minute in
self?.onMinuteSelected(minute)
}
clockCollection.onHourSelectionEnded = { [weak self] value in
self?.onHourSelectionEnded()
}
clockCollection.onMinuteSelectionEnded = { [weak self] value in
guard let time = self?.time else {
return
}
self?.onSelectionEnded?(time)
}
}
// MARK: - Helpers
private func onHourSelectionEnded() {
changeMode(to: .minutes) { _ in
switch self.timeFormat {
case .twelve:
self.clockCollection.moveIndicatorToMinute(self
.time
.twelveHoursFormat
.minutes)
case .twentyFour:
self.clockCollection.moveIndicatorToMinute(self
.time
.twentyFourHoursFormat
.minutes)
}
}
}
private func onHourSelected(_ hour: Int) {
selectHour(value: hour)
}
private func onMinuteSelected(_ minute: Int) {
selectMinutes(value: minute)
}
private func moveIndicatorToReflectSelection() {
switch currentMode {
case .hour:
switch timeFormat {
case .twelve:
clockCollection.moveIndicatorToHour(self.time.twelveHoursFormat.hours)
case .twentyFour:
clockCollection.moveIndicatorToHour(self.time.twentyFourHoursFormat.hours)
}
case .minutes:
switch timeFormat {
case .twelve:
clockCollection.moveIndicatorToMinute(self.time.twelveHoursFormat.minutes)
case .twentyFour:
clockCollection.moveIndicatorToMinute(self.time.twentyFourHoursFormat.minutes)
}
}
}
private func onHourLabelTapped() {
changeMode(to: .hour) { _ in
switch self.timeFormat {
case .twelve:
self.clockCollection.moveIndicatorToHour(self.time.twelveHoursFormat.hours)
case .twentyFour:
self.clockCollection.moveIndicatorToHour(self.time.twentyFourHoursFormat.hours)
}
}
}
private func onMinutesLabelTapped() {
changeMode(to: .minutes) { _ in
switch self.timeFormat {
case .twelve:
self.clockCollection.moveIndicatorToMinute(self.time.twelveHoursFormat.minutes)
case .twentyFour:
self.clockCollection.moveIndicatorToMinute(self.time.twentyFourHoursFormat.minutes)
}
}
}
private func onAmLabelTapped() {
currentTime.twelveHoursFormat.am = true
set(
hour: time.twelveHoursFormat.hours,
minutes: time.twelveHoursFormat.minutes,
am: true)
}
private func onPmLabelTapped() {
currentTime.twelveHoursFormat.am = false
set(
hour: time.twelveHoursFormat.hours,
minutes: time.twelveHoursFormat.minutes,
am: false)
}
private func selectHour(value: Int) {
switch timeFormat {
case .twelve:
currentTime.twelveHoursFormat.hours = value
if value == 12 {
currentTime
.twentyFourHoursFormat
.hours = (time.twelveHoursFormat.am ?? true) ? 0 : 12
} else {
currentTime
.twentyFourHoursFormat
.hours = value + (time.twelveHoursFormat.am ?? true ? 0 : 12)
}
case .twentyFour:
currentTime.twentyFourHoursFormat.hours = value
let isAm = value < 12
currentTime.twelveHoursFormat.am = isAm
currentTime.twelveHoursFormat.hours = isAm ? value - 12 : value
}
}
private func selectMinutes(value: Int) {
currentTime.twentyFourHoursFormat.minutes = value
currentTime.twelveHoursFormat.minutes = value
}
private func onModeChanged(completion: ((Bool) -> Void)?) {
clockCollection.currentMode = currentMode
highlight(mode: currentMode)
moveIndicatorToReflectSelection()
}
private func onStyleChanged() {
reloadData()
highlight(mode: currentMode)
timeIndicator.amPmFont = style.selectionFont
timeIndicator.timeFont = style.selectionFont.withSize(60)
clockCollection.indicatorColor = style.indicatorColor
clockCollection.outerCircleTextColor = style.outerCircleTextColor
clockCollection.outerCircleBackgroundColor = style.outerCircleBackgroundColor
clockCollection.innerCircleTextColor = style.innerCircleTextColor
clockCollection.innerCircleBackgroundColor = style.innerCircleBackgroundColor
clockCollection.numbersFont = style.numbersFont
onTimeFormatChanged()
}
private func highlight(mode: ClockSelectionMode) {
let selectedColor = style.selectedColor
let deselectedColor = style.deselectedColor
timeIndicator.hoursColor = mode == .hour ?
selectedColor :
deselectedColor
timeIndicator.minutesColor = mode == .minutes ?
selectedColor :
deselectedColor
if let isAm = time.twelveHoursFormat.am {
timeIndicator.amColor = isAm ?
selectedColor :
deselectedColor
timeIndicator.pmColor = !isAm ?
selectedColor :
deselectedColor
}
}
private func onCurrentTimeChanged() {
timeIndicator.time = self.currentTime
highlight(mode: currentMode)
}
private func changeMode(to mode: ClockSelectionMode, completion: ((Bool) -> Void)?) {
currentMode = mode
onModeChanged(completion: completion)
}
private func onTimeFormatChanged() {
clockCollection.timeFormat = self.timeFormat
timeIndicator.timeFormat = self.timeFormat
onCurrentTimeChanged()
}
private func reloadData() {
self.clockCollection.reloadData()
}
// MARK: - Public Interface
/// Set the current time selection to the given parameters.
/// - Parameters:
/// - hour: the hour number.
/// - minutes: the amount of minutes.
/// - am: if time is am/pm or nil for 24 hours format.
public func set(hour: Int, minutes: Int, am: Bool?) {
currentTime.twelveHoursFormat.am = am
self.selectHour(value: hour)
self.selectMinutes(value: minutes)
clockCollection.set(time: time)
onCurrentTimeChanged()
}
/// Set the current time selection to the given parameters.
/// - Parameter time: Time representing the time selection.
public func set(time: Time) {
currentTime = time
clockCollection.set(time: time)
onCurrentTimeChanged()
}
/// Reset the component. Sets time to 00:00 or 12am.
public func reset() {
currentTime = .init()
clockCollection.set(time: currentTime)
changeMode(to: .hour) { _ in
switch self.timeFormat {
case .twelve:
self.clockCollection.moveIndicatorToHour(self.time.twelveHoursFormat.hours)
case .twentyFour:
self.clockCollection.moveIndicatorToHour(self.time.twentyFourHoursFormat.hours)
}
}
onStyleChanged()
}
}
internal enum ClockSelectionMode {
case hour, minutes
}
| 31.406176 | 129 | 0.58985 |
612b38555297c1430cd75defb6f8420b323091cb | 1,207 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2018 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
//
//===----------------------------------------------------------------------===//
/// The context information for a Swift package.
///
/// The context encapsulates states that are known when Swift Package Manager interprets the package manifest,
/// for example the location in the file system where the current package resides.
@available(_PackageDescription, introduced: 5.6)
public struct Context {
private static let model = try! ContextModel.decode()
/// The directory that contains `Package.swift`.
public static var packageDirectory : String {
model.packageDirectory
}
/// Snapshot of the system environment variables.
public static var environment : [String : String] {
model.environment
}
private init() {
}
}
| 35.5 | 110 | 0.620547 |
11994ed82693f0c97b001f440d9d6e5e0df2b6ee | 758 | import UIKit
import XCTest
import Twitster
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.266667 | 111 | 0.604222 |
71344384b5f85e17e48568dd9c674702e7c0ef0a | 10,657 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | FileCheck %s
// REQUIRES: objc_interop
import gizmo
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test3FT_CSo8NSObject
func test3() -> NSObject {
// initializer returns at +1
return Gizmo()
// CHECK: [[CTOR:%[0-9]+]] = function_ref @_TFCSo5GizmoC{{.*}} : $@convention(thin) (@thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK-NEXT: [[GIZMO_META:%[0-9]+]] = metatype $@thick Gizmo.Type
// CHECK-NEXT: [[GIZMO:%[0-9]+]] = apply [[CTOR]]([[GIZMO_META]]) : $@convention(thin) (@thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK: [[GIZMO_NS:%[0-9]+]] = upcast [[GIZMO:%[0-9]+]] : $Gizmo to $NSObject
// CHECK: return [[GIZMO_NS]] : $NSObject
// CHECK-LABEL: sil shared @_TFCSo5GizmoC{{.*}} : $@convention(thin) (@thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// alloc is implicitly ns_returns_retained
// init is implicitly ns_consumes_self and ns_returns_retained
// CHECK: bb0([[GIZMO_META:%[0-9]+]] : $@thick Gizmo.Type):
// CHECK-NEXT: [[GIZMO_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[GIZMO_META]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type
// CHECK-NEXT: [[GIZMO:%[0-9]+]] = alloc_ref_dynamic [objc] [[GIZMO_META_OBJC]] : $@objc_metatype Gizmo.Type, $Gizmo
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[INIT_CTOR:%[0-9]+]] = function_ref @_TTOFCSo5Gizmoc{{.*}}
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[INIT_CTOR]]([[GIZMO]]) : $@convention(method) (@owned Gizmo) -> @owned ImplicitlyUnwrappedOptional<Gizmo>
// CHECK-NEXT: return [[RESULT]] : $ImplicitlyUnwrappedOptional<Gizmo>
}
// Normal message send with argument, no transfers.
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test5
func test5(g: Gizmo) {
var g = g
Gizmo.inspect(g)
// CHECK: [[CLASS:%.*]] = metatype $@thick Gizmo.Type
// CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[CLASS]] : {{.*}}, #Gizmo.inspect!1.foreign
// CHECK-NEXT: [[OBJC_CLASS:%[0-9]+]] = thick_to_objc_metatype [[CLASS]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type
// CHECK: [[V:%.*]] = load
// CHECK: strong_retain [[V]]
// CHECK: [[G:%.*]] = enum $ImplicitlyUnwrappedOptional<Gizmo>, #ImplicitlyUnwrappedOptional.Some!enumelt.1, [[V]]
// CHECK-NEXT: apply [[METHOD]]([[G]], [[OBJC_CLASS]])
// CHECK-NEXT: release_value [[G]]
}
// The argument to consume is __attribute__((ns_consumed)).
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test6
func test6(g: Gizmo) {
var g = g
Gizmo.consume(g)
// CHECK: [[CLASS:%.*]] = metatype $@thick Gizmo.Type
// CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[CLASS]] : {{.*}}, #Gizmo.consume!1.foreign
// CHECK-NEXT: [[OBJC_CLASS:%.*]] = thick_to_objc_metatype [[CLASS]] : $@thick Gizmo.Type to $@objc_metatype Gizmo.Type
// CHECK: [[V:%.*]] = load
// CHECK: strong_retain [[V]]
// CHECK: [[G:%.*]] = enum $ImplicitlyUnwrappedOptional<Gizmo>, #ImplicitlyUnwrappedOptional.Some!
// CHECK-NEXT: apply [[METHOD]]([[G]], [[OBJC_CLASS]])
// CHECK-NOT: release_value [[G]]
}
// fork is __attribute__((ns_consumes_self)).
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test7
func test7(g: Gizmo) {
var g = g
g.fork()
// CHECK: [[G:%.*]] = load
// CHECK-NEXT: retain [[G]]
// CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[G]] : {{.*}}, #Gizmo.fork!1.foreign
// CHECK-NEXT: apply [[METHOD]]([[G]])
// CHECK-NOT: release [[G]]
}
// clone is __attribute__((ns_returns_retained)).
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test8
func test8(g: Gizmo) -> Gizmo {
return g.clone()
// CHECK: bb0([[G:%.*]] : $Gizmo):
// CHECK-NOT: retain
// CHECK: alloc_stack $ImplicitlyUnwrappedOptional<Gizmo>
// CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[G]] : {{.*}}, #Gizmo.clone!1.foreign
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[G]])
// CHECK-NEXT: store
// CHECK-NEXT: function_ref
// CHECK-NEXT: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue
// CHECK-NEXT: alloc_stack
// CHECK-NEXT: apply
// CHECK-NEXT: [[RESULT:%.*]] = load
// CHECK-NEXT: dealloc_stack
// CHECK-NOT: release [[G]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: release [[G]]
// CHECK-NEXT: return [[RESULT]]
}
// duplicate returns an autoreleased object at +0.
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions5test9
func test9(g: Gizmo) -> Gizmo {
return g.duplicate()
// CHECK: bb0([[G:%.*]] : $Gizmo):
// CHECK-NOT: retain [[G:%0]]
// CHECK: alloc_stack
// CHECK-NEXT: [[METHOD:%.*]] = class_method [volatile] [[G]] : {{.*}}, #Gizmo.duplicate!1.foreign
// CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[G]])
// CHECK-NEXT: store [[RESULT]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue
// CHECK-NEXT: alloc_stack
// CHECK-NEXT: apply
// CHECK-NEXT: [[RESULT:%.*]] = load
// CHECK-NEXT: dealloc_stack
// CHECK-NOT: release [[G]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: release [[G]]
// CHECK-NEXT: return [[RESULT]]
}
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions6test10
func test10(g: Gizmo) -> AnyClass {
// CHECK: bb0([[G:%[0-9]+]] : $Gizmo):
// CHECK: strong_retain [[G]]
// CHECK-NEXT: [[NS_G:%[0-9]+]] = upcast [[G:%[0-9]+]] : $Gizmo to $NSObject
// CHECK-NEXT: [[GETTER:%[0-9]+]] = class_method [volatile] [[NS_G]] : $NSObject, #NSObject.classProp!getter.1.foreign : NSObject -> () -> AnyObject.Type! , $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type>
// CHECK-NEXT: [[OPT_OBJC:%.*]] = apply [[GETTER]]([[NS_G]]) : $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type>
// CHECK: select_enum [[OPT_OBJC]]
// CHECK: [[OBJC:%.*]] = unchecked_enum_data [[OPT_OBJC]]
// CHECK-NEXT: [[THICK:%.*]] = objc_to_thick_metatype [[OBJC]]
// CHECK: [[T0:%.*]] = enum $ImplicitlyUnwrappedOptional<AnyObject.Type>, #ImplicitlyUnwrappedOptional.Some!enumelt.1, [[THICK]]
// CHECK: [[T0:%.*]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue
// CHECK: apply [[T0]]<AnyObject.Type>([[THICK_BUF:%[0-9]*]], {{.*}})
// CHECK-NEXT: [[RES:%.*]] = load [[THICK_BUF]]
// CHECK: strong_release [[G]] : $Gizmo
// CHECK: strong_release [[G]] : $Gizmo
// CHECK-NEXT: return [[RES]] : $@thick AnyObject.Type
return g.classProp
}
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions6test11
func test11(g: Gizmo) -> AnyClass {
// CHECK: bb0([[G:%[0-9]+]] : $Gizmo):
// CHECK: strong_retain [[G]]
// CHECK: [[NS_G:%[0-9]+]] = upcast [[G:%[0-9]+]] : $Gizmo to $NSObject
// CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[NS_G]] : $NSObject, #NSObject.qualifiedClassProp!getter.1.foreign : NSObject -> () -> AnyObject.Type! , $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type>
// CHECK-NEXT: [[OPT_OBJC:%.*]] = apply [[GETTER]]([[NS_G]]) : $@convention(objc_method) (NSObject) -> ImplicitlyUnwrappedOptional<@objc_metatype AnyObject.Type>
// CHECK: select_enum [[OPT_OBJC]]
// CHECK: [[OBJC:%.*]] = unchecked_enum_data [[OPT_OBJC]]
// CHECK-NEXT: [[THICK:%.*]] = objc_to_thick_metatype [[OBJC]]
// CHECK: [[T0:%.*]] = enum $ImplicitlyUnwrappedOptional<AnyObject.Type>, #ImplicitlyUnwrappedOptional.Some!enumelt.1, [[THICK]]
// CHECK: [[T0:%.*]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue
// CHECK: apply [[T0]]<AnyObject.Type>([[THICK_BUF:%[0-9]*]], {{.*}})
// CHECK-NEXT: [[RES:%.*]] = load [[THICK_BUF]]
// CHECK: strong_release [[G]] : $Gizmo
// CHECK: strong_release [[G]] : $Gizmo
// CHECK-NEXT: return [[RES]] : $@thick AnyObject.Type
return g.qualifiedClassProp
}
// ObjC blocks should have cdecl calling convention and follow C/ObjC
// ownership conventions, where the callee, arguments, and return are all +0.
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions10applyBlock
func applyBlock(f: @convention(block) Gizmo -> Gizmo, x: Gizmo) -> Gizmo {
// CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (Gizmo) -> @autoreleased Gizmo, [[ARG:%.*]] : $Gizmo):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
// CHECK: strong_retain [[BLOCK_COPY]]
// CHECK: [[RESULT:%.*]] = apply [[BLOCK_COPY]]([[ARG]])
// CHECK: strong_release [[BLOCK_COPY]]
// CHECK: strong_release [[ARG]]
// CHECK: strong_release [[BLOCK_COPY]]
// CHECK: strong_release [[BLOCK]]
// CHECK: return [[RESULT]]
return f(x)
}
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions15maybeApplyBlock
func maybeApplyBlock(f: (@convention(block) Gizmo -> Gizmo)?, x: Gizmo) -> Gizmo? {
// CHECK: bb0([[BLOCK:%.*]] : $Optional<@convention(block) Gizmo -> Gizmo>, [[ARG:%.*]] : $Gizmo):
// CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]]
return f?(x)
}
func useInnerPointer(p: UnsafeMutablePointer<Void>) {}
// Handle inner-pointer methods by autoreleasing self after the call.
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions18innerPointerMethod
// CHECK: [[USE:%.*]] = function_ref @_TF26objc_ownership_conventions15useInnerPointer
// CHECK: [[METHOD:%.*]] = class_method [volatile] %0 : $Gizmo, #Gizmo.getBytes!1.foreign : Gizmo -> () -> UnsafeMutablePointer<()> , $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutablePointer<()>
// CHECK: strong_retain %0
// CHECK: [[PTR:%.*]] = apply [[METHOD]](%0)
// CHECK: autorelease_value %0
// CHECK: apply [[USE]]([[PTR]])
// CHECK: strong_release %0
func innerPointerMethod(g: Gizmo) {
useInnerPointer(g.getBytes())
}
// CHECK-LABEL: sil hidden @_TF26objc_ownership_conventions20innerPointerProperty
// CHECK: [[USE:%.*]] = function_ref @_TF26objc_ownership_conventions15useInnerPointer
// CHECK: [[METHOD:%.*]] = class_method [volatile] %0 : $Gizmo, #Gizmo.innerProperty!getter.1.foreign : Gizmo -> () -> UnsafeMutablePointer<()> , $@convention(objc_method) (Gizmo) -> @unowned_inner_pointer UnsafeMutablePointer<()>
// CHECK: strong_retain %0
// CHECK: [[PTR:%.*]] = apply [[METHOD]](%0)
// CHECK: autorelease_value %0
// CHECK: apply [[USE]]([[PTR]])
// CHECK: strong_release %0
func innerPointerProperty(g: Gizmo) {
useInnerPointer(g.innerProperty)
}
| 52.757426 | 261 | 0.642301 |
d6fb372f3cab7006be43be40035c761c893c2559 | 2,318 | //
// AreaSetUpPageModels.swift
// fuelhunter
//
// Created by Guntis on 10/07/2019.
// Copyright (c) 2019 . All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
enum AreaSetUpPage {
// MARK: Use cases
enum SetUp {
struct Request {
}
struct Response {
// var value: Int
// var convertedValue: String
// var minValue: Int
// var maxValue: Int
// var sortedCities: [CityAndDistance]
// var selectedCityName: String
}
struct ViewModel {
struct DisplayedItem: Equatable {
// var description: String
// var value: Int
// var minValue: Int
// var maxValue: Int
// var sortedCities: [CityAndDistance]
// var selectedCityName: String
}
var displayedItem: DisplayedItem
}
}
enum AreaEditPage {
struct Request {
}
struct Response {
var fetchedArea: AreasEntity
}
struct ViewModel {
struct DisplayedCell: Equatable {
var name: String
var toggleOrCheckmarkIsOn: Bool
var iconName: String
var description: String
var accessoryType: CellAccessoryType
var functionalityType: CellFunctionalityType
}
var displayedCells: [[DisplayedCell]]
var newAreaName: String
}
}
enum UserSelectedNext {
struct Request {
var addresses: [AddressEntity]
var areaName: String
}
struct Response {
struct CompanyEntry: Equatable {
var name: String = ""
var imageName: String = ""
var stationCount: Int = 0
var addresses = [AddressEntity]()
var enabled: Bool = true
}
var companyEntries: [CompanyEntry]
var areaName: String
var cheapestPriceIsOn: Bool
}
}
enum ToggleCompanyStatus {
struct Request {
var companyName: String
var state: Bool
}
}
enum ChangeAreaName {
struct Request {
var areaName: String
}
}
enum ToggleCheapestPrice {
struct Request {
var cheapestPriceIsOn: Bool
}
}
enum SavingData {
struct Request {
var areaName: String
var cheapestPriceIsOn: Bool
var notifToggleIsOn: Bool
var radiusCompanies: [CompanyEntity]
var enabledCompanies: [CompanyEntity]
var radiusStations: [AddressEntity]
var enabledStations: [AddressEntity]
}
}
}
| 20.882883 | 66 | 0.678602 |
ccdd8a537c3f03709a327e7691bd5878f7384a34 | 449 | //
// UserDefaults+Extension.swift
// LoginItem Sample
//
// Created by zhaoxin on 2020/1/12.
// Copyright © 2020 zhaoxin. All rights reserved.
//
import Foundation
extension UserDefaults {
public enum Key: String {
case autoLaunchWhenUserLogin
case startFromLauncher
}
public static let shared = UserDefaults(suiteName: "96NM39SGJ5.group.com.parussoft.LoginItem-Sample.shared")!
}
| 19.521739 | 113 | 0.66147 |
ebac4ad445a4ea7b3cb28c7bfc52c0e72e6935af | 372 | import Foundation
public struct TransactionParentReceipt : Decodable {
public let status: String
public let cpu_usage_us: Int
public let net_usage_words: Int
public init(status: String, cpu_usage_us: Int, net_usage_words: Int) {
self.status = status
self.cpu_usage_us = cpu_usage_us
self.net_usage_words = net_usage_words
}
}
| 26.571429 | 74 | 0.715054 |
e93e84b30f7112b97bf41839d47046cd8c435dfd | 5,823 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2018 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
*/
/// A semantic version.
///
/// A package's version must conform to the semantic versioning standard in order to ensure
/// that your package behaves in a predictable manner once developers update their
/// package dependency to a newer version. To achieve predictability, the semantic versioning specification proposes a set of rules and
/// requirements that dictate how version numbers are assigned and incremented.
///
/// A package version is a three period-separated integer. An example is `1.0.0`.
///
/// **The Major Version**
///
/// The first digit of a version, or *major version*, signifies breaking changes to the API that require
/// updates to existing clients. For example, the semantic versioning specification
/// considers renaming an existing type, removing a method, or changing a method's signature
/// breaking changes. This also includes any backward-incompatible bug fixes or
/// behavioral changes of the existing API.
///
/// **The Minor Version**
//
/// Update the second digit of a version, or *minor version*, if you add functionality in a backward-compatible manner.
/// For example, the semantic versioning specification considers adding a new method
/// or type without changing any other API to be backward-compatible.
///
/// ## The Patch Version
///
/// Increase the third digit of a version, or *patch version* if you are making a backward-compatible bug fix.
/// This allows clients to benefit from bugfixes to your package without incurring
/// any maintenance burden.
///
/// To learn more about the semantic versioning specification, visit
/// [semver.org](www.semver.org).
public struct Version {
/// The major version according to the semantic versioning standard.
public let major: Int
/// The minor version according to the semantic versioning standard.
public let minor: Int
/// The patch version according to the semantic versioning standard.
public let patch: Int
/// The pre-release identifier according to the semantic versioning standard, such as `-beta.1`.
public let prereleaseIdentifiers: [String]
/// The build metadata of this version according to the semantic versioning standard, such as a commit hash.
public let buildMetadataIdentifiers: [String]
/// Initializes and returns a newly allocated version struct
/// for the provided components of a semantic version.
///
/// - Parameters:
/// - major: The major version numner.
/// - minor: The minor version number.
/// - patch: The patch version number.
/// - prereleaseIdentifiers: The pre-release identifier.
/// - buildMetaDataIdentifiers: Build metadata that identifies a build.
public init(
_ major: Int,
_ minor: Int,
_ patch: Int,
prereleaseIdentifiers: [String] = [],
buildMetadataIdentifiers: [String] = []
) {
precondition(major >= 0 && minor >= 0 && patch >= 0, "Negative versioning is invalid.")
self.major = major
self.minor = minor
self.patch = patch
self.prereleaseIdentifiers = prereleaseIdentifiers
self.buildMetadataIdentifiers = buildMetadataIdentifiers
}
}
extension Version: Comparable {
public static func < (lhs: Version, rhs: Version) -> Bool {
let lhsComparators = [lhs.major, lhs.minor, lhs.patch]
let rhsComparators = [rhs.major, rhs.minor, rhs.patch]
if lhsComparators != rhsComparators {
return lhsComparators.lexicographicallyPrecedes(rhsComparators)
}
guard lhs.prereleaseIdentifiers.count > 0 else {
return false // Non-prerelease lhs >= potentially prerelease rhs
}
guard rhs.prereleaseIdentifiers.count > 0 else {
return true // Prerelease lhs < non-prerelease rhs
}
let zippedIdentifiers = zip(lhs.prereleaseIdentifiers, rhs.prereleaseIdentifiers)
for (lhsPrereleaseIdentifier, rhsPrereleaseIdentifier) in zippedIdentifiers {
if lhsPrereleaseIdentifier == rhsPrereleaseIdentifier {
continue
}
let typedLhsIdentifier: Any = Int(lhsPrereleaseIdentifier) ?? lhsPrereleaseIdentifier
let typedRhsIdentifier: Any = Int(rhsPrereleaseIdentifier) ?? rhsPrereleaseIdentifier
switch (typedLhsIdentifier, typedRhsIdentifier) {
case let (int1 as Int, int2 as Int): return int1 < int2
case let (string1 as String, string2 as String): return string1 < string2
case (is Int, is String): return true // Int prereleases < String prereleases
case (is String, is Int): return false
default:
return false
}
}
return lhs.prereleaseIdentifiers.count < rhs.prereleaseIdentifiers.count
}
}
extension Version: CustomStringConvertible {
/// A textual description of the version object.
public var description: String {
var base = "\(major).\(minor).\(patch)"
if !prereleaseIdentifiers.isEmpty {
base += "-" + prereleaseIdentifiers.joined(separator: ".")
}
if !buildMetadataIdentifiers.isEmpty {
base += "+" + buildMetadataIdentifiers.joined(separator: ".")
}
return base
}
}
extension Version: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(description)
}
}
| 40.4375 | 135 | 0.681951 |
2f4fce924e2e4019555fa39f6c792ab0a5c8d7d7 | 7,848 | //
// MainViewController.swift
// PeerClientApp
//
// Created by Akira Murao on 9/9/15.
// Copyright (c) 2017 Akira Murao. All rights reserved.
//
import UIKit
import MapKit
import PeerClient
class MainViewController: UIViewController, PeerDelegate {
let showContactsViewSegue = "showContactsView"
@IBOutlet weak var signInButton: UIButton!
var _contactsButton: UIBarButtonItem?
var contactsButton: UIBarButtonItem {
get {
if let button = self._contactsButton {
return button
}
else {
let button = UIBarButtonItem(title: "Contacts", style: .plain, target: self, action: #selector(contactsButtonPressed(sender:)))
self._contactsButton = button
return button
}
}
}
var videoViewController: VideoViewController?
var statusBarOrientation: UIInterfaceOrientation = UIInterfaceOrientation.portrait
var _peer: Peer?
var peer: Peer? {
get {
if _peer == nil {
let peerOptions = PeerOptions(key: Configuration.key, host: Configuration.host, path: Configuration.path, secure: Configuration.secure, port: Configuration.port, iceServerOptions: Configuration.iceServerOptions)
peerOptions.keepAliveTimerInterval = Configuration.herokuPingInterval
_peer = Peer(options: peerOptions, delegate: self)
}
return _peer
}
set {
_peer = newValue
}
}
enum SignInStatus {
case signedOut
case signingIn
case signedIn
case signingOut
var string: String {
switch self {
case .signedOut:
return "signed out"
case .signingIn:
return "signing in"
case .signedIn:
return "signed in"
case .signingOut:
return "signing out"
}
}
}
var signInStatus: SignInStatus {
didSet {
switch self.signInStatus {
case .signingIn:
if oldValue != .signingIn {
self.signInButton.setTitle("Signing In ...", for: .normal)
self.signInButton.isEnabled = false
self.navigationItem.rightBarButtonItem = nil
}
case .signedIn:
if oldValue != .signedIn {
self.signInButton.setTitle("Sign Out", for: .normal)
self.signInButton.isEnabled = true
self.navigationItem.rightBarButtonItem = self.contactsButton
self.performSegue(withIdentifier: self.showContactsViewSegue, sender: self)
}
case .signedOut:
if oldValue != .signedOut {
self.signInButton.setTitle("Sign In", for: .normal)
self.signInButton.isEnabled = true
self.navigationItem.rightBarButtonItem = nil
self.peer?.destroy({ [weak self] (error) in
print(error.debugDescription)
self?.peer = nil
})
}
case .signingOut:
if oldValue != .signingOut {
self.signInButton.setTitle("Signing Out ...", for: .normal)
self.signInButton.isEnabled = false
self.navigationItem.rightBarButtonItem = nil
}
}
}
}
required init?(coder: NSCoder) {
self.signInStatus = .signedOut
super.init(coder:coder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.statusBarOrientation = UIApplication.shared.statusBarOrientation
self.connectToSignailingServer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
- (void)applicationWillResignActive:(UIApplication*)application {
[self disconnect];
}
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print(segue.identifier ?? "")
if segue.identifier == self.showContactsViewSegue {
if let vc = segue.destination as? ContactsViewController {
vc.peer = self.peer
vc.peer?.delegate = vc
}
}
}
// MARK: actions
@IBAction func signInButtonPressed(sender: UIButton) {
print("Sign In button pressed")
guard let peer = self.peer else {
return
}
if peer.isOpen {
self.disconnectFromSignailingServer()
}
else {
self.connectToSignailingServer()
}
}
@IBAction func contactsButtonPressed(sender: UIBarButtonItem) {
print("Contacts button pressed")
guard let peer = self.peer else {
return
}
guard peer.isOpen else {
return
}
self.performSegue(withIdentifier: self.showContactsViewSegue, sender: self)
}
@IBAction func mainViewReturnAction(for segue: UIStoryboardSegue) {
print(segue.identifier ?? "")
guard let peer = self.peer else {
self.signInStatus = .signedOut
return
}
guard peer.isOpen else {
self.signInStatus = .signedOut
return
}
}
// MARK: Private
func showAlertWithMessage(message: String?) {
let alertView = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
print("OK button was tapped")
}))
}
func connectToSignailingServer() {
print("connectToSignailingServer")
if self.peer == nil {
let peerOptions = PeerOptions(key: Configuration.key, host: Configuration.host, path: Configuration.path, secure: Configuration.secure, port: Configuration.port, iceServerOptions: Configuration.iceServerOptions)
peerOptions.keepAliveTimerInterval = Configuration.herokuPingInterval
self.peer = Peer(options: peerOptions, delegate: self)
}
self.signInStatus = .signingIn
self.peer?.open(nil) { [weak self] (result) in
switch result {
case let .success(peerId):
self?.signInStatus = .signedIn
case let .failure(error):
print("Peer open failed error: \(error)")
self?.signInStatus = .signedOut
}
}
}
func disconnectFromSignailingServer() {
print("disconnectFromSignailingServer")
self.signInStatus = .signingOut
self.peer?.disconnect { [weak self] (error) in
self?.signInStatus = .signedOut
}
}
// MARK: PeerPeerDelegate
func peer(_ peer: Peer, didOpen peerId: String?) {
print("peer didOpen peerId: \(peerId ?? "")")
self.signInStatus = .signedIn
}
func peer(_ peer: Peer, didClose peerId: String?) {
print("peer didClose peerId: \(peerId ?? "")")
self.signInButton.setTitle("Sign In", for: .normal)
self.signInStatus = .signedOut
}
func peer(_ peer: Peer, didReceiveError error: Error?) {
self.showAlertWithMessage(message: "\(String(describing: error))")
}
func peer(_ peer: Peer, didReceiveConnection connection: PeerConnection) {
}
func peer(_ peer: Peer, didCloseConnection connection: PeerConnection) {
}
func peer(_ peer: Peer, didReceiveRemoteStream stream: MediaStream) {
}
func peer(_ peer: Peer, didReceiveData data: Data) {
}
}
| 28.129032 | 227 | 0.571738 |
9b9eb3e2b5a9317df358150732d3fc9d1f7b75c0 | 5,738 |
import Foundation
import UIKit
import SwiftyJSON
import RealmSwift
import SwiftDate
let defaults = NSUserDefaults.standardUserDefaults()
var jsonDataList:JSON?
var isLogined = defaults.objectForKey("isLogined") as? Bool ?? Bool()
var amistudent: Bool = defaults.objectForKey("amistudent") as? Bool ?? Bool()
var subjectNameMemory = defaults.objectForKey("subjectName") as? String ?? String()
var subjectIDMemory = defaults.objectForKey("subjectID") as? Int ?? Int()
var timestampMemory = defaults.objectForKey("timestamp") as? Int ?? Int()
var lectorsArray: [String] = []
var groupsArray: [String] = []
var segueSide:CGFloat = 1
var groupNamesList: [String: Int] = [:]
var lectorsNamesList: [String: Int] = [:]
var rowH: CGFloat = 0
var slString:String?
var subjectName: (Int, String) = (0,"")
struct GlobalColors{
static let lightBlueColor = UIColor(red: 0/255, green: 118/255, blue: 225/255, alpha: 1.0)
static let BlueColor = UIColor(red: 0/255,green: 71/255,blue: 119/255,alpha: 1.0)
}
func before(value1: String, value2: String) -> Bool {
return value1 < value2;
}
func parse(jsontoparse:JSON,successBlock: Bool -> ())
{
let realm = try! Realm()
try! realm.write {
realm.deleteAll()
}
SwiftSpinner.show("Немного волшебства")
let rasp = Schedule()
rasp.year = "2016"
for semestr in jsontoparse["success"]["data"] {
let week = Week()
week.number = semestr.1["weekNum"].int
// weekData - is one week
for weekData in semestr.1 {
// dayData - is one day
for dayData in weekData.1 {
let day = Day()
day.dayName = dayData.0
day.date = dayData.1["date"].string
// lessonData - is one lesson
for lessonData in dayData.1["lessons"] {
if(lessonData.1 != nil) {
// Main properties
let subject = Lesson()
try! realm.write {
subject.lessonNumber = lessonData.0
subject.hashID = lessonData.1["hash_id"].string
subject.lessonType = lessonData.1["lesson_type"].stringValue
subject.room = lessonData.1["room"].string
subject.lessonStart = lessonData.1["lesson_start"].string
subject.lessonEnd = lessonData.1["lesson_end"].string
subject.discipline = lessonData.1["discipline"].string
subject.lessonType = lessonData.1["lessontype"].string
subject.building = lessonData.1["building"].string
subject.lector = lessonData.1["lector"].string
subject.house = lessonData.1["housing"].stringValue
subject.startWeek = lessonData.1["week_start"].stringValue
subject.endWeek = lessonData.1["week_end"].stringValue
}
try! realm.write {
day.lessons.append(subject)
}
}
}
try! realm.write {
week.days.append(day)
}
}
}
try! realm.write {
rasp.weeks.append(week)
}
}
try! realm.write(){
realm.add(rasp, update: true)
}
successBlock(true)
SwiftSpinner.hide()
}
func updateSchedule(itemID itemID: Int, successBlock: Void -> ()) {
var Who:String
if(amistudent)
{
Who = "group"
}else{
Who = "lector"
}
InternetManager.sharedInstance.getLessonsList(["who":Who,"id":itemID,"timestamp":0], success: {
success in
jsonDataList = success
successBlock()
}, failure: {error in
print(error)
})
}
func updateSch()
{
SwiftSpinner.show("")
let id = defaults.objectForKey("subjectID") as! Int
dispatch_async(dispatch_get_main_queue(), {
updateSchedule(itemID: id, successBlock: {
successBlock in
dispatch_async(dispatch_get_main_queue(), {
parse(jsonDataList!, successBlock: { (true) in
print("FIX ME,THAT'S AN ERROR")
})
})
})
})
}
func getCurrentViewController() -> UIViewController? {
// If the root view is a navigation controller, we can just return the visible ViewController
if let navigationController = getNavigationController() {
return navigationController.visibleViewController
}
// Otherwise, we must get the root UIViewController and iterate through presented views
if let rootController = UIApplication.sharedApplication().keyWindow?.rootViewController {
var currentController: UIViewController! = rootController
// Each ViewController keeps track of the view it has presented, so we
// can move from the head to the tail, which will always be the current view
while( currentController.presentedViewController != nil ) {
currentController = currentController.presentedViewController
}
return currentController
}
return UIViewController()
}
func getNavigationController()-> UINavigationController? {
if let navigationController = UIApplication.sharedApplication().keyWindow?.rootViewController {
return navigationController as? UINavigationController
}
return nil
}
| 32.235955 | 100 | 0.572848 |
26e6a1ecbadcdc7cb42bc66885ffa9b840751cf2 | 2,824 | //
// PhoneNumber.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 26/09/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
/**
Parsed phone number object
- numberString: String used to generate phone number struct
- countryCode: Country dialing code as an unsigned. Int.
- leadingZero: Some countries (e.g. Italy) require leading zeros. Bool.
- nationalNumber: National number as an unsigned. Int.
- numberExtension: Extension if available. String. Optional
- type: Computed phone number type on access. Returns from an enumeration - PNPhoneNumberType.
*/
public struct PhoneNumber: Codable {
public let numberString: String
public let countryCode: UInt64
public let leadingZero: Bool
public let nationalNumber: UInt64
public let numberExtension: String?
public let type: PhoneNumberType
public let regionID: String?
}
extension PhoneNumber : Equatable {
public static func ==(lhs: PhoneNumber, rhs: PhoneNumber) -> Bool {
return (lhs.countryCode == rhs.countryCode)
&& (lhs.leadingZero == rhs.leadingZero)
&& (lhs.nationalNumber == rhs.nationalNumber)
&& (lhs.numberExtension == rhs.numberExtension)
}
}
extension PhoneNumber : Hashable {
public var hashValue: Int {
return countryCode.hashValue ^ nationalNumber.hashValue ^ leadingZero.hashValue ^ (numberExtension?.hashValue ?? 0)
}
}
extension PhoneNumber {
public static func notPhoneNumber() -> PhoneNumber {
return PhoneNumber(numberString: "", countryCode: 0, leadingZero: false, nationalNumber: 0, numberExtension: nil, type: .notParsed, regionID: nil)
}
public func notParsed() -> Bool {
return type == .notParsed
}
}
/// In past versions of PhoneNumebrKit you were able to initialize a PhoneNumber object to parse a String. Please use a PhoneNumberKit object's methods.
public extension PhoneNumber {
/**
DEPRECATED.
Parse a string into a phone number object using default region. Can throw.
- Parameter rawNumber: String to be parsed to phone number struct.
*/
@available(*, unavailable, message: "use PhoneNumberKit instead to produce PhoneNumbers")
init(rawNumber: String) throws {
assertionFailure(PhoneNumberError.deprecated.localizedDescription)
throw PhoneNumberError.deprecated
}
/**
DEPRECATED.
Parse a string into a phone number object using custom region. Can throw.
- Parameter rawNumber: String to be parsed to phone number struct.
- Parameter region: ISO 639 compliant region code.
*/
@available(*, unavailable, message: "use PhoneNumberKit instead to produce PhoneNumbers")
init(rawNumber: String, region: String) throws {
throw PhoneNumberError.deprecated
}
}
| 32.837209 | 154 | 0.71211 |
48fa5a82278d62b352eddfe84aa55de5d62df838 | 8,149 | import Foundation
import XCTest
import CarPlay
@testable import MapboxNavigation
@testable import MapboxCoreNavigation
@testable import MapboxDirections
import CarPlayTestHelper
import TestHelper
@available(iOS 12.0, *)
func simulateCarPlayConnection(_ manager: CarPlayManager) {
let fakeInterfaceController = FakeCPInterfaceController(context: #function)
let fakeWindow = CPWindow()
manager.application(UIApplication.shared, didConnectCarInterfaceController: fakeInterfaceController, to: fakeWindow)
if let mapViewController = manager.carWindow?.rootViewController?.view {
manager.carWindow?.addSubview(mapViewController)
}
}
@available(iOS 12.0, *)
class CarPlayManagerFailureDelegateSpy: CarPlayManagerDelegate {
private(set) var recievedError: DirectionsError?
@available(iOS 12.0, *)
func carPlayManager(_ carPlayManager: CarPlayManager, didFailToFetchRouteBetween waypoints: [Waypoint]?, options: RouteOptions, error: DirectionsError) -> CPNavigationAlert? {
recievedError = error
return nil
}
func carPlayManager(_ carPlayManager: CarPlayManager, navigationServiceFor routeResponse: RouteResponse, routeIndex: Int, routeOptions: RouteOptions, desiredSimulationMode: SimulationMode) -> NavigationService? {
fatalError("This is an empty stub.")
}
func carPlayManager(_ carPlayManager: CarPlayManager, didBeginNavigationWith service: NavigationService) {
fatalError("This is an empty stub.")
}
func carPlayManager(_ carPlayManager: CarPlayManager, shouldPresentArrivalUIFor waypoint: Waypoint) -> Bool {
fatalError("This is an empty stub.")
}
func carPlayManagerDidEndNavigation(_ carPlayManager: CarPlayManager) {
fatalError("This is an empty stub.")
}
func carPlayManager(_ carPlayManager: CarPlayManager, didPresent navigationViewController: CarPlayNavigationViewController) {
fatalError("This is an empty stub.")
}
}
// MARK: Test Objects / Classes.
@available(iOS 12.0, *)
class TestCarPlayManagerDelegate: CarPlayManagerDelegate {
public fileprivate(set) var navigationInitiated = false
public fileprivate(set) var currentService: NavigationService?
public fileprivate(set) var navigationEnded = false
public var interfaceController: CPInterfaceController?
public var searchController: CarPlaySearchController?
public var leadingBarButtons: [CPBarButton]?
public var trailingBarButtons: [CPBarButton]?
public var mapButtons: [CPMapButton]?
func carPlayManager(_ carPlayManager: CarPlayManager, navigationServiceFor routeResponse: RouteResponse, routeIndex: Int, routeOptions: RouteOptions, desiredSimulationMode: SimulationMode) -> NavigationService? {
let response = Fixture.routeResponse(from: jsonFileName, options: routeOptions)
let service = MapboxNavigationService(routeResponse: response,
routeIndex: 0,
routeOptions: routeOptions,
routingProvider: MapboxRoutingProvider(.offline),
credentials: Fixture.credentials,
locationSource: NavigationLocationManager(),
eventsManagerType: NavigationEventsManagerSpy.self,
simulating: desiredSimulationMode)
return service
}
func carPlayManager(_ carPlayManager: CarPlayManager, leadingNavigationBarButtonsCompatibleWith traitCollection: UITraitCollection, in: CPTemplate, for activity: CarPlayActivity) -> [CPBarButton]? {
return leadingBarButtons
}
func carPlayManager(_ carPlayManager: CarPlayManager, trailingNavigationBarButtonsCompatibleWith traitCollection: UITraitCollection, in: CPTemplate, for activity: CarPlayActivity) -> [CPBarButton]? {
return trailingBarButtons
}
func carPlayManager(_ carPlayManager: CarPlayManager, mapButtonsCompatibleWith traitCollection: UITraitCollection, in template: CPTemplate, for activity: CarPlayActivity) -> [CPMapButton]? {
return mapButtons
}
func carPlayManager(_ carPlayManager: CarPlayManager, didBeginNavigationWith service: NavigationService) {
currentService = service
}
func carPlayManager(_ carPlayManager: CarPlayManager, shouldPresentArrivalUIFor waypoint: Waypoint) -> Bool {
return true
}
func carPlayManagerDidEndNavigation(_ carPlayManager: CarPlayManager) {
XCTAssertTrue(navigationInitiated)
navigationEnded = true
currentService = nil
}
func carPlayManager(_ carPlayManager: CarPlayManager, didPresent navigationViewController: CarPlayNavigationViewController) {
XCTAssertFalse(navigationInitiated)
navigationInitiated = true
XCTAssertTrue(navigationInitiated)
}
}
@available(iOS 12.0, *)
class CarPlayNavigationViewControllerTestable: CarPlayNavigationViewController {
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
completion?()
}
}
@available(iOS 12.0, *)
class TestCarPlaySearchControllerDelegate: NSObject, CarPlaySearchControllerDelegate {
public fileprivate(set) var interfaceController: CPInterfaceController?
public fileprivate(set) var carPlayManager: CarPlayManager?
func carPlaySearchController(_ searchController: CarPlaySearchController,
carPlayManager: CarPlayManager,
interfaceController: CPInterfaceController) {
self.interfaceController = interfaceController
}
func previewRoutes(to waypoint: Waypoint, completionHandler: @escaping () -> Void) {
carPlayManager?.previewRoutes(to: waypoint, completionHandler: completionHandler)
}
func resetPanButtons(_ mapTemplate: CPMapTemplate) {
carPlayManager?.resetPanButtons(mapTemplate)
}
func pushTemplate(_ template: CPTemplate, animated: Bool) {
interfaceController?.pushTemplate(template, animated: animated)
}
func popTemplate(animated: Bool) {
interfaceController?.popTemplate(animated: animated)
}
var recentSearchItems: [CPListItem]?
var recentSearchText: String?
func searchTemplate(_ searchTemplate: CPSearchTemplate,
updatedSearchText searchText: String,
completionHandler: @escaping ([CPListItem]) -> Void) {
completionHandler([])
}
func searchTemplate(_ searchTemplate: CPSearchTemplate,
selectedResult item: CPListItem,
completionHandler: @escaping () -> Void) {
completionHandler()
}
func searchResults(with items: [CPListItem], limit: UInt?) -> [CPListItem] {
return []
}
}
@available(iOS 12.0, *)
class MapTemplateSpy: CPMapTemplate {
private(set) var currentTripPreviews: [CPTrip]?
private(set) var currentPreviewTextConfiguration: CPTripPreviewTextConfiguration?
private(set) var estimatesUpdate: (CPTravelEstimates, CPTrip, CPTimeRemainingColor)?
var fakeSession: CPNavigationSession!
override func showTripPreviews(_ tripPreviews: [CPTrip], textConfiguration: CPTripPreviewTextConfiguration?) {
currentTripPreviews = tripPreviews
currentPreviewTextConfiguration = textConfiguration
}
override func update(_ estimates: CPTravelEstimates, for trip: CPTrip, with timeRemainingColor: CPTimeRemainingColor) {
estimatesUpdate = (estimates, trip, timeRemainingColor)
}
override func hideTripPreviews() {
currentTripPreviews = nil
currentPreviewTextConfiguration = nil
}
override func startNavigationSession(for trip: CPTrip) -> CPNavigationSession {
return fakeSession
}
}
@available(iOS 12.0, *)
public class MapTemplateSpyProvider: MapTemplateProvider {
override public func createMapTemplate() -> CPMapTemplate {
return MapTemplateSpy()
}
}
| 39.946078 | 216 | 0.710517 |
1e2aa4137045db76fc97a1e35d13e1b239600a0a | 351 | //
// NSObject.swift
// 911
//
// Created by William Falcon on 11/17/16.
// Copyright © 2016 William Falcon. All rights reserved.
//
import Foundation
extension NSObject {
var _className: String {
return String(describing: type(of: self))
}
class var _className: String {
return String(describing: self)
}
}
| 17.55 | 57 | 0.635328 |
2850c741b54e4205716a6527415140e127d0563e | 609 | //
// TabBar.swift
// Sileo
//
// Created by CoolStar on 7/27/19.
// Copyright © 2019 Sileo Team. All rights reserved.
//
import Foundation
class TabBar: UITabBar {
override var traitCollection: UITraitCollection {
if UIDevice.current.userInterfaceIdiom == .phone {
return super.traitCollection
}
if UIApplication.shared.statusBarOrientation.isLandscape && self.bounds.width >= 400 {
return super.traitCollection
}
return UITraitCollection(traitsFrom: [super.traitCollection, UITraitCollection(horizontalSizeClass: .compact)])
}
}
| 27.681818 | 119 | 0.681445 |
6a2e3021f91ea408dde4b600e2b82b76c7942223 | 1,828 | //
// HMAC.swift
// Hash
//
// Created by Ross Butler on 6/19/19.
//
import Foundation
import CommonCrypto
@objcMembers public class HMAC: NSObject, StringRepresentable {
public typealias Algorithm = HashAlgorithm
private let key: String
private let message: Data
private let hashAlgorithm: Algorithm
public init?(message: Data, key: String, algorithm: Algorithm) {
guard algorithm.ccAlgorithm() != nil else {
return nil
}
self.key = key
self.message = message
self.hashAlgorithm = algorithm
}
public init?(message: String, encoding: String.Encoding = .utf8, key: String, algorithm: Algorithm) {
guard let messageData = message.data(using: encoding), algorithm.ccAlgorithm() != nil else {
return nil
}
self.key = key
self.message = messageData
self.hashAlgorithm = algorithm
}
public func data() -> Data {
let data = message
let length = hashAlgorithm.digestLength()
var digestData = Data(count: length)
_ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
data.withUnsafeBytes { messageBytes -> UInt8 in
if let baseAddress = messageBytes.baseAddress, let digestBytes = digestBytes.bindMemory(to: UInt8.self).baseAddress {
let messageLength = size_t(messageBytes.count)
if let algorithm = hashAlgorithm.ccAlgorithm() {
CCHmac(algorithm, key, key.count, baseAddress, messageLength, digestBytes)
}
}
return 0
}
}
return digestData
}
override public var description: String {
return string(representation: .hex)
}
}
| 30.466667 | 133 | 0.598468 |
2f7f103a8bf20c07f17258d9e8e4b710570d9fcc | 3,756 | //
// AppDelegate.swift
// Adam_20191206_Functional_Swift
//
// Created by Adonis_HongYang on 2019/12/6.
// Copyright © 2019 Adonis_HongYang. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "Adam_20191206_Functional_Swift")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 45.253012 | 199 | 0.674121 |
08ff1f3ba442d1de3f5daa422bf39478387375dc | 2,198 | import Foundation
/// A thin wrapper around a DispatchQueue that provides easy methods to do a sync/async task on a queue,
/// without having to always queue the work on the end of the queue
public final class Queue {
/// The underlying DispatchQueue. Feel free to use it directly if you need.
public let queue: DispatchQueue
private let value = UUID()
private let key = DispatchSpecificKey<UUID>()
public init(label: String, qos: DispatchQoS = .userInteractive, attributes: DispatchQueue.Attributes = [],
autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .workItem, target: DispatchQueue? = .global(qos: .default)) {
queue = DispatchQueue(label: label, qos: qos, attributes: attributes, autoreleaseFrequency: autoreleaseFrequency, target: target)
queue.setSpecific(key: key, value: value)
}
/// If you call this while already executing on the internal queue, then the closure is directly executed, with no call to
/// `queue.sync()` added. This can be helpful in preventing situations where you need to ensure work is done on the queue,
/// but you might already be on the queue, and don't want a deadlock.
///
/// - Parameter closure: The work to perform
public func syncOnQueueIfNeeded(_ closure: () -> Void) {
if DispatchQueue.getSpecific(key: key) == value {
dispatchPrecondition(condition: .onQueue(queue))
closure()
} else {
queue.sync(execute: closure)
}
}
/// If you call this while already executing on the internal queue, then the closure is directly executed, with no call to
/// `queue.sync()` added. This can be helpful in preventing situations where you need to ensure work is done on the queue,
/// but you might already be on the queue, and don't want a deadlock.
///
/// - Parameter closure: The work to perform
public func asyncOnQueueIfNeeded(_ closure: @escaping () -> Void) {
if DispatchQueue.getSpecific(key: key) == value {
dispatchPrecondition(condition: .onQueue(queue))
closure()
} else {
queue.async(execute: closure)
}
}
}
| 47.782609 | 137 | 0.674249 |
bb9eaf416f285dc530e3af0aa1570b6861123cd5 | 5,224 | //
// OnboardingView.swift
// Enhance
//
// Created by Micah Yong on 5/4/19.
// Copyright © 2019 Micah Yong. All rights reserved.
//
import UIKit
class OnboardingView: UIView {
let imageView : UIImageView = UIImageView()
let headerText : UILabel = UILabel()
let subText : UILabel = UILabel()
var image : UIImage = UIImage(named: "onboarding1")!
var header : String = "Improve your physique"
var sub : String = "Train with 3 essential exercises that improve your everyday strength, stamina, and core."
var screenHeight : CGFloat = 0
var screenWidth : CGFloat = 0
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
func setToPage(_ pageNumber : Int) {
if pageNumber == 1 {
image = UIImage(named: "onboarding1")!
header = "Improve your physique"
sub = "Train with 3 essential exercises that improve your everyday strength, stamina, and core."
} else if pageNumber == 2 {
image = UIImage(named: "onboarding2")!
sub = "Enhance is more than a fitness training plan. It uses frameworks like OpenPose and CoreMotion to verify your activity and correct your form."
header = "Stay accountable"
} else {
image = UIImage(named: "onboarding3")!
header = "Track your progress"
sub = "Enhance customizes a training program, analyzes your performance, and tracks your improvement."
}
imageView.image = image
headerText.text = header
subText.text = sub
}
// UI
func setupUI() {
self.screenHeight = self.screenSize().size.height
self.screenWidth = self.screenSize().size.width
self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight)
self.backgroundColor = .clear
setupImage()
setupHeader()
setupSubHeader()
self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(equalToConstant: screenHeight).isActive = true
self.widthAnchor.constraint(equalToConstant: screenWidth).isActive = true
}
func setupHeader() {
headerText.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight * 0.05)
headerText.backgroundColor = .clear
headerText.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
headerText.font = UIFont(name: "HelveticaNeue-Medium", size: 20)
headerText.minimumScaleFactor = 0.5
headerText.adjustsFontSizeToFitWidth = true
headerText.textAlignment = .center
headerText.text = header
self.addSubview(headerText)
headerText.translatesAutoresizingMaskIntoConstraints = false
headerText.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
headerText.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.05).isActive = true
headerText.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
headerText.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 0).isActive = true
}
func setupSubHeader() {
subText.frame = CGRect(x: 0, y: 0, width: screenWidth * 0.8, height: screenHeight * 0.09)
subText.backgroundColor = .clear
subText.textColor = UIColor(red: 0.47, green: 0.47, blue: 0.47, alpha: 1)
subText.font = UIFont(name: "HelveticaNeue-Medium", size: 14)
subText.minimumScaleFactor = 0.5
subText.adjustsFontSizeToFitWidth = true
subText.numberOfLines = 0
subText.lineBreakMode = .byWordWrapping
subText.textAlignment = .center
subText.text = sub
self.addSubview(subText)
subText.translatesAutoresizingMaskIntoConstraints = false
subText.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.8).isActive = true
subText.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.09).isActive = true
subText.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
subText.topAnchor.constraint(equalTo: headerText.bottomAnchor, constant: 0).isActive = true
}
func setupImage() {
imageView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenWidth)
imageView.contentMode = .center
imageView.contentMode = .scaleAspectFit
imageView.backgroundColor = .white
imageView.image = image
self.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
imageView.heightAnchor.constraint(equalTo: self.widthAnchor).isActive = true
imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: -20).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 41.133858 | 160 | 0.658116 |
69d68d86e5f911157b61f74c3712605dbda23cae | 2,756 | //
// WeightedList.swift
//
//
// Created by Enzo Maruffa Moreira on 24/12/20.
//
import Foundation
/// A list in which elements can have different weights
public class WeightedList<Element> {
/// The count of elements in the list
public var count: Int {
elements.count
}
/// A `Bool` that returns if the list is empty
public var isEmpty: Bool {
count == 0
}
/// The sum of the weight of all elements in th list
public var totalWeight: Double {
elements.reduce(Double(0), { $0 + $1.weight })
}
/// The list of elements with its respective weights
internal var elements: [(element: Element, weight: Double)]
/// Creates an empty list
public init() {
elements = []
}
/// Sorts the internal elements list by weight
internal func sortByWeight() {
elements.sort(by: { $0.weight < $1.weight })
}
/// Adds a new element into the `WeightedList`
/// - Parameter element: The element to be added
/// - Note: The weight, in this case, defaults to 1
public func add(_ element: Element) {
try! add(element, weight: 1)
}
/// Adds a new element into the `WeightedList`
/// - Parameters:
/// - element: The element to be added
/// - weight: The weight of the element
/// - Throws: Throws a `WeightedListErrors.InvalidWeight` if the weight is `<= 0`
public func add(_ element: Element, weight: Double) throws {
guard weight > 0 else { throw WeightedListErrors.InvalidWeight }
elements.append((element: element, weight: weight))
// Keep the list sorted
sortByWeight()
}
/// Gets a random element from the list
/// - Returns: A randomly selected element from the list
public func randomElement() -> Element? {
guard !isEmpty else {
return nil
}
let totalWeight = self.totalWeight
let randomWeight = Double.random(in: 0..<totalWeight)
var currentWeight = Double(0)
for element in elements {
// Add the weight for the first element before veryfing if the total weight so far is bigger than the random weight.
currentWeight += element.weight
if currentWeight > randomWeight {
return element.element
}
}
return nil
}
/// Removes all elements from the list
public func removeAll() {
elements.removeAll()
}
}
/// The errors that the `WeightedList` can throw
enum WeightedListErrors: Error {
/// Error thrown if an element with invalid weight is added into the list
case InvalidWeight
}
| 28.708333 | 128 | 0.597605 |
33ed24d974c12f5ab67ceed4eab49ec5d6eab4a1 | 10,882 | //
// WalletCoordinator.swift
// breadwallet
//
// Created by Adrian Corscadden on 2017-01-07.
// Copyright © 2017 breadwallet LLC. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
private let lastBlockHeightKey = "LastBlockHeightKey"
private let progressUpdateInterval: TimeInterval = 0.5
private let updateDebounceInterval: TimeInterval = 0.4
class WalletCoordinator : Subscriber, Trackable {
var kvStore: BRReplicatedKVStore? {
didSet {
requestTxUpdate()
}
}
private let walletManager: WalletManager
private let store: Store
private var progressTimer: Timer?
private var updateTimer: Timer?
private let defaults = UserDefaults.standard
private var backgroundTaskId: UIBackgroundTaskIdentifier?
private var reachability = ReachabilityMonitor()
private var retryTimer: RetryTimer?
init(walletManager: WalletManager, store: Store) {
self.walletManager = walletManager
self.store = store
addWalletObservers()
addSubscriptions()
updateBalance()
reachability.didChange = { [weak self] isReachable in
self?.reachabilityDidChange(isReachable: isReachable)
}
}
private var lastBlockHeight: UInt32 {
set {
defaults.set(newValue, forKey: lastBlockHeightKey)
}
get {
return UInt32(defaults.integer(forKey: lastBlockHeightKey))
}
}
@objc private func updateProgress() {
DispatchQueue.walletQueue.async {
guard let progress = self.walletManager.peerManager?.syncProgress(fromStartHeight: self.lastBlockHeight), let timestamp = self.walletManager.peerManager?.lastBlockTimestamp else { return }
DispatchQueue.main.async {
self.store.perform(action: WalletChange.setProgress(progress: progress, timestamp: timestamp))
}
}
self.updateBalance()
}
private func onSyncStart() {
endBackgroundTask()
startBackgroundTask()
progressTimer = Timer.scheduledTimer(timeInterval: progressUpdateInterval, target: self, selector: #selector(WalletCoordinator.updateProgress), userInfo: nil, repeats: true)
store.perform(action: WalletChange.setSyncingState(.syncing))
startActivity()
}
private func onSyncStop(notification: Notification) {
if UIApplication.shared.applicationState != .active {
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.disconnect()
}
}
endBackgroundTask()
if notification.userInfo != nil {
guard let code = notification.userInfo?["errorCode"] else { return }
guard let message = notification.userInfo?["errorDescription"] else { return }
store.perform(action: WalletChange.setSyncingState(.connecting))
saveEvent("event.syncErrorMessage", attributes: ["message": "\(message) (\(code))"])
endActivity()
if retryTimer == nil && reachability.isReachable {
retryTimer = RetryTimer()
retryTimer?.callback = strongify(self) { myself in
myself.store.trigger(name: .retrySync)
}
retryTimer?.start()
}
return
}
retryTimer?.stop()
retryTimer = nil
if let height = walletManager.peerManager?.lastBlockHeight {
self.lastBlockHeight = height
}
progressTimer?.invalidate()
progressTimer = nil
store.perform(action: WalletChange.setSyncingState(.success))
store.perform(action: WalletChange.setIsRescanning(false))
endActivity()
}
private func endBackgroundTask() {
if let taskId = backgroundTaskId {
UIApplication.shared.endBackgroundTask(taskId)
backgroundTaskId = nil
}
}
private func startBackgroundTask() {
backgroundTaskId = UIApplication.shared.beginBackgroundTask(expirationHandler: {
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.disconnect()
}
})
}
private func requestTxUpdate() {
if updateTimer == nil {
updateTimer = Timer.scheduledTimer(timeInterval: updateDebounceInterval, target: self, selector: #selector(updateTransactions), userInfo: nil, repeats: false)
}
}
@objc private func updateTransactions() {
updateTimer?.invalidate()
updateTimer = nil
DispatchQueue.walletQueue.async {
guard let txRefs = self.walletManager.wallet?.transactions else { return }
let transactions = self.makeTransactionViewModels(transactions: txRefs, walletManager: self.walletManager, kvStore: self.kvStore, rate: self.store.state.currentRate)
if transactions.count > 0 {
DispatchQueue.main.async {
self.store.perform(action: WalletChange.setTransactions(transactions))
}
}
}
}
func makeTransactionViewModels(transactions: [BRTxRef?], walletManager: WalletManager, kvStore: BRReplicatedKVStore?, rate: Rate?) -> [Transaction] {
return transactions.flatMap{ $0 }.sorted {
if $0.pointee.timestamp == 0 {
return true
} else if $1.pointee.timestamp == 0 {
return false
} else {
return $0.pointee.timestamp > $1.pointee.timestamp
}
}.flatMap {
return Transaction($0, walletManager: walletManager, kvStore: kvStore, rate: rate)
}
}
private func addWalletObservers() {
NotificationCenter.default.addObserver(forName: .WalletBalanceChangedNotification, object: nil, queue: nil, using: { note in
self.updateBalance()
self.requestTxUpdate()
})
NotificationCenter.default.addObserver(forName: .WalletTxStatusUpdateNotification, object: nil, queue: nil, using: {note in
self.requestTxUpdate()
})
NotificationCenter.default.addObserver(forName: .WalletTxRejectedNotification, object: nil, queue: nil, using: {note in
guard let recommendRescan = note.userInfo?["recommendRescan"] as? Bool else { return }
self.requestTxUpdate()
if recommendRescan {
self.store.perform(action: RecommendRescan.set(recommendRescan))
}
})
NotificationCenter.default.addObserver(forName: .WalletSyncStartedNotification, object: nil, queue: nil, using: {note in
self.onSyncStart()
})
NotificationCenter.default.addObserver(forName: .WalletSyncStoppedNotification, object: nil, queue: nil, using: {note in
self.onSyncStop(notification: note)
})
}
private func updateBalance() {
DispatchQueue.walletQueue.async {
guard let newBalance = self.walletManager.wallet?.balance else { return }
DispatchQueue.main.async {
self.checkForReceived(newBalance: newBalance)
self.store.perform(action: WalletChange.setBalance(newBalance))
}
}
}
private func checkForReceived(newBalance: UInt64) {
if let oldBalance = store.state.walletState.balance {
if newBalance > oldBalance {
if store.state.walletState.syncState == .success {
self.showReceived(amount: newBalance - oldBalance)
}
}
}
}
private func showReceived(amount: UInt64) {
if let rate = store.state.currentRate {
let amount = Amount(amount: amount, rate: rate, maxDigits: store.state.maxDigits)
let primary = store.state.isBtcSwapped ? amount.localCurrency : amount.bits
let secondary = store.state.isBtcSwapped ? amount.bits : amount.localCurrency
let message = String(format: S.TransactionDetails.received, "\(primary) (\(secondary))")
store.trigger(name: .lightWeightAlert(message))
showLocalNotification(message: message)
ping()
}
}
private func ping() {
if let url = Bundle.main.url(forResource: "coinflip", withExtension: "aiff"){
var id: SystemSoundID = 0
AudioServicesCreateSystemSoundID(url as CFURL , &id)
AudioServicesAddSystemSoundCompletion(id, nil, nil, { soundId, _ in
AudioServicesDisposeSystemSoundID(soundId)
}, nil)
AudioServicesPlaySystemSound(id)
}
}
private func showLocalNotification(message: String) {
guard UIApplication.shared.applicationState == .background || UIApplication.shared.applicationState == .inactive else { return }
guard store.state.isPushNotificationsEnabled else { return }
UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber + 1
let notification = UILocalNotification()
notification.alertBody = message
notification.soundName = "coinflip.aiff"
UIApplication.shared.presentLocalNotificationNow(notification)
}
private func reachabilityDidChange(isReachable: Bool) {
if !isReachable {
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.disconnect()
DispatchQueue.main.async {
self.store.perform(action: WalletChange.setSyncingState(.connecting))
}
}
}
}
private func addSubscriptions() {
store.subscribe(self, name: .retrySync, callback: { _ in
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.connect()
}
})
store.subscribe(self, name: .rescan, callback: { _ in
self.store.perform(action: RecommendRescan.set(false))
//In case rescan is called while a sync is in progess
//we need to make sure it's false before a rescan starts
//self.store.perform(action: WalletChange.setIsSyncing(false))
DispatchQueue.walletQueue.async {
self.walletManager.peerManager?.rescan()
}
})
store.subscribe(self, name: .rescan, callback: { _ in
self.store.perform(action: WalletChange.setIsRescanning(true))
})
}
private func startActivity() {
UIApplication.shared.isIdleTimerDisabled = true
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
private func endActivity() {
UIApplication.shared.isIdleTimerDisabled = false
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
| 38.864286 | 200 | 0.634167 |
16d7625e0855086316853798f6eef3c413581b40 | 35,607 | //
// DKPlayerView.swift
// DKPhotoGallery
//
// Created by ZhangAo on 28/09/2017.
// Copyright © 2017 ZhangAo. All rights reserved.
//
import UIKit
import AVFoundation
private var DKPlayerViewKVOContext = 0
private class DKPlayerControlView: UIView {
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let hitTestingView = super.hitTest(point, with: event)
return hitTestingView == self ? nil : hitTestingView
}
}
open class DKPlayerView: UIView {
public var url: URL? {
willSet {
if self.url == newValue && self.error == nil {
return
}
if let newValue = newValue {
DispatchQueue.global().async {
if newValue == self.url {
let asset = AVURLAsset(url: newValue)
DispatchQueue.main.async {
if newValue == self.url {
self.asset = asset
}
}
}
}
} else {
self.asset = nil
}
}
}
public var asset: AVAsset? {
didSet {
if self.asset == oldValue {
return
}
if let oldAsset = oldValue {
oldAsset.cancelLoading()
}
self.playerItem = nil
if let newValue = self.asset {
self.bufferingIndicator.startAnimating()
newValue.loadValuesAsynchronously(forKeys: ["duration", "tracks"], completionHandler: {
if newValue == self.asset {
var error: NSError?
let loadStatus = newValue.statusOfValue(forKey: "duration", error: &error)
var item: AVPlayerItem?
if loadStatus == .loaded {
item = AVPlayerItem(asset: newValue)
} else if loadStatus == .failed {
self.error = error
}
DispatchQueue.main.async {
if newValue == self.asset {
self.bufferingIndicator.stopAnimating()
if let item = item {
self.playerItem = item
} else if let error = self.error, self.autoPlayOrShowErrorOnce {
self.showPlayError(error.localizedDescription)
}
}
}
}
})
}
}
}
public var playerItem: AVPlayerItem? {
willSet {
if self.playerItem == newValue {
return
}
if let oldPlayerItem = self.playerItem {
self.removeObservers(for: oldPlayerItem)
self.player.pause()
self.player.replaceCurrentItem(with: nil)
}
if let newPlayerItem = newValue {
self.player.replaceCurrentItem(with: newPlayerItem)
self.addObservers(for: newPlayerItem)
}
}
}
public var closeBlock: (() -> Void)? {
willSet {
self.closeButton.isHidden = newValue == nil
}
}
public var beginPlayBlock: (() -> Void)?
public var isControlHidden: Bool {
get { return self.controlView.isHidden }
set { self.controlView.isHidden = newValue }
}
public var isPlaying: Bool {
get { return self.player.rate == 1.0 }
}
public var autoHidesControlView = true
public var tapToToggleControlView = true {
willSet {
self.tapGesture.isEnabled = newValue
}
}
public var isFinishedPlaying = false
public let playButton = UIButton(type: .custom)
private let closeButton = UIButton(type: .custom)
private let playPauseButton = UIButton(type: .custom)
private let timeSlider = UISlider()
private let startTimeLabel = UILabel()
private let durationLabel = UILabel()
private var tapGesture: UITapGestureRecognizer!
private lazy var bufferingIndicator: UIActivityIndicatorView = {
return UIActivityIndicatorView(style: .gray)
}()
private var playerLayer: AVPlayerLayer {
return self.layer as! AVPlayerLayer
}
private let player = AVPlayer()
private var currentTime: Double {
get {
return CMTimeGetSeconds(player.currentTime())
}
set {
guard let _ = self.player.currentItem else { return }
let newTime = CMTimeMakeWithSeconds(Double(Int64(newValue)), preferredTimescale: 1)
self.player.seek(to: newTime, toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero)
}
}
private let controlView = DKPlayerControlView()
private var autoPlayOrShowErrorOnce = false
private var _error: NSError?
private var error: NSError? {
get {
return _error ?? self.player.currentItem?.error as NSError?
}
set {
_error = newValue
}
}
/*
A formatter for individual date components used to provide an appropriate
value for the `startTimeLabel` and `durationLabel`.
*/
private let timeRemainingFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.zeroFormattingBehavior = .pad
formatter.allowedUnits = [.minute, .second]
return formatter
}()
/*
A token obtained from calling `player`'s `addPeriodicTimeObserverForInterval(_:queue:usingBlock:)`
method.
*/
private var timeObserverToken: Any?
open override class var layerClass: AnyClass {
return AVPlayerLayer.self
}
convenience init() {
self.init(frame: CGRect.zero, controlParentView: nil)
}
convenience init(controlParentView: UIView?) {
self.init(frame: CGRect.zero, controlParentView: controlParentView)
}
private weak var controlParentView: UIView?
public init(frame: CGRect, controlParentView: UIView?) {
super.init(frame: frame)
self.controlParentView = controlParentView
self.setupUI()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupUI()
}
deinit {
guard let currentItem = self.player.currentItem, currentItem.observationInfo != nil else { return }
self.removeObservers(for: currentItem)
}
@objc public func playAndHidesControlView() {
self.play()
self.beginPlayBlock?()
if self.autoHidesControlView {
self.isControlHidden = true
}
}
public func play() {
guard !self.isPlaying else { return }
if let error = self.error {
if let avAsset = self.asset ?? self.playerItem?.asset, self.isTriableError(error) {
self.autoPlayOrShowErrorOnce = true
if let URLAsset = avAsset as? AVURLAsset {
self.asset = nil
self.url = URLAsset.url
} else {
self.url = nil
self.asset = avAsset
}
self.error = nil
} else {
self.showPlayError(error.localizedDescription)
}
return
}
if let currentItem = self.playerItem {
if currentItem.status == .readyToPlay {
if self.isFinishedPlaying {
self.isFinishedPlaying = false
self.currentTime = 0.0
}
self.player.play()
self.updateBufferingIndicatorStateIfNeeded()
} else if currentItem.status == .unknown {
self.player.play()
}
}
}
@objc public func pause() {
guard let _ = self.player.currentItem, self.isPlaying else { return }
self.player.pause()
}
public func stop() {
self.asset?.cancelLoading()
self.pause()
}
public func updateContextBackground(alpha: CGFloat) {
self.playButton.alpha = alpha
self.controlView.alpha = alpha
}
public func reset() {
self.asset?.cancelLoading()
self.url = nil
self.asset = nil
self.playerItem = nil
self.error = nil
self.autoPlayOrShowErrorOnce = false
self.isFinishedPlaying = false
self.bufferingIndicator.stopAnimating()
self.playButton.isHidden = false
self.playPauseButton.isEnabled = false
self.timeSlider.isEnabled = false
self.timeSlider.value = 0
self.startTimeLabel.isEnabled = false
self.startTimeLabel.text = "0:00"
self.durationLabel.isEnabled = false
self.durationLabel.text = "0:00"
}
// MARK: - Private
private func setupUI() {
self.playerLayer.player = self.player
self.playButton.setImage(DKPhotoGalleryResource.videoPlayImage(), for: .normal)
self.playButton.addTarget(self, action: #selector(playAndHidesControlView), for: .touchUpInside)
self.addSubview(self.playButton)
self.playButton.sizeToFit()
self.playButton.center = self.center
self.playButton.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
self.bufferingIndicator.hidesWhenStopped = true
self.bufferingIndicator.isUserInteractionEnabled = false
self.bufferingIndicator.center = self.center
self.bufferingIndicator.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
self.addSubview(self.bufferingIndicator)
self.closeButton.setImage(DKPhotoGalleryResource.closeVideoImage(), for: .normal)
self.closeButton.addTarget(self, action: #selector(close), for: .touchUpInside)
self.controlView.addSubview(self.closeButton)
self.closeButton.translatesAutoresizingMaskIntoConstraints = false
self.closeButton.addConstraint(NSLayoutConstraint(item: self.closeButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40))
self.closeButton.addConstraint(NSLayoutConstraint(item: self.closeButton,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40))
self.controlView.addConstraint(NSLayoutConstraint(item: self.closeButton,
attribute: .top,
relatedBy: .equal,
toItem: self.controlView,
attribute: .top,
multiplier: 1,
constant: 25))
self.controlView.addConstraint(NSLayoutConstraint(item: self.closeButton,
attribute: .left,
relatedBy: .equal,
toItem: self.controlView,
attribute: .left,
multiplier: 1,
constant: 15))
let bottomView = UIView()
bottomView.translatesAutoresizingMaskIntoConstraints = false
self.controlView.addSubview(bottomView)
self.playPauseButton.setImage(DKPhotoGalleryResource.videoToolbarPlayImage(), for: .normal)
self.playPauseButton.setImage(DKPhotoGalleryResource.videoToolbarPauseImage(), for: .selected)
self.playPauseButton.addTarget(self, action: #selector(playPauseButtonWasPressed), for: .touchUpInside)
bottomView.addSubview(self.playPauseButton)
self.playPauseButton.translatesAutoresizingMaskIntoConstraints = false
self.playPauseButton.addConstraint(NSLayoutConstraint(item: self.playPauseButton,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40))
self.playPauseButton.addConstraint(NSLayoutConstraint(item: self.playPauseButton,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40))
bottomView.addConstraint(NSLayoutConstraint(item: self.playPauseButton,
attribute: .left,
relatedBy: .equal,
toItem: bottomView,
attribute: .left,
multiplier: 1,
constant: 20))
bottomView.addConstraint(NSLayoutConstraint(item: self.playPauseButton,
attribute: .top,
relatedBy: .equal,
toItem: bottomView,
attribute: .top,
multiplier: 1,
constant: 0))
bottomView.addConstraint(NSLayoutConstraint(item: self.playPauseButton,
attribute: .bottom,
relatedBy: .equal,
toItem: bottomView,
attribute: .bottom,
multiplier: 1,
constant: 0))
bottomView.addSubview(self.startTimeLabel)
self.startTimeLabel.textColor = UIColor.white
self.startTimeLabel.textAlignment = .right
self.startTimeLabel.font = UIFont(name: "Helvetica Neue", size: 13)
self.startTimeLabel.translatesAutoresizingMaskIntoConstraints = false
bottomView.addConstraint(NSLayoutConstraint(item: self.startTimeLabel,
attribute: .left,
relatedBy: .equal,
toItem: self.playPauseButton,
attribute: .right,
multiplier: 1,
constant: 0))
bottomView.addConstraint(NSLayoutConstraint(item: self.startTimeLabel,
attribute: .centerY,
relatedBy: .equal,
toItem: self.playPauseButton,
attribute: .centerY,
multiplier: 1,
constant: 0))
bottomView.addSubview(self.timeSlider)
self.timeSlider.addTarget(self, action: #selector(timeSliderDidChange(sender:event:)), for: .valueChanged)
self.timeSlider.setThumbImage(DKPhotoGalleryResource.videoTimeSliderImage(), for: .normal)
self.timeSlider.translatesAutoresizingMaskIntoConstraints = false
self.timeSlider.addConstraint(NSLayoutConstraint(item: self.timeSlider,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 40))
bottomView.addConstraint(NSLayoutConstraint(item: self.timeSlider,
attribute: .left,
relatedBy: .equal,
toItem: self.startTimeLabel,
attribute: .right,
multiplier: 1,
constant: 15))
bottomView.addConstraint(NSLayoutConstraint(item: self.timeSlider,
attribute: .centerY,
relatedBy: .equal,
toItem: self.playPauseButton,
attribute: .centerY,
multiplier: 1,
constant: 0))
bottomView.addSubview(self.durationLabel)
self.durationLabel.textColor = UIColor.white
self.durationLabel.font = self.startTimeLabel.font
self.durationLabel.translatesAutoresizingMaskIntoConstraints = false
self.durationLabel.addConstraint(NSLayoutConstraint(item: self.durationLabel,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 50))
bottomView.addConstraint(NSLayoutConstraint(item: self.durationLabel,
attribute: .width,
relatedBy: .equal,
toItem: self.startTimeLabel,
attribute: .width,
multiplier: 1,
constant: 0))
bottomView.addConstraint(NSLayoutConstraint(item: self.durationLabel,
attribute: .left,
relatedBy: .equal,
toItem: self.timeSlider,
attribute: .right,
multiplier: 1,
constant: 15))
bottomView.addConstraint(NSLayoutConstraint(item: self.durationLabel,
attribute: .right,
relatedBy: .equal,
toItem: bottomView,
attribute: .right,
multiplier: 1,
constant: -10))
bottomView.addConstraint(NSLayoutConstraint(item: self.durationLabel,
attribute: .centerY,
relatedBy: .equal,
toItem: self.startTimeLabel,
attribute: .centerY,
multiplier: 1,
constant: 0))
self.controlView.addConstraint(NSLayoutConstraint(item: bottomView,
attribute: .left,
relatedBy: .equal,
toItem: self.controlView,
attribute: .left,
multiplier: 1,
constant: 0))
self.controlView.addConstraint(NSLayoutConstraint(item: bottomView,
attribute: .right,
relatedBy: .equal,
toItem: self.controlView,
attribute: .right,
multiplier: 1,
constant: 0))
self.controlView.addConstraint(NSLayoutConstraint(item: bottomView,
attribute: .bottom,
relatedBy: .equal,
toItem: self.controlView,
attribute: .bottom,
multiplier: 1,
constant: DKPhotoBasePreviewVC.isIphoneX() ? -34 : 0))
if let controlParentView = self.controlParentView {
controlParentView.addSubview(self.controlView)
} else {
self.addSubview(self.controlView)
}
self.controlView.frame = self.controlView.superview!.bounds
self.controlView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let backgroundImageView = UIImageView(image: DKPhotoGalleryResource.videoPlayControlBackgroundImage())
backgroundImageView.frame = self.controlView.bounds
backgroundImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.controlView.insertSubview(backgroundImageView, at: 0)
self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggleControlView(tapGesture:)))
self.addGestureRecognizer(self.tapGesture)
self.timeSlider.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(sliderTappedAction(tapGesture:))))
self.controlView.isHidden = self.isControlHidden
}
@objc private func playPauseButtonWasPressed() {
if !self.isPlaying {
self.play()
} else {
self.pause()
}
}
@objc private func timeSliderDidChange(sender: UISlider, event: UIEvent) {
if let touchEvent = event.allTouches?.first {
switch touchEvent.phase {
case .began:
if self.isPlaying {
self.pause()
}
case .moved:
self.currentTime = Double(self.timeSlider.value)
case .ended,
.cancelled:
self.play()
default:
break
}
} else {
self.currentTime = Double(self.timeSlider.value)
self.play()
}
}
@objc private func sliderTappedAction(tapGesture: UITapGestureRecognizer) {
if let slider = tapGesture.view as? UISlider {
if slider.isHighlighted { return }
let point = tapGesture.location(in: slider)
let percentage = Float(point.x / slider.bounds.width)
let delta = percentage * Float(slider.maximumValue - slider.minimumValue)
let value = slider.minimumValue + delta
slider.setValue(value, animated: true)
slider.sendActions(for: .valueChanged)
}
}
@objc private func toggleControlView(tapGesture: UITapGestureRecognizer) {
self.isControlHidden = !self.isControlHidden
self.startHidesControlTimerIfNeeded()
}
private var hidesControlViewTimer: Timer?
private func startHidesControlTimerIfNeeded() {
guard self.autoHidesControlView else { return }
self.stopHidesControlTimer()
if !self.isControlHidden && self.isPlaying {
self.hidesControlViewTimer = Timer.scheduledTimer(timeInterval: 3.5,
target: self,
selector: #selector(hidesControlViewIfNeeded),
userInfo: nil,
repeats: false)
}
}
private func stopHidesControlTimer() {
guard self.autoHidesControlView else { return }
self.hidesControlViewTimer?.invalidate()
self.hidesControlViewTimer = nil
}
@objc private func hidesControlViewIfNeeded() {
if self.isPlaying {
self.isControlHidden = true
}
}
@objc private func close() {
if let closeBlock = self.closeBlock {
closeBlock()
}
}
private func createTimeString(time: Float) -> String {
let components = NSDateComponents()
components.second = Int(max(0.0, time))
return timeRemainingFormatter.string(from: components as DateComponents)!
}
private func showPlayError(_ message: String) {
self.makeSimpleToast(message)
}
private func isTriableError(_ error: NSError) -> Bool {
let untriableCodes: Set<Int> = [
URLError.badURL.rawValue,
URLError.fileDoesNotExist.rawValue,
URLError.unsupportedURL.rawValue,
]
return !untriableCodes.contains(error.code)
}
private func updateBufferingIndicatorStateIfNeeded() {
if self.isPlaying, let currentItem = self.player.currentItem {
if currentItem.isPlaybackBufferEmpty {
self.bufferingIndicator.startAnimating()
} else if currentItem.isPlaybackLikelyToKeepUp {
self.bufferingIndicator.stopAnimating()
} else {
self.bufferingIndicator.stopAnimating()
}
}
}
// MARK: - Observer
private func addObservers(for playerItem: AVPlayerItem) {
playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.duration), options: [.new, .initial], context: &DKPlayerViewKVOContext)
playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: [.new, .initial], context: &DKPlayerViewKVOContext)
playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: [.new, .initial], context: &DKPlayerViewKVOContext)
playerItem.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: [.new, .initial], context: &DKPlayerViewKVOContext)
player.addObserver(self, forKeyPath: #keyPath(AVPlayer.rate), options: [.new, .initial], context: &DKPlayerViewKVOContext)
NotificationCenter.default.addObserver(self, selector: #selector(itemDidPlayToEndTime), name: .AVPlayerItemDidPlayToEndTime, object: playerItem)
let interval = CMTime(value: 1, timescale: 1)
self.timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { [weak self] (time) in
guard let strongSelf = self else { return }
let timeElapsed = Float(CMTimeGetSeconds(time))
strongSelf.startTimeLabel.text = strongSelf.createTimeString(time: timeElapsed)
if strongSelf.isPlaying {
strongSelf.timeSlider.value = timeElapsed
strongSelf.playButton.isHidden = true
}
})
}
private func removeObservers(for playerItem: AVPlayerItem) {
playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.duration), context: &DKPlayerViewKVOContext)
playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), context: &DKPlayerViewKVOContext)
playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), context: &DKPlayerViewKVOContext)
playerItem.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), context: &DKPlayerViewKVOContext)
self.player.removeObserver(self, forKeyPath: #keyPath(AVPlayer.rate), context: &DKPlayerViewKVOContext)
NotificationCenter.default.removeObserver(self)
if let timeObserverToken = self.timeObserverToken {
self.player.removeTimeObserver(timeObserverToken)
self.timeObserverToken = nil
}
}
@objc func itemDidPlayToEndTime(notification: Notification) {
if (notification.object as? AVPlayerItem) == self.player.currentItem {
self.isFinishedPlaying = true
self.playButton.isHidden = false
}
}
// Update our UI when player or `player.currentItem` changes.
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &DKPlayerViewKVOContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if keyPath == #keyPath(AVPlayerItem.duration) {
// Update timeSlider and enable/disable controls when duration > 0.0
/*
Handle `NSNull` value for `NSKeyValueChangeNewKey`, i.e. when
`player.currentItem` is nil.
*/
let newDuration: CMTime
if let newDurationAsValue = change?[NSKeyValueChangeKey.newKey] as? NSValue {
newDuration = newDurationAsValue.timeValue
} else {
newDuration = CMTime.zero
}
let hasValidDuration = newDuration.isNumeric && newDuration.value != 0
let newDurationSeconds = hasValidDuration ? CMTimeGetSeconds(newDuration) : 0.0
let currentTime = hasValidDuration ? Float(CMTimeGetSeconds(player.currentTime())) : 0.0
self.timeSlider.maximumValue = Float(newDurationSeconds)
self.timeSlider.value = currentTime
self.playPauseButton.isEnabled = hasValidDuration
self.timeSlider.isEnabled = hasValidDuration
self.startTimeLabel.isEnabled = hasValidDuration
self.startTimeLabel.text = createTimeString(time: currentTime)
self.durationLabel.isEnabled = hasValidDuration
self.durationLabel.text = self.createTimeString(time: Float(newDurationSeconds))
} else if keyPath == #keyPath(AVPlayerItem.status) {
guard let currentItem = object as? AVPlayerItem else { return }
guard self.autoPlayOrShowErrorOnce else { return }
// Display an error if status becomes `.Failed`.
/*
Handle `NSNull` value for `NSKeyValueChangeNewKey`, i.e. when
`player.currentItem` is nil.
*/
let newStatus: AVPlayerItem.Status
if let newStatusAsNumber = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
newStatus = AVPlayerItem.Status(rawValue: newStatusAsNumber.intValue)!
} else {
newStatus = .unknown
}
if newStatus == .readyToPlay {
self.play()
self.autoPlayOrShowErrorOnce = false
} else if newStatus == .failed {
if let error = currentItem.error {
self.showPlayError(error.localizedDescription)
} else {
self.showPlayError(DKPhotoGalleryResource.localizedStringWithKey("preview.player.error.unknown"))
}
self.autoPlayOrShowErrorOnce = false
}
} else if keyPath == #keyPath(AVPlayer.rate) {
// Update UI status.
let newRate = (change?[NSKeyValueChangeKey.newKey] as! NSNumber).doubleValue
if newRate == 1.0 {
self.startHidesControlTimerIfNeeded()
self.playPauseButton.isSelected = true
} else {
self.stopHidesControlTimer()
self.playPauseButton.isSelected = false
}
} else if keyPath == #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp) {
self.updateBufferingIndicatorStateIfNeeded()
} else if keyPath == #keyPath(AVPlayerItem.isPlaybackBufferEmpty) {
self.updateBufferingIndicatorStateIfNeeded()
}
}
}
| 44.453184 | 158 | 0.487348 |
9b2f08ad7e132b649dee9ca09692508fd82c4463 | 5,601 | import Dispatch
import Nimble
import Quick
@testable import ReactiveSwift
private class Object {
var value: Int = 0
}
class UnidirectionalBindingSpec: QuickSpec {
override func spec() {
describe("BindingTarget") {
var token: Lifetime.Token!
var lifetime: Lifetime!
beforeEach {
token = Lifetime.Token()
lifetime = Lifetime(token)
}
describe("closure binding target") {
var target: BindingTarget<Int>?
var optionalTarget: BindingTarget<Int?>?
var value: Int?
beforeEach {
target = BindingTarget(lifetime: lifetime, action: { value = $0 })
optionalTarget = BindingTarget(lifetime: lifetime, action: { value = $0 })
value = nil
}
describe("non-optional target") {
it("should pass through the lifetime") {
expect(target!.lifetime).to(beIdenticalTo(lifetime))
}
it("should trigger the supplied setter") {
expect(value).to(beNil())
target!.action(1)
expect(value) == 1
}
it("should accept bindings from properties") {
expect(value).to(beNil())
let property = MutableProperty(1)
target! <~ property
expect(value) == 1
property.value = 2
expect(value) == 2
}
}
describe("target of optional value") {
it("should pass through the lifetime") {
expect(optionalTarget!.lifetime).to(beIdenticalTo(lifetime))
}
it("should trigger the supplied setter") {
expect(value).to(beNil())
optionalTarget!.action(1)
expect(value) == 1
}
it("should accept bindings from properties") {
expect(value).to(beNil())
let property = MutableProperty(1)
optionalTarget! <~ property
expect(value) == 1
property.value = 2
expect(value) == 2
}
}
describe("optional LHS binding with non-nil LHS at runtime") {
it("should pass through the lifetime") {
expect(target.bindingTarget.lifetime).to(beIdenticalTo(lifetime))
}
it("should accept bindings from properties") {
expect(value).to(beNil())
let property = MutableProperty(1)
optionalTarget <~ property
expect(value) == 1
property.value = 2
expect(value) == 2
}
}
describe("optional LHS binding with nil LHS at runtime") {
it("should pass through the empty lifetime") {
let nilTarget: BindingTarget<Int>? = nil
expect(nilTarget.bindingTarget.lifetime).to(beIdenticalTo(Lifetime.empty))
}
}
}
describe("key path binding target") {
var target: BindingTarget<Int>!
var object: Object!
beforeEach {
object = Object()
target = BindingTarget(lifetime: lifetime, object: object, keyPath: \.value)
}
it("should pass through the lifetime") {
expect(target.lifetime).to(beIdenticalTo(lifetime))
}
it("should trigger the supplied setter") {
expect(object.value) == 0
target.action(1)
expect(object.value) == 1
}
it("should accept bindings from properties") {
expect(object.value) == 0
let property = MutableProperty(1)
target <~ property
expect(object.value) == 1
property.value = 2
expect(object.value) == 2
}
}
it("should not deadlock on the same queue") {
var value: Int?
let target = BindingTarget(on: UIScheduler(),
lifetime: lifetime,
action: { value = $0 })
let property = MutableProperty(1)
target <~ property
expect(value) == 1
}
it("should not deadlock on the main thread even if the context was switched to a different queue") {
var value: Int?
let queue = DispatchQueue(label: #file)
let target = BindingTarget(on: UIScheduler(),
lifetime: lifetime,
action: { value = $0 })
let property = MutableProperty(1)
queue.sync {
_ = target <~ property
}
expect(value).toEventually(equal(1))
}
it("should not deadlock even if the value is originated from the same queue indirectly") {
var value: Int?
let key = DispatchSpecificKey<Void>()
DispatchQueue.main.setSpecific(key: key, value: ())
let mainQueueCounter = Atomic(0)
let setter: (Int) -> Void = {
value = $0
mainQueueCounter.modify { $0 += DispatchQueue.getSpecific(key: key) != nil ? 1 : 0 }
}
let target = BindingTarget(on: UIScheduler(),
lifetime: lifetime,
action: setter)
let scheduler: QueueScheduler
if #available(OSX 10.10, *) {
scheduler = QueueScheduler()
} else {
scheduler = QueueScheduler(queue: DispatchQueue(label: "com.reactivecocoa.ReactiveSwift.UnidirectionalBindingSpec"))
}
let property = MutableProperty(1)
target <~ property.producer
.start(on: scheduler)
.observe(on: scheduler)
expect(value).toEventually(equal(1))
expect(mainQueueCounter.value).toEventually(equal(1))
property.value = 2
expect(value).toEventually(equal(2))
expect(mainQueueCounter.value).toEventually(equal(2))
}
describe("observer binding operator") {
it("should forward values to observer") {
let targetPipe = Signal<Int?, Never>.pipe()
let sourcePipe = Signal<Int?, Never>.pipe()
let targetProperty = Property<Int?>(initial: nil, then: targetPipe.output)
targetPipe.input <~ sourcePipe.output
expect(targetProperty.value).to(beNil())
sourcePipe.input.send(value: 1)
expect(targetProperty.value).to(equal(1))
}
}
}
}
}
| 25.575342 | 121 | 0.620246 |
22f23f9552656494521acd8654a30135c37b4895 | 3,325 | import Fluent
import SQL
import Vapor
public protocol OffsetPaginatable {
associatedtype Element
func makeOffsetPaginationDataSource() -> OffsetPaginationDataSource<Element>
}
extension EventLoopFuture: OffsetPaginatable where T: Collection, T.Index == Int {
public typealias Element = T.Element
public func makeOffsetPaginationDataSource() -> OffsetPaginationDataSource<T.Element> {
return .init(
results: { range in self.map { Array($0[range.clamped(to: 0..<$0.count)]) } },
totalCount: { self.map { $0.count } }
)
}
}
extension QueryBuilder: OffsetPaginatable {
/// Make an OffsetPaginationDataSource from the query builder.
public func makeOffsetPaginationDataSource() -> OffsetPaginationDataSource<Result> {
return .init(
results: { range in
self.copy().range(range).all()
},
totalCount: copy().count
)
}
}
extension OffsetPaginationDataSource: OffsetPaginatable {
public func makeOffsetPaginationDataSource() -> OffsetPaginationDataSource<Element> {
return self
}
}
extension OffsetPaginationDataSource where Element: Decodable {
struct CountResult: Decodable {
let count: Int
}
public init<C: DatabaseConnection>(
resultBuilder: SQLRawBuilder<C>,
countBuilder: SQLRawBuilder<C>
) {
self.results = { range in
let resultBuilderCopy = resultBuilder.copy()
resultBuilderCopy.sql.append(
"\nLIMIT \(range.upperBound - range.lowerBound)\nOFFSET \(range.lowerBound)"
)
return resultBuilder.all(decoding: Element.self)
}
self.totalCount = {
countBuilder.first(decoding: CountResult.self).map { $0?.count ?? 0 }
}
}
}
private extension SQLRawBuilder {
func copy() -> SQLRawBuilder {
let copy = SQLRawBuilder(sql, on: connectable)
copy.binds = binds
return copy
}
}
public extension OffsetPaginatable {
func paginate(
parameters: OffsetParameters,
url: URL
) -> Future<OffsetPaginator<Element>> {
let source = makeOffsetPaginationDataSource()
return source
.results(parameters.range)
.map { results in
try OffsetPaginator(
data: results,
metadata: .init(
parameters: parameters,
total: 0,
url: url
)
)
}
}
}
// MARK: Creating `OffsetPaginator`s from `Request`s
public extension OffsetPaginatable {
func paginate(
on request: Request
) -> EventLoopFuture<OffsetPaginator<Element>> {
return request.offsetParameters().flatMap {
self.paginate(parameters: $0, url: request.http.url)
}
}
}
public extension Request {
func offsetParameters() -> EventLoopFuture<OffsetParameters> {
return EventLoopFuture.map(on: self) {
try self.query.decode(OffsetQueryParameters.self)
}.map {
OffsetParameters(
config: (try? self.make(OffsetPaginatorConfig.self)) ?? .default,
queryParameters: $0
)
}
}
}
| 29.166667 | 92 | 0.600301 |
ff8cc02bf9aac2261a57a3c075d08429e8b88fa3 | 375 | //
// Typealiases.swift
// LayoutBuilder
//
// Created by Ihor Malovanyi on 10.05.2021.
//
#if canImport(UIKit)
import UIKit
public typealias View = UIView
public typealias LayoutPriority = UILayoutPriority
#elseif canImport(AppKit)
import AppKit
public typealias View = NSView
public typealias LayoutPriority = NSLayoutConstraint.Priority
#endif
| 22.058824 | 65 | 0.736 |
6173effe04c6345e8384d7d5d925081a0ffd36f2 | 18,732 | // DO NOT EDIT.
// swift-format-ignore-file
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: akash/provider/v1beta2/provider.proto
//
// For information on using the generated types, please see the documentation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that you are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
/// ProviderInfo
struct Akash_Provider_V1beta2_ProviderInfo {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var email: String = String()
var website: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// MsgCreateProvider defines an SDK message for creating a provider
struct Akash_Provider_V1beta2_MsgCreateProvider {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var owner: String = String()
var hostUri: String = String()
var attributes: [Akash_Base_V1beta2_Attribute] = []
var info: Akash_Provider_V1beta2_ProviderInfo {
get {return _info ?? Akash_Provider_V1beta2_ProviderInfo()}
set {_info = newValue}
}
/// Returns true if `info` has been explicitly set.
var hasInfo: Bool {return self._info != nil}
/// Clears the value of `info`. Subsequent reads from it will return its default value.
mutating func clearInfo() {self._info = nil}
var jwtHostUri: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _info: Akash_Provider_V1beta2_ProviderInfo? = nil
}
/// MsgCreateProviderResponse defines the Msg/CreateProvider response type.
struct Akash_Provider_V1beta2_MsgCreateProviderResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// MsgUpdateProvider defines an SDK message for updating a provider
struct Akash_Provider_V1beta2_MsgUpdateProvider {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var owner: String = String()
var hostUri: String = String()
var attributes: [Akash_Base_V1beta2_Attribute] = []
var info: Akash_Provider_V1beta2_ProviderInfo {
get {return _info ?? Akash_Provider_V1beta2_ProviderInfo()}
set {_info = newValue}
}
/// Returns true if `info` has been explicitly set.
var hasInfo: Bool {return self._info != nil}
/// Clears the value of `info`. Subsequent reads from it will return its default value.
mutating func clearInfo() {self._info = nil}
var jwtHostUri: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _info: Akash_Provider_V1beta2_ProviderInfo? = nil
}
/// MsgUpdateProviderResponse defines the Msg/UpdateProvider response type.
struct Akash_Provider_V1beta2_MsgUpdateProviderResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// MsgDeleteProvider defines an SDK message for deleting a provider
struct Akash_Provider_V1beta2_MsgDeleteProvider {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var owner: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// MsgDeleteProviderResponse defines the Msg/DeleteProvider response type.
struct Akash_Provider_V1beta2_MsgDeleteProviderResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
/// Provider stores owner and host details
struct Akash_Provider_V1beta2_Provider {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var owner: String = String()
var hostUri: String = String()
var attributes: [Akash_Base_V1beta2_Attribute] = []
var info: Akash_Provider_V1beta2_ProviderInfo {
get {return _info ?? Akash_Provider_V1beta2_ProviderInfo()}
set {_info = newValue}
}
/// Returns true if `info` has been explicitly set.
var hasInfo: Bool {return self._info != nil}
/// Clears the value of `info`. Subsequent reads from it will return its default value.
mutating func clearInfo() {self._info = nil}
var jwtHostUri: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
fileprivate var _info: Akash_Provider_V1beta2_ProviderInfo? = nil
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "akash.provider.v1beta2"
extension Akash_Provider_V1beta2_ProviderInfo: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".ProviderInfo"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "email"),
2: .same(proto: "website"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.email) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.website) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.email.isEmpty {
try visitor.visitSingularStringField(value: self.email, fieldNumber: 1)
}
if !self.website.isEmpty {
try visitor.visitSingularStringField(value: self.website, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_ProviderInfo, rhs: Akash_Provider_V1beta2_ProviderInfo) -> Bool {
if lhs.email != rhs.email {return false}
if lhs.website != rhs.website {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_MsgCreateProvider: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MsgCreateProvider"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "owner"),
2: .standard(proto: "host_uri"),
3: .same(proto: "attributes"),
4: .same(proto: "info"),
5: .standard(proto: "jwt_host_uri"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.owner) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.hostUri) }()
case 3: try { try decoder.decodeRepeatedMessageField(value: &self.attributes) }()
case 4: try { try decoder.decodeSingularMessageField(value: &self._info) }()
case 5: try { try decoder.decodeSingularStringField(value: &self.jwtHostUri) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.owner.isEmpty {
try visitor.visitSingularStringField(value: self.owner, fieldNumber: 1)
}
if !self.hostUri.isEmpty {
try visitor.visitSingularStringField(value: self.hostUri, fieldNumber: 2)
}
if !self.attributes.isEmpty {
try visitor.visitRepeatedMessageField(value: self.attributes, fieldNumber: 3)
}
if let v = self._info {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
if !self.jwtHostUri.isEmpty {
try visitor.visitSingularStringField(value: self.jwtHostUri, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_MsgCreateProvider, rhs: Akash_Provider_V1beta2_MsgCreateProvider) -> Bool {
if lhs.owner != rhs.owner {return false}
if lhs.hostUri != rhs.hostUri {return false}
if lhs.attributes != rhs.attributes {return false}
if lhs._info != rhs._info {return false}
if lhs.jwtHostUri != rhs.jwtHostUri {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_MsgCreateProviderResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MsgCreateProviderResponse"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_MsgCreateProviderResponse, rhs: Akash_Provider_V1beta2_MsgCreateProviderResponse) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_MsgUpdateProvider: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MsgUpdateProvider"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "owner"),
2: .standard(proto: "host_uri"),
3: .same(proto: "attributes"),
4: .same(proto: "info"),
5: .standard(proto: "jwt_host_uri"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.owner) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.hostUri) }()
case 3: try { try decoder.decodeRepeatedMessageField(value: &self.attributes) }()
case 4: try { try decoder.decodeSingularMessageField(value: &self._info) }()
case 5: try { try decoder.decodeSingularStringField(value: &self.jwtHostUri) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.owner.isEmpty {
try visitor.visitSingularStringField(value: self.owner, fieldNumber: 1)
}
if !self.hostUri.isEmpty {
try visitor.visitSingularStringField(value: self.hostUri, fieldNumber: 2)
}
if !self.attributes.isEmpty {
try visitor.visitRepeatedMessageField(value: self.attributes, fieldNumber: 3)
}
if let v = self._info {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
if !self.jwtHostUri.isEmpty {
try visitor.visitSingularStringField(value: self.jwtHostUri, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_MsgUpdateProvider, rhs: Akash_Provider_V1beta2_MsgUpdateProvider) -> Bool {
if lhs.owner != rhs.owner {return false}
if lhs.hostUri != rhs.hostUri {return false}
if lhs.attributes != rhs.attributes {return false}
if lhs._info != rhs._info {return false}
if lhs.jwtHostUri != rhs.jwtHostUri {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_MsgUpdateProviderResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MsgUpdateProviderResponse"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_MsgUpdateProviderResponse, rhs: Akash_Provider_V1beta2_MsgUpdateProviderResponse) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_MsgDeleteProvider: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MsgDeleteProvider"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "owner"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.owner) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.owner.isEmpty {
try visitor.visitSingularStringField(value: self.owner, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_MsgDeleteProvider, rhs: Akash_Provider_V1beta2_MsgDeleteProvider) -> Bool {
if lhs.owner != rhs.owner {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_MsgDeleteProviderResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".MsgDeleteProviderResponse"
static let _protobuf_nameMap = SwiftProtobuf._NameMap()
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let _ = try decoder.nextFieldNumber() {
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_MsgDeleteProviderResponse, rhs: Akash_Provider_V1beta2_MsgDeleteProviderResponse) -> Bool {
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Akash_Provider_V1beta2_Provider: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".Provider"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "owner"),
2: .standard(proto: "host_uri"),
3: .same(proto: "attributes"),
4: .same(proto: "info"),
5: .standard(proto: "jwt_host_uri"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
// The use of inline closures is to circumvent an issue where the compiler
// allocates stack space for every case branch when no optimizations are
// enabled. https://github.com/apple/swift-protobuf/issues/1034
switch fieldNumber {
case 1: try { try decoder.decodeSingularStringField(value: &self.owner) }()
case 2: try { try decoder.decodeSingularStringField(value: &self.hostUri) }()
case 3: try { try decoder.decodeRepeatedMessageField(value: &self.attributes) }()
case 4: try { try decoder.decodeSingularMessageField(value: &self._info) }()
case 5: try { try decoder.decodeSingularStringField(value: &self.jwtHostUri) }()
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.owner.isEmpty {
try visitor.visitSingularStringField(value: self.owner, fieldNumber: 1)
}
if !self.hostUri.isEmpty {
try visitor.visitSingularStringField(value: self.hostUri, fieldNumber: 2)
}
if !self.attributes.isEmpty {
try visitor.visitRepeatedMessageField(value: self.attributes, fieldNumber: 3)
}
if let v = self._info {
try visitor.visitSingularMessageField(value: v, fieldNumber: 4)
}
if !self.jwtHostUri.isEmpty {
try visitor.visitSingularStringField(value: self.jwtHostUri, fieldNumber: 5)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Akash_Provider_V1beta2_Provider, rhs: Akash_Provider_V1beta2_Provider) -> Bool {
if lhs.owner != rhs.owner {return false}
if lhs.hostUri != rhs.hostUri {return false}
if lhs.attributes != rhs.attributes {return false}
if lhs._info != rhs._info {return false}
if lhs.jwtHostUri != rhs.jwtHostUri {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
| 39.686441 | 160 | 0.736814 |
64a3f46d809e769e58d4ffb0c169c9d05bfc3fe5 | 327 | //
// DrawerActionableItem.swift
// ToDo
//
// Created by Dmitry Klimkin on 1/2/18.
// Copyright © 2018 Dev4Jam. All rights reserved.
//
import RxSwift
public protocol DrawerActionableItem: class {
func waitForList() -> Observable<(ListActionableItem, ())>
func sayHi() -> Observable<(ListActionableItem, ())>
}
| 20.4375 | 62 | 0.691131 |
5694dc4528d5c782189166ec1d6c1fc8e7ef2d05 | 9,075 | //
// NSAttributedStringVC.swift
// LTExtensionDemo
//
// Created by TopSky on 2018/2/27.
// Copyright © 2018年 TopSky. All rights reserved.
//
import UIKit
class NSAttributedStringVC: BaseContentViewController {
let label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
label.backgroundColor = UIColor.green
label.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 100)
label.textAlignment = .center
contentView.addSubview(label)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func add() {
addAction(title: "属性字符串拼接测试") {
let text = "$"
var dict = [NSAttributedStringKey: Any]()
dict[NSAttributedStringKey.font] = UIFont.systemFont(ofSize: 20)
dict[NSAttributedStringKey.foregroundColor] = UIColor.red
let attributedText = NSAttributedString(string: text, attributes: dict)
var dict2 = [NSAttributedStringKey: Any]()
dict2[NSAttributedStringKey.foregroundColor] = UIColor.blue
dict2[NSAttributedStringKey.font] = UIFont.systemFont(ofSize: 15)
dict2[NSAttributedStringKey.underlineStyle] = NSUnderlineStyle.styleSingle.rawValue
dict2[NSAttributedStringKey.underlineColor] = UIColor.black
var dict3 = [NSAttributedStringKey: Any]()
dict3[NSAttributedStringKey.foregroundColor] = UIColor.gray
dict3[NSAttributedStringKey.font] = UIFont.systemFont(ofSize: 10)
var dict4 = [NSAttributedStringKey: Any]()
dict4[NSAttributedStringKey.foregroundColor] = UIColor.blue
dict4[NSAttributedStringKey.font] = UIFont.systemFont(ofSize: 15)
dict4[NSAttributedStringKey.strikethroughStyle] = NSUnderlineStyle.styleSingle.rawValue
dict4[NSAttributedStringKey.strikethroughColor] = UIColor.black
dict4[NSAttributedStringKey.backgroundColor] = UIColor.yellow
var dict5 = [NSAttributedStringKey: Any]()
dict5[NSAttributedStringKey.backgroundColor] = UIColor.darkGray
self.label.attributedText = attributedText.append("123.00", dict2).append("起", dict3).append("12345.00", dict4).append(dict5).append("15", nil)
}
addAction(title: "属性测试") {
let attributedText = NSAttributedString()
self.label.font = UIFont.systemFont(ofSize: 15)
self.label.numberOfLines = 0
self.label.attributedText = attributedText.append("A", { (content) in
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.firstLineHeadIndent = 15
content.paragraphStyle = paragraphStyle
}).append("B", { (content) in
content.font = UIFont.systemFont(ofSize: 20)
content.foregroundColor = UIColor.red
content.backgroundColor = UIColor.yellow
}).append("fl", { (content) in
content.font = UIFont.init(name: "futura", size: 20)
content.ligature = 0
}).append("fl", { (content) in
content.font = UIFont.init(name: "futura", size: 20)
content.ligature = 4
}).append("cc", { (content) in
content.kern = 2
}).append("cc", { (content) in
content.kern = 0.5
}).append("ee", { (content) in
content.strikethroughStyle = NSUnderlineStyle.styleSingle
content.strikethroughColor = UIColor.red
content.font = UIFont.systemFont(ofSize: 20)
}).append("ll", { (content) in
content.underlineStyle = NSUnderlineStyle.styleSingle
content.underlineColor = UIColor.red
content.font = UIFont.systemFont(ofSize: 20)
}).append("E", { (content) in
content.strokeColor = UIColor.red
// content.foregroundColor = UIColor.blue 字体颜色失效
content.strokeWidth = 5
content.backgroundColor = UIColor.yellow
content.font = UIFont.systemFont(ofSize: 40)
}).append("F", { (content) in
let shadow = NSShadow()
shadow.shadowOffset = CGSize(width: 20, height: 20)
shadow.shadowBlurRadius = 4
shadow.shadowColor = UIColor.blue
content.font = UIFont.systemFont(ofSize: 40)
content.shadow = shadow
}).append("Hello,中秋节!", { (content) in
content.font = UIFont.systemFont(ofSize: 40)
content.textEffect = .letterpressStyle
content.foregroundColor = UIColor.gray
})
}
addAction(title: "排版测试") {
let attributedText = NSAttributedString()
self.label.font = UIFont.systemFont(ofSize: 15)
self.label.numberOfLines = 0
self.label.attributedText = attributedText.append("百度", { (content) in
content.link = "www.baidu.com"
}).append("T", { (content) in
content.baselineOffset = 10
}).append("T", { (content) in
// content.baselineOffset = 0
}).append("T", { (content) in
content.baselineOffset = -10
}).append("H", { (content) in
content.obliqueness = 0.5
}).append("H", { (content) in
// content.obliqueness = 0
}).append("H", { (content) in
content.obliqueness = -0.5
}).append(" ", { (content) in
}).append("D", { (content) in
content.expansion = 0.5
}).append("D", { (content) in
// content.expansion = -0.5
}).append("D", { (content) in
content.expansion = -0.5
}).append("lt ", { (content) in
content.writingDirection = 0
}).append("lt ", { (content) in
content.writingDirection = 1
}).append("lt ", { (content) in
content.writingDirection = 2
}).append("lt ", { (content) in
content.writingDirection = 3
}).append("", { (content) in
let attachment = NSTextAttachment()
attachment.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
attachment.image = self.imageWithColor(UIColor.red, size: CGSize.init(width: 20, height: 20), alpha: 1)
content.attachment = attachment
}).append("over", { (content) in
// content.writingDirection = 3
}).append("AA", { (content) in
let attachment = NSTextAttachment()
attachment.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
attachment.image = self.imageWithColor(UIColor.blue, size: CGSize.init(width: 20, height: 20), alpha: 1)
content.attachment = attachment
})
}
addAction(title: "附件") {
let attr = NSMutableAttributedString(string: "name", attributes: nil)
let attachment = NSTextAttachment()
attachment.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
attachment.image = self.imageWithColor(UIColor.red, size: CGSize.init(width: 20, height: 20), alpha: 1)
self.label.attributedText = attr.appendAttachment(attachment).append({ (content) in
let attachment2 = NSTextAttachment()
attachment2.bounds = CGRect(x: 0, y: 0, width: 20, height: 20)
attachment2.image = self.imageWithColor(UIColor.blue, size: CGSize.init(width: 20, height: 20), alpha: 1)
content.attachment = attachment2
})
}
addAction(title: "删除线") {
self.label.attributedText = NSAttributedString(string: "name").appendDeleteLine()
}
}
func imageWithColor(_ color: UIColor, size: CGSize, alpha: CGFloat) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let ref = UIGraphicsGetCurrentContext()
ref!.setAlpha(alpha)
ref!.setFillColor(color.cgColor)
ref!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
func test(closure: (String) -> Void) {
// closure("zhang")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 41.62844 | 155 | 0.579174 |
33d57217c90038f859df64a481f47f8ebc6f0b0a | 3,512 | //
// Networking.swift
// MovieApp-Client
//
// Created by Tansel Kahyaoglu on 29.08.2020.
// Copyright © 2020 Tansel Kahyaoglu. All rights reserved.
//
import Foundation
class Networking {
private static let baseUrl = "http://www.omdbapi.com"
enum HTTPMethod: String {
case get = "GET"
case post = "POST"
case put = "PUT"
case delete = "DELETE"
}
class func request<S: Decodable, F: BaseErrorResponse>(method: HTTPMethod,
urlParameters: [String: String],
showLoading: Bool = true,
succeed: @escaping (S) -> Void,
failed: @escaping (F) -> Void) {
guard var components = URLComponents(string: baseUrl) else { return }
components.queryItems = urlParameters.map {
URLQueryItem(name: $0.key, value: $0.value)
}
guard let url = components.url else { return }
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if showLoading {
showIndicator()
}
URLSession.shared.dataTask(with: request,
completionHandler: { data, response, error in
if showLoading {
hideIndicator()
}
if let error = error {
DispatchQueue.main.async {
failed(F(error: error.localizedDescription))
}
}
if let status = response as? HTTPURLResponse {
guard let data = data else { return }
print("Response Code: \(status.statusCode)")
if status.statusCode >= 200 && status.statusCode <= 399 {
do {
let decoder = try JSONDecoder().decode(S.self, from: data)
DispatchQueue.main.async {
succeed(decoder)
}
} catch {
DispatchQueue.main.async {
failed(F(error: "Decoding Error", code: status.statusCode))
}
}
} else {
DispatchQueue.main.async {
failed(F(error: "Error on server. Response code: \(status.statusCode)", code: status.statusCode))
}
}
}
}).resume()
}
private class func showIndicator() {
LoadingHelper.shared.show()
}
private class func hideIndicator() {
LoadingHelper.shared.hide()
}
}
| 41.809524 | 145 | 0.369021 |
1678975c98a479a689789caeb7c2a32a4ed51d68 | 1,524 | //
// ContentView.swift
// Instafilter
//
// Created by Ramsey on 2020/6/22.
// Copyright © 2020 Ramsey. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var blurAmount: CGFloat = 0
@State private var showingActionSheet = false
@State private var backgroundColor = Color.white
var body: some View {
let blur = Binding<CGFloat>(
get: {
self.blurAmount
},
set: {
self.blurAmount = $0
print("New value is \(self.blurAmount)")
}
)
return VStack {
Text("Hello, World!")
.blur(radius: blurAmount)
.background(backgroundColor)
.onTapGesture {
self.showingActionSheet = true
}
.actionSheet(isPresented: $showingActionSheet) {
ActionSheet(title: Text("Change background"), message: Text("Select a new color"), buttons: [
.default(Text("Red")) { self.backgroundColor = .red },
.default(Text("Green")) { self.backgroundColor = .green },
.default(Text("Blue")) { self.backgroundColor = .blue },
.cancel()
])
}
Slider(value: blur, in: 0...20)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| 28.754717 | 113 | 0.503281 |
ff49507256d759b4379a209e3277f3f3a71c3fe0 | 10,941 | //
// StdOutAppender.swift
// log4swift
//
// Created by Jérôme Duquennoy on 14/06/2015.
// Copyright © 2015 Jérôme Duquennoy. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/**
StdOutAppender will print the log to stdout or stderr depending on thresholds and levels.
* If general threshold is reached but error threshold is undefined or not reached, log will be printed to stdout
* If both general and error threshold are reached, log will be printed to stderr
*/
public class StdOutAppender: Appender {
public enum DictionaryKey: String {
case ErrorThreshold = "ErrorThresholdLevel"
case TextColors = "TextColors"
case BackgroundColors = "BackgroundColors"
case ForcedTTYType = "ForcedTTYType"
}
public enum TTYType {
/// Xcode with XcodeColors plugin
case XcodeColors
/// xterm-256color terminal
case XtermColor
/// non color-compatible tty
case Other
init(_ name: String) {
switch(name.lowercased()) {
case "xterm" : self = .XtermColor
case "xcodecolors" : self = .XcodeColors
default: self = .Other
}
}
}
/// ttyType will determine what color codes should be used if colors are enabled.
/// This is supposed to be automatically detected when creating the logger.
/// Change that only if you need to override the automatic detection.
public var ttyType: TTYType
public var errorThresholdLevel: LogLevel? = .Error
internal fileprivate(set) var textColors = [LogLevel: TTYColor]()
internal fileprivate(set) var backgroundColors = [LogLevel: TTYColor]()
@objc
public required init(_ identifier: String) {
let xcodeColors = ProcessInfo().environment["XcodeColors"]
let terminalType = ProcessInfo().environment["TERM"]
switch (xcodeColors, terminalType) {
case (.some("YES"), _):
self.ttyType = .XcodeColors
case (_, .some("xterm-256color")):
self.ttyType = .XtermColor
default:
self.ttyType = .Other
}
super.init(identifier)
}
public override func update(withDictionary dictionary: Dictionary<String, Any>, availableFormatters: Array<Formatter>) throws {
try super.update(withDictionary: dictionary, availableFormatters: availableFormatters)
if let errorThresholdString = (dictionary[DictionaryKey.ErrorThreshold.rawValue] as? String) {
if let errorThreshold = LogLevel(errorThresholdString) {
errorThresholdLevel = errorThreshold
} else {
throw NSError.Log4swiftError(description: "Invalide '\(DictionaryKey.ErrorThreshold.rawValue)' value for Stdout appender '\(self.identifier)'")
}
} else {
errorThresholdLevel = nil
}
if let textColors = (dictionary[DictionaryKey.TextColors.rawValue] as? Dictionary<String, String>) {
for (levelName, colorName) in textColors {
guard let level = LogLevel(levelName) else {
throw NSError.Log4swiftError(description: "Invalide level '\(levelName)' in '\(DictionaryKey.TextColors.rawValue)' for Stdout appender '\(self.identifier)'")
}
guard let color = TTYColor(colorName) else {
throw NSError.Log4swiftError(description: "Invalide color '\(colorName)' in '\(DictionaryKey.TextColors.rawValue)' for Stdout appender '\(self.identifier)'")
}
self.textColors[level] = color
}
}
if let backgroundColors = (dictionary[DictionaryKey.BackgroundColors.rawValue] as? Dictionary<String, String>) {
for (levelName, colorName) in backgroundColors {
guard let level = LogLevel(levelName) else {
throw NSError.Log4swiftError(description: "Invalide level '\(levelName)' in '\(DictionaryKey.BackgroundColors.rawValue)' for Stdout appender '\(self.identifier)'")
}
guard let color = TTYColor(colorName) else {
throw NSError.Log4swiftError(description: "Invalide color '\(colorName)' in '\(DictionaryKey.BackgroundColors.rawValue)' for Stdout appender '\(self.identifier)'")
}
self.backgroundColors[level] = color
}
}
if let forcedTtyType = (dictionary[DictionaryKey.ForcedTTYType.rawValue] as? String) {
self.ttyType = TTYType(forcedTtyType)
}
}
public override func performLog(_ log: String, level: LogLevel, info: LogInfoDictionary) {
var destinationFile = stdout
if let errorThresholdLevel = self.errorThresholdLevel {
if(level.rawValue >= errorThresholdLevel.rawValue) {
destinationFile = stderr
}
}
let finalLogString = self.colorizeLog(log: log, level: level) + "\n"
fputs(finalLogString, destinationFile)
}
}
// MARK: - Color management extension
extension StdOutAppender {
public enum TTYColor {
case Black
case DarkGrey
case Grey
case LightGrey
case White
case LightRed
case Red
case DarkRed
case LightGreen
case Green
case DarkGreen
case LightBlue
case Blue
case DarkBlue
case LightYellow
case Yellow
case DarkYellow
case Purple
case LightPurple
case DarkPurple
case LightOrange
case Orange
case DarkOrange
init?(_ name: String) {
switch(name.lowercased()) {
case "black" : self = .Black
case "darkgrey" : self = .DarkGrey
case "grey" : self = .Grey
case "lightgrey" : self = .LightGrey
case "white" : self = .White
case "lightred" : self = .LightRed
case "red" : self = .Red
case "darkred" : self = .DarkRed
case "lightgreen" : self = .LightGreen
case "green" : self = .Green
case "darkgreen" : self = .DarkGreen
case "lightblue" : self = .LightBlue
case "blue" : self = .Blue
case "darkblue" : self = .DarkBlue
case "lightyellow" : self = .LightYellow
case "yellow" : self = .Yellow
case "darkyellow" : self = .DarkYellow
case "lightpurple" : self = .LightPurple
case "purple" : self = .Purple
case "darkpurple" : self = .DarkPurple
case "lightorange" : self = .LightOrange
case "orange" : self = .Orange
case "darkorange" : self = .DarkOrange
default: return nil
}
}
private func xtermCode() -> Int {
switch(self) {
case .Black : return 0
case .DarkGrey : return 238
case .Grey : return 241
case .LightGrey : return 251
case .White : return 15
case .LightRed : return 199
case .Red : return 9
case .DarkRed : return 1
case .LightGreen : return 46
case .Green : return 2
case .DarkGreen : return 22
case .LightBlue : return 45
case .Blue : return 21
case .DarkBlue : return 18
case .LightYellow : return 228
case .Yellow : return 11
case .DarkYellow : return 3
case .Purple : return 93
case .LightPurple : return 135
case .DarkPurple : return 55
case .LightOrange: return 215
case .Orange: return 208
case .DarkOrange: return 166
}
}
private func xcodeCode() -> String {
switch(self) {
case .Black : return "0,0,0"
case .DarkGrey : return "68,68,68"
case .Grey : return "98,98,98"
case .LightGrey : return "200,200,200"
case .White : return "255,255,255"
case .LightRed : return "255,37,174"
case .Red : return "255,0,0"
case .DarkRed : return "201,14,19"
case .LightGreen : return "57,255,42"
case .Green : return "0,255,0"
case .DarkGreen : return "18,94,11"
case .LightBlue : return "47,216,255"
case .Blue : return "0,0,255"
case .DarkBlue : return "0,18,133"
case .LightYellow : return "255,255,143"
case .Yellow : return "255,255,56"
case .DarkYellow : return "206,203,43"
case .Purple : return "131,46,252"
case .LightPurple : return "172,105,252"
case .DarkPurple : return "92,28,173"
case .LightOrange: return "255,176,95"
case .Orange: return "255,135,0"
case .DarkOrange: return "216,96,0"
}
}
fileprivate func code(forTTYType type: TTYType) -> String {
switch(type) {
case .XtermColor: return String(self.xtermCode())
case .XcodeColors: return self.xcodeCode()
case .Other: return ""
}
}
}
private var textColorPrefix: String {
switch(self.ttyType) {
case .XcodeColors: return "\u{1B}[fg"
case .XtermColor: return "\u{1B}[38;5;"
case .Other: return ""
}
}
private var backgroundColorPrefix: String {
switch(self.ttyType) {
case .XcodeColors: return "\u{1B}[bg"
case .XtermColor: return "\u{1B}[48;5;"
case .Other: return ""
}
}
private var colorSuffix: String {
switch(self.ttyType) {
case .XcodeColors: return ";"
case .XtermColor: return "m"
case .Other: return ""
}
}
private var resetColorSequence: String {
switch(self.ttyType) {
case .XcodeColors: return "\u{1B}[;"
case .XtermColor: return "\u{1B}[0m"
case .Other: return ""
}
}
fileprivate func colorizeLog(log: String, level: LogLevel) -> String {
var shouldResetColors = false
var colorizedLog = ""
if let textColor = self.textColors[level] {
shouldResetColors = true
colorizedLog += self.textColorPrefix + textColor.code(forTTYType: self.ttyType) + self.colorSuffix
}
if let backgroundColor = self.backgroundColors[level] {
shouldResetColors = true
colorizedLog += self.backgroundColorPrefix + backgroundColor.code(forTTYType: self.ttyType) + self.colorSuffix
}
colorizedLog += log
if(shouldResetColors) {
colorizedLog += self.resetColorSequence
}
return colorizedLog
}
/// :param: color The color to set, or nil to set no color
/// :param: level The log level to which the provided color applies
public func setTextColor(_ color: TTYColor?, forLevel level: LogLevel) {
if let color = color {
self.textColors[level] = color
} else {
self.textColors.removeValue(forKey: level)
}
}
/// :param: color The color to set, or nil to set no color
/// :param: level The log level to which the provided color applies
public func setBackgroundColor(_ color: TTYColor?, forLevel level: LogLevel) {
if let color = color {
self.backgroundColors[level] = color
} else {
self.backgroundColors.removeValue(forKey: level)
}
}
}
| 33.054381 | 173 | 0.654236 |
1a77a772dcf8c2b33c551c4e8b593ac3832ccd9c | 926 | //
// EasyDownloaderTests.swift
// EasyDownloaderTests
//
// Created by Kumamoto on 2019/07/12.
// Copyright © 2019 Kumamoto. All rights reserved.
//
import XCTest
@testable import EasyDownloader
class EasyDownloaderTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.457143 | 111 | 0.664147 |
034a979a1585abe5653c8e79bc48e73e49046de8 | 490 | //
// FungibleTokenCell.swift
// iOS-Example
//
// Created by Simon Mcloughlin on 10/06/2021.
// Copyright © 2021 Kukai AB. All rights reserved.
//
import UIKit
class FungibleTokenCell: UITableViewCell {
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var label: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| 20.416667 | 65 | 0.695918 |
1c2f57e70299ecbab17a7027237263574ea8a58b | 2,297 | //
// SceneDelegate.swift
// SwiftyRadio-iOS
//
// Created by Eric Conner on 4/27/20.
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let _ = (scene as? UIWindowScene) else { return }
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| 43.339623 | 147 | 0.713104 |
bb7fb0d6aad817ddf90f8abd3b72d7fc8ceb1a9d | 1,771 | //
// Copyright (c) 2022-Present, Okta, Inc. and/or its affiliates. All rights reserved.
// The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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
@testable import AuthFoundation
extension Token {
static let mockContext = Token.Context(
configuration: OAuth2Client.Configuration(
baseURL: URL(string: "https://example.com")!,
clientId: "0oa3en4fIMQ3ddc204w5",
scopes: "offline_access profile openid"),
clientSettings: [ "client_id": "0oa3en4fIMQ3ddc204w5" ])
static let simpleMockToken = mockToken()
static func mockToken(id: String = "TokenId",
refreshToken: String? = nil,
deviceSecret: String? = nil,
issuedOffset: TimeInterval = 0,
expiresIn: TimeInterval = 3600) -> Token
{
Token(id: id,
issuedAt: Date(timeIntervalSinceNow: -issuedOffset),
tokenType: "Bearer",
expiresIn: expiresIn,
accessToken: JWT.mockAccessToken,
scope: "openid",
refreshToken: refreshToken,
idToken: try? JWT(JWT.mockIDToken),
deviceSecret: deviceSecret,
context: mockContext)
}
}
| 40.25 | 120 | 0.631282 |
3993ef7519a20e59d8f9eca1ec5dd12f6ca2d670 | 5,468 | //
// RVC+NavigationBar.swift
// FawGen
//
// Created by Erick Olibo on 02/08/2019.
// Copyright © 2019 DEFKUT Creations OU. All rights reserved.
//
import UIKit
extension RandomizeViewController {
public func setupNavigationBarItems() {
setupRemainingNavItems()
setupRightNavItems()
setupNewLeftNavItems()
}
private func setupNewLeftNavItems() {
let checkerButton = UIButton(type: .system)
checkerButton.translatesAutoresizingMaskIntoConstraints = false
checkerButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
checkerButton.setImage(UIImage(named: "checker")?.withRenderingMode(.alwaysOriginal), for: .normal)
checkerButton.addTarget(self, action: #selector(presentCheckerViewController), for: .touchUpInside)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: checkerButton)
}
/// Sets the navigation bar 3 right items as listed in letf-to-right order:
/// Favorite, Filter, Favorites.
private func setupRightNavItems() {
let collection = [("Settings" , #selector(presentSettingsViewController)),
("Filter" , #selector(presentFilterViewController)),
("favorite" , #selector(presentSavedListViewController))]
var barButtonItems = [UIBarButtonItem]()
for (imageName, selector) in collection {
let itemButton = UIButton(type: .system)
itemButton.translatesAutoresizingMaskIntoConstraints = false
itemButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
itemButton.setImage(UIImage(named: imageName)?.withRenderingMode(.alwaysOriginal), for: .normal)
itemButton.addTarget(self, action: selector, for: .touchUpInside)
let itemBarButton = UIBarButtonItem(customView: itemButton)
barButtonItems.append(itemBarButton)
}
navigationItem.rightBarButtonItems = barButtonItems
}
/// sets the remainder items not set in the setupNavigationBarItems(),
/// setupLeftNavItems(), and setupRightNavItems().
private func setupRemainingNavItems() {
navigationController?.navigationBar.backgroundColor = .white
navigationController?.navigationBar.isTranslucent = false
}
// MARK: - Navigation Bar Button Actions
// Presents as Stork transition and ViewController
@objc private func presentCheckerViewController() {
let checkerVC: CheckerViewController = {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
return storyBoard.instantiateViewController(withIdentifier: "CheckerVC") as! CheckerViewController
}()
let transitionDelegate = SPStorkTransitioningDelegate()
checkerVC.transitioningDelegate = transitionDelegate
checkerVC.modalPresentationStyle = .custom
checkerVC.modalPresentationCapturesStatusBarAppearance = true
self.present(checkerVC, animated: true, completion: nil)
}
/// Presents as push transition the settings view controller
/// - Note: SettingsViewController is access via its StoryBoard identifier
@objc private func presentSettingsViewController() {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let settingsVC = storyBoard.instantiateViewController(withIdentifier: "SettingsVC")
self.navigationController?.pushViewController(settingsVC, animated: true)
}
/// Presents the Filter View Controller as Lark transition
/// (slides up to reveal behind)
/// - Note: FilterViewController is access via its StoryBoard identifier
@objc private func presentFilterViewController() {
let filterVC: FilterViewController = {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
return storyBoard.instantiateViewController(withIdentifier: "FilterVC") as! FilterViewController
}()
let transitionDelegate = SPLarkTransitioningDelegate()
filterVC.delegate = self
filterVC.transitioningDelegate = transitionDelegate
filterVC.modalPresentationStyle = .custom
filterVC.modalPresentationCapturesStatusBarAppearance = true
self.presentAsLark(filterVC, height: larkPresentHeight, complection: nil)
}
/// Presents as push transition the FavoritesView controller
/// - Warning: Missing implementation for FavoritesViewController
@objc private func presentSavedListViewController() {
printConsole("pushedSavedListButton")
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let savedListVC = storyBoard.instantiateViewController(withIdentifier: "SavedListVC") as! SavedListViewController
self.navigationController?.pushViewController(savedListVC, animated: true)
}
/// Presents as push transition the DetailsView Controller
/// - Note: DetailsViewController is access via its StoryBoard identifier
public func presentDetailsViewController(_ fakeWord: FakeWord) {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let detailsVC = storyBoard.instantiateViewController(withIdentifier: "DetailsVC") as! DetailsViewController
detailsVC.fakeWord = fakeWord
self.navigationController?.pushViewController(detailsVC, animated: true)
}
}
| 45.94958 | 121 | 0.70117 |
722fdeb80c7dcc22498ec02df2f8cfc45ff28455 | 4,225 |
import Foundation
public extension NSObject {
/// Creates a Listener for key-value observing.
func on <T> (_ keyPath: String, _ handler: @escaping (Change<T>) -> Void) -> ChangeListener<T> {
return on(keyPath, [.old, .new], handler)
}
/// Creates a single-use Listener for key-value observing.
@discardableResult
func once <T> (_ keyPath: String, _ handler: @escaping (Change<T>) -> Void) -> ChangeListener<T> {
return once(keyPath, [.old, .new], handler)
}
/// Creates a Listener for key-value observing.
func on <T> (_ keyPath: String, _ options: NSKeyValueObservingOptions, _ handler: @escaping (Change<T>) -> Void) -> ChangeListener<T> {
return ChangeListener(false, self, keyPath, options, handler)
}
/// Creates a single-use Listener for key-value observing.
@discardableResult
func once <T> (_ keyPath: String, _ options: NSKeyValueObservingOptions, _ handler: @escaping (Change<T>) -> Void) -> ChangeListener<T> {
return ChangeListener(true, self, keyPath, options, handler)
}
/// Call this before your NSObject's dealloc phase if the given Listener array has ChangeListeners.
func removeListeners (_ listeners: [Listener]) {
for listener in listeners {
if let listener = listener as? ChangeListener<NSObject> {
listener.isListening = false
}
}
}
}
public class Change <T> : CustomStringConvertible {
public let keyPath: String
public let oldValue: T!
public let newValue: T!
public let isPrior: Bool
public var description: String {
return "(Change = { address: \(getHash(self)), keyPath: \(keyPath), oldValue: \(oldValue), newValue: \(newValue), isPrior: \(isPrior) })"
}
init (_ keyPath: String, _ oldValue: T!, _ newValue: T!, _ isPrior: Bool) {
self.keyPath = keyPath
self.oldValue = oldValue
self.newValue = newValue
self.isPrior = isPrior
}
}
public class ChangeListener <T> : Listener {
public let keyPath: String
public let options: NSKeyValueObservingOptions
public unowned let object: NSObject
var _observer: ChangeObserver!
func _trigger (_ data: NSDictionary) {
let oldValue = data[NSKeyValueChangeKey.oldKey] as? T
let newValue = data[NSKeyValueChangeKey.newKey] as? T
let isPrior = data[NSKeyValueChangeKey.notificationIsPriorKey] != nil
_trigger(Change<T>(keyPath, oldValue, newValue, isPrior))
}
override func _startListening () {
// A middleman to prevent pollution of ChangeListener property list.
_observer = ChangeObserver({ [unowned self] in
self._trigger($0)
})
self.object.addObserver(_observer, forKeyPath: self.keyPath, options: self.options, context: nil)
// Add self to global cache.
var targets = ChangeListenerCache[self.keyPath] ?? [:]
var listeners = targets[_targetID] ?? [:]
listeners[getHash(self)] = self.once ? StrongPointer(self) : WeakPointer(self)
targets[_targetID] = listeners
ChangeListenerCache[self.keyPath] = targets
}
override func _stopListening() {
self.object.removeObserver(_observer, forKeyPath: self.keyPath)
// Remove self from global cache.
var targets = ChangeListenerCache[self.keyPath]!
var listeners = targets[_targetID]!
listeners[getHash(self)] = nil
targets[_targetID] = listeners.nilIfEmpty
ChangeListenerCache[self.keyPath] = targets.nilIfEmpty
}
init (_ once: Bool, _ object: NSObject, _ keyPath: String, _ options: NSKeyValueObservingOptions, _ handler: @escaping (Change<T>) -> Void) {
self.object = object
self.keyPath = keyPath
self.options = options
super.init(nil, once) {
handler($0 as! Change<T>)
}
}
}
// 1 - Listener.keyPath
// 2 - getHash(Listener.target)
// 3 - getHash(Listener)
// 4 - DynamicPointer<Listener>
var ChangeListenerCache = [String:[String:[String:DynamicPointer<Listener>]]]()
class ChangeObserver : NSObject {
let _handler: (NSDictionary) -> Void
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
_handler(change as NSDictionary? ?? [:])
}
init (_ handler: @escaping (NSDictionary) -> Void) {
_handler = handler
}
}
| 31.296296 | 149 | 0.693964 |
7a1b2643d24052d5c8b0ae082c6259badfa27962 | 15,163 | //
// Functions.swift
// Announcer
//
// Created by JiaChen(: on 28/5/20.
// Copyright © 2020 SST Inc. All rights reserved.
//
import Foundation
import SystemConfiguration
import UserNotifications
import UIKit
import BackgroundTasks
import SafariServices
import CoreSpotlight
/// Functions meant to fetch data
struct Fetch {
/**
Get the labels, tags or categories from the posts.
- returns: An array of labels or tags from the post
This method gets labels, tags or categories, from blog posts and removes duplicates.
*/
static func labels() -> [String] {
let parser = FeedParser(URL: GlobalLinks.rssURL)
let result = parser.parse()
switch result {
case .success(let feed):
var labels: [String] = []
let entries = feed.atomFeed?.entries ?? []
for i in entries {
for item in i.categories ?? [] {
labels.append(item.attributes?.term ?? "")
}
}
labels.removeDuplicates()
return labels
case .failure(let error):
print(error.localizedDescription)
// Present alert
}
return []
}
/**
Fetch blog post from the blogURL
- returns: An array of Announcements stored as Post
- parameters:
- vc: Takes in Announcement View Controller to present an alert in a case of an error
This method fetches the blog post from the blogURL and will alert the user if an error occurs and it is unable to get the announcements
*/
static func posts(with vc: AnnouncementsViewController) -> [Post] {
let parser = FeedParser(URL: GlobalLinks.rssURL)
let result = parser.parse()
switch result {
case .success(let feed):
let feed = feed.atomFeed
let posts = convertFromEntries(feed: (feed?.entries!)!)
UserDefaults.standard.set(posts[0].title, forKey: UserDefaultsIdentifiers.recentsTitle.rawValue)
UserDefaults.standard.set(posts[0].content, forKey: UserDefaultsIdentifiers.recentsContent.rawValue)
return posts
case .failure(let error):
print(error.localizedDescription)
// Present alert
DispatchQueue.main.async {
// No internet error
let alert = UIAlertController(title: ErrorMessages.unableToLoadPost.title,
message: ErrorMessages.unableToLoadPost.description,
preferredStyle: .alert)
// Try to reload and hopefully it works
let tryAgain = UIAlertAction(title: "Try Again", style: .default, handler: { action in
vc.reload(UILabel())
})
alert.addAction(tryAgain)
alert.preferredAction = tryAgain
// Open the settings app
alert.addAction(UIAlertAction(title: "Open Settings", style: .default, handler: { action in
UIApplication.shared.open(GlobalLinks.settingsURL, options: [:]) { (success) in
print(success)
}
}))
// Just dismiss it
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
vc.present(alert, animated: true, completion: nil)
}
}
return []
}
/**
Fetches latest blog post for notifications
- returns: A tuple with the title and content of the post or `nil` if no new content has been posted
This method will fetch the latest posts from the RSS feed and if it is a new post, it will return the title and content for notifications, otherwise, it will return nil.
*/
static func latestNotification() -> (title: String, content: String)? {
let parser = FeedParser(URL: GlobalLinks.rssURL)
let result = parser.parse()
switch result {
case .success(let feed):
let feed = feed.atomFeed
let posts = convertFromEntries(feed: (feed?.entries)!)
if posts[0].title != UserDefaults.standard.string(forKey: UserDefaultsIdentifiers.recentsTitle.rawValue) && posts[0].content != UserDefaults.standard.string(forKey: UserDefaultsIdentifiers.recentsContent.rawValue) {
UserDefaults.standard.set(posts[0].title, forKey: UserDefaultsIdentifiers.recentsTitle.rawValue)
UserDefaults.standard.set(posts[0].content, forKey: UserDefaultsIdentifiers.recentsContent.rawValue)
let title = convertFromEntries(feed: (feed?.entries!)!).first!.title
let content = convertFromEntries(feed: (feed?.entries!)!).first!.content.htmlToAttributedString?.htmlToString
return (title: title, content: content!)
}
default:
break
}
return nil
}
/**
Fetches the blog posts from the blogURL
- returns: An array of `Post` from the blog
- important: This method will handle errors it receives by returning an empty array
This method will fetch the posts from the blog and return it as [Post]
*/
static func values() -> [Post] {
let parser = FeedParser(URL: GlobalLinks.rssURL)
let result = parser.parse()
switch result {
case .success(let feed):
let feed = feed.atomFeed
return convertFromEntries(feed: (feed?.entries)!)
default:
break
}
return []
}
/**
Converts an array of `AtomFeedEntry` to an array of `Post`
- returns: An array of `Post`
- parameters:
- feed: An array of `AtomFeedEntry`
This method will convert the array of `AtomFeedEntry` from `FeedKit` to an array of `Post`.
*/
static func convertFromEntries(feed: [AtomFeedEntry]) -> [Post] {
var posts = [Post]()
for entry in feed {
let cat = entry.categories ?? []
posts.append(Post(title: entry.title ?? "",
content: (entry.content?.value) ?? "",
date: entry.published ?? Date(),
pinned: false,
read: false,
reminderDate: nil,
categories: {
var categories: [String] = []
for i in cat {
categories.append((i.attributes?.term!)!)
}
return categories
}()))
}
return posts
}
}
/**
Gets the labels from search queries
- returns: Label within the search query
- parameters:
- query: A String containing the search query
This method locates the squared brackets `[]` in search queries and returns the Label within the query.
*/
func getLabelsFromSearch(with query: String) -> String {
// Labels in search are a mess to deal with
if query.first == "[" {
let split = query.split(separator: "]")
var result = split[0]
result.removeFirst()
return String(result.lowercased())
}
return ""
}
/**
Launches post using the post title
- parameters:
- postTitle: The title of the post to be found
- note: This method is generally for search and notifications
This method launches post using the post title and will show an open in safari button if there is an error.
*/
func launchPost(withTitle postTitle: String) {
let posts = Fetch.values()
var post: Post?
// Finding the post to present
for item in posts {
if item.title == postTitle {
post = item
break
}
}
var announcementVC: AnnouncementsViewController!
if I.wantToBeMac || I.mac {
let splitVC = UIApplication.shared.windows.first?.rootViewController as! SplitViewController
announcementVC = splitVC.announcementVC!
} else {
let navigationController = UIApplication.shared.windows.first?.rootViewController as! UINavigationController
announcementVC = navigationController.topViewController as? AnnouncementsViewController
}
if let post = post {
// Marking post as read
var readAnnouncements = ReadAnnouncements.loadFromFile() ?? []
readAnnouncements.append(post)
ReadAnnouncements.saveToFile(posts: readAnnouncements)
// Handles when post is found
announcementVC.receivePost(with: post)
} else {
// Handle when unable to get post
// Show an alert to the user to tell them that the post was unable to be found :(
print("failed to get post :(")
let alert = UIAlertController(title: ErrorMessages.unableToLaunchPost.title,
message: ErrorMessages.unableToLaunchPost.description,
preferredStyle: .alert)
// If user opens post in Safari, it will simply bring them to student blog home page
let openInSafari = UIAlertAction(title: "Open in Safari", style: .default, handler: { (_) in
let svc = SFSafariViewController(url: URL(string: GlobalLinks.blogURL)!)
announcementVC.present(svc, animated: true)
})
alert.addAction(openInSafari)
alert.preferredAction = openInSafari
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
announcementVC.present(alert, animated: true)
}
}
/**
Continuing userActivity from Spotlight Search
- parameters:
- userActivity: UserActivity received from Delegate
This method opens the post that is received from spotlight search.
*/
func continueFromCoreSpotlight(with userActivity: NSUserActivity) {
if userActivity.activityType == CSSearchableItemActionType {
if let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
launchPost(withTitle: uniqueIdentifier)
}
}
}
struct ScrollSelection {
static func setNormalState(for item: UIView? = nil, barButton: UIBarButtonItem? = nil) {
if let item = item {
if let button = item as? UIButton {
button.layer.borderWidth = 0
button.layer.borderColor = GlobalColors.borderColor
} else if let searchBar = item as? UISearchBar {
searchBar.alpha = 1
}
} else {
barButton?.tintColor = GlobalColors.greyOne
}
}
static func setSelectedState(for item: UIView? = nil, barButton: UIBarButtonItem? = nil, withOffset offset: CGFloat, andConstant constant: CGFloat) {
let multiplier = (offset * -1 - constant) / 100
if let item = item {
if let button = item as? UIButton {
button.layer.borderWidth = 25 * multiplier
button.layer.borderColor = GlobalColors.borderColor
} else if let searchBar = item as? UISearchBar {
searchBar.alpha = 1 - (multiplier * 2)
}
} else {
barButton?.tintColor = GlobalColors.greyOne.withAlphaComponent(1 - (multiplier * 2))
}
}
}
struct LinkFunctions {
/**
Gets the share URL from a `Post`
- returns: The URL of the blog post
- parameters:
- post: The post to be shared
- important: This method handles error 404 by simply returning the `blogURL`
- note: Versions of SST Announcer before 11.0 shared the full content of the post instead of the URL
This method generates a URL for the post by merging the date and the post title.
*/
static func getShareURL(with post: Post) -> URL {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "/yyyy/MM/"
var shareLink = ""
let formatted = post.title.filter { (a) -> Bool in
a.isLetter || a.isNumber || a.isWhitespace
}.lowercased()
let split = formatted.split(separator: " ")
// Add "-" between words. Ensure that it is under 45 characters, because blogger.
for i in split {
if shareLink.count + i.count < 45 {
shareLink += i + "-"
} else {
break
}
}
shareLink.removeLast()
shareLink = GlobalLinks.blogURL + dateFormatter.string(from: post.date) + shareLink + ".html"
let shareURL = URL(string: shareLink) ?? URL(string: GlobalLinks.blogURL)!
// Checking if the URL brings up a 404 page
let isURLValid: Bool = {
let str = try? String(contentsOf: shareURL)
if let str = str {
return !str.contains("Sorry, the page you were looking for in this blog does not exist.")
} else {
return false
}
}()
if isURLValid {
return shareURL
}
return URL(string: GlobalLinks.blogURL)!
}
/**
Gets the links within the `Post`
- returns: An array of `URL`s which are in the post.
- parameters:
- post: The selected post
- important: This process takes a bit so it is better to do it asyncronously so the app will not freeze while searching for URLs.
This method gets the URLs found within the blog post and filters out images from blogger's content delivery network because no one wants those URLs.
*/
static func getLinksFromPost(post: Post) -> [URL] {
let items = post.content.components(separatedBy: "href=\"")
var links: [URL] = []
for item in items {
var newItem = ""
for character in item {
if character != "\"" {
newItem += String(character)
} else {
break
}
}
if let url = URL(string: newItem) {
links.append(url)
}
}
links.removeDuplicates()
links = links.filter { (link) -> Bool in
!link.absoluteString.contains("bp.blogspot.com/")
}
return links
}
}
| 33.472406 | 227 | 0.557673 |
9c9a502387b18a5f7b2c1ac403c8f014c282ed0d | 2,156 | //
// AppDelegate.swift
// Weather
//
// Created by Joe on 26/02/20.
// Copyright © 2020 Joe. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 45.87234 | 285 | 0.753711 |
76f2b11ac0e2ade8d1679d4d2813e13222139385 | 3,648 | //
// BaseTableViewController.swift
// one
//
// Created by sidney on 2021/3/21.
//
import UIKit
class BaseTableViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
lazy var tableView = UITableView()
var tableData: [Any] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .systemGray6
view.addSubview(tableView)
tableView.snp.makeConstraints { (maker) in
maker.leading.trailing.bottom.equalToSuperview()
maker.top.equalToSuperview().offset(44 + STATUS_BAR_HEIGHT)
}
tableView.tableFooterView = UIView()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = dequeueReusableCell(withIdentifier: "BaseTableViewCell", tableView: tableView) as! BaseTableViewCell
return cell
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| 35.076923 | 137 | 0.67352 |
cc0dfca63584c8f0b45735efb7b2d2ca5e1ae65e | 15,658 | //
// DFUOTAUpdater.swift
// MyBike_BLE
//
// Created by Andrea Finollo on 09/04/2019.
// Copyright © 2019 Andrea Finollo. All rights reserved.
//
import Foundation
import Bluejay
import PromiseKit
import CoreBluetooth
import ZIPFoundation
public struct Firmware {
let version: UInt8
let deviceType: DeviceType
let firmwareZipURL: URL?
let firmwareManifestURL: URL?
let firmwareBinURL: URL?
let firmwareDatURL: URL?
public init(version: UInt8, deviceType: DeviceType, firmwareZipURL: URL, shouldUnzip: Bool = false) throws {
self.version = version
self.deviceType = deviceType
self.firmwareZipURL = firmwareZipURL
if shouldUnzip {
let fileManager = FileManager()
let fileName = firmwareZipURL.deletingPathExtension().lastPathComponent.replacingOccurrences(of: "_", with: "")
let destFolder = try ZipArchive.createTemporaryFolderPath(fileName)
try fileManager.unzipItem(at: firmwareZipURL, to: URL(fileURLWithPath:destFolder))
// Get folder content
let files = try ZipArchive.getFilesFromDirectory(destFolder)
let binName = files.first { (string) -> Bool in
return string.hasSuffix("bin") || string.hasSuffix("S")
}!
let datName = files.first { (string) -> Bool in
return string.hasSuffix("dat")
}!
let manifestName = files.first { (string) -> Bool in
return string.hasSuffix("json")
}!
self.firmwareBinURL = URL(fileURLWithPath: destFolder + binName)
self.firmwareDatURL = URL(fileURLWithPath: destFolder + datName)
self.firmwareManifestURL = URL(fileURLWithPath: destFolder + manifestName)
} else {
self.firmwareBinURL = nil
self.firmwareDatURL = nil
self.firmwareManifestURL = nil
}
}
public init(version: UInt8, deviceType: DeviceType, firmwareManifestURL: URL, firmwareBinURL: URL, firmwareDatURL: URL) {
self.version = version
self.deviceType = deviceType
self.firmwareManifestURL = firmwareManifestURL
self.firmwareBinURL = firmwareBinURL
self.firmwareDatURL = firmwareDatURL
self.firmwareZipURL = nil
}
public func getType() -> DeviceType {
return deviceType
}
}
public enum DeviceType {
case bms
case dsc
case ble
case ble_remote
}
public protocol DFUOTAUpdater {
func requestFirmwareUpdateForBLE(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void>
func requestFirmwareUpdateForDriver(bluejay: Bluejay, firmwareInfo: Firmware, transferCallBack: @escaping (_ progress: Int) -> (), progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void>
func requestFirmwareUpdateForBMS(bluejay: Bluejay, firmwareInfo: Firmware, transferCallBack: @escaping (_ progress: Int) -> (), progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void>
func requestFirmwareUpdateRemote(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void>
}
public class OTAFirmwareUpdater: DFUOTAUpdater {
let bluejay: Bluejay
private var progressCallback: ((_ dfuType: DeviceType, _ progress: Int) -> ())?
private var completion: ((_ success: String?, _ error: Error?) -> ())!
private var btState: (manager: CBCentralManager, peripheral: CBPeripheral?)?
private var updateController: DFUServiceController?
private let deviceType: DeviceType
public var isUpdatingFirmware = false
public init(with bluejay: Bluejay, for deviceType: DeviceType) {
self.bluejay = bluejay
self.deviceType = deviceType
}
/**
This method provides an encapsulated way to update ble application firmware of the Remote, in a promisable mean
- Parameters:
- bluejay: current blujay instance connected to the peripheral we want to update
- firmwareInfo: firmware information with the path of the zip URL
- progressCallback: callback called to manage progress during firlware update
- progress: percent value
- Returns: a promise to `void`
*/
public func requestFirmwareUpdateRemote(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void> {
let dfuFirmware = DFUFirmware(urlToZipFile: firmwareInfo.firmwareZipURL!)!
return ZehusServiceInitiator.requestFirmwareUpdateForRemote(bluejay: bluejay, firmwareInfo: dfuFirmware, progressCallback: progressCallback)
}
/**
This method provides an encapsulated way to update Driver(dsc) firmware, in a promisable mean
Driver update is split in 2 steps:
* file transfer from device to peripheral
* firmware update
- Parameters:
- bluejay: current blujay instance connected to the peripheral we want to update
- firmwareInfo: firmware information with the path of the zip URL
- transferCallBack: callback called to manage progress during firlware transfer
- progressCallback: callback called to manage progress during firlware update
- Returns: a promise to `void`
*/
public func requestFirmwareUpdateForDriver(bluejay: Bluejay, firmwareInfo: Firmware, transferCallBack: @escaping (_ progress: Int) -> (), progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void> {
let dfuFirmware = DFUFirmware(urlToZipFile: firmwareInfo.firmwareZipURL!)!
return firstly { () -> Promise<Void> in
Common.BLEProcedure.promise_requestFirmwareUpdate(for: bluejay, firmwareInfo: firmwareInfo)
}.then {
ZehusServiceInitiator.requestFirmwareUpdateForDriver(bluejay: bluejay, firmwareInfo: dfuFirmware, transferCallBack: transferCallBack, progressCallback: progressCallback)
}
}
/**
This method provides an encapsulated way to update ble application firmware, in a promisable mean
- Parameters:
- bluejay: current blujay instance connected to the peripheral we want to update
- firmwareInfo: firmware information with the path of the zip URL
- progressCallback: callback called to manage progress during firlware update
- progress: percent value
- Returns: a promise to `void`
*/
public func requestFirmwareUpdateForBLE(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void> {
let dfuFirmware = DFUFirmware(urlToZipFile: firmwareInfo.firmwareZipURL!)!
return firstly { () -> Promise<Void> in
Common.BLEProcedure.promise_requestFirmwareUpdate(for: bluejay, firmwareInfo: firmwareInfo)
}.then {
ZehusServiceInitiator.requestFirmwareUpdateForBLE(bluejay: bluejay, firmwareInfo: dfuFirmware, progressCallback: progressCallback)
}
}
public func forceFirmwareUpdateForBLE(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (_ progress: Int) -> ()) -> Promise<Void> {
let dfuFirmware = DFUFirmware(urlToZipFile: firmwareInfo.firmwareZipURL!)!
return ZehusServiceInitiator.forceUpdateBLEFW(bluejay: bluejay, firmwareInfo: dfuFirmware, progressCallback: progressCallback)
}
/**
This method provides an encapsulated way to update ble application firmware, in a promisable mean
- Parameters:
- bluejay: current blujay instance connected to the peripheral we want to update
- firmwareInfo: firmware information with the path of the zip URL
- progressCallback: callback called to manage progress during firlware update
- progress: percent value
- Returns: a promise to `void`
*/
public func requestFirmwareUpdateForBMS(bluejay: Bluejay, firmwareInfo: Firmware, transferCallBack: @escaping (Int) -> (), progressCallback: @escaping (Int) -> ()) -> Promise<Void> {
let dfuFirmware = DFUFirmware(urlToZipFile: firmwareInfo.firmwareZipURL!)!
return firstly { () -> Promise<Void> in
Common.BLEProcedure.promise_requestFirmwareUpdate(for: bluejay, firmwareInfo: firmwareInfo)
}.then {
ZehusServiceInitiator.requestFirmwareUpdateForBMS(bluejay: bluejay, firmwareInfo: dfuFirmware, transferCallBack: transferCallBack, progressCallback: progressCallback)
}
}
func requestFirmwareUpdate(firmwareInfo: Firmware, progressCallback: ((_ dfuType: DeviceType, _ progress: Int) -> ())?, completion: @escaping (_ success: String?, _ error: Error?) -> ()) {
guard !isUpdatingFirmware else {
return
}
self.progressCallback = progressCallback
self.completion = completion
// Check of firmware version must be done before
isUpdatingFirmware = true
firstly {
Common.BLEProcedure.promise_requestFirmwareUpdate(for: self.bluejay, firmwareInfo: firmwareInfo)
}.map { _ -> Void in
// stop blujay
self.btState = self.bluejay.stopAndExtractBluetoothState()
let dfuFirmware = DFUFirmware(urlToZipFile: firmwareInfo.firmwareZipURL!)!
let initiator = ZehusServiceInitiator(deviceType: self.deviceType).with(firmware: dfuFirmware)
initiator.logger = self
initiator.delegate = self
initiator.progressDelegate = self
self.updateController = initiator.start(target: self.btState!.peripheral!)
}.catch { (error) in
log("Error while upadting the firware \(error)")
}
}
fileprivate func listenToDriverUpdateProgress() {
firstly {
after(seconds: 3)
}.then {
self.bluejay.promise_listen(from: Common.BLEConstant.Characteristic.BluejayUUID.otaDFUIdentifier) { (result: Common.FirmwareUpdateStatus?, error) in
if let result = result {
switch result.answer {
case .unknown:
log("Unknown reply from driver update")
case .completed:
log("Driver update completed")
case .progress(let percent):
log("Driver progress \(percent)")
case .drivereNotResponding:
log("Driver not responding") // Should throw
case .driverGenericError:
log("Driver generic error") // Should throw
case .bleMemoryError:
log("Ble memory error") // Should throw
case .bleInProgress:
log("Ble transfer in progress")
case .invalidCommand:
log("Invalid command") // Should throw
case .bmsNotResponding:
log("bmsNotResponding") // Should throw
case .bmsGenericError:
log("bmsGenericError") // Should throw
}
if case Common.FirmwareUpdatStatusAnswer.progress(_) = result.answer {
} else {
self.cleanUp()
self.bluejay.endListen(to: Common.BLEConstant.Characteristic.BluejayUUID.otaDFUIdentifier)
}
}
}
}.catch { (error) in
self.bluejay.endListen(to: Common.BLEConstant.Characteristic.BluejayUUID.otaDFUIdentifier)
log("Error listening to driver update \(error)")
}
}
fileprivate func restartBluejay() {
bluejay.start()
}
fileprivate func cleanUp() {
isUpdatingFirmware = false
updateController = nil
btState = nil
}
}
extension OTAFirmwareUpdater: LoggerDelegate, DFUServiceDelegate, DFUProgressDelegate {
public func logWith(_ level: LogLevel, message: String) {
log("[Nordic-Log] \(message)")
}
public func dfuStateDidChange(to state: DFUState) {
log("[Nordic-Service] State changed: \(state.description())")
switch state {
case .connecting:
break
case .starting:
break
case .enablingDfuMode:
break
case .uploading:
break
case .validating:
break
case .disconnecting:
break
case .completed:
if deviceType == .ble {
// BLE DFU completed
restartBluejay()
cleanUp()
self.completion?("Success", nil)
} else {
// Driver/BMS DFU upload completed => start of update progress notification
restartBluejay()
// try to understand what happens if peripheral is nil
bluejay.connect(PeripheralIdentifier(uuid: btState!.peripheral!.identifier, name: nil)) { (result) in
switch result {
case .success(_):
self.listenToDriverUpdateProgress()
// Start observing other progress from Driver
case .failure(let error):
print("error \(error)")
}
}
}
case .aborted:
restartBluejay()
cleanUp()
self.completion?(nil, ZehusDfuOtaError.dfuAborted)
}
}
public func dfuError(_ error: DFUError, didOccurWithMessage message: String) {
log("[Nordic-Service] Error \(error.rawValue): \(message)")
restartBluejay()
cleanUp()
completion?(nil, ZehusDfuOtaError.dfuFailed(message: message, originalError: error))
}
public func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
log("[Nordic-Progress] Parts: \(part) / \(totalParts) - Progress: \(progress) % - Speed: \(currentSpeedBytesPerSecond) - Avg speed: \(avgSpeedBytesPerSecond)")
progressCallback?(deviceType, progress)
}
}
internal func log(_ message: String) {
debugPrint("[BSDfuOta] \(message)")
}
public class MockOTAFirmwareUpdater: DFUOTAUpdater {
public init(){}
public func requestFirmwareUpdateForBLE(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (Int) -> ()) -> Promise<Void> {
return Promise()
}
public func requestFirmwareUpdateForDriver(bluejay: Bluejay, firmwareInfo: Firmware, transferCallBack: @escaping (Int) -> (), progressCallback: @escaping (Int) -> ()) -> Promise<Void> {
return Promise()
}
public func requestFirmwareUpdateForBMS(bluejay: Bluejay, firmwareInfo: Firmware, transferCallBack: @escaping (Int) -> (), progressCallback: @escaping (Int) -> ()) -> Promise<Void> {
return Promise{seal in
progressCallback(1)
seal.reject(ZehusDfuOtaError.peripheralConnectionLost)
}
}
public func requestFirmwareUpdateRemote(bluejay: Bluejay, firmwareInfo: Firmware, progressCallback: @escaping (Int) -> ()) -> Promise<Void> {
return Promise()
}
}
| 44.609687 | 214 | 0.62856 |
f8431362c9818cad7ec36f093d65ea606d15969d | 418 | //
// Observable+ParseCreate.swift
// Parse-RxSwift Extensions
//
// Created by Eric Kuck on 10/8/15.
// Copyright © 2015 BlueLine Labs. All rights reserved.
//
import RxSwift
func createWithParseCallback<T>(callback: (AnyObserver<T> -> Void)) -> Observable<T> {
return Observable.create({ (observer: AnyObserver<T>) -> Disposable in
callback(observer)
return NopDisposable.instance
})
}
| 24.588235 | 86 | 0.686603 |
e5ca694cc0700d277c9647456b1947dc626c9d0e | 23,203 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import NIO
import NIOConcurrencyHelpers
import XCTest
class SelectorTest: XCTestCase {
func testDeregisterWhileProcessingEvents() throws {
try assertDeregisterWhileProcessingEvents(closeAfterDeregister: false)
}
func testDeregisterAndCloseWhileProcessingEvents() throws {
try assertDeregisterWhileProcessingEvents(closeAfterDeregister: true)
}
private func assertDeregisterWhileProcessingEvents(closeAfterDeregister: Bool) throws {
struct TestRegistration: Registration {
var interested: SelectorEventSet
let socket: Socket
}
let selector = try NIO.Selector<TestRegistration>()
defer {
XCTAssertNoThrow(try selector.close())
}
let socket1 = try Socket(protocolFamily: PF_INET, type: Posix.SOCK_STREAM)
defer {
if socket1.isOpen {
XCTAssertNoThrow(try socket1.close())
}
}
try socket1.setNonBlocking()
let socket2 = try Socket(protocolFamily: PF_INET, type: Posix.SOCK_STREAM)
defer {
if socket2.isOpen {
XCTAssertNoThrow(try socket2.close())
}
}
try socket2.setNonBlocking()
let serverSocket = try assertNoThrowWithValue(ServerSocket.bootstrap(protocolFamily: PF_INET,
host: "127.0.0.1",
port: 0))
defer {
XCTAssertNoThrow(try serverSocket.close())
}
_ = try socket1.connect(to: serverSocket.localAddress())
_ = try socket2.connect(to: serverSocket.localAddress())
let accepted1 = try serverSocket.accept()!
defer {
XCTAssertNoThrow(try accepted1.close())
}
let accepted2 = try serverSocket.accept()!
defer {
XCTAssertNoThrow(try accepted2.close())
}
// Register both sockets with .write. This will ensure both are ready when calling selector.whenReady.
try selector.register(selectable: socket1 , interested: [.reset, .write], makeRegistration: { ev in
TestRegistration(interested: ev, socket: socket1)
})
try selector.register(selectable: socket2 , interested: [.reset, .write], makeRegistration: { ev in
TestRegistration(interested: ev, socket: socket2)
})
var readyCount = 0
try selector.whenReady(strategy: .block) { ev in
readyCount += 1
if socket1 === ev.registration.socket {
try selector.deregister(selectable: socket2)
if closeAfterDeregister {
try socket2.close()
}
} else if socket2 === ev.registration.socket {
try selector.deregister(selectable: socket1)
if closeAfterDeregister {
try socket1.close()
}
} else {
XCTFail("ev.registration.socket was neither \(socket1) or \(socket2) but \(ev.registration.socket)")
}
}
XCTAssertEqual(1, readyCount)
}
private static let testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse = 10
func testWeDoNotDeliverEventsForPreviouslyClosedChannels() {
/// We use this class to box mutable values, generally in this test anything boxed should only be read/written
/// on the event loop `el`.
class Box<T> {
init(_ value: T) {
self._value = value
}
private var _value: T
var value: T {
get {
XCTAssertNotNil(MultiThreadedEventLoopGroup.currentEventLoop)
return self._value
}
set {
XCTAssertNotNil(MultiThreadedEventLoopGroup.currentEventLoop)
self._value = newValue
}
}
}
enum DidNotReadError: Error {
case didNotReadGotInactive
case didNotReadGotReadComplete
}
/// This handler is inserted in the `ChannelPipeline` that are re-connected. So we're closing a bunch of
/// channels and (in the same event loop tick) we then connect the same number for which I'm using the
/// terminology 're-connect' here.
/// These re-connected channels will re-use the fd numbers of the just closed channels. The interesting thing
/// is that the `Selector` will still have events buffered for the _closed fds_. Note: the re-connected ones
/// will end up using the _same_ fds and this test ensures that we're not getting the outdated events. In this
/// case the outdated events are all `.readEOF`s which manifest as `channelReadComplete`s. If we're delivering
/// outdated events, they will also happen in the _same event loop tick_ and therefore we do quite a few
/// assertions that we're either in or not in that interesting event loop tick.
class HappyWhenReadHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private let didReadPromise: EventLoopPromise<Void>
private let hasReConnectEventLoopTickFinished: Box<Bool>
private var didRead: Bool = false
init(hasReConnectEventLoopTickFinished: Box<Bool>, didReadPromise: EventLoopPromise<Void>) {
self.didReadPromise = didReadPromise
self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished
}
func channelActive(context: ChannelHandlerContext) {
// we expect these channels to be connected within the re-connect event loop tick
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
}
func channelInactive(context: ChannelHandlerContext) {
// we expect these channels to be close a while after the re-connect event loop tick
XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value)
XCTAssertTrue(self.didRead)
if !self.didRead {
self.didReadPromise.fail(DidNotReadError.didNotReadGotInactive)
context.close(promise: nil)
}
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
// we expect these channels to get data only a while after the re-connect event loop tick as it's
// impossible to get a read notification in the very same event loop tick that you got registered
XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value)
XCTAssertFalse(self.didRead)
var buf = self.unwrapInboundIn(data)
XCTAssertEqual(1, buf.readableBytes)
XCTAssertEqual("H", buf.readString(length: 1)!)
self.didRead = true
self.didReadPromise.succeed(())
}
func channelReadComplete(context: ChannelHandlerContext) {
// we expect these channels to get data only a while after the re-connect event loop tick as it's
// impossible to get a read notification in the very same event loop tick that you got registered
XCTAssertTrue(self.hasReConnectEventLoopTickFinished.value)
XCTAssertTrue(self.didRead)
if !self.didRead {
self.didReadPromise.fail(DidNotReadError.didNotReadGotReadComplete)
context.close(promise: nil)
}
}
}
/// This handler will wait for all client channels to have come up and for one of them to have received EOF.
/// (We will see the EOF as they're set to support half-closure). Then, it'll close half of those file
/// descriptors and open the same number of new ones. The new ones (called re-connected) will share the same
/// fd numbers as the recently closed ones. That brings us in an interesting situation: There will (very likely)
/// be `.readEOF` events enqueued for the just closed ones and because the re-connected channels share the same
/// fd numbers danger looms. The `HappyWhenReadHandler` above makes sure nothing bad happens.
class CloseEveryOtherAndOpenNewOnesHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private let allChannels: Box<[Channel]>
private let serverAddress: SocketAddress
private let everythingWasReadPromise: EventLoopPromise<Void>
private let hasReConnectEventLoopTickFinished: Box<Bool>
init(allChannels: Box<[Channel]>,
hasReConnectEventLoopTickFinished: Box<Bool>,
serverAddress: SocketAddress,
everythingWasReadPromise: EventLoopPromise<Void>) {
self.allChannels = allChannels
self.serverAddress = serverAddress
self.everythingWasReadPromise = everythingWasReadPromise
self.hasReConnectEventLoopTickFinished = hasReConnectEventLoopTickFinished
}
func channelActive(context: ChannelHandlerContext) {
// collect all the channels
context.channel.getOption(ChannelOptions.allowRemoteHalfClosure).whenSuccess { halfClosureAllowed in
precondition(halfClosureAllowed,
"the test configuration is bogus: half-closure is dis-allowed which breaks the setup of this test")
}
self.allChannels.value.append(context.channel)
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
// this is the `.readEOF` that is triggered by the `ServerHandler`'s `close` calls because our channel
// supports half-closure
guard self.allChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse else {
return
}
// all channels are up, so let's construct the situation we want to be in:
// 1. let's close half the channels
// 2. then re-connect (must be synchronous) the same number of channels and we'll get fd number re-use
context.channel.eventLoop.execute {
// this will be run immediately after we processed all `Selector` events so when
// `self.hasReConnectEventLoopTickFinished.value` becomes true, we're out of the event loop
// tick that is interesting.
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
self.hasReConnectEventLoopTickFinished.value = true
}
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value)
let everyOtherIndex = stride(from: 0, to: SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, by: 2)
for f in everyOtherIndex {
XCTAssertTrue(self.allChannels.value[f].isActive)
// close will succeed synchronously as we're on the right event loop.
self.allChannels.value[f].close(promise: nil)
XCTAssertFalse(self.allChannels.value[f].isActive)
}
// now we have completed stage 1: we freed up a bunch of file descriptor numbers, so let's open
// some new ones
var reconnectedChannelsHaveRead: [EventLoopFuture<Void>] = []
for _ in everyOtherIndex {
var hasBeenAdded: Bool = false
let p = context.channel.eventLoop.makePromise(of: Void.self)
reconnectedChannelsHaveRead.append(p.futureResult)
let newChannel = ClientBootstrap(group: context.eventLoop)
.channelInitializer { channel in
channel.pipeline.addHandler(HappyWhenReadHandler(hasReConnectEventLoopTickFinished: self.hasReConnectEventLoopTickFinished,
didReadPromise: p)).map {
hasBeenAdded = true
}
}
.connect(to: self.serverAddress)
.map { (channel: Channel) -> Void in
XCTAssertFalse(self.hasReConnectEventLoopTickFinished.value,
"""
This is bad: the connect of the channels to be re-connected has not
completed synchronously.
We assumed that on all platform a UNIX Domain Socket connect is
synchronous but we must be wrong :(.
The good news is: Not everything is lost, this test should also work
if you instead open a regular file (in O_RDWR) and just use this file's
fd with `ClientBootstrap(group: group).withConnectedSocket(fileFD)`.
Sure, a file is not a socket but it's always readable and writable and
that fulfills the requirements we have here.
I still hope this change will never have to be done.
Note: if you changed anything about the pipeline's handler adding/removal
you might also have a bug there.
""")
}
// just to make sure we got `newChannel` synchronously and we could add our handler to the
// pipeline synchronously too.
XCTAssertTrue(newChannel.isFulfilled)
XCTAssertTrue(hasBeenAdded)
}
// if all the new re-connected channels have read, then we're happy here.
EventLoopFuture.andAllSucceed(reconnectedChannelsHaveRead, on: context.eventLoop)
.cascade(to: self.everythingWasReadPromise)
// let's also remove all the channels so this code will not be triggered again.
self.allChannels.value.removeAll()
}
}
// all of the following are boxed as we need mutable references to them, they can only be read/written on the
// event loop `el`.
let allServerChannels: Box<[Channel]> = Box([])
let allChannels: Box<[Channel]> = Box([])
let hasReConnectEventLoopTickFinished: Box<Bool> = Box(false)
let numberOfConnectedChannels: Box<Int> = Box(0)
/// This spawns a server, always send a character immediately and after the first
/// `SelectorTest.numberOfChannelsToUse` have been established, we'll close them all. That will trigger
/// an `.readEOF` in the connected client channels which will then trigger other interesting things (see above).
class ServerHandler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
private var number: Int = 0
private let allServerChannels: Box<[Channel]>
private let numberOfConnectedChannels: Box<Int>
init(allServerChannels: Box<[Channel]>, numberOfConnectedChannels: Box<Int>) {
self.allServerChannels = allServerChannels
self.numberOfConnectedChannels = numberOfConnectedChannels
}
func channelActive(context: ChannelHandlerContext) {
var buf = context.channel.allocator.buffer(capacity: 1)
buf.writeString("H")
context.channel.writeAndFlush(buf, promise: nil)
self.number += 1
self.allServerChannels.value.append(context.channel)
if self.allServerChannels.value.count == SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse {
// just to be sure all of the client channels have connected
XCTAssertEqual(SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse, numberOfConnectedChannels.value)
self.allServerChannels.value.forEach { c in
c.close(promise: nil)
}
}
}
}
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1)
let el = elg.next()
defer {
XCTAssertNoThrow(try elg.syncShutdownGracefully())
}
XCTAssertNoThrow(try withTemporaryUnixDomainSocketPathName { udsPath in
let secondServerChannel = try! ServerBootstrap(group: el)
.childChannelInitializer { channel in
channel.pipeline.addHandler(ServerHandler(allServerChannels: allServerChannels,
numberOfConnectedChannels: numberOfConnectedChannels))
}
.bind(to: SocketAddress(unixDomainSocketPath: udsPath))
.wait()
let everythingWasReadPromise = el.makePromise(of: Void.self)
XCTAssertNoThrow(try el.submit { () -> [EventLoopFuture<Channel>] in
(0..<SelectorTest.testWeDoNotDeliverEventsForPreviouslyClosedChannels_numberOfChannelsToUse).map { (_: Int) in
ClientBootstrap(group: el)
.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
.channelInitializer { channel in
channel.pipeline.addHandler(CloseEveryOtherAndOpenNewOnesHandler(allChannels: allChannels,
hasReConnectEventLoopTickFinished: hasReConnectEventLoopTickFinished,
serverAddress: secondServerChannel.localAddress!,
everythingWasReadPromise: everythingWasReadPromise))
}
.connect(to: secondServerChannel.localAddress!)
.map { channel in
numberOfConnectedChannels.value += 1
return channel
}
}
}.wait().forEach { XCTAssertNoThrow(try $0.wait()) } as Void)
XCTAssertNoThrow(try everythingWasReadPromise.futureResult.wait())
})
}
func testTimerFDIsLevelTriggered() throws {
// this is a regression test for https://github.com/apple/swift-nio/issues/872
let delayToUseInMicroSeconds: Int64 = 100_000 // needs to be much greater than time it takes to EL.execute
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
class FakeSocket: Socket {
private let hasBeenClosedPromise: EventLoopPromise<Void>
init(hasBeenClosedPromise: EventLoopPromise<Void>, descriptor: CInt) throws {
self.hasBeenClosedPromise = hasBeenClosedPromise
try super.init(descriptor: descriptor)
}
override func close() throws {
self.hasBeenClosedPromise.succeed(())
try super.close()
}
}
var socketFDs: [CInt] = [-1, -1]
XCTAssertNoThrow(try Posix.socketpair(domain: PF_LOCAL,
type: Posix.SOCK_STREAM,
protocol: 0,
socketVector: &socketFDs))
let numberFires = Atomic<Int>(value: 0)
let el = group.next() as! SelectableEventLoop
let channelHasBeenClosedPromise = el.makePromise(of: Void.self)
let channel = try SocketChannel(socket: FakeSocket(hasBeenClosedPromise: channelHasBeenClosedPromise,
descriptor: socketFDs[0]), eventLoop: el)
let sched = el.scheduleRepeatedTask(initialDelay: .microseconds(delayToUseInMicroSeconds),
delay: .microseconds(delayToUseInMicroSeconds)) { (_: RepeatedTask) in
_ = numberFires.add(1)
}
XCTAssertNoThrow(try el.submit {
// EL tick 1: this is used to
// - actually arm the timer (timerfd_settime)
// - set the channel restration up
if numberFires.load() > 0 {
print("WARNING: This test hit a race and this result doesn't mean it actually worked." +
" This should really only ever happen in very bizarre conditions.")
}
channel.interestedEvent = [.readEOF, .reset]
func workaroundSR9815() {
channel.registerAlreadyConfigured0(promise: nil)
}
workaroundSR9815()
}.wait())
usleep(10_000) // this makes this repro very stable
el.execute {
// EL tick 2: this is used to
// - close one end of the socketpair so that in EL tick 3, we'll see a EPOLLHUP
// - sleep `delayToUseInMicroSeconds + 10` so in EL tick 3, we'll also see timerfd fire
close(socketFDs[1])
usleep(.init(delayToUseInMicroSeconds))
}
// EL tick 3: happens in the background here. We will likely lose the timer signal because of the
// `deregistrationsHappened` workaround in `Selector.swift` and we expect to pick it up again when we enter
// `epoll_wait`/`kevent` next. This however only works if the timer event is level triggered.
assert(numberFires.load() > 5, within: .seconds(1), "timer only fired \(numberFires.load()) times")
sched.cancel()
XCTAssertNoThrow(try channelHasBeenClosedPromise.futureResult.wait())
}
}
| 53.463134 | 162 | 0.582899 |
18bf7701c9a49a324a2f64d4f179d8835c896a02 | 2,227 | import Foundation
public enum PBXProductType: String, Decodable {
case none = ""
case application = "com.apple.product-type.application"
case framework = "com.apple.product-type.framework"
case dynamicLibrary = "com.apple.product-type.library.dynamic"
case staticLibrary = "com.apple.product-type.library.static"
case bundle = "com.apple.product-type.bundle"
case unitTestBundle = "com.apple.product-type.bundle.unit-test"
case uiTestBundle = "com.apple.product-type.bundle.ui-testing"
case appExtension = "com.apple.product-type.app-extension"
case commandLineTool = "com.apple.product-type.tool"
case watchApp = "com.apple.product-type.application.watchapp"
case watch2App = "com.apple.product-type.application.watchapp2"
case watchExtension = "com.apple.product-type.watchkit-extension"
case watch2Extension = "com.apple.product-type.watchkit2-extension"
case tvExtension = "com.apple.product-type.tv-app-extension"
case messagesApplication = "com.apple.product-type.application.messages"
case messagesExtension = "com.apple.product-type.app-extension.messages"
case stickerPack = "com.apple.product-type.app-extension.messages-sticker-pack"
case xpcService = "com.apple.product-type.xpc-service"
case ocUnitTestBundle = "com.apple.product-type.bundle.ocunit-test"
/// Returns the file extension for the given product type.
public var fileExtension: String? {
switch self {
case .application, .watchApp, .watch2App, .messagesApplication:
return "app"
case .framework:
return "framework"
case .dynamicLibrary:
return "dylib"
case .staticLibrary:
return "a"
case .bundle:
return "bundle"
case .unitTestBundle, .uiTestBundle:
return "xctest"
case .appExtension, .tvExtension, .watchExtension, .watch2Extension, .messagesExtension, .stickerPack:
return "appex"
case .commandLineTool:
return ""
case .xpcService:
return "xpc"
case .ocUnitTestBundle:
return "octest"
case .none:
return nil
}
}
}
| 42.018868 | 110 | 0.672654 |
62a4670bf8ffd7473cb96d12b7c1976db34a951f | 1,202 | //
// UIViewController+Utils.swift
// SendInvites
//
// Created by Oluwadamisi Pikuda on 09/05/2020.
// Copyright © 2020 Damisi Pikuda. All rights reserved.
//
import UIKit
extension UIViewController {
func showActivityIndicator() {
// Prevent multiple activity indicators from being added to the view
guard view.viewWithTag(UIConstants.activityTag.rawValue) == nil else {
return
}
let activityIndicator = SIActivityIndicatorView()
activityIndicator.tag = UIConstants.activityTag.rawValue
self.view.addSubview(activityIndicator)
activityIndicator.snp.makeConstraints { make in
make.height.width.equalToSuperview()
make.centerX.centerY.equalToSuperview()
}
activityIndicator.startAnimating()
activityIndicator.isUserInteractionEnabled = true
self.view.layoutIfNeeded()
self.view.isUserInteractionEnabled = false
}
func hideActivityIndicator() {
view.isUserInteractionEnabled = true
if let activityIndicator = view.viewWithTag(UIConstants.activityTag.rawValue) {
activityIndicator.removeFromSuperview()
}
}
}
| 29.317073 | 87 | 0.685524 |
e2cf5bebfa3a68501fc8f18a1f8a874d6c2b3129 | 1,547 | import ArgumentParser
import SwiftFusion
import BeeDataset
import BeeTracking
import PythonKit
import Foundation
/// Fan01: AE Tracker, with sampling-based initialization
struct Fan01: ParsableCommand {
@Option(help: "Run on track number x")
var trackId: Int = 0
@Option(help: "Run for number of frames")
var trackLength: Int = 80
@Option(help: "Size of feature space")
var featureSize: Int = 30
@Option(help: "Pretrained weights")
var weightsFile: String?
// Make sure you have a folder `Results/frank02` before running
func run() {
let np = Python.import("numpy")
let kHiddenDimension = 100
let dataDir = URL(fileURLWithPath: "./OIST_Data")
let (imageHeight, imageWidth, imageChannels) =
(40, 70, 1)
var rae = DenseRAE(
imageHeight: imageHeight, imageWidth: imageWidth, imageChannels: imageChannels,
hiddenDimension: kHiddenDimension, latentDimension: featureSize
)
if let weightsFile = weightsFile {
rae.load(weights: np.load(weightsFile, allow_pickle: true))
} else {
rae.load(weights: np.load("./oist_rae_weight_\(featureSize).npy", allow_pickle: true))
}
let (fig, _, _) = runProbabilisticTracker(
directory: dataDir,
encoder: rae,
onTrack: trackId, forFrames: trackLength, withSampling: true,
withFeatureSize: featureSize,
savePatchesIn: "Results/fan01"
)
/// Actual track v.s. ground truth track
fig.savefig("Results/fan01/fan01_track\(trackId)_\(featureSize).pdf", bbox_inches: "tight")
}
}
| 29.188679 | 95 | 0.69554 |
e53bbe0e1b9086bfcfe527b3695abb1df4cc1540 | 661 | // Generated automatically by Perfect Assistant Application
// Date: 2018-05-13 10:33:02 +0000
import PackageDescription
let package = Package(
name: "PerfectCURD",
targets: [],
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", versions: Version(3,0,0)..<Version(3,9223372036854775807,9223372036854775807)),
.Package(url: "https://github.com/PerfectlySoft/Perfect-CRUD.git", versions: Version(1,0,0)..<Version(1,9223372036854775807,9223372036854775807)),
.Package(url: "https://github.com/PerfectlySoft/Perfect-PostgreSQL.git", versions: Version(3,0,0)..<Version(3,9223372036854775807,9223372036854775807)),
]
)
| 50.846154 | 154 | 0.763994 |
91757e93c5055da647a83dcaeb77ce095d680289 | 2,173 | //
// AppDelegate.swift
// RxSwiftDemo2
//
// Created by miaoxiaodong on 2017/11/23.
// Copyright © 2017年 mark. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.234043 | 285 | 0.756098 |
8f91c843b8ccdac9fc1051a44d4cf03d46de4319 | 2,193 | //
// AppDelegate.swift
// CalendarDateRangePickerViewController
//
// Created by miraan on 10/15/2017.
// Copyright (c) 2017 miraan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.659574 | 285 | 0.756954 |
0a3ff92bb9c47d5576d3d36cbb339857790547da | 1,705 | //
// ManagerFiles.swift
// TSMXMPPFramework
//
// Created by Smith Huamani Hilario on 4/13/18.
// Copyright © 2018 demos. All rights reserved.
//
import Foundation
import AWSS3
struct ManagerFiles {
static var sharedInstance = ManagerFiles()
private var folder = "xmppDemoLib/"
func uploadingFiles(arrayUrlPath: [URL]) -> [TSMFile] {
var arrayFiles = [TSMFile]()
AWSServiceManager.default().defaultServiceConfiguration = ManagerAWSS3.sharedInstances.serviceConfiguration()
for itemURL in arrayUrlPath {
let S3Client = AWSS3.default()
let putObjectRequest = AWSS3PutObjectRequest()
putObjectRequest?.acl = .publicRead
putObjectRequest?.bucket = Configurations.sharedInstance.bucket
putObjectRequest?.key = folder + itemURL.lastPathComponent
putObjectRequest?.body = itemURL
do {
let fileAttributes = try FileManager.default.attributesOfItem(atPath: itemURL.path)
let fileSizeNumber = fileAttributes[FileAttributeKey.size] as! NSNumber
putObjectRequest?.contentLength = NSNumber(value: fileSizeNumber.int64Value)
} catch let error {
print("Error upload file 😡😡😡: " + error.localizedDescription)
}
S3Client.putObject(putObjectRequest!)
let urlAWSS3 = Configurations.sharedInstance.urlAmazonWS + folder + itemURL.lastPathComponent
let tsmFile = TSMFile(id: UUID().uuidString, nameFile: itemURL.lastPathComponent, mimeType: itemURL.pathExtension, url: urlAWSS3)
arrayFiles.append(tsmFile)
}
return arrayFiles
}
}
| 31.574074 | 141 | 0.662757 |
3a69b2a0b20879befe4dec1c776846f55c57a662 | 749 | import XCTest
import NLSwiftSuger
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| 25.827586 | 111 | 0.602136 |
39e35083149b9b1ae67816bf6680f90739d201ab | 521 | //
// ViewController.swift
// ScrollViewWithAutoLayout
//
// Created by Akanksha Sharma on 23/05/17.
// Copyright © 2017 Nexgear. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 20.038462 | 80 | 0.679463 |
911f96e75dea14fc6b2c70f33fba0764e23be648 | 571 | //
// feedCell.swift
// instagram
//
// Created by Robert Bolt on 10/2/18.
// Copyright © 2018 Robert Bolt. All rights reserved.
//
import UIKit
class feedCell: UITableViewCell {
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var captionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.392857 | 65 | 0.661996 |
2856b2339862e1ca922df40d345dc2c412c35a02 | 1,145 |
import UIKit
import UIFontComplete
public extension PlayerVC {
/// if progress is nil - assumes 0
func setupProgressUI(trackLength: Double,
progress: Double = 0.0) {
setupTrackLength(trackLength)
updateProgressUI(progress:progress)
}
func setupTrackLength(_ trackLength: Double) {
progressSlider.minimumValue = 0.0
progressSlider.maximumValue = trackLength.float
trackLengthLabel.text = makeProgressString(duration: trackLength)
}
/// updates progress slider and timer views with given progress
func updateProgressUI(progress: Double) {
progressSlider.value = progress.float
progressTimerLabel.text = makeProgressString(duration: progress)
}
/// sets track name, artist, album, artwork based on current track index
func updateTrackInfoUIForDisplayedTrack() {
artistLabel.text = displayedArtistName
albumLabel.text = displayedAlbum
trackNameLabel.text = displayedTrackName
// testing gesture
albumArtworkImageView.image = displayedArtworkImage
}
}
| 30.131579 | 76 | 0.679476 |
0eeee820946fff6b4f1374f2f0e37e31f1803b7f | 299 | import Foundation
import FearlessUtils
import BigInt
struct ValidatorExposure: Codable {
@StringCodable var total: BigUInt
@StringCodable var own: BigUInt
let others: [IndividualExposure]
}
struct IndividualExposure: Codable {
let who: Data
@StringCodable var value: BigUInt
}
| 19.933333 | 37 | 0.759197 |
699628e4667841f09a6ac8030542aa2bd72d7304 | 1,693 | // HEADS UP!: Auto-generated file, changes made directly here will be overwritten by code generators.
import blend2d
/// Extend mode.
public extension BLExtendMode {
/// Pad extend [default].
static let pad = BL_EXTEND_MODE_PAD
/// Repeat extend.
static let `repeat` = BL_EXTEND_MODE_REPEAT
/// Reflect extend.
static let reflect = BL_EXTEND_MODE_REFLECT
/// Alias to `BLExtendMode.pad`.
static let padXPadY = BL_EXTEND_MODE_PAD_X_PAD_Y
/// Pad X and repeat Y.
static let padXRepeatY = BL_EXTEND_MODE_PAD_X_REPEAT_Y
/// Pad X and reflect Y.
static let padXReflectY = BL_EXTEND_MODE_PAD_X_REFLECT_Y
/// Alias to `BLExtendMode.repeat`.
static let repeatXRepeatY = BL_EXTEND_MODE_REPEAT_X_REPEAT_Y
/// Repeat X and pad Y.
static let repeatXPadY = BL_EXTEND_MODE_REPEAT_X_PAD_Y
/// Repeat X and reflect Y.
static let repeatXReflectY = BL_EXTEND_MODE_REPEAT_X_REFLECT_Y
/// Alias to `BLExtendMode.reflect`.
static let reflectXReflectY = BL_EXTEND_MODE_REFLECT_X_REFLECT_Y
/// Reflect X and pad Y.
static let reflectXPadY = BL_EXTEND_MODE_REFLECT_X_PAD_Y
/// Reflect X and repeat Y.
static let reflectXRepeatY = BL_EXTEND_MODE_REFLECT_X_REPEAT_Y
/// Count of simple extend modes (that use the same value for X and Y).
static let simpleMaxValue = BL_EXTEND_MODE_SIMPLE_MAX_VALUE
/// Count of complex extend modes (that can use independent values for X and Y).
static let complexMaxValue = BL_EXTEND_MODE_COMPLEX_MAX_VALUE
/// Maximum value of `BLExtendMode`.
static let maxValue = BL_EXTEND_MODE_MAX_VALUE
}
| 32.557692 | 101 | 0.709392 |
7208e9914e1de4e4ea49ce8cf7d27e5fac41fbde | 598 | //
// Injector.swift
// ios-swift-start
//
// Created by alopezh on 22/09/2020.
// Copyright © 2020 com.herranz.all. All rights reserved.
//
import Foundation
import Swinject
import InjectPropertyWrapper
class Injector : InjectPropertyWrapper.Resolver {
static let shared = Injector()
private let assembler = Assembler([PresAssembly(), DomainAssembly(), DataAssembly()])
init() {
InjectSettings.resolver = self
}
func resolve<T>(_ type: T.Type, name: String? = nil) -> T? {
return assembler.resolver.resolve(type, name: name)
}
}
| 20.62069 | 89 | 0.653846 |
08201547728c5f3596b5ad21191fe9692641177d | 2,552 | //
// SwipeTableViewCell+Accessibility.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
extension SwipeTableViewCell {
/// :nodoc:
open override func accessibilityElementCount() -> Int {
guard state != .center else {
return super.accessibilityElementCount()
}
return 1
}
/// :nodoc:
open override func accessibilityElement(at index: Int) -> Any? {
guard state != .center else {
return super.accessibilityElement(at: index)
}
return actionsView
}
/// :nodoc:
open override func index(ofAccessibilityElement element: Any) -> Int {
guard state != .center else {
return super.index(ofAccessibilityElement: element)
}
return element is SwipeActionsView ? 0 : NSNotFound
}
}
extension SwipeTableViewCell {
/// :nodoc:
open override var accessibilityCustomActions: [UIAccessibilityCustomAction]? {
get {
guard let tableView = tableView, let indexPath = tableView.indexPath(for: self) else {
return super.accessibilityCustomActions
}
let leftActions = delegate?.tableView(tableView, editActionsForRowAt: indexPath, for: .left) ?? []
let rightActions = delegate?.tableView(tableView, editActionsForRowAt: indexPath, for: .right) ?? []
let actions = [rightActions.first, leftActions.first].compactMap({ $0 }) + rightActions.dropFirst() + leftActions.dropFirst()
if actions.count > 0 {
return actions.compactMap({ SwipeAccessibilityCustomAction(action: $0,
indexPath: indexPath,
target: self,
selector: #selector(performAccessibilityCustomAction(accessibilityCustomAction:))) })
} else {
return super.accessibilityCustomActions
}
}
set {
super.accessibilityCustomActions = newValue
}
}
@objc func performAccessibilityCustomAction(accessibilityCustomAction: SwipeAccessibilityCustomAction) -> Bool {
let swipeAction = accessibilityCustomAction.action
swipeAction.handler?(swipeAction, accessibilityCustomAction.indexPath)
return true
}
}
| 34.026667 | 153 | 0.576803 |