text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```swift
import Foundation
import UIKit
import Gridicons
//import AutomatticTracks
/// Privacy: Lets our users Opt Out from any (and all) trackers.
///
class SPPrivacyViewController: SPTableViewController {
/// Switch Control: Rules the Analytics State
///
private let analyticsSwitch = UISwitch()
/// TableView Sections
///
private var sections: [Section] {
var sections = [ Section(rows: [.share, .legend, .learn]) ]
if BuildConfiguration.is(.debug) {
sections.append(Section(rows: [.crash]))
}
return sections
}
/// Indicates if Analytics are Enabled
///
private var isAnalyticsEnabled: Bool {
let simperium = SPAppDelegate.shared().simperium
guard let isAnalyticsEnabled = simperium.preferencesObject().analytics_enabled else {
return true
}
return isAnalyticsEnabled.boolValue
}
// MARK: - Overridden Methods
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
setupTableView()
setupSwitch()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
switch rowAtIndexPath(indexPath) {
case .share:
setupAnalyticsCell(cell)
case .legend:
setupLegendCell(cell)
case .learn:
setupLearnMoreCell(cell)
case .crash:
setupCrashCell(cell)
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch rowAtIndexPath(indexPath) {
case .learn:
displayPrivacyLink()
case .crash:
CrashLoggingShim.shared.crash()
default:
break
}
}
/// Returns the Row at the specified IndexPath
///
private func rowAtIndexPath(_ indexPath: IndexPath) -> Row {
return sections[indexPath.section].rows[indexPath.row]
}
}
// MARK: - Event Handlers
//
extension SPPrivacyViewController {
/// Updates the Analytics Setting
///
@objc func switchDidChange(sender: UISwitch) {
let simperium = SPAppDelegate.shared().simperium
let preferences = simperium.preferencesObject()
preferences.analytics_enabled = NSNumber(booleanLiteral: sender.isOn)
simperium.save()
}
/// Opens the `kAutomatticAnalyticLearnMoreURL` in Apple's Safari.
///
@objc func displayPrivacyLink() {
guard let url = URL(string: kAutomatticAnalyticLearnMoreURL) else {
return
}
UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
}
// MARK: - Initialization Methods
//
private extension SPPrivacyViewController {
/// Setup: NavigationItem
///
func setupNavigationItem() {
title = NSLocalizedString("Privacy Settings", comment: "Privacy Settings")
}
/// Setup: TableView
///
func setupTableView() {
tableView.applySimplenoteGroupedStyle()
}
/// Setup: Switch
///
func setupSwitch() {
analyticsSwitch.onTintColor = .simplenoteSwitchOnTintColor
analyticsSwitch.tintColor = .simplenoteSwitchTintColor
analyticsSwitch.addTarget(self, action: #selector(switchDidChange(sender:)), for: .valueChanged)
analyticsSwitch.isOn = isAnalyticsEnabled
}
/// Setup: UITableViewCell so that the current Analytics Settings are displayed
///
func setupAnalyticsCell(_ cell: UITableViewCell) {
cell.imageView?.image = Gridicon.iconOfType(.stats)
cell.textLabel?.text = NSLocalizedString("Share Analytics", comment: "Option to disable Analytics.")
cell.selectionStyle = .none
cell.accessoryView = analyticsSwitch
}
/// Setup: Legend
///
func setupLegendCell(_ cell: UITableViewCell) {
cell.imageView?.image = Gridicon.iconOfType(.info)
cell.textLabel?.text = NSLocalizedString("Help us improve Simplenote by sharing usage data with our analytics tool.", comment: "Privacy Details")
cell.textLabel?.numberOfLines = 0
cell.selectionStyle = .none
}
/// Setup: Learn More
///
func setupLearnMoreCell(_ cell: UITableViewCell) {
// Placeholder: This way we'll get an even left padding
UIGraphicsBeginImageContext(Gridicon.defaultSize)
cell.imageView?.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
// And the actual text!
cell.textLabel?.text = NSLocalizedString("Learn more", comment: "Learn More Action")
cell.textLabel?.textColor = .simplenoteTintColor
}
/// Setup: Crash
///
func setupCrashCell(_ cell: UITableViewCell) {
cell.imageView?.image = Gridicon.iconOfType(.bug)
cell.textLabel?.text = NSLocalizedString("Send a Test Crash", comment: "For debugging use")
cell.textLabel?.numberOfLines = 0
cell.selectionStyle = .none
}
}
// MARK: - Private Types
//
private struct Section {
let rows: [Row]
}
private enum Row {
case share
case crash
case legend
case learn
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] {
return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)})
}
``` | /content/code_sandbox/Simplenote/SPPrivacyViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,240 |
```swift
import UIKit
// MARK: - Card dismissal animator
//
final class SPCardDismissalAnimator: NSObject, UIViewControllerAnimatedTransitioning {
private var animator: UIViewImplicitlyAnimating?
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return UIKitConstants.animationShortDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let animator = interruptibleAnimator(using: transitionContext)
animator.startAnimation()
}
func interruptibleAnimator(using transitionContext: UIViewControllerContextTransitioning) -> UIViewImplicitlyAnimating {
// According to docs we must return the same animator object during transition
if let animator = animator {
return animator
}
guard let view = transitionContext.view(forKey: .from) else {
fatalError("Transition view doesn't exist")
}
let animationBlock: () -> Void = {
view.transform = CGAffineTransform(translationX: 0.0, y: view.frame.size.height)
}
let animator = UIViewPropertyAnimator(duration: transitionDuration(using: transitionContext),
curve: .easeIn,
animations: animationBlock)
animator.addCompletion { (_) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
self.animator = animator
return animator
}
}
``` | /content/code_sandbox/Simplenote/SPCardDismissalAnimator.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 270 |
```swift
import Foundation
// MARK: - NSAttributedString to Markdown Converter
//
struct NSAttributedStringToMarkdownConverter {
/// Markdown replacement for "Unchecked Checklist"
///
private static let unchecked = "- [ ]"
/// Markdown replacement for "Checked Checklist"
///
private static let checked = "- [x]"
/// Returns the NSString representation of a given NSAttributedString.
///
static func convert(string: NSAttributedString) -> String {
let fullRange = NSRange(location: 0, length: string.length)
let adjusted = NSMutableAttributedString(attributedString: string)
adjusted.enumerateAttribute(.attachment, in: fullRange, options: .reverse) { (value, range, _) in
guard let attachment = value as? SPTextAttachment else {
return
}
let markdown = attachment.isChecked ? checked : unchecked
adjusted.replaceCharacters(in: range, with: markdown)
}
return adjusted.string
}
}
``` | /content/code_sandbox/Simplenote/NSAttributedStringToMarkdownConverter.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 193 |
```swift
import Foundation
extension NSURLComponents {
@objc
func contentFromQuery() -> String? {
return queryItems?.first(where: { query in
query.name == "content"
})?.value
}
@objc
func tagsFromQuery() -> [String]? {
queryItems?
.filter({ $0.name == "tag" })
.compactMap({ $0.value })
.flatMap({ $0.components(separatedBy: .whitespacesAndNewlines) })
.filter({ !$0.isEmpty })
}
}
``` | /content/code_sandbox/Simplenote/NSURLComponents+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 119 |
```swift
import Foundation
import UIKit
// MARK: - Value1TableViewCell
//
class Value1TableViewCell: UITableViewCell {
/// Indicates if the row is Selectable
///
var selectable: Bool = true {
didSet {
reloadTextStyles()
}
}
/// Indicates if the row has clear background
///
var hasClearBackground = false {
didSet {
if oldValue != hasClearBackground {
reloadBackgroundStyles()
}
}
}
/// Wraps the TextLabel's Text Property
///
var title: String? {
get {
textLabel?.text
}
set {
textLabel?.text = newValue
}
}
/// Wraps the DetailTextLabel's Text Property
///
var value: String? {
get {
detailTextLabel?.text
}
set {
detailTextLabel?.text = newValue
}
}
/// Image tint color
///
var imageTintColor: UIColor? {
didSet {
if oldValue != imageTintColor {
reloadTextStyles()
}
}
}
// MARK: - Initializers
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
reloadBackgroundStyles()
reloadTextStyles()
}
required init?(coder: NSCoder) {
fatalError("Unsupported Initializer")
}
// MARK: - Overriden
override func prepareForReuse() {
super.prepareForReuse()
selectable = true
accessoryType = .none
}
}
// MARK: - Private API(s)
//
private extension Value1TableViewCell {
func reloadBackgroundStyles() {
let selectedView = UIView(frame: bounds)
selectedView.backgroundColor = .simplenoteLightBlueColor
backgroundColor = hasClearBackground ? .clear : .simplenoteTableViewCellBackgroundColor
selectedBackgroundView = selectedView
}
func reloadTextStyles() {
let textColor: UIColor = selectable ? .simplenoteTextColor : .simplenotePlaceholderTextColor
let detailTextColor: UIColor = selectable ? .simplenoteSecondaryTextColor : .simplenotePlaceholderTextColor
textLabel?.textColor = textColor
detailTextLabel?.textColor = detailTextColor
imageView?.tintColor = imageTintColor ?? textColor
selectionStyle = selectable ? .default : .none
}
}
``` | /content/code_sandbox/Simplenote/Value1TableViewCell.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 503 |
```swift
import UIKit
// MARK: - SPShadowView
//
// SPShadowView draws outside shadow, while everyting inside is kept transparent
//
@IBDesignable
final class SPShadowView: UIView {
private let maskLayer = CAShapeLayer()
/// Corner Radius
///
@IBInspectable
var cornerRadius: CGFloat = .zero {
didSet {
updatePath()
}
}
/// Defines the Shadow Path's rounded corners
///
var roundedCorners: UIRectCorner = .allCorners {
didSet {
updatePath()
}
}
/// Shadow color
///
@IBInspectable
var shadowColor: UIColor? {
get {
layer.shadowColor.map {
UIColor(cgColor: $0)
}
}
set {
layer.shadowColor = newValue?.cgColor
}
}
/// Shadow Offset
///
@IBInspectable
var shadowOffset: CGSize {
get {
layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
/// Shadow Opacity
///
@IBInspectable
var shadowOpacity: CGFloat {
get {
CGFloat(layer.shadowOpacity)
}
set {
layer.shadowOpacity = Float(newValue)
}
}
/// Shadow Radius
///
@IBInspectable
var shadowRadius: CGFloat {
get {
layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
override var bounds: CGRect {
didSet {
updatePath()
}
}
/// Designated Initializer
///
/// - Parameters:
/// - cornerRadius: The radius of each corner oval
/// - roundedCorners: A bitmask value that identifies the corners that you want rounded
///
init(cornerRadius: CGFloat, roundedCorners: UIRectCorner) {
self.cornerRadius = cornerRadius
self.roundedCorners = roundedCorners
super.init(frame: .zero)
configure()
}
/// NSCoder support!
///
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
}
// MARK: - Private Methods
//
private extension SPShadowView {
/// Initial configuration of the view
///
func configure() {
backgroundColor = .clear
configureShadow()
configureMask()
updatePath()
}
/// Configuration of the shadow
///
func configureShadow() {
shadowColor = Constants.shadowColor
shadowOffset = Constants.shadowOffset
shadowOpacity = Constants.shadowOpacity
shadowRadius = Constants.shadowRadius
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
/// Configuration of the mask
///
func configureMask() {
maskLayer.backgroundColor = UIColor.black.cgColor
maskLayer.fillRule = .evenOdd
layer.mask = maskLayer
}
/// Updates paths of the shadow and the mask to reflect the view bounds
///
func updatePath() {
let roundedPath = UIBezierPath(roundedRect: bounds,
byRoundingCorners: roundedCorners,
cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
layer.shadowPath = roundedPath.cgPath
// Path including outside shadow
let maskPath = UIBezierPath(rect: bounds.insetBy(dx: -Constants.shadowRadius * 2 - abs(layer.shadowOffset.width),
dy: -Constants.shadowRadius * 2 - abs(layer.shadowOffset.height)))
maskPath.append(roundedPath)
maskPath.usesEvenOddFillRule = true
maskLayer.path = maskPath.cgPath
}
}
// MARK: - Constants
//
private extension SPShadowView {
struct Constants {
static let shadowColor = UIColor.black
static let shadowOpacity: CGFloat = 0.1
static let shadowRadius: CGFloat = 20.0
static let shadowOffset = CGSize(width: 0, height: -2)
}
}
``` | /content/code_sandbox/Simplenote/SPShadowView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 856 |
```swift
import Foundation
/// NSObject: Helper Methods
///
extension NSObject {
/// Returns the receiver's classname as a string, not including the namespace.
///
class var classNameWithoutNamespaces: String {
return String(describing: self)
}
}
``` | /content/code_sandbox/Simplenote/NSObject+Helpers.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 52 |
```swift
/*
See LICENSE.txt for this samples licensing information
Abstract:
A struct for accessing generic password keychain items.
*/
import Foundation
enum KeychainError: Error {
case noPassword
case unexpectedPasswordData
case unexpectedItemData
case unhandledError(status: OSStatus)
}
/// Ref. path_to_url
///
struct KeychainPasswordItem {
// MARK: Properties
let service: String
private(set) var account: String
let accessGroup: String?
// MARK: Intialization
init(service: String, account: String, accessGroup: String? = nil) {
self.service = service
self.account = account
self.accessGroup = accessGroup
}
// MARK: Keychain access
func readPassword() throws -> String {
/*
Build a query to find the item that matches the service, account and
access group.
*/
var query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitOne
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanTrue
// Try to fetch the existing keychain item that matches the query.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// Check the return status and throw an error if appropriate.
guard status != errSecItemNotFound else { throw KeychainError.noPassword }
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
// Parse the password string from the query result.
guard let existingItem = queryResult as? [String: AnyObject],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: String.Encoding.utf8)
else {
throw KeychainError.unexpectedPasswordData
}
return password
}
func savePassword(_ password: String) throws {
// Encode the password into an Data object.
let encodedPassword = password.data(using: String.Encoding.utf8)!
do {
// Check for an existing item in the keychain.
try _ = readPassword()
// Update the existing item with the new password.
var attributesToUpdate = [String: AnyObject]()
attributesToUpdate[kSecValueData as String] = encodedPassword as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
}
catch KeychainError.noPassword {
/*
No password was found in the keychain. Create a dictionary to save
as a new keychain item.
*/
var newItem = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
newItem[kSecValueData as String] = encodedPassword as AnyObject?
// Add a the new item to the keychain.
let status = SecItemAdd(newItem as CFDictionary, nil)
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
}
}
mutating func renameAccount(_ newAccountName: String) throws {
// Try to update an existing item with the new account name.
var attributesToUpdate = [String: AnyObject]()
attributesToUpdate[kSecAttrAccount as String] = newAccountName as AnyObject?
let query = KeychainPasswordItem.keychainQuery(withService: service, account: self.account, accessGroup: accessGroup)
let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError(status: status) }
self.account = newAccountName
}
func deleteItem() throws {
// Delete the existing item from the keychain.
let query = KeychainPasswordItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup)
let status = SecItemDelete(query as CFDictionary)
// Throw an error if an unexpected status was returned.
guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError(status: status) }
}
static func passwordItems(forService service: String, accessGroup: String? = nil) throws -> [KeychainPasswordItem] {
// Build a query for all items that match the service and access group.
var query = KeychainPasswordItem.keychainQuery(withService: service, accessGroup: accessGroup)
query[kSecMatchLimit as String] = kSecMatchLimitAll
query[kSecReturnAttributes as String] = kCFBooleanTrue
query[kSecReturnData as String] = kCFBooleanFalse
// Fetch matching items from the keychain.
var queryResult: AnyObject?
let status = withUnsafeMutablePointer(to: &queryResult) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
// If no items were found, return an empty array.
guard status != errSecItemNotFound else { return [] }
// Throw an error if an unexpected status was returned.
guard status == noErr else { throw KeychainError.unhandledError(status: status) }
// Cast the query result to an array of dictionaries.
guard let resultData = queryResult as? [[String: AnyObject]] else { throw KeychainError.unexpectedItemData }
// Create a `KeychainPasswordItem` for each dictionary in the query result.
var passwordItems = [KeychainPasswordItem]()
for result in resultData {
guard let account = result[kSecAttrAccount as String] as? String else { throw KeychainError.unexpectedItemData }
let passwordItem = KeychainPasswordItem(service: service, account: account, accessGroup: accessGroup)
passwordItems.append(passwordItem)
}
return passwordItems
}
// MARK: Convenience
private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String: AnyObject] {
var query = [String: AnyObject]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecAttrService as String] = service as AnyObject?
if let account = account {
query[kSecAttrAccount as String] = account as AnyObject?
}
if let accessGroup = accessGroup {
query[kSecAttrAccessGroup as String] = accessGroup as AnyObject?
}
return query
}
}
``` | /content/code_sandbox/Simplenote/KeychainPasswordItem.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,512 |
```swift
import Foundation
// MARK: - Verification
//
extension SPTracker {
static func trackVerificationReviewScreenViewed() {
trackAutomatticEvent(withName: "verification_review_screen_viewed", properties: nil)
}
static func trackVerificationVerifyScreenViewed() {
trackAutomatticEvent(withName: "verification_verify_screen_viewed", properties: nil)
}
static func trackVerificationConfirmButtonTapped() {
trackAutomatticEvent(withName: "verification_confirm_button_tapped", properties: nil)
}
static func trackVerificationChangeEmailButtonTapped() {
trackAutomatticEvent(withName: "verification_change_email_button_tapped", properties: nil)
}
static func trackVerificationResendEmailButtonTapped() {
trackAutomatticEvent(withName: "verification_resend_email_button_tapped", properties: nil)
}
static func trackVerificationDismissed() {
trackAutomatticEvent(withName: "verification_dismissed", properties: nil)
}
}
// MARK: - In App Notifications
//
extension SPTracker {
static func trackPresentedNotice(ofType type: NoticeType) {
trackAutomatticEvent(withName: "notice_presented", properties: ["notice": type.rawValue])
}
static func trackPreformedNoticeAction(ofType type: NoticeType, noticeType: NoticeActionType) {
trackAutomatticEvent(withName: "notice_action_tapped", properties: ["notice": noticeType.rawValue, "notice_action": type.rawValue])
}
enum NoticeType: String {
case internalLinkCopied = "internal_link_copied"
case publicLinkCopied = "public_link_copied"
case publishing
case unpublishing
case noteTrashed = "note_trashed"
case multipleNotesTrashed = "multi_notes_trashed"
case unpublished
case published
}
enum NoticeActionType: String {
case undo
case copyLink = "copy_link"
}
}
// MARK: - Shortcuts
//
extension SPTracker {
private static func trackShortcut(_ value: String) {
trackAutomatticEvent(withName: "shortcut_used", properties: ["shortcut": value])
}
static func trackShortcutSearch() {
trackShortcut("focus_search")
}
static func trackShortcutSearchNext() {
trackShortcut("search_next")
}
static func trackShortcutSearchPrev() {
trackShortcut("search_previous")
}
static func trackShortcutCreateNote() {
trackShortcut("create_note")
}
static func trackShortcutToggleMarkdownPreview() {
trackShortcut("markdown")
}
static func trackShortcutToggleChecklist() {
trackShortcut("toggle_checklist")
}
}
// MARK: Account Deletion
//
extension SPTracker {
static func trackDeleteAccountButttonTapped() {
trackAutomatticEvent(withName: "spios_delete_account_button_clicked", properties: nil)
}
}
// MARK: - IAP
//
extension SPTracker {
static func trackSustainerMonthlyButtonTapped() {
trackAutomatticEvent(withName: "iap_monthly_button_tapped", properties: nil)
}
static func trackSustainerYearlyButtonTapped() {
trackAutomatticEvent(withName: "iap_yearly_button_tapped", properties: nil)
}
static func trackSustainerDismissButtonTapped() {
trackAutomatticEvent(withName: "iap_dismiss_button_tapped", properties: nil)
}
@MainActor
static func trackSustainerPurchaseCompleted(storeProduct: StoreProduct) {
trackAutomatticEvent(withName: "iap_purchase_completed", properties: [
"product": storeProduct.identifier
])
}
}
``` | /content/code_sandbox/Simplenote/SPTracker+Extensions.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 805 |
```swift
import Foundation
enum BuildConfiguration: String {
case debug
case `internal`
case appStore
case release
case unknown
static var current: BuildConfiguration {
#if DEBUG
return .debug
#elseif BUILD_INTERNAL
return .internal
#elseif BUILD_APP_STORE
return .appStore
#elseif BUILD_RELEASE
return .release
#else
return .unknown
#endif
}
static func `is`(_ configuration: BuildConfiguration) -> Bool {
return configuration == current
}
}
extension BuildConfiguration: CustomStringConvertible {
var description: String {
return self.rawValue
}
}
``` | /content/code_sandbox/Simplenote/BuildConfiguration.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 146 |
```swift
import Foundation
import SwiftUI
import Gridicons
// MARK: - MagicLinkConfirmationView
//
struct MagicLinkInvalidView: View {
@Environment(\.presentationMode) var presentationMode
var onPressRequestNewLink: (() -> Void)?
var body: some View {
NavigationView {
VStack(alignment: .center, spacing: 10) {
Image(uiImage: MagicLinkImages.cross)
.renderingMode(.template)
.foregroundColor(Color(.simplenoteLightBlueColor))
Text("Link no longer valid")
.bold()
.font(.system(size: Metrics.titleFontSize))
.multilineTextAlignment(.center)
.padding(.bottom, Metrics.titlePaddingBottom)
Button(action: pressedRequestNewLink) {
Text("Request a new Link")
.fontWeight(.bold)
.foregroundStyle(.white)
}
.padding()
.background(Color(.simplenoteBlue50Color))
.cornerRadius(Metrics.actionCornerRadius)
.buttonStyle(PlainButtonStyle())
}
.padding()
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
presentationMode.wrappedValue.dismiss()
}) {
Image(uiImage: MagicLinkImages.dismiss)
.renderingMode(.template)
.foregroundColor(Color(.darkGray))
}
}
}
}
.navigationViewStyle(.stack)
/// Force Light Mode (since the Authentication UI is all light!)
.environment(\.colorScheme, .light)
}
func pressedRequestNewLink() {
presentationMode.wrappedValue.dismiss()
onPressRequestNewLink?()
}
}
// MARK: - Constants
//
private enum Metrics {
static let crossIconSize = CGSize(width: 100, height: 100)
static let dismissSize = CGSize(width: 30, height: 30)
static let titleFontSize: CGFloat = 20
static let titlePaddingBottom: CGFloat = 30
static let actionCornerRadius: CGFloat = 10
}
private enum MagicLinkImages {
static let cross = Gridicon.iconOfType(.crossCircle, withSize: Metrics.crossIconSize)
static let dismiss = Gridicon.iconOfType(.crossCircle, withSize: Metrics.dismissSize)
}
// MARK: - Preview
//
struct MagicLinkInvalidView_Previews: PreviewProvider {
static var previews: some View {
MagicLinkInvalidView()
}
}
``` | /content/code_sandbox/Simplenote/MagicLinkInvalidView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 531 |
```swift
import Foundation
// MARK: - SPHistoryVersion: Represents a version of an object
//
struct SPHistoryVersion {
/// Version
///
let version: Int
/// Note's Payload
///
let content: String
/// Latest modification date
///
let modificationDate: Date
/// Designated Initializer
///
init?(version: Int, payload: [AnyHashable: Any]) {
guard let modification = payload[Keys.modificationDate.rawValue] as? Double,
let content = payload[Keys.content.rawValue] as? String
else {
return nil
}
self.version = version
self.modificationDate = Date(timeIntervalSince1970: TimeInterval(modification))
self.content = content
}
}
// MARK: - Parsing Keys
//
extension SPHistoryVersion {
private enum Keys: String {
case modificationDate
case content
}
}
// MARK: - SPHistoryVersion Hashable
//
extension SPHistoryVersion: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(version)
}
}
``` | /content/code_sandbox/Simplenote/SPHistoryVersion.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 234 |
```swift
import Foundation
@objcMembers
class StorageSettings: NSObject {
private let fileManager: FileManager
init(fileManager: FileManager = FileManager.default) {
self.fileManager = fileManager
}
/// URL for the managed object model resource
///
let modelURL = Bundle.main.url(forResource: Constants.modelName, withExtension: Constants.modelExtension)!
/// In app core data storage URL
///
var legacyStorageURL: URL {
fileManager.documentsURL.appendingPathComponent(Constants.sqlFile)
}
/// URL for core data storage in shared app group documents directory
///
var sharedStorageURL: URL {
fileManager.sharedContainerURL.appendingPathComponent(Constants.sqlFile)
}
/// URL for backing up the legacy storage
///
var legacyBackupURL: URL {
legacyStorageURL.appendingPathExtension(Constants.oldExtension)
}
}
private struct Constants {
static let sqlFile = "Simplenote.sqlite"
static let modelName = "Simplenote"
static let modelExtension = "momd"
static let oldExtension = "old"
}
``` | /content/code_sandbox/Simplenote/StorageSettings.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 233 |
```swift
import Foundation
import UIKit
// MARK: - ActivityViewController Simplenote Methods
//
extension UIActivityViewController {
/// Initializes a UIActivityViewController instance that will be able to export a given Note
///
@objc
convenience init?(note: Note) {
guard let content = note.content else {
return nil
}
let print = SPSimpleTextPrintFormatter(text: content)
let source = SimplenoteActivityItemSource(content: content, identifier: note.simperiumKey)
self.init(activityItems: [print, source], applicationActivities: nil)
// Share to ibooks feature that is added by the SimpleTextPrintFormatter requires a locally generated PDF or the share fails silently
// After much discussion the decision was to not implement a PDF generator into SN at this time, removing share to books as an option.
excludedActivityTypes = [
UIActivity.ActivityType.openInIBooks
]
}
}
``` | /content/code_sandbox/Simplenote/UIActivityViewController+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 200 |
```swift
import Foundation
// MARK: - SPNoteHistoryController: Business logic for history view controller
//
final class SPNoteHistoryController {
// MARK: - State of the screen
//
enum State {
/// Version (is fully loaded)
/// - Parameters
/// - versionNumber: version number
/// - date: formatted date of the version
/// - isRestorable: possibility to restore to this version
///
case version(versionNumber: Int, date: String, isRestorable: Bool)
/// Version (is being loaded)
/// - Parameters
/// - versionNumber: version number
///
case loadingVersion(versionNumber: Int)
/// Error
///
case error(String)
}
/// Observer sends changes of the state (to history view controller)
/// When assigned, it sends current state
///
var observer: ((State) -> Void)? {
didSet {
observer?(state)
}
}
/// Range of versions available to load
/// Contains at least the current version of an object
///
let versionRange: ClosedRange<Int>
/// Delegate
///
weak var delegate: SPNoteHistoryControllerDelegate?
private let note: Note
private let versionsController: VersionsController
private var versionsToken: Any?
private var state: State {
didSet {
observer?(state)
}
}
private var versions: [Int: SPHistoryVersion] = [:]
/// Designated initializer
///
/// - Parameters:
/// - note: Note
/// - loader: History loader for specified Note
///
init(note: Note, versionsController: VersionsController) {
self.note = note
self.versionsController = versionsController
versionRange = VersionsController.range(forCurrentVersion: note.versionInt)
state = .loadingVersion(versionNumber: versionRange.upperBound)
}
convenience init(note: Note) {
self.init(note: note, versionsController: SPAppDelegate.shared().versionsController)
}
}
// MARK: - Communications from UI
//
extension SPNoteHistoryController {
/// User tapped on close button
///
func handleTapOnCloseButton() {
delegate?.noteHistoryControllerDidCancel()
}
/// User tapped on restore button
///
func handleTapOnRestoreButton() {
delegate?.noteHistoryControllerDidFinish()
}
/// User selected a version
///
func select(versionNumber: Int) {
switchToVersion(versionNumber)
}
/// Invoked when view is loaded
///
func onViewLoad() {
guard SPAppDelegate.shared().simperium.authenticator.connected else {
state = .error(Localization.networkError)
return
}
loadData()
}
}
// MARK: - Private Methods
//
private extension SPNoteHistoryController {
func loadData() {
versionsToken = versionsController.requestVersions(for: note.simperiumKey, currentVersion: note.versionInt) { [weak self] (version) in
self?.process(noteVersion: version)
}
}
func process(noteVersion: SPHistoryVersion) {
versions[noteVersion.version] = noteVersion
// We received a note version with the same version as currently showing
// Update state using new information
if state.versionNumber == noteVersion.version {
switchToVersion(noteVersion.version)
}
}
func switchToVersion(_ versionNumber: Int) {
if let noteVersion = versions[versionNumber] {
state = .version(versionNumber: versionNumber,
date: note.dateString(noteVersion.modificationDate, brief: false),
isRestorable: noteVersion.version != note.versionInt)
delegate?.noteHistoryControllerDidSelectVersion(withContent: noteVersion.content)
} else {
state = .loadingVersion(versionNumber: versionNumber)
}
}
}
// MARK: - State extension
//
private extension SPNoteHistoryController.State {
var versionNumber: Int? {
switch self {
case .version(let versionNumber, _, _), .loadingVersion(let versionNumber):
return versionNumber
case .error:
return nil
}
}
}
// MARK: - Localization
//
private struct Localization {
static let networkError = NSLocalizedString("Couldn't Retrieve History", comment: "Error message shown when trying to view history of a note without an internet connection")
}
``` | /content/code_sandbox/Simplenote/SPNoteHistoryController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 936 |
```swift
import Foundation
import CoreData
import AutomatticTracks
@objc
class SharedStorageMigrator: NSObject {
private let storageSettings: StorageSettings
private let fileManager: FileManager
init(storageSettings: StorageSettings = StorageSettings(), fileManager: FileManager = FileManager.default) {
self.storageSettings = storageSettings
self.fileManager = fileManager
}
private var legacyStorageExists: Bool {
fileManager.fileExists(atPath: storageSettings.legacyStorageURL.path)
}
private var sharedStorageExists: Bool {
fileManager.fileExists(atPath: storageSettings.sharedStorageURL.path)
}
/// Database Migration
/// To be able to share data with app extensions, the CoreData database needs to be migrated to an app group
/// Must run before Simperium is setup
func performMigrationIfNeeded() -> MigrationResult {
// Confirm if the app group DB exists
guard migrationNeeded else {
NSLog("Core Data Migration not required")
return .notNeeded
}
return migrateCoreDataToAppGroup()
}
private var migrationNeeded: Bool {
return legacyStorageExists && !sharedStorageExists
}
private func migrateCoreDataToAppGroup() -> MigrationResult {
NSLog("Database needs migration to app group")
NSLog("Beginning database migration from: \(storageSettings.legacyStorageURL.path) to: \(storageSettings.sharedStorageURL.path)")
do {
try disableJournaling()
try migrateCoreDataFiles()
try attemptCreationOfCoreDataStack()
NSLog("Database migration successful!!")
backupLegacyDatabase()
return .success
} catch {
NSLog("Could not migrate database to app group " + error.localizedDescription)
CrashLoggingShim.shared.logError(error)
removeFailedMigrationFilesIfNeeded()
return .failed
}
}
/// This method disables journaling on the core data database
/// Per this doc: path_to_url
/// Core data databases have journaling enabled by default, without disabling the journaling first it is possible some notes may get lost in migration
///
private func disableJournaling() throws {
NSLog("Attempting to disable journaling on persistent store at \(storageSettings.legacyStorageURL)")
try loadPersistentStorage(at: storageSettings.legacyStorageURL, journaling: false)
}
private func loadPersistentStorage(at storagePath: URL, journaling: Bool) throws {
guard let mom = NSManagedObjectModel(contentsOf: storageSettings.modelURL) else {
fatalError("Could not load Managed Object Model at path: \(storagePath.path)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
let options = journaling ? nil : [NSSQLitePragmasOption: Constants.journalModeDisabled]
try psc.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil,
at: storagePath,
options: options)
// Remove the persistent store before exiting
// If removing fails, the migration can still continue so not throwing the errors
do {
for store in psc.persistentStores {
try psc.remove(store)
}
} catch {
NSLog("Could not remove temporary persistent Store " + error.localizedDescription)
}
}
private func migrateCoreDataFiles() throws {
try fileManager.copyItem(at: storageSettings.legacyStorageURL, to: storageSettings.sharedStorageURL)
}
private func attemptCreationOfCoreDataStack() throws {
NSLog("Confirming migrated database can be loaded at: \(storageSettings.sharedStorageURL)")
try loadPersistentStorage(at: storageSettings.sharedStorageURL, journaling: true)
}
private func removeFailedMigrationFilesIfNeeded() {
guard sharedStorageExists else {
return
}
do {
try fileManager.removeItem(at: storageSettings.sharedStorageURL)
} catch {
NSLog("Could not delete files from failed migration " + error.localizedDescription)
}
}
private func backupLegacyDatabase() {
do {
try fileManager.moveItem(at: storageSettings.legacyStorageURL, to: storageSettings.legacyBackupURL)
} catch {
NSLog("Could not backup legacy storage database" + error.localizedDescription)
}
}
}
enum MigrationResult {
case success
case notNeeded
case failed
}
private struct Constants {
static let journalModeDisabled = ["journal_mode": "DELETE"]
}
``` | /content/code_sandbox/Simplenote/SharedStorageMigrator.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 931 |
```swift
import Foundation
import WidgetKit
// MARK: - Initialization
//
extension SPAppDelegate {
/// Simperium Initialization
/// - Important: Buckets that don't have a backing `SPManagedObject` will be dynamic. Invoking `bucketForName` will initialize sync'ing!
///
@objc
func setupSimperium() {
simperium = Simperium(model: coreDataManager.managedObjectModel, context: coreDataManager.managedObjectContext, coordinator: coreDataManager.persistentStoreCoordinator)
#if USE_VERBOSE_LOGGING
simperium.verboseLoggingEnabled = true
NSLog("[Simperium] Verbose logging Enabled")
#else
simperium.verboseLoggingEnabled = false
#endif
simperium.authenticationViewControllerClass = SPOnboardingViewController.self
simperium.authenticationShouldBeEmbeddedInNavigationController = true
simperium.delegate = self
for bucket in simperium.allBuckets {
bucket.notifyWhileIndexing = true
bucket.delegate = self
}
}
@objc
func setupAuthenticator() {
let authenticator = simperium.authenticator
authenticator.providerString = "simplenote.com"
}
@objc
func setupStoreManager() {
StoreManager.shared.initialize()
}
}
// MARK: - Internal Methods
//
extension SPAppDelegate {
/// Returns the actual Selected Tag Name **Excluding** navigation tags, such as Trash or Untagged Notes.
///
/// TODO: This should be gone... **the second** the AppDelegate is Swift-y. We should simply keep a `NoteListFilter` instance.
///
@objc
var filteredTagName: String? {
guard let selectedTag = SPAppDelegate.shared().selectedTag,
case let .tag(name) = NotesListFilter(selectedTag: selectedTag) else {
return nil
}
return name
}
/// Returns the visible EditorViewController (when applicable!)
///
@objc
var noteEditorViewController: SPNoteEditorViewController? {
navigationController.firstChild(ofType: SPNoteEditorViewController.self)
}
}
// MARK: - Initialization
//
extension SPAppDelegate {
@objc
func configureVersionsController() {
versionsController = VersionsController(bucket: simperium.notesBucket)
}
@objc
func configurePublishController() {
publishController = PublishController()
publishController.onUpdate = { (note) in
PublishNoticePresenter.presentNotice(for: note)
}
}
@objc
func configureAccountDeletionController() {
accountDeletionController = AccountDeletionController()
}
}
// MARK: - URL Handlers and Deep Linking
//
extension SPAppDelegate {
/// Opens the Note associated with a given URL instance, when possible
///
@objc
func handleOpenNote(url: NSURL) -> Bool {
guard let simperiumKey = url.interlinkSimperiumKey, let note = simperium.loadNote(simperiumKey: simperiumKey) else {
return false
}
popToNoteList()
noteListViewController.open(note, ignoringSearchQuery: true, animated: false)
return true
}
/// Opens the Note list displaying a tag associated with a given URL instance, when possible
///
@objc
func handleOpenTagList(url: NSURL) -> Bool {
guard url.isInternalTagURL else {
return false
}
if let tag = url.internalTagKey {
selectedTag = SPObjectManager.shared().tagExists(tag) ? tag : selectedTag
} else {
selectedTag = nil
}
popToNoteList()
return true
}
/// Opens search
///
func presentSearch(animated: Bool = false) {
popToNoteList(animated: animated)
let block = {
// Switch from trash to all notes as trash doesn't have search
if self.selectedTag == kSimplenoteTrashKey {
self.selectedTag = nil
}
self.noteListViewController.startSearching()
}
if animated {
block()
} else {
UIView.performWithoutAnimation(block)
}
}
/// Opens editor with a new note
///
@objc
func presentNewNoteEditor(useSelectedTag: Bool = true, animated: Bool = false) {
performActionAfterUnlock {
if useSelectedTag {
self.presentNote(nil, animated: animated)
} else {
// If we use the standard new note option and a tag is selected then the tag is applied
// in some cases, like shortcuts, we don't want it do apply the tag cause you can't see
// what tag is selected when the shortcut runs
let note = SPObjectManager.shared().newDefaultNote()
self.presentNote(note, animated: true)
}
}
}
@objc
func presentNewNoteEditor(animated: Bool = false) {
presentNewNoteEditor(useSelectedTag: true, animated: animated)
}
var verifyController: PinLockVerifyController? {
(pinLockWindow?.rootViewController as? PinLockViewController)?.controller as? PinLockVerifyController
}
/// Opens a note with specified simperium key
///
func presentNoteWithSimperiumKey(_ simperiumKey: String) {
guard let note = simperium.loadNote(simperiumKey: simperiumKey) else {
return
}
presentNote(note)
}
/// Opens a note
///
@objc
func presentNote(_ note: Note?, animated: Bool = false) {
popToNoteList(animated: animated)
noteListViewController.open(note, animated: animated)
}
/// Dismisses all modals
///
@objc(dismissAllModalsAnimated:completion:)
func dismissAllModals(animated: Bool, completion: (() -> Void)?) {
navigationController.dismiss(animated: animated, completion: completion)
}
private func popToNoteList(animated: Bool = false) {
dismissAllModals(animated: animated, completion: nil)
sidebarViewController.hideSidebar(withAnimation: animated)
if navigationController.viewControllers.contains(noteListViewController) {
navigationController.popToViewController(noteListViewController, animated: animated)
}
}
@objc
func setupNoticeController() {
NoticeController.shared.setupNoticeController()
}
func performActionAfterUnlock(action: @escaping () -> Void) {
if isPresentingPasscodeLock && SPPinLockManager.shared.isEnabled {
verifyController?.addOnSuccesBlock {
action()
}
} else {
action()
}
}
}
// MARK: - UIViewControllerRestoration
//
@objc
extension SPAppDelegate: UIViewControllerRestoration {
@objc
func configureStateRestoration() {
EditorFactory.shared.restorationClass = SPAppDelegate.self
tagListViewController.restorationIdentifier = TagListViewController.defaultRestorationIdentifier
tagListViewController.restorationClass = SPAppDelegate.self
noteListViewController.restorationIdentifier = SPNoteListViewController.defaultRestorationIdentifier
noteListViewController.restorationClass = SPAppDelegate.self
navigationController.restorationIdentifier = SPNavigationController.defaultRestorationIdentifier
navigationController.restorationClass = SPAppDelegate.self
sidebarViewController.restorationIdentifier = SPSidebarContainerViewController.defaultRestorationIdentifier
sidebarViewController.restorationClass = SPAppDelegate.self
}
func viewController(restorationIdentifier: String, coder: NSCoder) -> UIViewController? {
switch restorationIdentifier {
case tagListViewController.restorationIdentifier:
return tagListViewController
case noteListViewController.restorationIdentifier:
return noteListViewController
case SPNoteEditorViewController.defaultRestorationIdentifier:
guard let simperiumKey = coder.decodeObject(forKey: SPNoteEditorViewController.CodingKeys.currentNoteKey.rawValue) as? String,
let note = simperium.bucket(forName: Note.classNameWithoutNamespaces)?.object(forKey: simperiumKey) as? Note
else {
return nil
}
return EditorFactory.shared.build(with: note)
case navigationController.restorationIdentifier:
return navigationController
case sidebarViewController.restorationIdentifier:
return sidebarViewController
default:
return nil
}
}
@objc
public static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? {
guard
let appDelegate = UIApplication.shared.delegate as? SPAppDelegate,
let restorationIdentifier = identifierComponents.last
else {
return nil
}
return appDelegate.viewController(restorationIdentifier: restorationIdentifier, coder: coder)
}
}
// MARK: - SimperiumDelegate
//
extension SPAppDelegate: SimperiumDelegate {
public func simperiumDidLogin(_ simperium: Simperium) {
guard let user = simperium.user else {
fatalError()
}
// Store the Token: Required by the Share Extension!
KeychainManager.extensionToken = user.authToken
// Tracker!
SPTracker.refreshMetadata(withEmail: user.email)
// Shortcuts!
ShortcutsHandler.shared.updateHomeScreenQuickActionsIfNeeded()
// Now that the user info is present, cache it for use by the crash logging system.
let analyticsEnabled = simperium.preferencesObject().analytics_enabled?.boolValue ?? true
CrashLoggingShim.shared.cacheUser(user)
CrashLoggingShim.cacheOptOutSetting(!analyticsEnabled)
syncWidgetDefaults()
setupVerificationController()
}
public func simperiumDidLogout(_ simperium: Simperium) {
// Nuke Extension Token
KeychainManager.extensionToken = nil
// Tracker!
SPTracker.refreshMetadataForAnonymousUser()
// Shortcuts!
ShortcutsHandler.shared.clearHomeScreenQuickActions()
syncWidgetDefaults()
destroyVerificationController()
}
public func simperium(_ simperium: Simperium, didFailWithError error: Error) {
SPTracker.refreshMetadataForAnonymousUser()
guard let simperiumError = SPSimperiumErrors(rawValue: (error as NSError).code) else {
return
}
switch simperiumError {
case .invalidToken:
logOutIfAccountDeletionRequested()
default:
break
}
}
}
// MARK: - Passcode
//
extension SPAppDelegate {
/// Show passcode lock if passcode is enabled
///
@objc
func showPasscodeLockIfNecessary() {
guard SPPinLockManager.shared.isEnabled, !isPresentingPasscodeLock else {
verifyController?.removeSuccesBlocks()
return
}
let controller = PinLockVerifyController(delegate: self)
let viewController = PinLockViewController(controller: controller)
pinLockWindow = UIWindow(frame: UIScreen.main.bounds)
pinLockWindow?.accessibilityViewIsModal = true
pinLockWindow?.rootViewController = viewController
pinLockWindow?.makeKeyAndVisible()
}
/// Dismiss the passcode lock window if the user has returned to the app before their preferred timeout length
///
@objc
func dismissPasscodeLockIfPossible() {
guard pinLockWindow?.isKeyWindow == true, SPPinLockManager.shared.shouldBypassPinLock else {
return
}
dismissPasscodeLock()
}
private func dismissPasscodeLock() {
window.makeKeyAndVisible()
pinLockWindow?.removeFromSuperview()
pinLockWindow = nil
}
private var isPresentingPasscodeLock: Bool {
return pinLockWindow?.isKeyWindow == true
}
}
// MARK: - PinLockVerifyControllerDelegate
//
extension SPAppDelegate: PinLockVerifyControllerDelegate {
func pinLockVerifyControllerDidComplete(_ controller: PinLockVerifyController) {
UIView.animate(withDuration: UIKitConstants.animationShortDuration) {
self.pinLockWindow?.alpha = UIKitConstants.alpha0_0
} completion: { (_) in
self.dismissPasscodeLock()
}
}
}
// MARK: - Account Verification
//
private extension SPAppDelegate {
func setupVerificationController() {
guard let email = simperium.user?.email, !email.isEmpty else {
return
}
verificationController = AccountVerificationController(email: email)
verificationController?.onStateChange = { [weak self] (oldState, state) in
switch (oldState, state) {
case (.unknown, .unverified):
self?.showVerificationViewController(with: .review)
case (.unknown, .verificationInProgress):
self?.showVerificationViewController(with: .verify)
case (.unverified, .verified), (.verificationInProgress, .verified):
self?.dismissVerificationViewController()
default:
break
}
}
}
func destroyVerificationController() {
verificationController = nil
}
func showVerificationViewController(with configuration: AccountVerificationViewController.Configuration) {
guard let controller = verificationController, verificationViewController == nil else {
return
}
let viewController = AccountVerificationViewController(configuration: configuration, controller: controller)
verificationViewController = viewController
viewController.presentFromRootViewController()
}
func dismissVerificationViewController() {
verificationViewController?.dismiss(animated: true, completion: nil)
verificationViewController = nil
}
}
// MARK: - Magic Link authentication
//
extension SPAppDelegate {
@objc @discardableResult
func performMagicLinkAuthentication(with url: URL) -> Bool {
MagicLinkAuthenticator(authenticator: simperium.authenticator).handle(url: url)
}
@objc(performMagicLinkAuthenticationWithUserActivity:)
func performMagicLinkAuthentication(with userActivity: NSUserActivity) -> Bool {
guard let url = userActivity.webpageURL else {
return false
}
return performMagicLinkAuthentication(with: url)
}
}
// MARK: - Scroll position cache
//
extension SPAppDelegate {
@objc
func cleanupScrollPositionCache() {
let allNotes = SPObjectManager.shared().notes()
let allIdentifiers: [String] = allNotes.compactMap { note in
note.deleted ? nil : note.simperiumKey
}
EditorFactory.shared.scrollPositionCache.cleanup(keeping: allIdentifiers)
}
}
// MARK: - Account Deletion
//
extension SPAppDelegate {
@objc
func authenticateSimperiumIfAccountDeletionRequested() {
guard let deletionController = accountDeletionController,
deletionController.hasValidDeletionRequest else {
return
}
simperium.authenticateIfNecessary()
}
@objc
func logOutIfAccountDeletionRequested() {
guard accountDeletionController?.hasValidDeletionRequest == true else {
return
}
logoutAndReset(self)
}
}
// MARK: - Core Data
//
extension SPAppDelegate {
@objc
var managedObjectContext: NSManagedObjectContext {
coreDataManager.managedObjectContext
}
@objc
func setupStorage() {
let migrationResult = SharedStorageMigrator().performMigrationIfNeeded()
do {
try setupCoreData(migrationResult: migrationResult)
} catch {
fatalError(error.localizedDescription)
}
}
private func setupCoreData(migrationResult: MigrationResult) throws {
let settings = StorageSettings()
switch migrationResult {
case .notNeeded, .success:
coreDataManager = try CoreDataManager(settings.sharedStorageURL)
case .failed:
coreDataManager = try CoreDataManager(settings.legacyStorageURL)
}
}
}
// MARK: - Widgets
extension SPAppDelegate {
@objc
func resetWidgetTimelines() {
WidgetController.resetWidgetTimelines()
}
@objc
func syncWidgetDefaults() {
let authenticated = simperium.user?.authenticated() ?? false
let sortMode = Options.shared.listSortMode
WidgetController.syncWidgetDefaults(authenticated: authenticated, sortMode: sortMode)
}
}
// MARK: - Sustainer migration
extension SPAppDelegate {
@objc
func migrateSimperiumPreferencesIfNeeded() {
guard UserDefaults.standard.bool(forKey: .hasMigratedSustainerPreferences) == false else {
return
}
guard isFirstLaunch() == false else {
UserDefaults.standard.set(true, forKey: .hasMigratedSustainerPreferences)
return
}
NSLog("Migrating Simperium Preferences object to include was_sustainer value")
UserDefaults.standard.removeObject(forKey: Simperium.preferencesLastChangedSignatureKey)
let prefs = simperium.preferencesObject()
prefs.ghostData = ""
simperium.saveWithoutSyncing()
UserDefaults.standard.set(true, forKey: .hasMigratedSustainerPreferences)
}
}
// MARK: - Content Recovery
//
extension SPAppDelegate {
@objc
func attemptContentRecoveryIfNeeded() {
RecoveryUnarchiver(simperium: simperium).insertNotesFromRecoveryFilesIfNeeded()
}
}
``` | /content/code_sandbox/Simplenote/SPAppDelegate+Extensions.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 3,576 |
```swift
import UIKit
import SimplenoteFoundation
// MARK: - NoteInformationViewController
//
final class NoteInformationViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var dragBar: SPDragBar!
private var transitioningManager: UIViewControllerTransitioningDelegate?
private var sections: [NoteInformationController.Section] = []
private let controller: NoteInformationController
private var onDismissCallback: (() -> Void)?
/// Designated initializer
///
/// - Parameters:
/// - controller: NoteInformationController
///
init(controller: NoteInformationController) {
self.controller = controller
super.init(nibName: nil, bundle: nil)
}
/// Convenience initializer
///
/// - Parameters:
/// - note: Note
///
convenience init(note: Note) {
self.init(controller: NoteInformationController(note: note))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
stopListeningToNotifications()
}
override func viewDidLoad() {
super.viewDidLoad()
configureViews()
configureNavigation()
configureDragBar()
refreshPreferredSize()
startListeningToNotifications()
startListeningForControllerChanges()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
refreshPreferredSize()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
additionalSafeAreaInsets = Consts.tableViewSafeAreaInsets
}
override func accessibilityPerformEscape() -> Bool {
dismiss(animated: true, completion: nil)
return true
}
}
// MARK: - Controller
//
private extension NoteInformationViewController {
func startListeningForControllerChanges() {
controller.observer = { [weak self] sections in
self?.update(with: sections)
}
}
func update(with sections: [NoteInformationController.Section]) {
self.sections = sections
tableView.reloadData()
refreshPreferredSize()
}
}
// MARK: - Configuration
//
private extension NoteInformationViewController {
func configureNavigation() {
title = Localization.document
navigationItem.rightBarButtonItem = UIBarButtonItem(title: Localization.done,
style: .done,
target: self,
action: #selector(handleTapOnDismissButton))
}
func configureViews() {
configureTableView()
styleTableView()
}
func configureTableView() {
// Otherwise additional safe area insets don't work :/
tableView.contentInsetAdjustmentBehavior = .always
tableView.register(Value1TableViewCell.self, forCellReuseIdentifier: Value1TableViewCell.reuseIdentifier)
tableView.register(SubtitleTableViewCell.self, forCellReuseIdentifier: SubtitleTableViewCell.reuseIdentifier)
tableView.register(TableHeaderViewCell.self, forCellReuseIdentifier: TableHeaderViewCell.reuseIdentifier)
// remove separator for last cell if we're in popover
if popoverPresentationController != nil {
tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
}
}
func refreshPreferredSize() {
preferredContentSize = tableView.contentSize
}
private func configureDragBar() {
dragBar.isHidden = navigationController != nil
dragBar.accessibilityLabel = Localization.dismissAccessibilityLabel
if UIAccessibility.isVoiceOverRunning == true {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(informationSheetToBeDismissed))
dragBar.addGestureRecognizer(gestureRecognizer)
}
}
@objc
func informationSheetToBeDismissed() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - Styling
//
private extension NoteInformationViewController {
func styleTableView() {
tableView.separatorColor = .simplenoteDividerColor
}
}
// MARK: - Handling button events
//
private extension NoteInformationViewController {
@IBAction func handleTapOnDismissButton() {
dismiss(animated: true, completion: nil)
onDismissCallback?()
}
}
// MARK: - UITableViewDelegate
//
extension NoteInformationViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let row = sections[indexPath.section].rows[indexPath.row]
switch row {
case .reference(let interLink, _, _):
if let interLink = interLink, let url = URL(string: interLink) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
default:
break
}
}
}
// MARK: - UITableViewDataSource
//
extension NoteInformationViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = sections[indexPath.section].rows[indexPath.row]
switch row {
case .metric(let title, let value):
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
configure(cell: cell, withTitle: title, value: value)
return cell
case .reference(_, let title, let reference):
let cell = tableView.dequeueReusableCell(ofType: SubtitleTableViewCell.self, for: indexPath)
configure(cell: cell, withTitle: title, reference: reference)
return cell
case .header(let title):
let cell = tableView.dequeueReusableCell(ofType: TableHeaderViewCell.self, for: indexPath)
configure(cell: cell, withTitle: title)
return cell
}
}
private func configure(cell: Value1TableViewCell, withTitle title: String, value: String?) {
cell.selectionStyle = .none
cell.hasClearBackground = true
cell.title = title
cell.detailTextLabel?.text = value
}
private func configure(cell: SubtitleTableViewCell, withTitle title: String, reference: String) {
cell.title = title
cell.value = reference
}
private func configure(cell: TableHeaderViewCell, withTitle title: String) {
cell.title = title
}
private func updateSeparator(for cell: UITableViewCell, at indexPath: IndexPath) {
let row = sections[indexPath.section].rows[indexPath.row]
switch row {
case .header:
cell.adjustSeparatorWidth(width: .standard)
default:
if indexPath.row == sections[indexPath.section].rows.count - 1 {
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
} else {
cell.adjustSeparatorWidth(width: .standard)
}
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
updateSeparator(for: cell, at: indexPath)
}
}
// MARK: - Notifications
//
private extension NoteInformationViewController {
func startListeningToNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(themeDidChange), name: .SPSimplenoteThemeChanged, object: nil)
}
func stopListeningToNotifications() {
NotificationCenter.default.removeObserver(self)
}
@objc
private func themeDidChange() {
styleTableView()
}
}
// MARK: - Presentation
//
extension NoteInformationViewController {
/// Configure view controller to be presented as a card
///
func configureToPresentAsCard(onDismissCallback: (() -> Void)? = nil) {
self.onDismissCallback = onDismissCallback
let transitioningManager = SPCardTransitioningManager()
self.transitioningManager = transitioningManager
transitioningManager.presentationDelegate = self
transitioningDelegate = transitioningManager
modalPresentationStyle = .custom
}
}
extension NoteInformationViewController: SPCardPresentationControllerDelegate {
func cardDidDismiss(_ viewController: UIViewController, reason: SPCardDismissalReason) {
onDismissCallback?()
}
}
private struct Localization {
static let done = NSLocalizedString("Done", comment: "Dismisses the Note Information UI")
static let dismissAccessibilityLabel = NSLocalizedString("Dismiss Information", comment: "Accessibility label describing a button used to dismiss an information view of the note")
static let document = NSLocalizedString("Document", comment: "Card title showing information about the note (metrics, references)")
}
private struct Consts {
static let tableViewSafeAreaInsets = UIEdgeInsets(top: 26, left: 0, bottom: 0, right: 0)
}
``` | /content/code_sandbox/Simplenote/Information/NoteInformationViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,792 |
```swift
import Foundation
import SimplenoteFoundation
final class NoteInformationController {
/// Section
///
struct Section {
let rows: [Row]
}
/// Row
///
enum Row {
/// Metric row
///
case metric(title: String, value: String?)
/// Reference
///
case reference(interLink: String?, title: String, reference: String)
/// Header
///
case header(title: String)
}
/// Observer sends changes in data
/// When assigned, it sends current state
///
var observer: (([Section]) -> Void)? {
didSet {
observer?(allSections())
if observer == nil {
stopListeningForChanges()
} else {
startListeningForChanges()
}
}
}
/// Main Context
///
private var mainContext: NSManagedObjectContext {
SPAppDelegate.shared().managedObjectContext
}
/// Note changes observer
///
private lazy var noteChangesObserver = EntityObserver(context: mainContext, object: note)
/// ResultsController: In charge of CoreData Queries!
///
private var referencesController: ResultsController<Note>?
private let note: Note
/// Designated initializer
///
/// - Parameters:
/// - note: Note
///
init(note: Note) {
self.note = note
configureReferencesController()
}
}
// MARK: - Private
//
private extension NoteInformationController {
func configureReferencesController() {
guard let noteLink = note.plainInternalLink else {
return
}
let predicate = NSPredicate.predicateForNotes(exactMatch: noteLink)
let sortDescriptors = [
NSSortDescriptor(keyPath: \Note.content, ascending: true)
]
let controller = ResultsController<Note>(viewContext: mainContext,
sectionNameKeyPath: nil,
matching: predicate,
sortedBy: sortDescriptors,
limit: 0)
referencesController = controller
try? controller.performFetch()
}
}
// MARK: - Listening for changes
//
private extension NoteInformationController {
func startListeningForChanges() {
noteChangesObserver.delegate = self
referencesController?.onDidChangeContent = { [weak self] _, _ in
self?.sendNewDataToObserver()
}
}
func stopListeningForChanges() {
noteChangesObserver.delegate = nil
referencesController?.onDidChangeContent = nil
}
}
// MARK: - Data
//
private extension NoteInformationController {
func allSections() -> [Section] {
var sections: [Section] = []
sections.append(metricSection())
sections.append(contentsOf: referenceSections())
return sections
}
func metricSection() -> Section {
let metrics = NoteMetrics(note: note)
let rows: [Row] = [
.metric(title: Localization.modified,
value: DateFormatter.dateTimeFormatter.string(from: metrics.modifiedDate)),
.metric(title: Localization.created,
value: DateFormatter.dateTimeFormatter.string(from: metrics.creationDate)),
.metric(title: Localization.words,
value: NumberFormatter.decimalFormatter.string(for: metrics.numberOfWords)),
.metric(title: Localization.characters,
value: NumberFormatter.decimalFormatter.string(for: metrics.numberOfChars))
]
return Section(rows: rows)
}
func referenceSections() -> [Section] {
guard let references = referencesController?.fetchedObjects, !references.isEmpty else {
return []
}
let referenceRows = references.map { (referenceNote) -> Row in
let date = DateFormatter.dateFormatter.string(from: referenceNote.modificationDate)
let instancesOfReference = referenceNote.instancesOfReference(to: note)
let value = "\(Localization.interlinkReferences(instancesOfReference)), \(Localization.lastModified(date))"
return .reference(interLink: referenceNote.plainInternalLink,
title: referenceNote.titlePreview,
reference: value)
}
let header = Section(rows: [
Row.header(title: Localization.references)
])
return [
header,
Section(rows: referenceRows)
]
}
func sendNewDataToObserver() {
observer?(allSections())
}
}
// MARK: - EntityObserverDelegate
//
extension NoteInformationController: EntityObserverDelegate {
func entityObserver(_ observer: EntityObserver, didObserveChanges identifiers: Set<NSManagedObjectID>) {
sendNewDataToObserver()
}
}
private struct Localization {
static let modified = NSLocalizedString("Modified", comment: "Note Modification Date")
static let created = NSLocalizedString("Created", comment: "Note Creation Date")
static let words = NSLocalizedString("Words", comment: "Number of words in the note")
static let characters = NSLocalizedString("Characters", comment: "Number of characters in the note")
static let references = NSLocalizedString("Referenced In", comment: "References section header on Info Card")
private static let referenceSigular = NSLocalizedString("%i Reference", comment: "Count of interlink references to a note")
private static let referencePlural = NSLocalizedString("%i References", comment: "Count of interlink references to a note")
static func interlinkReferences(_ references: Int) -> String {
let template = references > 1 ? referencePlural : referenceSigular
return String(format: template, references)
}
private static let lastModified = NSLocalizedString("Last Modified %1$@", comment: "Date of note last modified. Parameter: %1$@ - formatted date")
static func lastModified(_ dateString: String) -> String {
return String(format: lastModified, dateString)
}
}
``` | /content/code_sandbox/Simplenote/Information/NoteInformationController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,184 |
```objective-c
//
// main.m
// Simplenote
//
// Created by Tom Witkin on 7/3/13.
//
#import <UIKit/UIKit.h>
#import "SPAppDelegate.h"
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([SPAppDelegate class]));
}
}
``` | /content/code_sandbox/Simplenote/Supporting Files/main.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 75 |
```swift
import Foundation
// MARK: - CGRect Methods
//
extension CGRect {
/// Returns the resulting Rectangles by splitting the receiver in two, by the specified Rectangle's **minY** and **maxY**
/// - Note: We rely on this API to determine the available editing area above and below the cursor
///
func split(by rect: CGRect) -> (aboveSlice: CGRect, belowSlice: CGRect) {
var belowSlice = self
belowSlice.size.height = rect.minY - minY
var aboveSlice = self
aboveSlice.origin.y = rect.maxY
aboveSlice.size.height = maxY - rect.maxY
return (aboveSlice, belowSlice)
}
}
``` | /content/code_sandbox/Simplenote/Classes/CGRect+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 148 |
```objective-c
#import <Foundation/Foundation.h>
/**
* @class SPTracker
* @brief This class is meant to aid in the app's event tracking. We'll relay the appropriate events to
* either Automattic Tracks, or Google Analytics.
*/
@interface SPTracker : NSObject
#pragma mark - Metadata
+ (void)refreshMetadataWithEmail:(NSString *)email;
+ (void)refreshMetadataForAnonymousUser;
#pragma mark - Application State
+ (void)trackApplicationOpened;
+ (void)trackApplicationClosed;
#pragma mark - Note Editor
+ (void)trackEditorChecklistInserted;
+ (void)trackEditorNoteCreated;
+ (void)trackEditorNoteDeleted;
+ (void)trackEditorNoteRestored;
+ (void)trackEditorNotePublishEnabled:(BOOL)isOn;
+ (void)trackEditorNoteContentShared;
+ (void)trackEditorNoteEdited;
+ (void)trackEditorEmailTagAdded;
+ (void)trackEditorEmailTagRemoved;
+ (void)trackEditorTagAdded;
+ (void)trackEditorTagRemoved;
+ (void)trackEditorNotePinEnabled:(BOOL)isOn;
+ (void)trackEditorNoteMarkdownEnabled:(BOOL)isOn;
+ (void)trackEditorActivitiesAccessed;
+ (void)trackEditorVersionsAccessed;
+ (void)trackEditorCollaboratorsAccessed;
+ (void)trackEditorCopiedInternalLink;
+ (void)trackEditorCopiedPublicLink;
+ (void)trackEditorInterlinkAutocompleteViewed;
#pragma mark - Note List
+ (void)trackListNoteCreated;
+ (void)trackListNoteDeleted;
+ (void)trackListNoteOpened;
+ (void)trackListTrashEmptied;
+ (void)trackListNotesSearched;
+ (void)trackListPinToggled;
+ (void)trackListCopiedInternalLink;
+ (void)trackListTagViewed;
+ (void)trackListUntaggedViewed;
+ (void)trackTrashViewed;
#pragma mark - Preferences
+ (void)trackSettingsPinlockEnabled:(BOOL)isOn;
+ (void)trackSettingsListCondensedEnabled:(BOOL)isOn;
+ (void)trackSettingsNoteListSortMode:(NSString *)description;
+ (void)trackSettingsThemeUpdated:(NSString *)themeName;
#pragma mark - Sidebar
+ (void)trackSidebarSidebarPanned;
+ (void)trackSidebarButtonPresed;
#pragma mark - Tag List
+ (void)trackTagRowRenamed;
+ (void)trackTagRowDeleted;
+ (void)trackTagCellPressed;
+ (void)trackTagMenuRenamed;
+ (void)trackTagMenuDeleted;
+ (void)trackTagEditorAccessed;
#pragma mark - Ratings
+ (void)trackRatingsPromptSeen;
+ (void)trackRatingsAppRated;
+ (void)trackRatingsAppLiked;
+ (void)trackRatingsAppDisliked;
+ (void)trackRatingsDeclinedToRate;
+ (void)trackRatingsFeedbackScreenOpened;
+ (void)trackRatingsFeedbackSent;
+ (void)trackRatingsFeedbackDeclined;
#pragma mark - User
+ (void)trackUserAccountCreated;
+ (void)trackUserSignedIn;
+ (void)trackUserSignedOut;
#pragma mark - Login Links
+ (void)trackLoginLinkRequested;
+ (void)trackLoginLinkConfirmationSuccess;
+ (void)trackLoginLinkConfirmationFailure;
#pragma mark - WP.com Sign In
+ (void)trackWPCCButtonPressed;
+ (void)trackWPCCLoginSucceeded;
+ (void)trackWPCCLoginFailed;
#pragma mark -
+ (void)trackAutomatticEventWithName:(NSString *)name
properties:(NSDictionary *)properties;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPTracker.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 805 |
```swift
import Foundation
import SimplenoteFoundation
import SimplenoteSearch
// MARK: - NotesListController
//
class NotesListController: NSObject {
/// Main Context
///
private let viewContext: NSManagedObjectContext
/// Notes Controller
///
private lazy var notesController = ResultsController<Note>(viewContext: viewContext,
matching: state.predicateForNotes(filter: filter),
sortedBy: state.descriptorsForNotes(sortMode: sortMode))
/// Tags Controller
///
private lazy var tagsController = ResultsController<Tag>(viewContext: viewContext,
matching: state.predicateForTags(),
sortedBy: state.descriptorsForTags(),
limit: limitForTagResults)
/// Indicates the maximum number of Tag results we'll yield
///
/// - Known Issues: If new Tags are added in a second device, and sync'ed while we're in Search Mode,
/// ResultsController won't respect the limit.
///
let limitForTagResults = 5
/// FSM Current State
///
private(set) var state: NotesListState = .results {
didSet {
guard oldValue != state else {
return
}
refreshEverything()
}
}
/// Filter to be applied (whenever we're not in Search Mode)
///
var filter: NotesListFilter = .everything {
didSet {
guard oldValue != filter else {
return
}
refreshPredicates()
}
}
/// SortMode to be applied to **regular** results
///
var sortMode: SortMode = .alphabeticallyAscending {
didSet {
guard oldValue != sortMode else {
return
}
refreshSortDescriptors()
}
}
/// Callback to be executed whenever the NotesController or TagsController were updated
/// - NOTE: This only happens as long as the current state must render such entities!
///
var onBatchChanges: ((_ sectionsChangeset: ResultsSectionsChangeset, _ rowsChangeset: ResultsObjectsChangeset) -> Void)?
/// Designated Initializer
///
init(viewContext: NSManagedObjectContext) {
self.viewContext = viewContext
super.init()
startListeningToNoteEvents()
startListeningToTagEvents()
}
}
// MARK: - Public API
//
extension NotesListController {
/// Returns the Receiver's Number of Objects
///
@objc
var numberOfObjects: Int {
switch state {
case .results:
return notesController.numberOfObjects
case .searching:
return tagsController.numberOfObjects + notesController.numberOfObjects
}
}
/// Returns the Receiver's Sections
///
var sections: [NotesListSection] {
switch state {
case .results:
return [
NotesListSection(title: state.sectionTitleForNotes, objects: notesController.fetchedObjects)
]
case .searching:
return [
NotesListSection(title: state.sectionTitleForTags, objects: tagsController.fetchedObjects),
NotesListSection(title: state.sectionTitleForNotes, objects: notesController.fetchedObjects)
]
}
}
/// Returns the Object at a given IndexPath (If any!)
///
@objc(objectAtIndexPath:)
func object(at indexPath: IndexPath) -> Any? {
switch state {
case .results:
return notesController.object(at: indexPath)
case .searching where state.sectionIndexForTags == indexPath.section:
let tags = tagsController.fetchedObjects
return indexPath.row < tags.count ? tags[indexPath.row] : nil
case .searching where state.sectionIndexForNotes == indexPath.section:
let notes = notesController.fetchedObjects
return indexPath.row < notes.count ? notes[indexPath.row] : nil
default:
return nil
}
}
/// Returns the IndexPath for a given Object (If any!)
///
@objc(indexPathForObject:)
func indexPath(forObject object: Any) -> IndexPath? {
switch (state, object) {
case (.results, let note as Note):
return notesController.indexPath(forObject: note)
case (.searching, let tag as Tag):
return tagsController.fetchedObjects.firstIndex(of: tag).map { row in
IndexPath(row: row, section: state.sectionIndexForTags)
}
case (.searching, let note as Note):
return notesController.fetchedObjects.firstIndex(of: note).map { row in
IndexPath(row: row, section: state.sectionIndexForNotes)
}
default:
return nil
}
}
/// Reloads all of the FetchedObjects, as needed
///
@objc
func performFetch() {
if state.displaysNotes {
try? notesController.performFetch()
}
if state.displaysTags {
try? tagsController.performFetch()
}
}
}
// MARK: - Search API
//
extension NotesListController {
/// Sets the receiver in Search Mode
///
@objc
func beginSearch() {
// NO-OP: Initially meant for History, keeping it around for both consistency and future purposes.
}
/// Refreshes the FetchedObjects so that they match a given Keyword
///
/// - Note: Whenever the Keyword is actually empty, we'll fallback to regular results. Capisci?
///
@objc
func refreshSearchResults(keyword: String) {
let query = SearchQuery(searchText: keyword)
guard !query.isEmpty else {
state = .results
return
}
state = .searching(query: query)
}
/// Sets the receiver in "Results Mode"
///
@objc
func endSearch() {
state = .results
}
}
// MARK: - Convenience APIs
//
extension NotesListController {
/// Returns the Fetched Note with the specified SimperiumKey (if any)
///
@objc
func note(forSimperiumKey key: String) -> Note? {
return notesController.fetchedObjects.first { note in
note.simperiumKey == key
}
}
}
// MARK: - Private API: ResultsController Refreshing
//
private extension NotesListController {
func refreshPredicates() {
notesController.predicate = state.predicateForNotes(filter: filter)
tagsController.predicate = state.predicateForTags()
}
func refreshSortDescriptors() {
notesController.sortDescriptors = state.descriptorsForNotes(sortMode: sortMode)
tagsController.sortDescriptors = state.descriptorsForTags()
}
func refreshEverything() {
refreshPredicates()
refreshSortDescriptors()
performFetch()
}
}
// MARK: - Private API: Realtime Refreshing
//
private extension NotesListController {
func startListeningToNoteEvents() {
notesController.onDidChangeContent = { [weak self] (sectionsChangeset, objectsChangeset) in
self?.notifyNotesDidChange(sectionsChangeset: sectionsChangeset, objectsChangeset: objectsChangeset)
}
}
func startListeningToTagEvents() {
tagsController.onDidChangeContent = { [weak self] (sectionsChangeset, objectsChangeset) in
self?.notifyTagsDidChange(sectionsChangeset: sectionsChangeset, objectsChangeset: objectsChangeset)
}
}
/// When in Search Mode, we'll need to mix Tags + Notes. There's one slight problem: NSFetchedResultsController Is completely unaware that the
/// actual SectionIndex for Notes is (1) rather than (0). In that case we'll need to re-map Object and Section changes.
///
func notifyNotesDidChange(sectionsChangeset: ResultsSectionsChangeset, objectsChangeset: ResultsObjectsChangeset) {
guard state.displaysNotes else {
return
}
guard state.requiresNoteSectionIndexAdjustments else {
onBatchChanges?(sectionsChangeset, objectsChangeset)
return
}
let transposedSectionsChangeset = sectionsChangeset.transposed(toSection: state.sectionIndexForNotes)
let transposedObjectsChangeset = objectsChangeset.transposed(toSection: state.sectionIndexForNotes)
onBatchChanges?(transposedSectionsChangeset, transposedObjectsChangeset)
}
func notifyTagsDidChange(sectionsChangeset: ResultsSectionsChangeset, objectsChangeset: ResultsObjectsChangeset) {
guard state.displaysTags else {
return
}
onBatchChanges?(sectionsChangeset, objectsChangeset)
}
}
``` | /content/code_sandbox/Simplenote/Classes/NotesListController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,794 |
```swift
import UIKit
// MARK: - ApplicationStateProvider
//
extension UIApplication: ApplicationStateProvider {
}
extension UIApplication {
@objc
var keyWindowStatusBarHeight: CGSize {
guard let keyWindow = foregroundSceneWindows.first(where: { $0.isKeyWindow }) else {
return .zero
}
return keyWindow.windowScene?.statusBarManager?.statusBarFrame.size ?? .zero
}
/// Convenience method to return the applications window scene that's activationState is .foregroundActive
///
@objc
public var foregroundWindowScene: UIWindowScene? {
connectedScenes.first { $0.activationState == .foregroundActive } as? UIWindowScene
}
/// Convenience var to return the foreground scene's windows
///
public var foregroundSceneWindows: [UIWindow] {
foregroundWindowScene?.windows ?? []
}
/// Returns the first window from the current foregroundActive scene
///
@objc
public var foregroundWindow: UIWindow? {
foregroundWindowScene?.windows.first
}
}
extension UIApplication {
static var isRTL: Bool {
return shared.userInterfaceLayoutDirection == .rightToLeft
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIApplication+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 245 |
```swift
import Foundation
import MessageUI
import SafariServices
// MARK: - SPFeedbackManager
//
@objcMembers
class SPFeedbackManager: NSObject {
/// Ladies and gentlemen, yet another Singleton!
///
static let shared = SPFeedbackManager()
/// Let's just hide the initializer?
///
private override init() {
// NO-OP
}
/// Returns a ViewController capable of dealing with User Feedback. By default: MailComposer, and as a fallback... Safari!
///
func feedbackViewController() -> UIViewController {
guard MFMailComposeViewController.canSendMail() else {
return SFSafariViewController(url: SPCredentials.simplenoteFeedbackURL)
}
let subjectText = NSLocalizedString("Simplenote iOS Feedback", comment: "Simplenote's Feedback Email Title")
let mailViewController = MFMailComposeViewController()
mailViewController.setSubject(subjectText)
mailViewController.setToRecipients([SPCredentials.simplenoteFeedbackMail])
mailViewController.mailComposeDelegate = self
return mailViewController
}
}
// MARK: - MFMailComposeViewControllerDelegate
//
extension SPFeedbackManager: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: nil)
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPFeedbackManager.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 285 |
```swift
import UIKit
// MARK: - UIResponder
//
extension UIResponder {
private static weak var _currentFirstResponder: UIResponder?
static var currentFirstResponder: UIResponder? {
_currentFirstResponder = nil
UIApplication.shared.sendAction(#selector(UIResponder.findFirstResponder(_:)), to: nil, from: nil, for: nil)
return _currentFirstResponder
}
@objc
private func findFirstResponder(_ sender: Any) {
UIResponder._currentFirstResponder = self
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIResponder+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 100 |
```swift
import Foundation
// MARK: - UIKeyCommand
//
extension UIKeyCommand {
static var inputLeadingArrow: String {
return UIApplication.isRTL ? UIKeyCommand.inputRightArrow : UIKeyCommand.inputLeftArrow
}
static var inputTrailingArrow: String {
return UIApplication.isRTL ? UIKeyCommand.inputLeftArrow : UIKeyCommand.inputRightArrow
}
static let inputReturn = "\r"
static let inputTab = "\t"
convenience init(input: String,
modifierFlags: UIKeyModifierFlags,
action: Selector,
title: String? = nil) {
self.init(input: input, modifierFlags: modifierFlags, action: action)
if let title = title {
self.title = title
}
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIKeyCommand+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 164 |
```swift
import UIKit
// MARK: SignupVerificationViewController
//
class SignupVerificationViewController: UIViewController {
@IBOutlet private weak var iconView: UIImageView! {
didSet {
iconView.tintColor = .simplenoteTitleColor
}
}
@IBOutlet private weak var textLabel: UILabel! {
didSet {
let text = Localization.message(with: email)
textLabel.attributedText = NSMutableAttributedString(string: text,
attributes: [
.foregroundColor: UIColor.simplenoteTextColor,
.font: UIFont.preferredFont(forTextStyle: .body)
],
highlighting: email,
highlightAttributes: [
.font: UIFont.preferredFont(forTextStyle: .headline)
])
}
}
@IBOutlet private weak var footerTextView: UITextView! {
didSet {
let email = SPCredentials.simplenoteFeedbackMail
guard let emailURL = URL(string: "mailto:\(SPCredentials.simplenoteFeedbackMail)") else {
footerTextView.text = ""
return
}
footerTextView.textContainerInset = .zero
footerTextView.linkTextAttributes = [.foregroundColor: UIColor.simplenoteSecondaryTextColor]
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let text = Localization.footer(with: email)
footerTextView.attributedText = NSMutableAttributedString(string: text,
attributes: [
.foregroundColor: UIColor.simplenoteSecondaryTextColor,
.font: UIFont.preferredFont(forTextStyle: .subheadline),
.paragraphStyle: paragraphStyle
],
highlighting: email,
highlightAttributes: [
.underlineStyle: NSUnderlineStyle.single.rawValue,
.link: emailURL
])
}
}
private let email: String
init(email: String) {
self.email = email
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Localization
//
private struct Localization {
private static let messageTemplate = NSLocalizedString("Weve sent an email to %1$@. Please check your inbox and follow the instructions.", comment: "Message -> Sign up verification screen. Parameter: %1$@ - email address")
static func message(with email: String) -> String {
String(format: messageTemplate, email)
}
private static let footerTemplate = NSLocalizedString("Didn't get an email? There may already be an account associated with this email address. Contact %1$@ for help.", comment: "Footer -> Sign up verification screen. Parameter: %1$@ - support email address")
static func footer(with email: String) -> String {
String(format: footerTemplate, email)
}
}
``` | /content/code_sandbox/Simplenote/Classes/SignupVerificationViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 578 |
```objective-c
//
// TWAcitivityOpenInSafari.m
// Poster
//
// 8/17/12.
//
//
#import "SPAcitivitySafari.h"
@implementation SPAcitivitySafari
- (NSString *)activityType
{
return @"SPAcitivitySafari";
}
- (NSString *)activityTitle
{
return @"Safari";
}
- (UIImage *)activityImage {
return [UIImage imageNamed:@"button_safari"];
}
- (BOOL)canPerformWithActivityItems:(NSArray *)activityItems
{
for (NSObject *o in activityItems) {
if ([o isKindOfClass:NSURL.class]) {
return YES;
}
}
return NO;
}
- (void)prepareWithActivityItems:(NSArray *)activityItems
{
for (NSObject *o in activityItems) {
if ([o isKindOfClass:NSURL.class]) {
openURL = (NSURL *)o;
return;
}
}
}
- (void)performActivity
{
if (openURL) {
[[UIApplication sharedApplication] openURL:openURL options:@{} completionHandler:nil];
}
[self activityDidFinish:YES];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPAcitivitySafari.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 246 |
```swift
import Foundation
import UIKit
// MARK: - Simplenote's UIImage Static Methods
//
extension UIImage {
/// Returns the UIColor instance matching a given UIColorName. If any
///
@objc
static func image(name: UIImageName) -> UIImage? {
UIImage(named: name.lightAssetFilename)
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIImage+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 69 |
```objective-c
//
// NSString+Attributed.m
// Simplenote
//
// Created by Tom Witkin on 9/2/13.
//
#import "NSString+Attributed.h"
@implementation NSString (Attributed)
- (NSAttributedString *)attributedString {
return [[NSAttributedString alloc] initWithString:self];
}
- (NSMutableAttributedString *)mutableAttributedString {
return [[NSMutableAttributedString alloc] initWithString:self];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/NSString+Attributed.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 89 |
```objective-c
//
// Settings.m
// Simplenote
//
// Created by Jorge Leandro Perez on 3/16/15.
//
#import "Settings.h"
@implementation Settings
@dynamic ghostData;
@dynamic simperiumKey;
@dynamic ratings_disabled;
@dynamic minimum_events;
@dynamic minimum_interval_days;
@dynamic like_skip_versions;
@dynamic decline_skip_versions;
@dynamic dislike_skip_versions;
@end
``` | /content/code_sandbox/Simplenote/Classes/Settings.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 79 |
```objective-c
//
// UITextView+Simplenote.m
// Simplenote
//
// Created by Jorge Leandro Perez on 3/25/15.
//
#import "UITextView+Simplenote.h"
#import "NSString+Bullets.h"
#pragma mark ====================================================================================
#pragma mark NSTextView (Simplenote)
#pragma mark ====================================================================================
@implementation UITextView (Simplenote)
const int ChecklistItemLength = 3;
- (BOOL)applyAutoBulletsWithReplacementText:(NSString *)replacementText replacementRange:(NSRange)replacementRange
{
// ReplacementText must be a TAB or NewLine
if (!replacementText.isNewlineString && !replacementText.isTabString) {
return NO;
}
// Determine what kind of bullet we should insert
NSString *rawString = self.text;
NSRange lineRange = [rawString lineRangeForRange:replacementRange];
NSString *lineString = [rawString substringWithRange:lineRange];
NSString *cleanLineString = [lineString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *textAttachmentCode = @"\U0000fffc"; // Represents the glyph of an NSTextAttachment
NSArray *const bullets = @[@"*", @"+", @"-", @"", textAttachmentCode];
NSString *stringToAppendToNewLine = nil;
for (NSString *bullet in bullets) {
if ([cleanLineString hasPrefix:bullet]) {
stringToAppendToNewLine = [bullet isEqualToString:textAttachmentCode] ? @"- [ ] " : bullet;
break;
}
}
// Stop right here... if there's no bullet!
if (!stringToAppendToNewLine) {
return NO;
}
NSUInteger bulletLength = stringToAppendToNewLine.length;
BOOL isApplyingChecklist = [cleanLineString hasPrefix:textAttachmentCode];
NSInteger indexOfBullet = [lineString rangeOfString:isApplyingChecklist
? textAttachmentCode
: stringToAppendToNewLine].location;
NSRange newSelectedRange = self.selectedRange;
NSString *insertionString = nil;
NSRange insertionRange = lineRange;
// Tab entered: Move the bullet along
if (replacementText.isTabString) {
if (isApplyingChecklist) {
return NO;
}
// Proceed only if the user is entering Tab's right by the first one
// - Something
// ^
//
NSInteger const IndentationIndexDelta = 2;
if (replacementRange.location != lineRange.location + indexOfBullet + IndentationIndexDelta) {
return NO;
}
insertionString = [replacementText stringByAppendingString:lineString];
newSelectedRange.location += replacementText.length;
// Empty Line: Remove the bullet
} else if (cleanLineString.length == 1) {
insertionString = [NSString newLineString];
newSelectedRange.location -= lineRange.length - (isApplyingChecklist ? 1 : bulletLength);
// Attempt to apply the bullet
} else {
// Substring: [0 - Bullet]
if (isApplyingChecklist) {
NSRange bulletPrefixRange = NSMakeRange(0, [lineString rangeOfString:textAttachmentCode].location);
stringToAppendToNewLine = [[lineString substringWithRange:bulletPrefixRange] stringByAppendingString:stringToAppendToNewLine];
} else {
NSRange bulletPrefixRange = NSMakeRange(0, [lineString rangeOfString:stringToAppendToNewLine].location + 1);
stringToAppendToNewLine = [lineString substringWithRange:bulletPrefixRange];
}
// Do we need to append a whitespace?
if (lineRange.length > indexOfBullet + bulletLength && !isApplyingChecklist) {
unichar bulletTrailing = [lineString characterAtIndex:indexOfBullet + bulletLength];
if ([[NSCharacterSet whitespaceCharacterSet] characterIsMember:bulletTrailing]) {
NSString *trailing = [NSString stringWithFormat:@"%c", bulletTrailing];
stringToAppendToNewLine = [stringToAppendToNewLine stringByAppendingString:trailing];
}
}
// Replacement + NewRange
insertionString = [[NSString newLineString] stringByAppendingString:stringToAppendToNewLine];
insertionRange = replacementRange;
newSelectedRange.location += isApplyingChecklist ? [stringToAppendToNewLine length] - ChecklistItemLength : insertionString.length;
}
// Apply the Replacements
NSTextStorage *storage = self.textStorage;
[storage beginEditing];
[storage replaceCharactersInRange:insertionRange withString:insertionString];
[storage endEditing];
// Update the Selected Range (If needed)
[self setSelectedRange:newSelectedRange];
// Signal that the text was changed!
[self.delegate textViewDidChange:self];
// Set the capitalization type to 'Words' temporarily so that we get a capital word next to the bullet.
self.autocapitalizationType = UITextAutocapitalizationTypeWords;
[self reloadInputViews];
return YES;
}
- (NSRange)visibleTextRange
{
CGRect bounds = self.bounds;
UITextPosition *start = [self characterRangeAtPoint:bounds.origin].start;
UITextPosition *end = [self characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end;
return NSMakeRange([self offsetFromPosition:self.beginningOfDocument toPosition:start],
[self offsetFromPosition:start toPosition:end]);
}
@end
``` | /content/code_sandbox/Simplenote/Classes/UITextView+Simplenote.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,227 |
```swift
import Foundation
import SimplenoteFoundation
// MARK: - SPObjectManager
//
extension SPObjectManager {
var managedObjectContext: NSManagedObjectContext {
return SPAppDelegate.shared().managedObjectContext
}
@objc
func newDefaultNote() -> Note {
guard let note = NSEntityDescription.insertNewObject(forEntityName: Note.entityName, into: managedObjectContext) as? Note else {
fatalError()
}
note.modificationDate = Date()
note.creationDate = Date()
// Set the note's markdown tag according to the global preference (defaults NO for new accounts)
note.markdown = Options.shared.markdown
return note
}
@objc
func notesWithTag(_ tag: Tag?, includeDeleted: Bool) -> [Note] {
guard let tagName = tag?.name else {
return []
}
let request = NSFetchRequest<Note>(entityName: Note.entityName)
var predicates: [NSPredicate] = []
predicates.append(.predicateForNotes(tag: tagName))
if includeDeleted == false {
predicates.append(.predicateForNotes(deleted: includeDeleted))
}
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
return (try? managedObjectContext.fetch(request)) ?? []
}
@objc
func notesWithTag(_ tag: Tag?) -> [Note] {
return notesWithTag(tag, includeDeleted: false)
}
@objc
func newNote(withContent content: String?, tags: [String]?) -> Note {
let newNote = newDefaultNote()
if let content = content {
newNote.content = content
}
let validator = TagTextFieldInputValidator()
tags?
.compactMap({ validator.preprocessForPasting(tag: $0) })
.forEach { tag in
newNote.addTag(tag)
SPObjectManager.shared().createTag(from: tag)
}
return newNote
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPObjectManager+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 413 |
```objective-c
#import "StatusChecker.h"
#import "Note.h"
@import Simperium;
#pragma mark ================================================================================
#pragma mark Workaround: Exposing Private SPBucket methods
#pragma mark ================================================================================
@interface SPBucket ()
- (BOOL)hasLocalChangesForKey:(NSString *)key;
@end
#pragma mark ================================================================================
#pragma mark Constants
#pragma mark ================================================================================
static NSString *kEntityName = @"Note";
#pragma mark ================================================================================
#pragma mark StatusChecker
#pragma mark ================================================================================
@implementation StatusChecker
+ (BOOL)hasUnsentChanges:(Simperium *)simperium
{
if (simperium.user.authenticated == false) {
return false;
}
SPBucket *bucket = [simperium bucketForName:kEntityName];
NSArray *allNotes = [bucket allObjects];
NSDate *startDate = [NSDate date];
NSLog(@"<> Status Checker: Found %ld Entities [%f seconds elapsed]", (unsigned long)allNotes.count, startDate.timeIntervalSinceNow);
// Compare the Ghost Content string, against the Entity Content
for (Note *note in allNotes) {
if ([bucket hasLocalChangesForKey:note.simperiumKey]) {
NSLog(@"<> Status Checker: FOUND entities with local changes [%f seconds elapsed]", startDate.timeIntervalSinceNow);
return true;
}
}
NSLog(@"<> Status Checker: No entities with local changes [%f seconds elapsed]", startDate.timeIntervalSinceNow);
return false;
}
@end
``` | /content/code_sandbox/Simplenote/Classes/StatusChecker.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 303 |
```swift
import Foundation
import UIKit
// MARK: - UIFont Simplenote Helpers
//
extension UIFont {
/// Default Asset Height Multiplier
///
static let defaultInlineAssetSizeMultiplier = CGFloat(0.7)
/// Returns the (Expected) InlineAsset Height: We consider the lineHeight, and apply a (default) multiplier, to account for ascending and descending metrics.
///
func inlineAssetHeight(multiplier: CGFloat = defaultInlineAssetSizeMultiplier) -> CGFloat {
return ceil(lineHeight * multiplier)
}
/// Returns the System Font for a given Style and Weight
///
@objc
static func preferredFont(for style: TextStyle, weight: Weight) -> UIFont {
if let cachedFont = FontCache.shared.cachedFont(for: style, weight: weight) {
return cachedFont
}
let preferredFont = uncachedPreferredFont(for: style, weight: weight)
FontCache.shared.storeFont(preferredFont, style: style, weight: weight)
return preferredFont
}
///
///
private static func uncachedPreferredFont(for style: TextStyle, weight: Weight) -> UIFont {
let descriptor = UIFontDescriptor
.preferredFontDescriptor(withTextStyle: style)
.addingAttributes([.traits: [UIFontDescriptor.TraitKey.weight: weight]])
return UIFont(descriptor: descriptor, size: .zero)
}
/// Returns Italic version of the font
///
func italic() -> UIFont {
guard let descriptor = fontDescriptor.withSymbolicTraits(.traitItalic) else {
return self
}
return UIFont(descriptor: descriptor, size: .zero)
}
}
// MARK: - FontCache: Performance Helper!
//
private class FontCache {
/// Internal Cache
///
private var cache = [UIFont.TextStyle: [UIFont.Weight: UIFont]]()
/// Yes. Another Singleton!
///
static let shared = FontCache()
/// (Private) Initializer
///
private init() {
startListeningToNotifications()
}
/// Returns the stored entry for the specified Style + Weight combination (If Any!)
/// - Note: This method is, definitely, non threadsafe!
///
func cachedFont(for style: UIFont.TextStyle, weight: UIFont.Weight) -> UIFont? {
assert(Thread.isMainThread)
return cache[style]?[weight]
}
/// Stores a given UIFont instance, under the specified Style and Weight keys
/// - Note: This method is, definitely, non threadsafe!
///
func storeFont(_ font: UIFont, style: UIFont.TextStyle, weight: UIFont.Weight) {
assert(Thread.isMainThread)
var updatedStyleMap = cache[style] ?? [:]
updatedStyleMap[weight] = font
cache[style] = updatedStyleMap
}
}
// MARK: - Private Methods
//
private extension FontCache {
func startListeningToNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(contentSizeCategoryDidChange),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
@objc
func contentSizeCategoryDidChange() {
cache.removeAll()
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIFont+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 666 |
```objective-c
//
// WPAuthHandler.m
// Simplenote
// Handles oauth authentication with WordPress.com
//
#import <Foundation/Foundation.h>
#import <SafariServices/SafariServices.h>
#import "WPAuthHandler.h"
#import "SPConstants.h"
#import "SPTracker.h"
#import "Simplenote-Swift.h"
@import Simperium;
static NSString * const SPAuthSessionKey = @"SPAuthSessionKey";
@implementation WPAuthHandler
+ (BOOL)isWPAuthenticationUrl:(NSURL*)url {
return [[url host] isEqualToString:@"auth"];
}
+ (void)presentWordPressSSOFromViewController:(UIViewController *)presenter
{
NSString *sessionState = [[NSUUID UUID] UUIDString];
sessionState = [@"app-" stringByAppendingString:sessionState];
[[NSUserDefaults standardUserDefaults] setObject:sessionState forKey:SPAuthSessionKey];
NSString *requestUrl = [NSString stringWithFormat:kWordPressAuthURL, [SPCredentials wpcomClientID], [SPCredentials wpcomRedirectURL], sessionState];
NSString *encodedUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
SFSafariViewController *sfvc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:encodedUrl]];
sfvc.modalPresentationStyle = UIModalPresentationFormSheet;
[presenter presentViewController:sfvc animated:YES completion:nil];
[SPTracker trackWPCCButtonPressed];
}
+ (SPUser *)authorizeSimplenoteUserFromUrl:(NSURL*)url forAppId:(NSString *)appId {
if (url == nil || appId == nil) {
return nil;
}
NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:NO];
NSArray *queryItems = urlComponents.queryItems;
NSString *state = [self valueForKey:@"state" fromQueryItems:queryItems];
NSString *user = [self valueForKey:@"user" fromQueryItems:queryItems];
NSString *token = [self valueForKey:@"token" fromQueryItems:queryItems];
NSString *wpcomToken = [self valueForKey:@"wp_token" fromQueryItems:queryItems];
NSString *errorCode = [self valueForKey:@"code" fromQueryItems:queryItems];
if (state == nil || user == nil || token == nil) {
NSDictionary *errorInfo;
if (errorCode != nil && [errorCode isEqualToString:@"1"]) {
NSString *errorMessage = NSLocalizedString(@"Please activate your WordPress.com account via email and try again.", @"Error message displayed when user has not verified their WordPress.com account");
errorInfo = [NSDictionary dictionaryWithObject:errorMessage forKey:NSLocalizedDescriptionKey];
}
[[NSNotificationCenter defaultCenter] postNotificationName:kSignInErrorNotificationName
object:nil
userInfo:errorInfo];
[SPTracker trackWPCCLoginFailed];
return nil;
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *storedState = [defaults stringForKey:SPAuthSessionKey];
if (![state isEqualToString: storedState]) {
// States don't match!
[[NSNotificationCenter defaultCenter] postNotificationName:kSignInErrorNotificationName
object:nil];
[SPTracker trackWPCCLoginFailed];
return nil;
}
[defaults removeObjectForKey:SPAuthSessionKey];
[defaults setObject:user forKey:@"SPUsername"];
NSError *error = nil;
BOOL success = [SPKeychain setPassword:token forService:appId account:user error:&error];
if (success == NO) {
[[NSNotificationCenter defaultCenter] postNotificationName:kSignInErrorNotificationName
object:nil];
[SPTracker trackWPCCLoginFailed];
return nil;
}
// Store wpcom token for future integrations
if (wpcomToken != nil) {
[SPKeychain setPassword:token forService:kSimplenoteWPServiceName account:user error:&error];
}
SPUser *spUser = [[SPUser alloc] initWithEmail:user token:token];
return spUser;
}
+ (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate] firstObject];
return queryItem.value;
}
@end
``` | /content/code_sandbox/Simplenote/Classes/WPAuthHandler.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 904 |
```swift
import Foundation
import UIKit
import SimplenoteFoundation
// MARK: - OptionsControllerDelegate
//
protocol OptionsControllerDelegate: AnyObject {
func optionsControllerDidPressHistory(_ sender: OptionsViewController)
func optionsControllerDidPressShare(_ sender: OptionsViewController)
func optionsControllerDidPressTrash(_ sender: OptionsViewController)
}
// MARK: - OptionsViewController
//
class OptionsViewController: UIViewController {
/// Options TableView
///
@IBOutlet private var tableView: UITableView!
/// EntityObserver: Allows us to listen to changes applied to the associated entity
///
private lazy var entityObserver = EntityObserver(context: SPAppDelegate.shared().managedObjectContext, object: note)
/// Sections onScreen
///
private let sections: [Section] = [
Section(rows: [.pinToTop, .markdown, .copyInternalURL, .share, .history]),
Section(rows: [.publish, .copyPublicURL]),
Section(rows: [.collaborate]),
Section(rows: [.trash])
]
/// Indicates if we're waiting for an update. If so, we'll skip the next "Reload Interface" call that might come across
///
/// - Important:
/// Updating any of the Note Flags (Pinned, Markdown, Published) involves updating the local database.
/// Since there is no way to match an Update Request with an actual CoreData refresh event, we'll rely on this simple flag to
/// attempt to debounce multiple Switch Toggle events that might happen.
///
/// Our goal is to prevent a race condition between the user's flip action, and the remote ACK.
///
private var pendingUpdate = false
/// Note for which we'll render the current Options
///
let note: Note
/// Options Delegate
///
weak var delegate: OptionsControllerDelegate?
/// Designated Initializer
///
init(note: Note) {
self.note = note
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) is not supported!")
}
// MARK: - Overridden Methods
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationTitle()
setupNavigationItem()
setupTableView()
setupEntityObserver()
refreshStyle()
refreshInterface()
refreshPreferredSize()
}
}
// MARK: - Initialization
//
private extension OptionsViewController {
func setupNavigationTitle() {
title = NSLocalizedString("Options", comment: "Note Options Title")
}
func setupNavigationItem() {
let doneTitle = NSLocalizedString("Done", comment: "Dismisses the Note Options UI")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: doneTitle,
style: .done,
target: self,
action: #selector(doneWasPressed))
}
func setupTableView() {
tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: SwitchTableViewCell.reuseIdentifier)
tableView.register(Value1TableViewCell.self, forCellReuseIdentifier: Value1TableViewCell.reuseIdentifier)
}
func setupEntityObserver() {
entityObserver.delegate = self
}
func refreshPreferredSize() {
preferredContentSize = tableView.contentSize
}
func refreshStyle() {
view.backgroundColor = .simplenoteTableViewBackgroundColor
tableView.applySimplenoteGroupedStyle()
}
}
// MARK: - EntityObserverDelegate
//
extension OptionsViewController: EntityObserverDelegate {
func entityObserver(_ observer: EntityObserver, didObserveChanges identifiers: Set<NSManagedObjectID>) {
if pendingUpdate {
pendingUpdate = false
return
}
refreshInterface()
}
}
// MARK: - UITableViewDelegate
//
extension OptionsViewController: UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
sections.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
rowWasPressed(indexPath)
}
}
// MARK: - UITableViewDataSource
//
extension OptionsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
sections[section].rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = rowAtIndexPath(indexPath)
return dequeueAndConfigureCell(for: row, at: indexPath, in: tableView)
}
}
// MARK: - Helper API(s)
//
private extension OptionsViewController {
func refreshInterface() {
tableView.reloadData()
}
func rowAtIndexPath(_ indexPath: IndexPath) -> Row {
sections[indexPath.section].rows[indexPath.row]
}
}
// MARK: - Building Cells
//
private extension OptionsViewController {
func dequeueAndConfigureCell(for row: Row, at indexPath: IndexPath, in tableView: UITableView) -> UITableViewCell {
switch row {
case .pinToTop:
return dequeuePinToTopCell(from: tableView, at: indexPath)
case .markdown:
return dequeueMarkdownCell(from: tableView, at: indexPath)
case .copyInternalURL:
return dequeueCopyInterlinkCell(from: tableView, at: indexPath)
case .share:
return dequeueShareCell(from: tableView, at: indexPath)
case .history:
return dequeueHistoryCell(from: tableView, at: indexPath)
case .publish:
return dequeuePublishCell(from: tableView, at: indexPath)
case .copyPublicURL:
return dequeueCopyPublicURLCell(from: tableView, at: indexPath)
case .collaborate:
return dequeueCollaborateCell(from: tableView, for: indexPath)
case .trash:
return dequeueTrashCell(from: tableView, for: indexPath)
}
}
func dequeuePinToTopCell(from tableView: UITableView, at indexPath: IndexPath) -> SwitchTableViewCell {
let cell = tableView.dequeueReusableCell(ofType: SwitchTableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .pin)
cell.title = NSLocalizedString("Pin to Top", comment: "Toggles the Pinned State")
cell.enabledAccessibilityHint = NSLocalizedString("Unpin note", comment: "Pin State Accessibility Hint")
cell.disabledAccessibilityHint = NSLocalizedString("Pin note", comment: "Pin State Accessibility Hint")
cell.isOn = note.pinned
cell.onChange = { [weak self] newState in
self?.pinnedWasPressed(newState)
}
return cell
}
func dequeueMarkdownCell(from tableView: UITableView, at indexPath: IndexPath) -> SwitchTableViewCell {
let cell = tableView.dequeueReusableCell(ofType: SwitchTableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .note)
cell.title = NSLocalizedString("Markdown", comment: "Toggles the Markdown State")
cell.enabledAccessibilityHint = NSLocalizedString("Disable Markdown formatting", comment: "Markdown Accessibility Hint")
cell.disabledAccessibilityHint = NSLocalizedString("Enable Markdown formatting", comment: "Markdown Accessibility Hint")
cell.isOn = note.markdown
cell.onChange = { [weak self] newState in
self?.markdownWasPressed(newState)
}
return cell
}
func dequeueCopyInterlinkCell(from tableView: UITableView, at indexPath: IndexPath) -> Value1TableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .link)
cell.title = NSLocalizedString("Copy Internal Link", comment: "Copies the Note's Interlink")
cell.selectable = true
return cell
}
func dequeueShareCell(from tableView: UITableView, at indexPath: IndexPath) -> Value1TableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .share)
cell.title = NSLocalizedString("Share", comment: "Opens the Share Sheet")
return cell
}
func dequeueHistoryCell(from tableView: UITableView, at indexPath: IndexPath) -> Value1TableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .history)
cell.title = NSLocalizedString("History", comment: "Opens the Note's History")
return cell
}
func dequeuePublishCell(from tableView: UITableView, at indexPath: IndexPath) -> SwitchTableViewCell {
let cell = tableView.dequeueReusableCell(ofType: SwitchTableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .published)
cell.title = NSLocalizedString("Publish", comment: "Publishes a Note to the Web")
cell.enabledAccessibilityHint = NSLocalizedString("Unpublish note", comment: "Publish Accessibility Hint")
cell.disabledAccessibilityHint = NSLocalizedString("Publish note", comment: "Publish Accessibility Hint")
cell.isOn = note.published
cell.onChange = { [weak self] newState in
self?.publishWasPressed(newState)
}
return cell
}
func dequeueCopyPublicURLCell(from tableView: UITableView, at indexPath: IndexPath) -> Value1TableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
cell.imageView?.image = .image(name: .copy)
cell.title = copyLinkText(for: note)
cell.selectable = canCopyLink(to: note)
return cell
}
func dequeueCollaborateCell(from tableView: UITableView, for indexPath: IndexPath) -> Value1TableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.imageView?.image = .image(name: .collaborate)
cell.title = NSLocalizedString("Collaborate", comment: "Opens the Collaborate UI")
return cell
}
func dequeueTrashCell(from tableView: UITableView, for indexPath: IndexPath) -> Value1TableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
cell.title = NSLocalizedString("Move to Trash", comment: "Delete Action")
cell.imageView?.image = .image(name: .trash)
return cell
}
}
// MARK: - Publishing
//
extension OptionsViewController {
func canCopyLink(to note: Note) -> Bool {
note.published && note.publishURL.count > .zero
}
func copyLinkText(for note: Note) -> String {
if note.published {
return note.publishURL.isEmpty ?
NSLocalizedString("Publishing...", comment: "Indicates the Note is being published") :
NSLocalizedString("Copy Link", comment: "Copies the Note's Public Link")
}
return note.publishURL.isEmpty ?
NSLocalizedString("Copy Link", comment: "Copies the Note's Public Link") :
NSLocalizedString("Unpublishing...", comment: "Indicates the Note is being unpublished")
}
}
// MARK: - Action Handlers
//
private extension OptionsViewController {
func rowWasPressed(_ indexPath: IndexPath) {
switch rowAtIndexPath(indexPath) {
case .copyInternalURL:
copyInterlinkWasPressed()
case .share:
shareWasPressed()
case .history:
historyWasPressed()
case .copyPublicURL:
copyLinkWasPressed()
case .collaborate:
collaborateWasPressed()
case .trash:
trashWasPressed()
default:
// NO-OP: Switches are handled via closures!
break
}
}
@IBAction
func pinnedWasPressed(_ newState: Bool) {
SPTracker.trackEditorNotePinEnabled(newState)
SPObjectManager.shared().updatePinnedState(newState, note: note)
pendingUpdate = true
}
@IBAction
func markdownWasPressed(_ newState: Bool) {
SPTracker.trackEditorNoteMarkdownEnabled(newState)
Options.shared.markdown = newState
SPObjectManager.shared().updateMarkdownState(newState, note: note)
pendingUpdate = true
}
@IBAction
func copyInterlinkWasPressed() {
SPTracker.trackEditorCopiedInternalLink()
UIPasteboard.general.copyInternalLink(to: note)
NoticeController.shared.present(NoticeFactory.linkCopied())
SPTracker.trackPresentedNotice(ofType: .internalLinkCopied)
dismiss(animated: true, completion: nil)
}
@IBAction
func shareWasPressed() {
delegate?.optionsControllerDidPressShare(self)
}
@IBAction
func historyWasPressed() {
delegate?.optionsControllerDidPressHistory(self)
}
@IBAction
func publishWasPressed(_ newState: Bool) {
SPTracker.trackEditorNotePublishEnabled(newState)
let publishController = SPAppDelegate.shared().publishController
publishController.updatePublishState(for: note, to: newState)
pendingUpdate = true
}
@IBAction
func copyLinkWasPressed() {
guard canCopyLink(to: note) else {
return
}
SPTracker.trackEditorCopiedPublicLink()
UIPasteboard.general.copyPublicLink(to: note)
NoticeController.shared.present(NoticeFactory.linkCopied())
SPTracker.trackPresentedNotice(ofType: .publicLinkCopied)
dismiss(animated: true, completion: nil)
}
@IBAction
func collaborateWasPressed() {
SPTracker.trackEditorCollaboratorsAccessed()
let collaborateViewController = SPAddCollaboratorsViewController()
collaborateViewController.collaboratorDelegate = self
collaborateViewController.setup(withCollaborators: note.emailTags)
navigationController?.pushViewController(collaborateViewController, animated: true)
}
@IBAction
func trashWasPressed() {
delegate?.optionsControllerDidPressTrash(self)
}
@IBAction
func doneWasPressed() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - SPCollaboratorDelegate
//
extension OptionsViewController: SPCollaboratorDelegate {
func collaboratorViewController(_ viewController: SPAddCollaboratorsViewController, shouldAddCollaborator collaboratorEmail: String) -> Bool {
note.hasTag(collaboratorEmail) == false
}
func collaboratorViewController(_ viewController: SPAddCollaboratorsViewController, didAddCollaborator collaboratorEmail: String) {
SPObjectManager.shared().insertTagNamed(collaboratorEmail, note: note)
SPTracker.trackEditorEmailTagAdded()
}
func collaboratorViewController(_ viewController: SPAddCollaboratorsViewController, didRemoveCollaborator collaboratorEmail: String) {
SPObjectManager.shared().removeTagNamed(collaboratorEmail, note: note)
SPTracker.trackEditorEmailTagRemoved()
}
}
// MARK: - Section: Defines a TableView Section
//
private struct Section {
let rows: [Row]
}
// MARK: - TableView Rows
//
private enum Row {
case pinToTop
case markdown
case copyInternalURL
case share
case history
case publish
case copyPublicURL
case collaborate
case trash
}
``` | /content/code_sandbox/Simplenote/Classes/OptionsViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 3,111 |
```objective-c
#import <Foundation/Foundation.h>
extern NSString *const SPTransitionControllerPopGestureTriggeredNotificationName;
@protocol SPInteractiveDismissableViewController
@property (readonly) BOOL requiresFirstResponderRestorationBypass;
@end
@interface SPTransitionController : NSObject <UINavigationControllerDelegate>
- (instancetype)initWithNavigationController:(UINavigationController *)navigationController;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPTransitionController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 67 |
```objective-c
//
// NSString+Bullets.m
// Simplenote
//
// Created by Tom Witkin on 8/25/13.
//
#import "NSString+Bullets.h"
#pragma mark ====================================================================================
#pragma mark Constants
#pragma mark ====================================================================================
static NSString *const SPNewLineString = @"\n";
static NSString *const SPTabString = @"\t";
static NSString *const SPSpaceString = @" ";
#pragma mark ====================================================================================
#pragma mark NSString (Bullets)
#pragma mark ====================================================================================
@implementation NSString (Bullets)
+ (NSString *)spaceString
{
return SPSpaceString;
}
+ (NSString *)tabString
{
return SPTabString;
}
+ (NSString *)newLineString
{
return SPNewLineString;
}
- (BOOL)isNewlineString
{
return [self isEqualToString:SPNewLineString];
}
- (BOOL)isTabString
{
return [self isEqualToString:SPTabString];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/NSString+Bullets.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 205 |
```swift
import Foundation
// MARK: - NSAttributedString + AuthError Helpers
//
extension NSAttributedString {
/// Returns an Attributed String that translates a Networking Error into human friendly text.
///
/// - Parameters:
/// - statusCode: Response Status Code
/// - response: Response Body (Text)
/// - error: Request Error, if any
///
/// - Returns: An Attributed String describing a Networking Error
///
class func stringFromNetworkError(statusCode: Int, response: String?, error: Error?) -> NSAttributedString {
let statusTitle = NSAttributedString(string: Title.statusCode, attributes: Style.title)
let statusText = NSAttributedString(string: statusCode.description, attributes: Style.title)
let output = NSMutableAttributedString()
output.append(statusTitle)
output.append(string: .space)
output.append(statusText)
if let error = error {
let title = NSAttributedString(string: Title.error, attributes: Style.title)
let text = NSAttributedString(string: error.localizedDescription, attributes: Style.text)
output.append(string: .newline)
output.append(string: .newline)
output.append(title)
output.append(string: .newline)
output.append(text)
}
if let response = response {
let title = NSAttributedString(string: Title.response, attributes: Style.title)
let text = NSAttributedString(string: response, attributes: Style.text)
output.append(string: .newline)
output.append(string: .newline)
output.append(title)
output.append(string: .newline)
output.append(text)
}
return output
}
}
// MARK: - Diagnostic Title(s)
//
private enum Title {
static let statusCode = NSLocalizedString("Status Code", comment: "Title for the response's Status Code")
static let error = NSLocalizedString("Error", comment: "Error Title")
static let response = NSLocalizedString("Response", comment: "Response Title")
}
// MARK: - Text Styles
//
private enum Style {
static let title: [NSAttributedString.Key: Any] = [
.font: UIFont.preferredFont(for: .title3, weight: .semibold)
]
static let text: [NSAttributedString.Key: Any] = [
.font: UIFont.preferredFont(for: .body, weight: .regular)
]
}
``` | /content/code_sandbox/Simplenote/Classes/NSAttributedString+AuthError.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 478 |
```objective-c
//
// SPMarkdownPreviewViewController.m
// Simplenote
//
// Created by James Frost on 01/10/2015.
//
#import "SPMarkdownPreviewViewController.h"
#import "SPMarkdownParser.h"
#import "Simplenote-Swift.h"
@import WebKit;
@import SafariServices;
@interface SPMarkdownPreviewViewController () <WKNavigationDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) SPBlurEffectView *navigationBarBackground;
@property (nonatomic, strong) WKWebView *webView;
@end
@implementation SPMarkdownPreviewViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = NSLocalizedString(@"Preview", @"Title of Markdown preview screen");
[self configureNavigationBarBackground];
[self configureWebView];
[self configureLayout];
[self applyStyle];
[self displayMarkdown];
}
- (void)configureNavigationBarBackground
{
NSAssert(self.navigationBarBackground == nil, @"NavigationBarBackground was already initialized!");
self.navigationBarBackground = [SPBlurEffectView navigationBarBlurView];
}
- (void)configureWebView
{
NSAssert(self.webView == nil, @"WebView was already initialized!");
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:config];
webView.opaque = NO;
webView.allowsLinkPreview = YES;
webView.scrollView.delegate = self;
webView.navigationDelegate = self;
webView.configuration.defaultWebpagePreferences.allowsContentJavaScript = NO;
self.webView = webView;
}
- (void)configureLayout
{
NSAssert(self.webView != nil, @"WebView wasn't properly initialized!");
NSAssert(self.navigationBarBackground != nil, @"NavigationBarBackground wasn't properly initialized!");
self.webView.translatesAutoresizingMaskIntoConstraints = NO;
self.navigationBarBackground.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:self.webView];
[self.view addSubview:self.navigationBarBackground];
[NSLayoutConstraint activateConstraints:@[
[self.navigationBarBackground.topAnchor constraintEqualToAnchor:self.view.topAnchor],
[self.navigationBarBackground.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor],
[self.navigationBarBackground.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
[self.navigationBarBackground.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
]];
[NSLayoutConstraint activateConstraints:@[
[self.webView.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
[self.webView.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
[self.webView.topAnchor constraintEqualToAnchor:self.view.topAnchor],
[self.webView.bottomAnchor constraintEqualToAnchor:self.view.bottomAnchor],
]];
}
- (void)applyStyle
{
UIColor *backgroundColor = [UIColor simplenoteBackgroundColor];
self.view.backgroundColor = backgroundColor;
self.webView.backgroundColor = backgroundColor;
}
- (void)displayMarkdown
{
NSString *html = [SPMarkdownParser renderHTMLFromMarkdownString:self.markdownText];
[self.webView loadHTMLString:html
baseURL:[[NSBundle mainBundle] bundleURL]];
}
#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// Slowly Fade-In the NavigationBar's Blur
[self.navigationBarBackground adjustAlphaMatchingContentOffsetOf:scrollView];
}
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURL* targetURL = navigationAction.request.URL;
NSURL* bundleURL = NSBundle.mainBundle.bundleURL;
BOOL isAnchorURL = targetURL != nil && [targetURL.absoluteString containsString:bundleURL.absoluteString];
/// Detect scenarios such as markdown/#someInternalLink
///
if (navigationAction.navigationType != WKNavigationTypeLinkActivated || isAnchorURL) {
decisionHandler(WKNavigationActionPolicyAllow);
return;
}
if (targetURL.isSimplenoteURL) {
decisionHandler(WKNavigationActionPolicyCancel);
[[UIApplication sharedApplication] openURL:targetURL options:@{} completionHandler:nil];
return;
}
if ([WKWebView handlesURLScheme:targetURL.scheme]) {
SFSafariViewController *sfvc = [[SFSafariViewController alloc] initWithURL:targetURL];
[self presentViewController:sfvc animated:YES completion:nil];
} else {
[UIApplication.sharedApplication openURL:targetURL options:@{} completionHandler:nil];
}
decisionHandler(WKNavigationActionPolicyCancel);
}
#pragma mark - Traits
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection
{
[super traitCollectionDidChange:previousTraitCollection];
if ([previousTraitCollection hasDifferentColorAppearanceComparedToTraitCollection:self.traitCollection] == false) {
return;
}
[self displayMarkdown];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPMarkdownPreviewViewController.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,014 |
```swift
import Foundation
import CoreSpotlight
import Intents
// MARK: - AppDelegate Shortcuts Methods
//
class ShortcutsHandler: NSObject {
/// This is, gentlemen, a singleton.
///
@objc
static var shared = ShortcutsHandler()
/// Is User authenticated?
///
private var isAuthenticated: Bool {
return SPAppDelegate.shared().simperium.user?.authenticated() == true
}
/// Supported Activities
///
private let activities = [
NSUserActivity.newNoteActivity(),
NSUserActivity.launchActivity()
]
/// Removes all of the shared UserActivities, whenever the API allows.
///
@objc
func unregisterSimplenoteActivities() {
NSUserActivity.deleteAllSavedUserActivities {
// No-Op: The SDK's API... doesn't take a nil callback. Neat!
}
}
/// Handles a UserActivity instance. Returns true on success.
///
@objc
func handleUserActivity(_ userActivity: NSUserActivity) -> Bool {
guard let type = ActivityType(rawValue: userActivity.activityType) else {
return false
}
guard isAuthenticated else {
return type == .launch
}
switch type {
case .launch:
break
case .newNote, .newNoteShortcut:
SPAppDelegate.shared().presentNewNoteEditor(useSelectedTag: false)
case .openNote, .openSpotlightItem:
presentNote(for: userActivity)
case .openNoteShortcut:
presentNote(for: userActivity.interaction)
}
return true
}
}
// MARK: - Home Screen Quick Actions
//
extension ShortcutsHandler {
private var shortcutUserInfoNoteIdentifierKey: String {
return "simperium_key"
}
/// Clears home screen quick actions
///
func clearHomeScreenQuickActions() {
UIApplication.shared.shortcutItems = nil
}
/// Updates home screen quick actions in case they are empty
///
@objc
func updateHomeScreenQuickActionsIfNeeded() {
guard UIApplication.shared.shortcutItems?.isEmpty != false else {
return
}
updateHomeScreenQuickActions(with: nil)
}
/// Updates home screen quick actions
///
func updateHomeScreenQuickActions(with recentNote: Note?) {
UIApplication.shared.shortcutItems = [
searchItem,
newNoteItem,
noteItem(with: recentNote)
].compactMap({ $0 })
}
/// Handles an application shortcut
///
@objc
func handleApplicationShortcut(_ shortcut: UIApplicationShortcutItem) {
guard isAuthenticated, let type = ApplicationShortcutItemType(rawValue: shortcut.type) else {
return
}
switch type {
case .search:
SPAppDelegate.shared().presentSearch()
case .newNote:
SPAppDelegate.shared().presentNewNoteEditor(useSelectedTag: false)
case .note:
if let simperiumKey = shortcut.userInfo?[shortcutUserInfoNoteIdentifierKey] as? String {
SPAppDelegate.shared().presentNoteWithSimperiumKey(simperiumKey)
}
}
}
private var searchItem: UIApplicationShortcutItem {
let icon = UIApplicationShortcutIcon(templateImageName: UIImageName.search.lightAssetFilename)
return UIApplicationShortcutItem(type: ApplicationShortcutItemType.search.rawValue,
localizedTitle: NSLocalizedString("Search", comment: "Home screen quick action: Search"),
localizedSubtitle: nil,
icon: icon,
userInfo: nil)
}
private var newNoteItem: UIApplicationShortcutItem {
let icon = UIApplicationShortcutIcon(templateImageName: UIImageName.newNote.lightAssetFilename)
return UIApplicationShortcutItem(type: ApplicationShortcutItemType.newNote.rawValue,
localizedTitle: NSLocalizedString("New Note", comment: "Home screen quick action: New Note"),
localizedSubtitle: nil,
icon: icon,
userInfo: nil)
}
private func noteItem(with note: Note?) -> UIApplicationShortcutItem? {
guard let note = note, let simperiumKey = note.simperiumKey else {
return nil
}
let icon = UIApplicationShortcutIcon(templateImageName: UIImageName.allNotes.lightAssetFilename)
return UIApplicationShortcutItem(type: ApplicationShortcutItemType.note.rawValue,
localizedTitle: NSLocalizedString("Recent", comment: "Home screen quick action: Recent Note"),
localizedSubtitle: note.titlePreview,
icon: icon,
userInfo: [shortcutUserInfoNoteIdentifierKey: simperiumKey as NSSecureCoding])
}
}
// MARK: - Private Methods
//
private extension ShortcutsHandler {
/// Displays a Note, whenever the UniqueIdentifier is contained within a given UserActivity instance.
///
func presentNote(for userActivity: NSUserActivity) {
guard let uniqueIdentifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String else {
return
}
SPAppDelegate.shared().presentNoteWithSimperiumKey(uniqueIdentifier)
}
func presentNote(for interaction: INInteraction?) {
guard let interaction,
let activity = interaction.intentResponse?.userActivity,
let uniqueIdentifier = activity.userInfo?[IntentsConstants.noteIdentifierKey] as? String else {
return
}
SPAppDelegate.shared().presentNoteWithSimperiumKey(uniqueIdentifier)
}
}
``` | /content/code_sandbox/Simplenote/Classes/ShortcutsHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,107 |
```objective-c
//
// Settings.h
// Simplenote
//
// Created by Jorge Leandro Perez on 3/16/15.
//
#import <Simperium/SPManagedObject.h>
@interface Settings : SPManagedObject
@property (nonatomic, copy) NSString *ghostData;
@property (nonatomic, copy) NSString *simperiumKey;
@property (nonatomic, strong) NSNumber *ratings_disabled;
@property (nonatomic, strong) NSNumber *minimum_events;
@property (nonatomic, strong) NSNumber *minimum_interval_days;
@property (nonatomic, strong) NSNumber *like_skip_versions;
@property (nonatomic, strong) NSNumber *decline_skip_versions;
@property (nonatomic, strong) NSNumber *dislike_skip_versions;
@end
``` | /content/code_sandbox/Simplenote/Classes/Settings.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 147 |
```swift
import Foundation
import UIKit
extension UIAlertController {
@discardableResult @objc
func addCancelActionWithTitle(_ title: String?, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return addActionWithTitle(title, style: .cancel, handler: handler)
}
@discardableResult @objc
func addDestructiveActionWithTitle(_ title: String?, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return addActionWithTitle(title, style: .destructive, handler: handler)
}
@discardableResult @objc
func addDefaultActionWithTitle(_ title: String?, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
return addActionWithTitle(title, style: .default, handler: handler)
}
@discardableResult @objc
func addActionWithTitle(_ title: String?, style: UIAlertAction.Style, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
let action = UIAlertAction(title: title, style: style, handler: handler)
addAction(action)
return action
}
static func dismissableAlert(title: String,
message: String,
style: UIAlertController.Style = .alert) -> UIAlertController {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
alert.addCancelActionWithTitle(NSLocalizedString("Ok", comment: "Alert dismiss action"))
return alert
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIAlertController+Helpers.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 295 |
```objective-c
//
// SPEntryListViewController.h
// Simplenote
//
// Created by Tom Witkin on 8/19/13.
//
#import <UIKit/UIKit.h>
#import "SPTextField.h"
@interface SPEntryListViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate> {
UITableView *primaryTableView;
UIView *entryFieldBackground;
SPTextField *entryTextField;
UIButton *entryFieldPlusButton;
UITableView *autoCompleteTableView;
}
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSArray *autoCompleteDataSource;
@property (nonatomic) BOOL showEntryFieldPlusButton;
- (void)dismiss:(id)sender;
// sub-classes need to enter these methods
- (void)removeItemFromDataSourceAtIndexPath:(NSIndexPath *)indexPath;
- (void)processTextInField;
- (void)updateAutoCompleteMatchesForString:(NSString *)string;
- (void)updatedAutoCompleteMatches;
- (void)entryFieldPlusButtonTapped:(id)sender;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPEntryListViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 215 |
```objective-c
#import <Foundation/Foundation.h>
@class Simperium;
#pragma mark ================================================================================
#pragma mark StatusChecker
#pragma mark ================================================================================
@interface StatusChecker : NSObject
+ (BOOL)hasUnsentChanges:(Simperium *)simperium;
@end
``` | /content/code_sandbox/Simplenote/Classes/StatusChecker.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 51 |
```swift
import Foundation
// MARK: - Simplenote UserDefaults Keys
//
extension UserDefaults {
enum Key: String {
case condensedNotes = "SPCondensedNoteListPref"
case firstLaunch = "SPFirstLaunch"
case lastKnownVersion
case listSortMode
case listSortModeLegacy = "SPAlphabeticalSortPref"
case markdown = "MarkdownDefault"
case theme
case themeLegacy = "SPThemePref"
case wordPressSessionKey = "SPAuthSessionKey"
case useBiometryInsteadOfPin = "SimplenoteUseTouchID"
case accountIsLoggedIn
case useSustainerIcon
case hasMigratedSustainerPreferences
case indexNotesInSpotlight
}
}
// MARK: - Convenience Methods
//
extension UserDefaults {
/// Returns the Booolean associated with the specified Key.
///
func bool(forKey key: Key) -> Bool {
return bool(forKey: key.rawValue)
}
/// Returns the Integer (if any) associated with the specified Key.
///
func integer(forKey key: Key) -> Int {
return integer(forKey: key.rawValue)
}
/// Returns the Object (if any) associated with the specified Key.
///
func object<T>(forKey key: Key) -> T? {
return value(forKey: key.rawValue) as? T
}
/// Returns the String (if any) associated with the specified Key.
///
func string(forKey key: Key) -> String? {
return value(forKey: key.rawValue) as? String
}
/// Stores the Key/Value Pair.
///
func set<T>(_ value: T?, forKey key: Key) {
set(value, forKey: key.rawValue)
}
/// Nukes any object associated with the specified Key.
///
func removeObject(forKey key: Key) {
removeObject(forKey: key.rawValue)
}
/// Indicates if there's an entry for the specified Key.
///
func containsObject(forKey key: Key) -> Bool {
return value(forKey: key.rawValue) != nil
}
/// Subscript Accessible via our new Key type!
///
subscript<T>(key: Key) -> T? {
get {
return value(forKey: key.rawValue) as? T
}
set {
set(newValue, forKey: key.rawValue)
}
}
/// Subscript: "Type Inference Fallback". To be used whenever the type cannot be automatically inferred!
///
subscript(key: Key) -> Any? {
get {
return value(forKey: key.rawValue)
}
set {
set(newValue, forKey: key.rawValue)
}
}
}
``` | /content/code_sandbox/Simplenote/Classes/UserDefaults+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 568 |
```swift
import Foundation
import UIKit
// MARK: - Renders a customized Action Sheet
//
class SPSheetController: UIViewController {
/// Dimming Background
///
@IBOutlet private var backgroundView: UIView!
/// View containing the bottom actions
///
@IBOutlet private var actionsView: UIView!
/// Constraint attaching the Actions View to the bottom of its container
///
@IBOutlet private var actionsBottomConstraint: NSLayoutConstraint!
/// Button #0: Top Button!
///
@IBOutlet private var button0: SPSquaredButton! {
didSet {
button0.backgroundColor = .simplenoteBlue50Color
}
}
/// Button #1: Bottom Button!
///
@IBOutlet private var button1: SPSquaredButton! {
didSet {
button1.backgroundColor = .simplenoteWPBlue50Color
}
}
/// Closure to be executed whenever button0 is clicked
///
var onClickButton0: (() -> Void)?
/// Closure to be executed whenever button1 is clicked
///
var onClickButton1: (() -> Void)?
/// Designated Initializer
///
init() {
super.init(nibName: nil, bundle: nil)
modalPresentationStyle = .overCurrentContext
}
/// Required!
///
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Required Methods
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hideSubviews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
performSlideUpAnimation()
}
// MARK: - Public Methods
func present(from viewController: UIViewController) {
guard let containerView = viewController.view else {
fatalError()
}
viewController.addChild(self)
attachView(to: containerView)
}
func setTitleForButton0(title: String) {
loadViewIfNeeded()
button0.setTitle(title, for: .normal)
}
func setTitleForButton1(title: String) {
loadViewIfNeeded()
button1.setTitle(title, for: .normal)
}
}
// MARK: - Private Methods
//
private extension SPSheetController {
func attachView(to containerView: UIView) {
containerView.addSubview(view)
NSLayoutConstraint.activate([
view.leftAnchor.constraint(equalTo: containerView.leftAnchor),
view.rightAnchor.constraint(equalTo: containerView.rightAnchor),
view.topAnchor.constraint(equalTo: containerView.topAnchor),
view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])
}
func dismissWithAnimation() {
performSlideDownAnimation { _ in
self.view.removeFromSuperview()
self.removeFromParent()
}
}
}
// MARK: - Actions
//
private extension SPSheetController {
@IBAction func button0WasPressed() {
dismissWithAnimation()
onClickButton0?()
}
@IBAction func button1WasPressed() {
dismissWithAnimation()
onClickButton1?()
}
@IBAction func backgroundWasPressed() {
dismissWithAnimation()
}
}
// MARK: - Animations
//
private extension SPSheetController {
func performSlideUpAnimation(onCompletion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: UIKitConstants.animationShortDuration, delay: .zero, usingSpringWithDamping: UIKitConstants.animationTightDampening, initialSpringVelocity: .zero, options: [], animations: {
self.showSubviews()
}, completion: onCompletion)
}
func performSlideDownAnimation(onCompletion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: UIKitConstants.animationShortDuration, delay: .zero, usingSpringWithDamping: UIKitConstants.animationTightDampening, initialSpringVelocity: .zero, options: [], animations: {
self.hideSubviews()
}, completion: onCompletion)
}
func hideSubviews() {
backgroundView.alpha = UIKitConstants.alpha0_0
actionsBottomConstraint.constant = actionsView.frame.height + view.safeAreaInsets.bottom
view.layoutIfNeeded()
}
func showSubviews() {
backgroundView.alpha = UIKitConstants.alpha1_0
actionsBottomConstraint.constant = .zero
view.layoutIfNeeded()
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPSheetController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 889 |
```swift
import Foundation
// MARK: - Simplenote's Upgrade handling flows
//
class MigrationsHandler: NSObject {
/// Returns the Runtime version
///
private let runtimeVersion = Bundle.main.shortVersionString
/// Stores the last known version.
///
private var lastKnownVersion: String {
get {
UserDefaults.standard.string(forKey: .lastKnownVersion) ?? String()
}
set {
UserDefaults.standard.set(newValue, forKey: .lastKnownVersion)
}
}
/// Processes any routines required to (safely) handle App Version Upgrades.
///
@objc
func ensureUpdateIsHandled() {
guard runtimeVersion != lastKnownVersion else {
return
}
processMigrations(from: lastKnownVersion, to: runtimeVersion)
lastKnownVersion = runtimeVersion
}
}
// MARK: - Private Methods
//
private extension MigrationsHandler {
/// Handles a migration *from* a given version, *towards* a given version
///
func processMigrations(from: String, to: String) {
// NO-OP: Keeping this around for future proof!
}
}
``` | /content/code_sandbox/Simplenote/Classes/MigrationsHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 242 |
```swift
import Foundation
import CoreSpotlight
// MARK: - Simplenote's NSUserActivities
//
extension NSUserActivity {
/// Registers the Launch Activity
///
@objc
class func launchActivity() -> NSUserActivity {
let title = NSLocalizedString("Open Simplenote", comment: "Siri Suggestion to open our app")
let activity = NSUserActivity(type: .launch, title: title)
return activity
}
/// Registers the New Note Activity
///
@objc
class func newNoteActivity() -> NSUserActivity {
let title = NSLocalizedString("Create a New Note", comment: "Siri Suggestion to create a New Note")
let activity = NSUserActivity(type: .newNote, title: title)
return activity
}
/// Register the Open Note Activity
///
@objc
class func openNoteActivity(for note: Note) -> NSUserActivity? {
guard let uniqueIdentifier = note.simperiumKey, let preview = note.titlePreview else {
NSLog("Note with missing SimperiumKey!!")
return nil
}
let title = NSLocalizedString("Open \"\(preview)\"", comment: "Siri Suggestion to open a specific Note")
let activity = NSUserActivity(type: .openNote, title: title)
activity.userInfo = [CSSearchableItemActivityIdentifier: uniqueIdentifier]
return activity
}
}
``` | /content/code_sandbox/Simplenote/Classes/NSUserActivity+Shortcuts.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 302 |
```objective-c
//
// PersonTag.m
// Simplenote
//
// Created by Michael Johnston on 11-08-23.
//
#import "PersonTag.h"
@implementation PersonTag
- (instancetype)initWithName:(NSString *)aName email:(NSString *)anEmail
{
if ((self = [super init])) {
self.name = aName;
self.email = anEmail;
self.active = YES;
}
return self;
}
- (NSUInteger)hash
{
return self.name.hash + self.email.hash;
}
- (BOOL)isEqual:(id)object
{
if ([object isKindOfClass:[PersonTag class]] == false) {
return false;
}
PersonTag *second = (PersonTag *)object;
return [self.name isEqual:second.name] && [self.email isEqual:second.email];
}
- (NSComparisonResult)compareName:(PersonTag *)anotherTag
{
NSString *str1 = _name.length == 0 ? _email : _name;
NSString *str2 = anotherTag.name.length == 0 ? anotherTag.email : anotherTag.name;
return [str1 localizedCaseInsensitiveCompare:str2];
}
- (NSComparisonResult)compareEmail:(PersonTag *)anotherTag
{
return [self.email localizedCaseInsensitiveCompare:anotherTag.email];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/PersonTag.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 274 |
```swift
import Foundation
import UIKit
// MARK: - SPNoteTableViewCell
//
@objcMembers
class SPNoteTableViewCell: UITableViewCell {
/// Title Label
///
@IBOutlet private var titleLabel: UILabel!
/// Body Label
///
@IBOutlet private var bodyLabel: UILabel!
/// Note's Left Accessory ImageView
///
@IBOutlet private var accessoryLeftImageView: UIImageView!
/// Note's Right Accessory ImageView
///
@IBOutlet private var accessoryRightImageView: UIImageView!
/// Acccesory LeftImage's Height
///
@IBOutlet private var accessoryLeftImageViewHeightConstraint: NSLayoutConstraint!
/// Acccesory RightImage's Height
///
@IBOutlet private var accessoryRightImageViewHeightConstraint: NSLayoutConstraint!
/// Main text area stack view
///
@IBOutlet weak var textAreaStackView: UIStackView!
/// Separator View
///
private let separatorsView = SeparatorsView()
/// Bottom Separator Visible
///
var shouldDisplayBottomSeparator: Bool {
get {
separatorsView.bottomVisible
}
set {
separatorsView.bottomVisible = newValue
}
}
/// Left Accessory Image
///
var accessoryLeftImage: UIImage? {
get {
accessoryLeftImageView.image
}
set {
accessoryLeftImageView.image = newValue
refreshAccessoriesVisibility()
}
}
/// Left AccessoryImage's Tint
///
var accessoryLeftTintColor: UIColor? {
get {
accessoryLeftImageView.tintColor
}
set {
accessoryLeftImageView.tintColor = newValue
}
}
/// Right AccessoryImage
///
var accessoryRightImage: UIImage? {
get {
accessoryRightImageView.image
}
set {
accessoryRightImageView.image = newValue
refreshAccessoriesVisibility()
}
}
/// Right AccessoryImage's Tint
///
var accessoryRightTintColor: UIColor? {
get {
accessoryRightImageView.tintColor
}
set {
accessoryRightImageView.tintColor = newValue
}
}
/// Highlighted Keywords
/// - Note: Once the cell is fully initialized, please remember to run `refreshAttributedStrings`
///
var keywords: [String]?
/// Highlighted Keywords's Tint Color
/// - Note: Once the cell is fully initialized, please remember to run `refreshAttributedStrings`
///
var keywordsTintColor: UIColor = .simplenoteTintColor
/// Note's Title
/// - Note: Once the cell is fully initialized, please remember to run `refreshAttributedStrings`
///
var titleText: String?
/// Body's Prefix: Designed to display Dates (with a slightly different style) when appropriate.
///
var prefixText: String?
/// Note's Body
/// - Note: Once the cell is fully initialized, please remember to run `refreshAttributedStrings`
///
var bodyText: String?
/// In condensed mode we simply won't render the bodyTextView
///
var rendersInCondensedMode: Bool {
get {
bodyLabel.isHidden
}
set {
bodyLabel.isHidden = newValue
}
}
/// Returns the Preview's Fragment Padding
///
var bodyLineFragmentPadding: CGFloat {
.zero
}
/// Deinitializer
///
deinit {
NotificationCenter.default.removeObserver(self)
}
/// Designated Initializer
///
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
startListeningToNotifications()
}
// MARK: - Overridden Methods
override func awakeFromNib() {
super.awakeFromNib()
setupMargins()
setupTextViews()
setupCellSeparatorView()
refreshStyle()
refreshConstraints()
}
override func prepareForReuse() {
super.prepareForReuse()
refreshStyle()
refreshConstraints()
}
/// Refreshed the Label(s) Attributed Strings: Keywords, Bullets and the Body Prefix will be taken into consideration
///
func refreshAttributedStrings() {
refreshTitleAttributedString()
refreshBodyAttributedString()
}
/// Refreshes the Title AttributedString: We'll consider Keyword Highlight and Text Attachments (bullets)
///
private func refreshTitleAttributedString() {
titleLabel.attributedText = titleText.map {
NSAttributedString.previewString(from: $0,
font: Style.headlineFont,
textColor: Style.headlineColor,
highlighing: keywords,
highlightColor: keywordsTintColor,
paragraphStyle: Style.paragraphStyle)
}
}
/// Refreshes the Body AttributedString: We'll consider Keyword Highlight and Text Attachments (bullets)
///
/// - Note: The `prefixText`, if any, will be prepended to the BodyText
///
private func refreshBodyAttributedString() {
let bodyString = NSMutableAttributedString()
if let prefixText = prefixText {
let prefixString = NSAttributedString(string: prefixText + String.space, attributes: [
.font: Style.prefixFont,
.foregroundColor: Style.headlineColor,
.paragraphStyle: Style.paragraphStyle,
])
bodyString.append(prefixString)
}
if let suffixText = bodyText {
let suffixString = NSAttributedString.previewString(from: suffixText,
font: Style.previewFont,
textColor: Style.previewColor,
highlighing: keywords,
highlightColor: keywordsTintColor,
paragraphStyle: Style.paragraphStyle)
bodyString.append(suffixString)
}
bodyLabel.attributedText = bodyString
}
}
// MARK: - Private Methods: Initialization
//
private extension SPNoteTableViewCell {
/// Setup: Layout Margins
///
func setupMargins() {
// Note: This one affects the TableView's separatorInsets
layoutMargins = .zero
}
/// Setup: TextView
///
func setupTextViews() {
titleLabel.isAccessibilityElement = false
bodyLabel.isAccessibilityElement = false
titleLabel.numberOfLines = Style.maximumNumberOfTitleLines
titleLabel.lineBreakMode = .byWordWrapping
bodyLabel.numberOfLines = Style.maximumNumberOfBodyLines
bodyLabel.lineBreakMode = .byWordWrapping
}
private func setupCellSeparatorView() {
separatorsView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(separatorsView)
NSLayoutConstraint.activate([
separatorsView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
separatorsView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
separatorsView.topAnchor.constraint(equalTo: contentView.topAnchor),
separatorsView.leadingAnchor.constraint(equalTo: textAreaStackView.leadingAnchor)
])
contentView.sendSubviewToBack(separatorsView)
separatorsView.bottomVisible = true
}
}
// MARK: - Notifications
//
private extension SPNoteTableViewCell {
/// Wires the (related) notifications to their handlers
///
func startListeningToNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(contentSizeCatoryWasUpdated),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
/// Handles the UIContentSizeCategory.didChange Notification
///
@objc
func contentSizeCatoryWasUpdated() {
refreshConstraints()
}
}
// MARK: - Private Methods: Skinning
//
private extension SPNoteTableViewCell {
/// Refreshes the current Style current style
///
func refreshStyle() {
backgroundColor = Style.backgroundColor
let selectedView = UIView(frame: bounds)
selectedView.backgroundColor = Style.selectionColor
selectedBackgroundView = selectedView
}
/// Accessory's StackView should be aligned against the PreviewTextView's first line center
///
func refreshConstraints() {
let dimension = Style.accessoryImageDimension
accessoryLeftImageViewHeightConstraint.constant = dimension
accessoryRightImageViewHeightConstraint.constant = dimension
}
/// Refreshes Accessory ImageView(s) and StackView(s) visibility, as needed
///
func refreshAccessoriesVisibility() {
let isRightImageEmpty = accessoryRightImageView.image == nil
accessoryRightImageView.isHidden = isRightImageEmpty
}
}
// MARK: - SPNoteTableViewCell
//
extension SPNoteTableViewCell {
/// TableView's Separator Insets: Expected to align **exactly** with the label(s) Leading.
/// In order to get the TableView to fully respect this the following must be fulfilled:
///
/// 1. tableViewCell(s).layoutMargins = .zero
/// 2. tableView.layoutMargins = .zero
/// 2. tableView.separatorInsetReference = `.fromAutomaticInsets
///
/// Then, and only then, this will work ferpectly
///
@objc
static var separatorInsets: UIEdgeInsets {
let left = Style.containerInsets.left + Style.accessoryImageDimension + Style.accessoryImagePaddingRight
return UIEdgeInsets(top: .zero, left: left, bottom: .zero, right: .zero)
}
/// Returns the Height that the receiver would require to be rendered, given the current User Settings (number of preview lines).
///
/// Note: Why these calculations? why not Autosizing cells?. Well... Performance.
///
@objc
static var cellHeight: CGFloat {
let numberLines = Options.shared.numberOfPreviewLines
let lineHeight = UIFont.preferredFont(forTextStyle: .headline).lineHeight
let paddingBetweenLabels = Options.shared.condensedNotesList ? .zero : Style.outerVerticalStackViewSpacing
let insets = Style.containerInsets
let result = insets.top + paddingBetweenLabels + CGFloat(numberLines) * lineHeight + insets.bottom
return max(result.rounded(.up), Constants.minCellHeight)
}
// Ref: path_to_url
// setHighlighted gets called on press down and on setSelected. This causes the highlighting to change on press down but selection is on press up
// By only updating the highlighting if the cell is the cell is selected fixes this issue
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
if isSelected {
super.setHighlighted(highlighted, animated: animated)
}
}
}
// MARK: - Cell Styles
//
private enum Style {
/// Accessory's Dimension, based on the (current) Headline Font Size
///
static var accessoryImageDimension: CGFloat {
max(min(headlineFont.inlineAssetHeight(), accessoryImageMaximumSize), accessoryImageMinimumSize)
}
/// Accessory's Minimum Size
///
static let accessoryImageMinimumSize = CGFloat(16)
/// Accessory's Maximum Size (1.5 the asset's size)
///
static let accessoryImageMaximumSize = CGFloat(24)
/// Accessory's Right Padding
///
static let accessoryImagePaddingRight = CGFloat(6)
/// Title's Maximum Lines
///
static let maximumNumberOfTitleLines = 1
/// Body's Maximum Lines
///
static let maximumNumberOfBodyLines = 2
/// Represents the Insets applied to the container view
///
static let containerInsets = UIEdgeInsets(top: 9, left: 6, bottom: 9, right: 0)
/// Outer Vertical StackView's Spacing
///
static let outerVerticalStackViewSpacing = CGFloat(2)
/// TextView's paragraphStyle
///
static let paragraphStyle: NSParagraphStyle = {
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
return style
}()
/// Returns the Cell's Background Color
///
static var backgroundColor: UIColor {
.simplenoteBackgroundColor
}
/// Headline Color: To be applied over the first preview line
///
static var headlineColor: UIColor {
.simplenoteTextColor
}
/// Headline Font: To be applied over the first preview line
///
static var headlineFont: UIFont {
.preferredFont(forTextStyle: .headline)
}
/// Preview Color: To be applied over the preview's body (everything minus the first line)
///
static var previewColor: UIColor {
.simplenoteNoteBodyPreviewColor
}
/// Preview Font: To be applied over the preview's body (everything minus the first line)
///
static var previewFont: UIFont {
.preferredFont(forTextStyle: .subheadline)
}
/// Prefix Font: To be applied over the Body's Prefix (if any)
///
static var prefixFont: UIFont {
.preferredFont(for: .subheadline, weight: .medium)
}
/// Color to be applied over the cell upon selection
///
static var selectionColor: UIColor {
.simplenoteLightBlueColor
}
}
// MARK: - NSAttributedString Private Methods
//
private extension NSAttributedString {
/// Returns a NSAttributedString instance, stylizing the receiver with the current Highlighted Keywords + Font + Colors
///
static func previewString(from string: String,
font: UIFont,
textColor: UIColor,
highlighing keywords: [String]?,
highlightColor: UIColor,
paragraphStyle: NSParagraphStyle) -> NSAttributedString {
let output = NSMutableAttributedString(string: string, attributes: [
.font: font,
.foregroundColor: textColor,
.paragraphStyle: paragraphStyle,
])
output.processChecklists(with: textColor, sizingFont: font, allowsMultiplePerLine: true)
if let keywords = keywords, !keywords.isEmpty {
output.apply(color: highlightColor, toSubstringsMatching: keywords)
}
return output
}
}
// MARK: - Constants
//
private struct Constants {
static let minCellHeight: CGFloat = 44
}
``` | /content/code_sandbox/Simplenote/Classes/SPNoteTableViewCell.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 2,881 |
```swift
import Foundation
// MARK: - ApplicationShortcutItemType: Types of application shortcuts
//
enum ApplicationShortcutItemType: String {
case search
case newNote
case note
}
``` | /content/code_sandbox/Simplenote/Classes/ApplicationShortcutItemType.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 39 |
```swift
import Foundation
import SimplenoteEndpoints
// MARK: - SPAuthError
//
enum SPAuthError: Error {
case loginBadCredentials
case signupBadCredentials
case signupUserAlreadyExists
case network
case compromisedPassword
case unverifiedEmail
case tooManyAttempts
case generic
case requestNotFound
case invalidCode
case unknown(statusCode: Int, response: String?, error: Error?)
}
// MARK: - SPAuthError Convenience Initializers
//
extension SPAuthError {
/// Returns an AuthError matching a RemoteError (Login) Counterpart
///
init(loginRemoteError: RemoteError) {
self = SPAuthError(loginErrorCode: loginRemoteError.statusCode, response: loginRemoteError.response, error: loginRemoteError.networkError)
}
/// Returns an AuthError matching a RemoteError (Signup) Counterpart
///
init(signupRemoteError: RemoteError) {
self = SPAuthError(signupErrorCode: signupRemoteError.statusCode, response: signupRemoteError.response, error: signupRemoteError.networkError)
}
/// Returns the AuthError matching a given Simperium Login Error Code
///
init(loginErrorCode: Int, response: String?, error: Error?) {
switch loginErrorCode {
case .zero:
self = .network
case 400 where response == Constants.requestNotFound:
self = .requestNotFound
case 400 where response == Constants.invalidCode:
self = .invalidCode
case 401 where response == Constants.compromisedPassword:
self = .compromisedPassword
case 401:
self = .loginBadCredentials
case 403 where response == Constants.requiresVerification:
self = .unverifiedEmail
case 429:
self = .tooManyAttempts
default:
self = .unknown(statusCode: loginErrorCode, response: response, error: error)
}
}
/// Returns the AuthError matching a given a Signup Error Code
///
init(signupErrorCode: Int, response: String?, error: Error?) {
switch signupErrorCode {
case .zero:
self = .network
case 401:
self = .signupBadCredentials
case 409:
self = .signupUserAlreadyExists
case 429:
self = .tooManyAttempts
default:
self = .unknown(statusCode: signupErrorCode, response: response, error: error)
}
}
}
// MARK: - SPAuthError Public Methods
//
extension SPAuthError {
/// Returns the Error Title, for Alert purposes
///
var title: String {
switch self {
case .signupUserAlreadyExists:
return NSLocalizedString("Email in use", comment: "Email Taken Alert Title")
case .compromisedPassword:
return NSLocalizedString("Compromised Password", comment: "Compromised password alert title")
case .unverifiedEmail:
return NSLocalizedString("Account Verification Required", comment: "Email verification required alert title")
case .tooManyAttempts:
return NSLocalizedString("Too Many Login Attempts", comment: "Title for too many login attempts error")
default:
return NSLocalizedString("Sorry!", comment: "Authentication Error Alert Title")
}
}
/// Returns the Error Message, for Alert purposes
///
var message: String {
switch self {
case .loginBadCredentials:
return NSLocalizedString("Could not login with the provided email address and password.", comment: "Message displayed when login fails")
case .signupBadCredentials:
return NSLocalizedString("Could not create an account with the provided email address and password.", comment: "Error for bad email or password")
case .signupUserAlreadyExists:
return NSLocalizedString("The email you've entered is already associated with a Simplenote account.", comment: "Error when address is in use")
case .network:
return NSLocalizedString("The network could not be reached.", comment: "Error when the network is inaccessible")
case .compromisedPassword:
return NSLocalizedString("This password has appeared in a data breach, which puts your account at high risk of compromise. To protect your data, you'll need to update your password before being able to log in again.", comment: "error for compromised password")
case .unverifiedEmail:
return NSLocalizedString("You must verify your email before being able to login.", comment: "Error for un verified email")
case .tooManyAttempts:
return NSLocalizedString("Too many login attempts. Try again later.", comment: "Error message for too many login attempts")
case .requestNotFound:
return NSLocalizedString("Your authentication code has expired. Please request a new one", comment: "Error message for Invalid Login Code")
case .invalidCode:
return NSLocalizedString("The code you've entered is not correct. Please try again", comment: "Error message for Invalid Login Code")
default:
return NSLocalizedString("We're having problems. Please try again soon.", comment: "Generic error")
}
}
}
private struct Constants {
static let compromisedPassword = "compromised password"
static let requiresVerification = "verification required"
static let requestNotFound = "request-not-found"
static let invalidCode = "invalid-code"
}
``` | /content/code_sandbox/Simplenote/Classes/SPAuthError.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,104 |
```swift
import Foundation
import UIKit
// MARK: - UITraitCollection Simplenote Methods
//
extension UITraitCollection {
/// Returns a UITraitCollection that *only* contains the Light Interface Style. No other attribute is initialized
///
static var purelyLightTraits: UITraitCollection {
UITraitCollection(userInterfaceStyle: .light)
}
/// Returns a UITraitCollection that *only* contains the Dark Interface Style. No other attribute is initialized
///
static var purelyDarkTraits: UITraitCollection {
UITraitCollection(userInterfaceStyle: .dark)
}
}
``` | /content/code_sandbox/Simplenote/Classes/UITraitCollection+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 124 |
```swift
import Foundation
import UIKit
// MARK: - UIBezierPath Methods
//
extension UIBezierPath {
/// Returns an UIImage representation of the receiver.
///
func imageRepresentation(color: UIColor) -> UIImage {
return UIGraphicsImageRenderer(size: bounds.size).image { [unowned self] context in
self.addClip()
color.setFill()
context.fill(bounds)
}
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIBezierPath+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 84 |
```objective-c
//
// SPCollaboratorCell.h
// Simplenote
//
// Created by Tom Witkin on 7/27/13.
//
#import <UIKit/UIKit.h>
@interface SPEntryListCell : UITableViewCell {
UILabel *primaryLabel;
UILabel *secondaryLabel;
UIImageView *checkmarkImageView;
}
- (void)setupWithPrimaryText:(NSString *)primaryText secondaryText:(NSString *)secondaryText checkmarked:(BOOL)checkmarked;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPEntryListCell.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 100 |
```swift
import UIKit
// MARK: - UITextInput
//
extension UITextInput {
/// Returns NSRange from UITextRange
///
var selectedRange: NSRange? {
guard let range = selectedTextRange else { return nil }
let location = offset(from: beginningOfDocument, to: range.start)
let length = offset(from: range.start, to: range.end)
return NSRange(location: location, length: length)
}
}
``` | /content/code_sandbox/Simplenote/Classes/UITextInput+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 95 |
```swift
import UIKit
// MARK: - RoundedView
//
class RoundedView: UIView {
override var bounds: CGRect {
didSet {
guard bounds.size != oldValue.size else {
return
}
updateCornerRadius()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
}
// MARK: - Private
//
private extension RoundedView {
func configure() {
layer.masksToBounds = true
updateCornerRadius()
}
func updateCornerRadius() {
layer.cornerRadius = min(frame.height, frame.width) / 2
}
}
``` | /content/code_sandbox/Simplenote/Classes/RoundedView.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 148 |
```swift
import Foundation
// MARK: - NSString Simplenote Helpers
//
extension NSString {
/// Returns the full range of the receiver
///
@objc
var fullRange: NSRange {
NSRange(location: .zero, length: length)
}
/// Encodes the receiver as a `Tag Hash`
///
@objc
var byEncodingAsTagHash: String {
precomposedStringWithCanonicalMapping
.lowercased()
.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? self as String
}
/// Indicates if the receiver contains a valid email address
///
@objc
var isValidEmailAddress: Bool {
let predicate = NSPredicate.predicateForEmailValidation()
return predicate.evaluate(with: self)
}
}
``` | /content/code_sandbox/Simplenote/Classes/NSString+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 164 |
```objective-c
//
// SPCollaboratorCell.m
// Simplenote
//
// Created by Tom Witkin on 7/27/13.
//
#import "SPEntryListCell.h"
#import "Simplenote-Swift.h"
static CGFloat const EntryListCellSidePadding = 15;
@implementation SPEntryListCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
self.backgroundColor = [UIColor simplenoteTableViewCellBackgroundColor];
primaryLabel = [[UILabel alloc] initWithFrame:CGRectZero];
primaryLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
primaryLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
primaryLabel.textColor = [UIColor simplenoteTextColor];
[self.contentView addSubview:primaryLabel];
secondaryLabel = [[UILabel alloc] initWithFrame:CGRectZero];
secondaryLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
secondaryLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
secondaryLabel.textColor = [UIColor simplenoteTitleColor];
[self.contentView addSubview:secondaryLabel];
UIImage *checkedImage = [UIImage imageWithName:UIImageNameCheckmarkChecked];
UIImage *uncheckedImage = [UIImage imageWithName:UIImageNameCheckmarkUnchecked];
checkmarkImageView = [[UIImageView alloc] initWithImage:uncheckedImage
highlightedImage:checkedImage];
checkmarkImageView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
[checkmarkImageView setHighlighted:NO];
[checkmarkImageView sizeToFit];
[self.contentView addSubview:checkmarkImageView];
checkmarkImageView.hidden = YES;
}
return self;
}
- (void)layoutSubviews {
// vertically center primary label if secondary label has no text
CGFloat primaryLabelHeight = primaryLabel.font.lineHeight;
CGFloat secondaryLabelHeight = secondaryLabel.text.length > 0 ? secondaryLabel.font.lineHeight : 0;
CGFloat cellHeight = self.bounds.size.height;
checkmarkImageView.frame = CGRectMake(self.bounds.size.width - checkmarkImageView.bounds.size.width - EntryListCellSidePadding,
(cellHeight - checkmarkImageView.bounds.size.height) / 2.0,
checkmarkImageView.frame.size.width,
checkmarkImageView.frame.size.height);
primaryLabel.frame = CGRectMake(EntryListCellSidePadding,
(cellHeight - (primaryLabelHeight + secondaryLabelHeight)) / 2.0,
checkmarkImageView.frame.origin.x - 2 * EntryListCellSidePadding,
primaryLabelHeight);
secondaryLabel.frame = CGRectMake(EntryListCellSidePadding,
primaryLabelHeight + primaryLabel.frame.origin.y,
checkmarkImageView.frame.origin.x - 2 * EntryListCellSidePadding,
secondaryLabelHeight);
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)setupWithPrimaryText:(NSString *)primaryText secondaryText:(NSString *)secondaryText checkmarked:(BOOL)checkmarked {
primaryLabel.text = primaryText;
secondaryLabel.text = secondaryText;
checkmarkImageView.highlighted = checkmarked;
[self setNeedsLayout];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPEntryListCell.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 705 |
```swift
import UIKit
// MARK: - SPMarkdownPreviewViewController
//
extension SPMarkdownPreviewViewController {
open override var canBecomeFirstResponder: Bool {
return true
}
open override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "p",
modifierFlags: [.command, .shift],
action: #selector(keyboardToggleMarkdownPreview),
title: Localization.Shortcuts.toggleMarkdown)
]
}
@objc
private func keyboardToggleMarkdownPreview() {
SPTracker.trackShortcutToggleMarkdownPreview()
navigationController?.popViewController(animated: true)
}
}
// MARK: - Localization
//
private enum Localization {
enum Shortcuts {
static let toggleMarkdown = NSLocalizedString("Toggle Markdown", comment: "Keyboard shortcut: Toggle Markdown")
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPMarkdownPreviewViewController+Extensions.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 172 |
```objective-c
#import <UIKit/UIKit.h>
#import "SPTableViewController.h"
@interface SPSettingsViewController : SPTableViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
//Preferences
NSNumber *sortOrderPref;
NSNumber *numPreviewLinesPref;
}
@end
extern NSString *const SPAlphabeticalTagSortPref;
extern NSString *const SPSustainerAppIconName;
``` | /content/code_sandbox/Simplenote/Classes/SPSettingsViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 78 |
```swift
import Foundation
// MARK: - ApplicationStateProvider
//
protocol ApplicationStateProvider {
var applicationState: UIApplication.State { get }
}
``` | /content/code_sandbox/Simplenote/Classes/ApplicationStateProvider.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 29 |
```objective-c
#import "SPInteractiveTextStorage.h"
NSString *const SPDefaultTokenName = @"SPDefaultTokenName";
NSString *const SPHeadlineTokenName = @"SPHeadlineTokenName";
@interface SPInteractiveTextStorage ()
@property (nonatomic, strong) NSMutableAttributedString *backingStore;
@property (nonatomic, assign) BOOL dynamicTextNeedsUpdate;
@end
@implementation SPInteractiveTextStorage
- (instancetype)init
{
self = [super init];
if (self) {
_backingStore = [[NSMutableAttributedString alloc] init];
}
return self;
}
- (NSString *)string
{
return [_backingStore string];
}
- (NSDictionary *)attributesAtIndex:(NSUInteger)location effectiveRange:(NSRangePointer)range
{
return [_backingStore attributesAtIndex:location effectiveRange:range];
}
- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str
{
[self beginEditing];
[_backingStore replaceCharactersInRange:range withString:str];
[self edited:NSTextStorageEditedCharacters|NSTextStorageEditedAttributes range:range changeInLength:str.length - range.length];
_dynamicTextNeedsUpdate = YES;
[self endEditing];
}
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range
{
[self beginEditing];
[_backingStore setAttributes:attrs range:range];
[self edited:NSTextStorageEditedAttributes range:range changeInLength:0];
[self endEditing];
}
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range
{
[_backingStore addAttribute:name value:value range:range];
[self edited:NSTextStorageEditedAttributes range:range changeInLength:0];
}
- (void)performReplacementsForCharacterChangeInRange:(NSRange)changedRange
{
NSString *rawString = _backingStore.string;
NSRange extendedRange = NSUnionRange(changedRange, [rawString lineRangeForRange:NSMakeRange(NSMaxRange(changedRange), 0)]);
[self applyTokenAttributesToRange:extendedRange];
}
- (void)processEditing
{
if(_dynamicTextNeedsUpdate)
{
_dynamicTextNeedsUpdate = NO;
[self performReplacementsForCharacterChangeInRange:[self editedRange]];
}
[super processEditing];
}
- (void)applyTokenAttributesToRange:(NSRange)searchRange {
if (!self.defaultStyle || !self.headlineStyle) {
return;
}
// If the range contains the first line, make sure to set the header's attribute
if (searchRange.location == 0) {
NSString *rawString = _backingStore.string;
NSRange firstLineRange = [rawString lineRangeForRange:NSMakeRange(0, 0)];
[self addAttributes:self.headlineStyle range:firstLineRange];
NSRange remainingRange = NSMakeRange(firstLineRange.location + firstLineRange.length, searchRange.length - firstLineRange.length);
if (remainingRange.location < rawString.length && remainingRange.length <= rawString.length) {
[self addAttributes:self.defaultStyle range:remainingRange];
}
} else {
[self addAttributes:self.defaultStyle range:searchRange];
}
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPInteractiveTextStorage.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 693 |
```swift
import Foundation
import SimplenoteEndpoints
// MARK: - Notifications
//
extension NSNotification.Name {
static let magicLinkAuthWillStart = NSNotification.Name("magicLinkAuthWillStart")
static let magicLinkAuthDidSucceed = NSNotification.Name("magicLinkAuthDidSucceed")
static let magicLinkAuthDidFail = NSNotification.Name("magicLinkAuthDidFail")
}
// MARK: - MagicLinkAuthenticator
//
struct MagicLinkAuthenticator {
let authenticator: SPAuthenticator
func handle(url: URL) -> Bool {
guard AllowedHosts.all.contains(url.host) else {
return false
}
guard let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems else {
return false
}
if attemptLoginWithToken(queryItems: queryItems) {
return true
}
return attemptLoginWithAuthCode(queryItems: queryItems)
}
}
// MARK: - Private API(s)
//
private extension MagicLinkAuthenticator {
@discardableResult
func attemptLoginWithToken(queryItems: [URLQueryItem]) -> Bool {
guard let email = queryItems.base64DecodedValue(for: Constants.emailField),
let token = queryItems.value(for: Constants.tokenField),
!email.isEmpty, !token.isEmpty else {
return false
}
authenticator.authenticate(withUsername: email, token: token)
return true
}
@discardableResult
func attemptLoginWithAuthCode(queryItems: [URLQueryItem]) -> Bool {
guard let email = queryItems.base64DecodedValue(for: Constants.emailField),
let authCode = queryItems.value(for: Constants.authCodeField),
!email.isEmpty, !authCode.isEmpty
else {
return false
}
NSLog("[MagicLinkAuthenticator] Requesting SyncToken for \(email) and \(authCode)")
NotificationCenter.default.post(name: .magicLinkAuthWillStart, object: nil)
Task { @MainActor in
do {
let remote = LoginRemote()
let confirmation = try await remote.requestLoginConfirmation(email: email, authCode: authCode)
Task { @MainActor in
NSLog("[MagicLinkAuthenticator] Should auth with token \(confirmation.syncToken)")
authenticator.authenticate(withUsername: confirmation.username, token: confirmation.syncToken)
NotificationCenter.default.post(name: .magicLinkAuthDidSucceed, object: nil)
SPTracker.trackLoginLinkConfirmationSuccess()
}
} catch {
NSLog("[MagicLinkAuthenticator] Magic Link TokenExchange Error: \(error)")
NotificationCenter.default.post(name: .magicLinkAuthDidFail, object: error)
SPTracker.trackLoginLinkConfirmationFailure()
}
}
return true
}
}
// MARK: - [URLQueryItem] Helper
//
private extension Array where Element == URLQueryItem {
func value(for name: String) -> String? {
first(where: { $0.name == name })?.value
}
func base64DecodedValue(for name: String) -> String? {
guard let base64String = value(for: name),
let data = Data(base64Encoded: base64String) else {
return nil
}
return String(data: data, encoding: .utf8)
}
}
// MARK: - Constants
//
private struct AllowedHosts {
static let hostForSimplenoteSchema = "login"
static let hostForUniversalLinks = URL(string: SPCredentials.defaultEngineURL)!.host
static let all = [hostForSimplenoteSchema, hostForUniversalLinks]
}
private struct Constants {
static let emailField = "email"
static let tokenField = "token"
static let authCodeField = "auth_code"
}
``` | /content/code_sandbox/Simplenote/Classes/MagicLinkAuthenticator.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 803 |
```objective-c
//
// SPCollaboratorCompletionCell.m
// Simplenote
//
// Created by Tom Witkin on 7/27/13.
//
#import "SPEntryListAutoCompleteCell.h"
@implementation SPEntryListAutoCompleteCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
primaryLabel.font = secondaryLabel.font;
checkmarkImageView.hidden = YES;
}
return self;
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPEntryListAutoCompleteCell.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 117 |
```objective-c
#import <UIKit/UIKit.h>
@interface SPModalActivityIndicator : UIView {
CGRect boxFrame;
UIView *topView;
}
@property (nonatomic, retain) UIView *contentView;
+ (SPModalActivityIndicator *)showInWindow:(UIWindow *)window;
- (void)dismiss:(BOOL)animated completion:(void (^)())completion;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPModalActivityIndicator.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 71 |
```objective-c
//
// SPTagTextView.h
// Simplenote
//
// Created by Tom Witkin on 7/24/13.
//
#import <UIKit/UIKit.h>
#import "SPTextField.h"
@class SPTagEntryField;
@protocol SPTagEntryFieldDelegate <NSObject>
@optional
- (void)tagEntryFieldDidChange:(SPTagEntryField *)tagTextField;
@end
@interface SPTagEntryField : SPTextField
@property (nonatomic, weak) id<SPTagEntryFieldDelegate> tagDelegate;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPTagEntryField.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 114 |
```swift
import Foundation
import UIKit
// MARK: - InterlinkViewController
//
class InterlinkViewController: UIViewController {
/// Autocomplete TableView
///
@IBOutlet private var tableView: HuggableTableView!
/// Closure to be executed whenever a Note is selected. The Interlink URL will be passed along.
///
var onInsertInterlink: ((String) -> Void)?
/// Interlink Notes to be presented onScreen
///
var notes = [Note]() {
didSet {
tableView?.reloadData()
}
}
var desiredHeight: CGFloat {
return Metrics.maximumTableHeight
}
// MARK: - Overridden API(s)
override func viewDidLoad() {
super.viewDidLoad()
setupRootView()
setupTableView()
}
}
// MARK: - Initialization
//
private extension InterlinkViewController {
func setupRootView() {
view.backgroundColor = .clear
}
func setupTableView() {
tableView.register(Value1TableViewCell.self, forCellReuseIdentifier: Value1TableViewCell.reuseIdentifier)
tableView.backgroundColor = .clear
tableView.separatorColor = .simplenoteDividerColor
tableView.tableFooterView = UIView()
tableView.alwaysBounceVertical = false
tableView.minHeightConstraint.constant = Metrics.minimumTableHeight
tableView.maxHeightConstraint.constant = Metrics.maximumTableHeight
}
}
// MARK: - UITableViewDataSource
//
extension InterlinkViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// "Drops" the last separator!
.leastNonzeroMagnitude
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
notes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let note = notes[indexPath.row]
note.ensurePreviewStringsAreAvailable()
let tableViewCell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
tableViewCell.title = note.titlePreview
tableViewCell.backgroundColor = .clear
tableViewCell.separatorInset = .zero
return tableViewCell
}
}
// MARK: - UITableViewDelegate
//
extension InterlinkViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let note = notes[indexPath.row]
performInterlinkInsert(for: note)
}
}
// MARK: - Private API(s)
//
private extension InterlinkViewController {
func performInterlinkInsert(for note: Note) {
guard let markdownInterlink = note.markdownInternalLink else {
return
}
onInsertInterlink?(markdownInterlink)
}
}
// MARK: - Metrics
//
private enum Metrics {
static let defaultCellHeight = CGFloat(44)
static let maximumVisibleCells = 3.5
static let maximumTableHeight = defaultCellHeight * CGFloat(maximumVisibleCells)
static let minimumTableHeight = defaultCellHeight
}
``` | /content/code_sandbox/Simplenote/Classes/InterlinkViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 607 |
```swift
import Foundation
import UIKit
// MARK: - Simplenote's Theme
//
@objc
class SPUserInterface: NSObject {
/// Ladies and gentlemen, this is a singleton.
///
@objc
static let shared = SPUserInterface()
/// Indicates if the User Interface is in Dark Mode
///
@objc
static var isDark: Bool {
return UITraitCollection.current.userInterfaceStyle == .dark
}
/// Deinitializer
///
deinit {
stopListeningToNotifications()
}
/// Initializer
///
private override init() {
super.init()
startListeningToNotifications()
}
/// Refreshes the UI so that it matches the latest Options.theme value
///
@objc
func refreshUserInterfaceStyle() {
refreshUIKitAppearance()
refreshOverrideInterfaceStyle()
}
}
// MARK: - Private Methods
//
private extension SPUserInterface {
func startListeningToNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(refreshUserInterfaceStyle), name: .SPSimplenoteThemeChanged, object: nil)
}
func stopListeningToNotifications() {
NotificationCenter.default.removeObserver(self)
}
func refreshUIKitAppearance() {
UIBarButtonItem.refreshAppearance()
UINavigationBar.refreshAppearance()
}
func refreshOverrideInterfaceStyle() {
let window = SPAppDelegate.shared().window
window.overrideUserInterfaceStyle = Options.shared.theme.userInterfaceStyle
}
}
// MARK: - Private Theme Methods
//
private extension Theme {
var userInterfaceStyle: UIUserInterfaceStyle {
switch self {
case .light:
return .light
case .dark:
return .dark
case .system:
return .unspecified
}
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPUserInterface.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 381 |
```objective-c
//
// JSONKit+Simplenote.m
// Simplenote-iOS
//
// Created by Jorge Leandro Perez on 1/4/14.
//
#import "JSONKit+Simplenote.h"
#ifdef DEBUG
static NSJSONWritingOptions const SPJSONWritingOptions = NSJSONWritingPrettyPrinted;
#else
static NSJSONWritingOptions const SPJSONWritingOptions = 0;
#endif
@implementation NSJSONSerialization (JSONKit)
+ (NSString *)JSONStringFromObject:(id)object {
if (!object) {
return nil;
}
NSError __autoreleasing *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:object
options:SPJSONWritingOptions
error:&error];
if (error) {
NSLog(@"JSON Serialization of object %@ failed due to error %@",object, error);
return nil;
}
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
+ (id)JSONObjectWithData:(NSData *)data {
if (!data) {
return nil;
}
NSError __autoreleasing *error = nil;
id value = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(@"JSON Deserialization of data %@ failed due to error %@",data, error);
return nil;
}
return value;
}
@end
@implementation NSArray (JSONKit)
- (NSString *)JSONString {
return [NSJSONSerialization JSONStringFromObject:self];
}
@end
@implementation NSDictionary (JSONKit)
- (NSString *)JSONString {
return [NSJSONSerialization JSONStringFromObject:self];
}
@end
@implementation NSString (JSONKit)
- (id)objectFromJSONString {
NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
return [NSJSONSerialization JSONObjectWithData:data];
}
@end
@implementation NSData (JSONKit)
- (id)objectFromJSONString {
return [NSJSONSerialization JSONObjectWithData:self];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/JSONKit+Simplenote.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 429 |
```objective-c
//
// SPTextView.h
// Simplenote
//
// Created by Tom Witkin on 7/19/13.
// Created by Michael Johnston on 7/19/13.
//
#import <UIKit/UIKit.h>
@class SPInteractiveTextStorage;
@interface SPTextView : UITextView {
NSMutableArray *highlightViews;
}
/// Interactive Storage: Custom formatting over the Header.
///
@property (nonatomic, retain, nonnull) SPInteractiveTextStorage *interactiveTextStorage;
/// Indicates if the `setContentOffset:animated` API should apply our custom animation
/// - Note: We'd want to use this only for Keyboard-Animation matching purposes.
/// - Important: Apparently the superclass implementation has a special handling when `UIAutoscroll` (private class) is involved.
///
@property (nonatomic, assign) BOOL enableScrollSmoothening;
- (void)highlightRange:(NSRange)range animated:(BOOL)animated withBlock:(void (^_Nonnull)(CGRect highlightFrame))block;
- (void)clearHighlights:(BOOL)animated;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPTextView.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 215 |
```swift
import Foundation
import UIKit
// MARK: - UIColor + Studio API(s)
//
extension UIColor {
/// Initializes a new UIColor instance with a given ColorStudio value
///
convenience init(studioColor: ColorStudio, alpha: CGFloat = UIKitConstants.alpha1_0) {
self.init(hexString: studioColor.rawValue, alpha: alpha)
}
/// Initializes a new UIColor instance with a given ColorStudio Dark / Light set.
/// Note: in `iOS <13` this method will always return a UIColor matching the `Current` Interface mode
///
convenience init(lightColor: ColorStudio,
darkColor: ColorStudio,
lightColorAlpha: CGFloat = UIKitConstants.alpha1_0,
darkColorAlpha: CGFloat = UIKitConstants.alpha1_0) {
let colorProvider: (_ isDark: Bool) -> (value: ColorStudio, alpha: CGFloat) = { isDark in
if isDark {
return (darkColor, darkColorAlpha)
}
return (lightColor, lightColorAlpha)
}
self.init(dynamicProvider: { traits in
let targetColor = colorProvider(traits.userInterfaceStyle == .dark)
return UIColor(studioColor: targetColor.value, alpha: targetColor.alpha)
})
}
}
// MARK: - Simplenote colors!
//
extension UIColor {
@objc
static var simplenoteBlue10Color: UIColor {
UIColor(studioColor: .spBlue10)
}
@objc
static var simplenoteBlue30Color: UIColor {
UIColor(studioColor: .spBlue30)
}
@objc
static var simplenoteBlue50Color: UIColor {
UIColor(studioColor: .spBlue50)
}
@objc
static var simplenoteBlue60Color: UIColor {
UIColor(studioColor: .spBlue60)
}
@objc
static var simplenoteGray5Color: UIColor {
UIColor(studioColor: .gray5)
}
@objc
static var simplenoteGray10Color: UIColor {
UIColor(studioColor: .gray10)
}
@objc
static var simplenoteGray20Color: UIColor {
UIColor(studioColor: .gray20)
}
@objc
static var simplenoteGray50Color: UIColor {
UIColor(studioColor: .gray50)
}
@objc
static var simplenoteGray60Color: UIColor {
UIColor(studioColor: .gray60)
}
@objc
static var simplenoteGray80Color: UIColor {
UIColor(studioColor: .gray80)
}
@objc
static var simplenoteGray100Color: UIColor {
UIColor(studioColor: .gray100)
}
@objc
static var simplenoteRed50Color: UIColor {
UIColor(studioColor: .red50)
}
@objc
static var simplenoteRed60Color: UIColor {
UIColor(studioColor: .red60)
}
@objc
static var simplenoteWPBlue50Color: UIColor {
UIColor(studioColor: .wpBlue50)
}
@objc
static var simplenoteAutocompleteBackgroundColor: UIColor {
UIColor(lightColor: .white, darkColor: .darkGray1).withAlphaComponent(UIKitConstants.alpha0_8)
}
@objc
static var simplenoteNoteHeadlineColor: UIColor {
UIColor(lightColor: .gray100, darkColor: .gray5)
}
@objc
static var simplenoteNoteBodyPreviewColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteNotePinStatusImageColor: UIColor {
.simplenoteTintColor
}
@objc
static var simplenoteNoteShareStatusImageColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteLockBackgroundColor: UIColor {
UIColor(lightColor: .spBlue50, darkColor: .darkGray1)
}
@objc
static var simplenoteLockTextColor: UIColor {
UIColor(studioColor: .white)
}
@objc
static var simplenoteNavigationBarTitleColor: UIColor {
UIColor(lightColor: .gray100, darkColor: .white)
}
@objc
static var simplenotePlaceholderImageColor: UIColor {
UIColor(studioColor: .gray5)
}
@objc
static var simplenotePlaceholderTextColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteDisabledPlaceholderTextColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30, lightColorAlpha: 0.5, darkColorAlpha: 0.5)
}
@objc
static var simplenoteSearchBarBackgroundColor: UIColor {
UIColor(lightColor: .gray10, darkColor: .darkGray4)
}
@objc
static var simplenoteSwitchTintColor: UIColor {
UIColor(lightColor: .gray5, darkColor: .darkGray3)
}
@objc
static var simplenoteSwitchOnTintColor: UIColor {
UIColor(lightColor: .green50, darkColor: .green30)
}
@objc
static var simplenoteSecondaryActionColor: UIColor {
UIColor(studioColor: .spBlue50)
}
@objc
static var simplenoteTertiaryActionColor: UIColor {
UIColor(studioColor: .purple50)
}
@objc
static var simplenoteQuaternaryActionColor: UIColor {
UIColor(studioColor: .gray50)
}
@objc
static var simplenoteDestructiveActionColor: UIColor {
UIColor(studioColor: .red50)
}
@objc
static var simplenoteRestoreActionColor: UIColor {
UIColor(lightColor: .spYellow0, darkColor: .spYellow10)
}
@objc
static var simplenoteBackgroundColor: UIColor {
UIColor(lightColor: .white, darkColor: .black)
}
@objc
static var simplenoteCardBackgroundColor: UIColor {
UIColor(lightColor: .white, darkColor: .darkGray1)
}
@objc
static var simplenoteCardDismissButtonBackgroundColor: UIColor {
UIColor(lightColor: .gray5, darkColor: .gray70)
}
@objc
static var simplenoteCardDismissButtonHighlightedBackgroundColor: UIColor {
UIColor(lightColor: .gray10, darkColor: .gray80)
}
@objc
static var simplenoteCardDismissButtonTintColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray20)
}
@objc
static var simplenoteNavigationBarBackgroundColor: UIColor {
UIColor(lightColor: .white, darkColor: .black).withAlphaComponent(UIKitConstants.alpha0_8)
}
@objc
static var simplenoteNavigationBarModalBackgroundColor: UIColor {
UIColor(lightColor: .white, darkColor: .darkGray2).withAlphaComponent(UIKitConstants.alpha0_8)
}
@objc
static var simplenoteSortBarBackgroundColor: UIColor {
UIColor(lightColor: .spGray1, darkColor: .darkGray1).withAlphaComponent(UIKitConstants.alpha0_8)
}
@objc
static var simplenoteBackgroundPreviewColor: UIColor {
UIColor(lightColor: .white, darkColor: .darkGray1)
}
@objc
static var simplenoteModalOverlayColor: UIColor {
UIColor(studioColor: .black).withAlphaComponent(UIKitConstants.alpha0_4)
}
@objc
static var simplenoteTableViewBackgroundColor: UIColor {
UIColor(lightColor: .gray0, darkColor: .darkGray1)
}
@objc
static var simplenoteNoticeViewBackgroundColor: UIColor {
UIColor(lightColor: .spGray3, darkColor: .darkGray3)
}
@objc
static var simplenoteSustainerViewBackgroundColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .darkGray2)
}
@objc
static var simplenoteTableViewCellBackgroundColor: UIColor {
UIColor(lightColor: .white, darkColor: .darkGray2)
}
@objc
static var simplenoteTableViewHeaderBackgroundColor: UIColor {
UIColor(lightColor: .spGray2, darkColor: .darkGray2)
}
@objc
static var simplenoteWindowBackgroundColor: UIColor {
UIColor(studioColor: .black)
}
@objc
static var simplenoteDividerColor: UIColor {
UIColor(lightColor: .gray40, darkColor: .darkGray4).withAlphaComponent(UIKitConstants.alpha0_6)
}
@objc
static var simplenoteTitleColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteTextColor: UIColor {
UIColor(lightColor: .gray100, darkColor: .white)
}
@objc
static var simplenoteSecondaryTextColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteTintColor: UIColor {
UIColor(lightColor: .spBlue50, darkColor: .spBlue30)
}
@objc
static var simplenoteLightBlueColor: UIColor {
UIColor(lightColor: .spBlue5, darkColor: .darkGray3)
}
@objc
static var simplenoteRedButtonColor: UIColor {
UIColor(lightColor: .red50, darkColor: .red30)
}
@objc
static var simplenoteInteractiveTextColor: UIColor {
UIColor(lightColor: .spBlue50, darkColor: .spBlue30)
}
@objc
static var simplenoteTagViewTextColor: UIColor {
UIColor(lightColor: .gray60, darkColor: .gray5)
}
@objc
static var simplenoteTagViewPlaceholderColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteTagViewCompleteColor: UIColor {
UIColor(lightColor: .gray50, darkColor: .gray30)
}
@objc
static var simplenoteTagViewCompleteHighlightedColor: UIColor {
UIColor(lightColor: .gray30, darkColor: .gray50)
}
@objc
static var simplenoteTagViewDeletionBackgroundColor: UIColor {
UIColor(lightColor: .spBlue5, darkColor: .darkGray3)
}
@objc
static var simplenoteDisabledButtonBackgroundColor: UIColor {
UIColor(lightColor: .gray20, darkColor: .gray70)
}
@objc
static var simplenoteSliderTrackColor: UIColor {
UIColor(lightColor: .gray50,
darkColor: .gray50,
lightColorAlpha: UIKitConstants.alpha0_2,
darkColorAlpha: UIKitConstants.alpha0_4)
}
@objc
static var simplenoteDimmingColor: UIColor {
UIColor.black.withAlphaComponent(UIKitConstants.alpha0_1)
}
@objc
static var simplenoteEditorSearchHighlightTextColor: UIColor {
UIColor(studioColor: .white)
}
@objc
static var simplenoteEditorSearchHighlightColor: UIColor {
UIColor(lightColor: .spBlue5,
darkColor: .spBlue50,
lightColorAlpha: UIKitConstants.alpha1_0,
darkColorAlpha: UIKitConstants.alpha0_5)
}
@objc
static var simplenoteEditorSearchHighlightSelectedColor: UIColor {
UIColor(lightColor: .spBlue50,
darkColor: .spBlue50)
}
static var simplenoteLockScreenBackgroudColor: UIColor {
return UIColor(studioColor: .spBlue50)
}
static var simplenoteLockScreenButtonColor: UIColor {
return UIColor(studioColor: .spBlue40)
}
static var simplenoteLockScreenHighlightedButtonColor: UIColor {
return UIColor(studioColor: .spBlue20)
}
static var simplenoteLockScreenMessageColor: UIColor {
return UIColor(studioColor: .spBlue5)
}
static var simplenoteVerificationScreenBackgroundColor: UIColor {
return UIColor(lightColor: .white, darkColor: .darkGray2)
}
static var simplenoteTagPillBackgroundColor: UIColor {
return UIColor(lightColor: .gray5, darkColor: .gray60)
}
static var simplenoteTagPillDeleteBackgroundColor: UIColor {
return UIColor(lightColor: .gray50, darkColor: .gray20)
}
static var simplenoteTagPillTextColor: UIColor {
return UIColor(lightColor: .gray100, darkColor: .white)
}
static var simplenoteWidgetBackgroundColor: UIColor {
return UIColor(lightColor: .white, darkColor: .darkGray1)
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIColor+Studio.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 2,882 |
```swift
import Foundation
import UIKit
// MARK: - UIGestureRecognizer Simplenote Methods
//
extension UIGestureRecognizer {
/// Forgive me: this is the only known way (AFAIK) to force a recognizer to fail. Seen in WWDC 2014 (somewhere), and a better way is yet to be found.
///
@objc
func fail() {
isEnabled = false
isEnabled = true
}
/// Translates the receiver's location into a Character Index within the specified TextView
///
@objc(characterIndexInTextView:)
func characterIndex(in textView: UITextView) -> Int {
var locationInContainer = location(in: textView)
locationInContainer.x -= textView.textContainerInset.left
locationInContainer.y -= textView.textContainerInset.top
return textView.layoutManager.characterIndex(for: locationInContainer,
in: textView.textContainer,
fractionOfDistanceBetweenInsertionPoints: nil)
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIGestureRecognizer+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 199 |
```swift
import UIKit
// MARK: - Keyboard shortcuts
//
extension SPSidebarContainerViewController {
open override var canBecomeFirstResponder: Bool {
return true
}
open override var keyCommands: [UIKeyCommand]? {
guard presentedViewController == nil else {
return nil
}
var commands: [UIKeyCommand] = []
if !noteListIsEditing() {
commands.append(UIKeyCommand(input: "n", modifierFlags: [.command], action: #selector(keyboardCreateNewNote), title: Localization.Shortcuts.newNote))
commands.append(UIKeyCommand(input: "f", modifierFlags: [.command, .shift], action: #selector(keyboardStartSearching), title: Localization.Shortcuts.search))
}
let currentFirstResponder = UIResponder.currentFirstResponder
if !(currentFirstResponder is UITextView) &&
!(currentFirstResponder is UITextField) {
commands.append(UIKeyCommand(input: UIKeyCommand.inputLeadingArrow, modifierFlags: [], action: #selector(keyboardGoBack)))
}
return commands
}
@objc
private func keyboardGoBack() {
if isSidebarVisible {
hideSidebar(withAnimation: true)
return
}
if let mainViewController = mainViewController as? UINavigationController, mainViewController.viewControllers.count > 1 {
mainViewController.popViewController(animated: true)
return
}
showSidebar()
}
private func noteListIsEditing() -> Bool {
return SPAppDelegate.shared().noteListViewController.isEditing
}
@objc
private func keyboardStartSearching() {
SPTracker.trackShortcutSearch()
SPAppDelegate.shared().presentSearch(animated: true)
}
@objc
private func keyboardCreateNewNote() {
SPTracker.trackShortcutCreateNote()
SPAppDelegate.shared().presentNewNoteEditor(animated: true)
}
}
private enum Localization {
enum Shortcuts {
static let search = NSLocalizedString("Search", comment: "Keyboard shortcut: Search")
static let newNote = NSLocalizedString("New Note", comment: "Keyboard shortcut: New Note")
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPSidebarViewController+Extensions.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 432 |
```objective-c
//
// UIImage+Colorization.h
//
// Created by Tom Witkin on 1/13/13.
//
#import <UIKit/UIKit.h>
@interface UIImage (Colorization)
- (UIImage *)imageWithOverlayColor:(UIColor *)color;
@end
``` | /content/code_sandbox/Simplenote/Classes/UIImage+Colorization.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 54 |
```objective-c
//
// SPMarkdownPreviewViewController.h
// Simplenote
//
// Created by James Frost on 01/10/2015.
//
#import <UIKit/UIKit.h>
#import "SPInteractivePushPopAnimationController.h"
/**
* @class SPMarkdownPreviewViewController
* @brief Displays Markdown text rendered as HTML in a web view.
*/
@interface SPMarkdownPreviewViewController : UIViewController <SPInteractivePushViewControllerContent>
/// Markdown text to render as HTML
@property (nonatomic, copy) NSString *markdownText;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPMarkdownPreviewViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 118 |
```swift
import UIKit
// MARK: - SortModePickerViewController
//
class SortModePickerViewController: UIViewController {
@IBOutlet private weak var tableView: HuggableTableView! {
didSet {
tableView.register(Value1TableViewCell.self, forCellReuseIdentifier: Value1TableViewCell.reuseIdentifier)
tableView.separatorColor = .simplenoteDividerColor
tableView.tableFooterView = UIView()
tableView.alwaysBounceVertical = false
tableView.backgroundColor = .clear
}
}
private let data: [SortMode] = [
.alphabeticallyAscending,
.alphabeticallyDescending,
.createdNewest,
.createdOldest,
.modifiedNewest,
.modifiedOldest
]
private let currentSelection: SortMode
/// Called when row is selected
///
var onSelectionCallback: ((SortMode) -> Void)?
init(currentSelection: SortMode) {
self.currentSelection = currentSelection
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
}
}
// MARK: - UITableViewDelegate
//
extension SortModePickerViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
onSelectionCallback?(data[indexPath.row])
}
}
// MARK: - UITableViewDataSource
//
extension SortModePickerViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(ofType: Value1TableViewCell.self, for: indexPath)
let sortMode = data[indexPath.row]
cell.accessoryType = sortMode == currentSelection ? .checkmark : .none
cell.tintColor = .simplenoteTextColor
cell.title = sortMode.description
cell.hasClearBackground = true
cell.separatorInset = .zero
return cell
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
// "Drops" the last separator!
.leastNonzeroMagnitude
}
}
``` | /content/code_sandbox/Simplenote/Classes/SortModePickerViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 486 |
```objective-c
#import <UIKit/UIKit.h>
@interface SPInteractiveTextStorage : NSTextStorage
@property (nonatomic, copy) NSDictionary<NSAttributedStringKey, id> *defaultStyle;
@property (nonatomic, copy) NSDictionary<NSAttributedStringKey, id> *headlineStyle;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPInteractiveTextStorage.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 53 |
```swift
import Foundation
@objc extension NSString {
var count: Int {
let aString = self as String
return aString.count
}
var charCount: Int {
let aString = self as String
var result = 0
for char in aString {
if !CharacterSet.newlines.contains(char.unicodeScalars.first!) {
result += 1
}
}
return result
}
var wordCount: Int {
guard length>0 else {
return 0
}
let ChineseCharacterSet = CharacterSet.CJKUniHan.union(CharacterSet.Hiragana).union(CharacterSet.Katakana)
var result = 0
enumerateSubstrings(in: NSMakeRange(0, length), options: [.byWords, .localized]) { (substring, substringRange, enclosingRange, stop) in
if ChineseCharacterSet.contains(substring!.unicodeScalars.first!) {
result += substring!.count
} else if !CharacterSet.whitespacesAndNewlines.contains(substring!.unicodeScalars.first!) { // Sometimes NSString treat "\n" and " " as a word.
result += 1
}
}
return result
}
}
extension CharacterSet {
// Chinese characters in Unicode 5.0
static var CJKUniHanBasic: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0x4E00))!...UnicodeScalar(UInt32(0x9FBB))!)
}
static var CJKUniHanExA: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0x3400))!...UnicodeScalar(UInt32(0x4DB5))!)
}
static var CJKUniHanExB: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0x20000))!...UnicodeScalar(UInt32(0x2A6D6))!)
}
static var CJKUniHanCompatibility1: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0xF900))!...UnicodeScalar(UInt32(0xFA2D))!)
}
static var CJKUniHanCompatibility2: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0xFA30))!...UnicodeScalar(UInt32(0xFA6A))!)
}
static var CJKUniHanCompatibility3: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0xFA70))!...UnicodeScalar(UInt32(0xFAD9))!)
}
static var CJKUniHanCompatibility4: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0x2F800))!...UnicodeScalar(UInt32(0x2FA1D))!)
}
static var CJKUniHan: CharacterSet {
return CJKUniHanBasic.union(CJKUniHanExA).union(CJKUniHanExB).union(CJKUniHanCompatibility1).union(CJKUniHanCompatibility2).union(CJKUniHanCompatibility3).union(CJKUniHanCompatibility4)
}
// Japanese Hiraganas and Katakanas
static var Hiragana: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0x3040))!...UnicodeScalar(UInt32(0x309f))!)
}
static var Katakana: CharacterSet {
return CharacterSet(charactersIn: UnicodeScalar(UInt32(0x30A0))!...UnicodeScalar(UInt32(0x30ff))!).union(CharacterSet(charactersIn: UnicodeScalar(UInt32(0x31f0))!...UnicodeScalar(UInt32(0x31ff))!)
)
}
// gets all characters from a CharacterSet. Only for testing.
var characters: [UnicodeScalar] {
var chars = [UnicodeScalar]()
for plane: UInt8 in 0...16 {
if self.hasMember(inPlane: plane) {
let p0 = UInt32(plane) << 16
let p1 = (UInt32(plane) + 1) << 16
for c: UInt32 in p0..<p1 {
if let us = UnicodeScalar(c) {
if self.contains(us) {
chars.append(us)
}
}
}
}
}
return chars
}
}
``` | /content/code_sandbox/Simplenote/Classes/NSString+Count.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 932 |
```objective-c
//
// SPAutomatticTracker.h
// Simplenote
//
// Created by Jorge Leandro Perez on 10/9/15.
//
#import <Foundation/Foundation.h>
/**
* @class SPAutomatticTracker
* @brief The purpose of this class is to encapsulate all of the interaction required with A8C's Tracks.
*/
@interface SPAutomatticTracker : NSObject
+ (instancetype)sharedInstance;
/**
* @details Refreshes the Tracker's metadata
* @param email The user's email account
*/
- (void)refreshMetadataWithEmail:(NSString *)email;
/**
* @details Refreshes the Tracker's metadata
*/
- (void)refreshMetadataForAnonymousUser;
/**
* @details Tracks a given event
* @param name The name of the event that should be tracked
* @param properties Optional collection of values, to be passed along
*/
- (void)trackEventWithName:(NSString *)name properties:(NSDictionary *)properties;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPAutomatticTracker.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 224 |
```swift
import Foundation
import UIKit
// MARK: - Dynamic Images
//
extension UIImage {
/// Returns the SearchBar Background Image
///
class var searchBarBackgroundImage: UIImage {
let tintColor = UIColor.simplenoteSearchBarBackgroundColor.withAlphaComponent(SearchBackgroundMetrics.alpha)
let path = UIBezierPath(roundedRect: SearchBackgroundMetrics.rect, cornerRadius: SearchBackgroundMetrics.radius)
return path.imageRepresentation(color: tintColor)
}
}
// MARK: - Constants
//
private enum SearchBackgroundMetrics {
static let alpha = CGFloat(0.3)
static let radius = CGFloat(10)
static let rect = CGRect(x: 0, y: 0, width: 16, height: 36)
}
``` | /content/code_sandbox/Simplenote/Classes/UIImage+Dynamic.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 156 |
```objective-c
#import "SPSettingsViewController.h"
#import "SPAppDelegate.h"
#import "SPConstants.h"
#import "StatusChecker.h"
#import "SPTracker.h"
#import "SPDebugViewController.h"
#import "Simplenote-Swift.h"
#import "Simperium+Simplenote.h"
NSString *const SPAlphabeticalTagSortPref = @"SPAlphabeticalTagSortPref";
NSString *const SPThemePref = @"SPThemePref";
NSString *const SPSustainerAppIconName = @"AppIcon-Sustainer";
@interface SPSettingsViewController ()
@property (nonatomic, strong) UISwitch *condensedNoteListSwitch;
@property (nonatomic, strong) UISwitch *alphabeticalTagSortSwitch;
@property (nonatomic, strong) UISwitch *biometrySwitch;
@property (nonatomic, strong) UISwitch *sustainerIconSwitch;
@property (nonatomic, strong) UITextField *pinTimeoutTextField;
@property (nonatomic, strong) UIPickerView *pinTimeoutPickerView;
@property (nonatomic, strong) UIToolbar *doneToolbar;
@property (nonatomic, strong) UISwitch *indexNotesSwitch;
@end
@implementation SPSettingsViewController {
NSArray *timeoutPickerOptions;
}
#define kTagNoteListSort 1
#define kTagTagsListSort 2
#define kTagCondensedNoteList 3
#define kTagTheme 4
#define kTagPasscode 5
#define kTagTimeout 6
#define kTagTouchID 7
#define kTagSustainerIcon 8
#define kTagIndexNotes 9
typedef NS_ENUM(NSInteger, SPOptionsViewSections) {
SPOptionsViewSectionsNotes = 0,
SPOptionsViewSectionsTags = 1,
SPOptionsViewSectionsAppearance = 2,
SPOptionsViewSectionsSecurity = 3,
SPOptionsViewSectionsAccount = 4,
SPOptionsViewSectionsDelete = 5,
SPOptionsViewSectionsAbout = 6,
SPOptionsViewSectionsHelp = 7,
SPOptionsViewSectionsDebug = 8,
SPOptionsViewSectionsCount = 9,
};
typedef NS_ENUM(NSInteger, SPOptionsAccountRow) {
SPOptionsAccountRowDescription = 0,
SPOptionsAccountRowPrivacy = 1,
SPOptionsAccountRowLogout = 2,
SPOptionsAccountRowCount = 3
};
typedef NS_ENUM(NSInteger, SPOptionsNotesRow) {
SPOptionsPreferencesRowSort = 0,
SPOptionsPreferencesRowCondensed = 1,
SPOptionsPreferencesRowIndexNotes = 2,
SPOptionsNotesRowCount = 3
};
typedef NS_ENUM(NSInteger, SPOptionsTagsRow) {
SPOptionsPreferencesRowTagSort = 0,
SPOptionsTagsRowCount = 1
};
typedef NS_ENUM(NSInteger, SPOptionsAppearanceRow) {
SPOptionsPreferencesRowTheme = 0,
SPOptionsAccountSustainerIcon = 1,
SPOptionsAppearanceRowCount = 2
};
typedef NS_ENUM(NSInteger, SPOptionsSecurityRow) {
SPOptionsSecurityRowRowPasscode = 0,
SPOptionsSecurityRowRowBiometry = 1,
SPOptionsSecurityRowTimeout = 2,
SPOptionsSecurityRowRowCount = 3
};
typedef NS_ENUM(NSInteger, SPOptionsDeleteRow) {
SPOptionsDeleteRowTitle = 0,
SPOptionsDeleteRowCount = 1
};
typedef NS_ENUM(NSInteger, SPOptionsAboutRow) {
SPOptionsAboutRowTitle = 0,
SPOptionsAboutRowCount = 1
};
typedef NS_ENUM(NSInteger, SPOptionsHelpRow) {
SPOptionsHelpRowTitle = 0,
SPOptionsHelpRowCount = 1
};
typedef NS_ENUM(NSInteger, SPOptionsDebugRow) {
SPOptionsDebugRowStats = 0,
SPOptionsDebugRowCount = 1
};
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype)initWithStyle:(UITableViewStyle)style
{
if (self = [super initWithStyle:UITableViewStyleGrouped])
{
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
timeoutPickerOptions = @[NSLocalizedString(@"Off", @"Instant passcode lock timeout"),
NSLocalizedString(@"15 Seconds", @"15 seconds passcode lock timeout"),
NSLocalizedString(@"30 Seconds", @"30 seconds passcode lock timeout"),
NSLocalizedString(@"1 Minute", @"1 minute passcode lock timeout"),
NSLocalizedString(@"2 Minutes", @"2 minutes passcode lock timeout"),
NSLocalizedString(@"3 Minutes", @"3 minutes passcode lock timeout"),
NSLocalizedString(@"4 Minutes", @"4 minutes passcode lock timeout"),
NSLocalizedString(@"5 Minutes", @"5 minutes passcode lock timeout")];
self.navigationController.navigationBar.translucent = YES;
self.navigationItem.title = NSLocalizedString(@"Settings", @"Title of options screen");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(doneAction:)];
// Setup the Switches
self.alphabeticalTagSortSwitch = [UISwitch new];
[self.alphabeticalTagSortSwitch addTarget:self
action:@selector(tagSortSwitchDidChangeValue:)
forControlEvents:UIControlEventValueChanged];
self.condensedNoteListSwitch = [UISwitch new];
[self.condensedNoteListSwitch addTarget:self
action:@selector(condensedSwitchDidChangeValue:)
forControlEvents:UIControlEventValueChanged];
self.indexNotesSwitch = [UISwitch new];
[self.indexNotesSwitch addTarget:self
action:@selector(indexNotesSwitchDidChangeValue:)
forControlEvents:UIControlEventValueChanged];
self.biometrySwitch = [UISwitch new];
[self.biometrySwitch addTarget:self
action:@selector(touchIdSwitchDidChangeValue:)
forControlEvents:UIControlEventValueChanged];
self.sustainerIconSwitch = [UISwitch new];
[self.sustainerIconSwitch addTarget:self
action:@selector(sustainerSwitchDidChangeValueWithSender:)
forControlEvents:UIControlEventValueChanged];
[self.sustainerIconSwitch setOn: [NSUserDefaults.standardUserDefaults boolForKey:@"useSustainerIcon"]];
self.pinTimeoutPickerView = [UIPickerView new];
self.pinTimeoutPickerView.delegate = self;
self.pinTimeoutPickerView.dataSource = self;
[self.pinTimeoutPickerView selectRow:[[NSUserDefaults standardUserDefaults] integerForKey:kPinTimeoutPreferencesKey] inComponent:0 animated:NO];
self.doneToolbar = [UIToolbar new];
self.doneToolbar.barStyle = UIBarStyleDefault;
self.doneToolbar.translucent = NO;
[self.doneToolbar sizeToFit];
UIBarButtonItem *doneButtonItem = [[UIBarButtonItem alloc] initWithTitle: NSLocalizedString(@"Done", @"Done toolbar button") style:UIBarButtonItemStylePlain target:self action:@selector(pinTimeoutDoneAction:)];
UIBarButtonItem *fixedSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
fixedSpace.width = self.doneToolbar.frame.size.width;
[self.doneToolbar setItems:[NSArray arrayWithObjects:fixedSpace, doneButtonItem, nil]];
self.pinTimeoutTextField = [UITextField new];
self.pinTimeoutTextField.frame = CGRectMake(0, 0, 0, 0);
self.pinTimeoutTextField.inputView = self.pinTimeoutPickerView;
self.pinTimeoutTextField.inputAccessoryView = self.doneToolbar;
[self.view addSubview:self.pinTimeoutTextField];
// Listen to Notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(themeDidChange)
name:SPSimplenoteThemeChangedNotification
object:nil];
[self refreshThemeStyles];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView reloadData];
}
- (void)doneAction:(id)sender
{
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Notifications
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#if INTERNAL_DISTRIBUTION
return SPOptionsViewSectionsCount;
#else
return SPOptionsViewSectionsCount - 1;
#endif
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section) {
case SPOptionsViewSectionsNotes: {
return SPOptionsNotesRowCount;
}
case SPOptionsViewSectionsTags: {
return SPOptionsTagsRowCount;
}
case SPOptionsViewSectionsAppearance: {
return self.showSustainerSwitch ? SPOptionsAppearanceRowCount : SPOptionsAppearanceRowCount - 1;
}
case SPOptionsViewSectionsSecurity: {
int rowsToRemove = [self isBiometryAvailable] ? 0 : 1;
int disabledPinLockRows = [self isBiometryAvailable] ? 2 : 1;
return [self isPinLockEnabled] ? SPOptionsSecurityRowRowCount - rowsToRemove : disabledPinLockRows;
}
case SPOptionsViewSectionsDelete: {
return SPOptionsDeleteRowCount;
}
case SPOptionsViewSectionsAbout: {
return SPOptionsAboutRowCount;
}
case SPOptionsViewSectionsHelp: {
return SPOptionsHelpRowCount;
}
case SPOptionsViewSectionsDebug: {
return SPOptionsDebugRowCount;
}
case SPOptionsViewSectionsAccount: {
return SPOptionsAccountRowCount;
}
default:
break;
}
return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
switch (section) {
case SPOptionsViewSectionsNotes:
return NSLocalizedString(@"Notes", nil);
case SPOptionsViewSectionsTags:
return NSLocalizedString(@"Tags", nil);
case SPOptionsViewSectionsAppearance:
return NSLocalizedString(@"Appearance", nil);
case SPOptionsViewSectionsSecurity:
return NSLocalizedString(@"Security", nil);
case SPOptionsViewSectionsAccount:
return NSLocalizedString(@"Account", nil);
default:
break;
}
return nil;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
#if INTERNAL_DISTRIBUTION
if (section == SPOptionsViewSectionsDebug) {
return [[NSString alloc] initWithFormat:@"Beta Distribution Channel\nv%@ (%@)", [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]], [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey]];
}
#endif
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
[self refreshTableViewCellStyle:cell];
switch (indexPath.section) {
case SPOptionsViewSectionsNotes: {
switch (indexPath.row) {
case SPOptionsPreferencesRowSort: {
cell.textLabel.text = NSLocalizedString(@"Sort Order", @"Option to sort notes in the note list alphabetically. The default is by modification date");
cell.detailTextLabel.text = [[Options shared] listSortModeDescription];
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.tag = kTagNoteListSort;
break;
}
case SPOptionsPreferencesRowCondensed: {
cell.textLabel.text = NSLocalizedString(@"Condensed Note List", @"Option to make the note list show only 1 line of text. The default is 3.");
self.condensedNoteListSwitch.on = [[Options shared] condensedNotesList];
cell.accessoryView = self.condensedNoteListSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.tag = kTagCondensedNoteList;
break;
}
case SPOptionsPreferencesRowIndexNotes: {
cell.textLabel.text = NSLocalizedString(@"Index Notes in Spotlight", @"Option to add notes to spotlight search");
self.indexNotesSwitch.on = [[Options shared] indexNotesInSpotlight];
cell.accessoryView = self.indexNotesSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.tag = kTagIndexNotes;
break;
}
default:
break;
}
break;
} case SPOptionsViewSectionsTags: {
switch (indexPath.row) {
case SPOptionsPreferencesRowTagSort: {
cell.textLabel.text = NSLocalizedString(@"Sort Alphabetically", @"Option to sort tags alphabetically. The default is by manual ordering.");
[self.alphabeticalTagSortSwitch setOn:[self alphabeticalTagSortPref]];
cell.accessoryView = self.alphabeticalTagSortSwitch;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.tag = kTagTagsListSort;
break;
}
default:
break;
}
break;
}
case SPOptionsViewSectionsAppearance: {
switch (indexPath.row) {
case SPOptionsPreferencesRowTheme: {
cell.textLabel.text = NSLocalizedString(@"Theme", @"Option to enable the dark app theme.");
cell.detailTextLabel.text = [[Options shared] themeDescription];
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.tag = kTagTheme;
break;
}
case SPOptionsAccountSustainerIcon: {
cell.textLabel.text = NSLocalizedString(@"Sustainer App Icon", @"Switch app icon");
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryView = self.sustainerIconSwitch;
cell.tag = kTagSustainerIcon;
break;
}
default:
break;
}
break;
}
case SPOptionsViewSectionsSecurity: {
switch (indexPath.row) {
case SPOptionsSecurityRowRowPasscode: {
cell.textLabel.text = NSLocalizedString(@"Passcode", @"A 4-digit code to lock the app when it is closed");
if ([self isPinLockEnabled])
cell.detailTextLabel.text = NSLocalizedString(@"On", nil);
else
cell.detailTextLabel.text = NSLocalizedString(@"Off", nil);
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.tag = kTagPasscode;
cell.accessibilityIdentifier = @"passcode-cell";
break;
}
case SPOptionsSecurityRowRowBiometry: {
if ([self isBiometryAvailable]) {
cell.textLabel.text = [self biometryTitle];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
self.biometrySwitch.on = SPPinLockManager.shared.shouldUseBiometry;
cell.accessoryView = self.biometrySwitch;
cell.tag = kTagTouchID;
break;
}
// No break here so we intentionally render the Timeout cell if biometry is disabled
}
case SPOptionsSecurityRowTimeout: {
cell.textLabel.text = NSLocalizedString(@"Lock Timeout", @"Setting for when the passcode lock should enable");
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
cell.accessoryView = nil;
cell.tag = kTagTimeout;
NSInteger timeoutPref = [[NSUserDefaults standardUserDefaults] integerForKey:kPinTimeoutPreferencesKey];
[cell.detailTextLabel setText:timeoutPickerOptions[timeoutPref]];
break;
}
default:
break;
}
break;
} case SPOptionsViewSectionsAccount: {
switch (indexPath.row) {
case SPOptionsAccountRowDescription: {
cell.textLabel.text = NSLocalizedString(@"Username", @"A user's Simplenote account");
cell.detailTextLabel.text = [SPAppDelegate sharedDelegate].simperium.user.email;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
break;
}
case SPOptionsAccountRowPrivacy: {
cell.textLabel.text = NSLocalizedString(@"Privacy Settings", @"Privacy Settings");
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
break;
}
case SPOptionsAccountRowLogout: {
cell.textLabel.text = NSLocalizedString(@"Log Out", @"Log out of the active account in the app");
cell.textLabel.textColor = [UIColor simplenoteTintColor];
break;
}
default:
break;
}
break;
} case SPOptionsViewSectionsDelete: {
switch (indexPath.row) {
case SPOptionsDeleteRowTitle: {
cell.textLabel.text = NSLocalizedString(@"Delete Account", @"Display Delete Account Alert");
cell.textLabel.textColor = [UIColor simplenoteRedButtonColor];
break;
}
}
break;
} case SPOptionsViewSectionsAbout: {
switch (indexPath.row) {
case SPOptionsAboutRowTitle: {
cell.textLabel.text = NSLocalizedString(@"About", @"Display app about screen");
break;
}
}
break;
} case SPOptionsViewSectionsHelp: {
switch (indexPath.row) {
case SPOptionsHelpRowTitle: {
cell.textLabel.text = NSLocalizedString(@"Help", @"Display help web page");
break;
}
}
break;
} case SPOptionsViewSectionsDebug: {
switch (indexPath.row) {
case SPOptionsDebugRowStats: {
cell.textLabel.text = NSLocalizedString(@"Debug", @"Display internal debug status");
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
break;
}
}
break;
}
default:
break;
}
return cell;
}
- (BOOL)isPinLockEnabled {
return SPPinLockManager.shared.isEnabled;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
switch (indexPath.section) {
case SPOptionsViewSectionsNotes: {
switch (cell.tag) {
case kTagNoteListSort: {
SPSortOrderViewController *controller = [SPSortOrderViewController new];
controller.selectedMode = [[Options shared] listSortMode];
controller.onChange = ^(SortMode newMode) {
[[Options shared] setListSortMode:newMode];
};
[self.navigationController pushViewController:controller animated:true];
break;
}
}
break;
}
case SPOptionsViewSectionsAppearance: {
switch (cell.tag) {
case kTagTheme: {
SPThemeViewController *controller = [SPThemeViewController new];
controller.selectedTheme = [[Options shared] theme];
controller.onChange = ^(Theme newTheme) {
[[Options shared] setTheme:newTheme];
};
[self.navigationController pushViewController:controller animated:true];
break;
}
}
break;
}
case SPOptionsViewSectionsSecurity: {
switch (cell.tag) {
case kTagPasscode: {
[self showPinLockViewController];
break;
case kTagTimeout:
[self.pinTimeoutTextField becomeFirstResponder];
break;
}
}
break;
} case SPOptionsViewSectionsAccount: {
switch (indexPath.row) {
case SPOptionsAccountRowPrivacy: {
SPPrivacyViewController *test = [[SPPrivacyViewController alloc] initWithStyle:UITableViewStyleGrouped];
[self.navigationController pushViewController:test animated:true];
break;
}
case SPOptionsAccountRowLogout: {
[self signOutAction:nil];
break;
}
default:
break;
}
break;
} case SPOptionsViewSectionsDelete: {
switch (indexPath.row) {
case SPOptionsDeleteRowTitle: {
[self deleteAccountWasPressed];
break;
}
}
break;
} case SPOptionsViewSectionsAbout: {
switch (indexPath.row) {
case SPOptionsAboutRowTitle: {
SPAboutViewController *aboutController = [[SPAboutViewController alloc] init];
aboutController.modalPresentationStyle = UIModalPresentationFormSheet;
[[self navigationController] presentViewController:aboutController animated:YES completion:nil];
break;
}
}
break;
} case SPOptionsViewSectionsHelp: {
switch (indexPath.row) {
case SPOptionsHelpRowTitle: {
NSURL *url = [NSURL URLWithString:@"path_to_url"];
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
break;
}
}
break;
} case SPOptionsViewSectionsDebug: {
switch (indexPath.row) {
case SPOptionsDebugRowStats: {
[self showDebugInformation];
break;
}
}
break;
}
default:
break;
}
[cell setSelected:NO animated:NO];
}
- (void)refreshTableViewCellStyle:(UITableViewCell *)cell
{
cell.backgroundColor = [UIColor simplenoteTableViewCellBackgroundColor];
cell.selectedBackgroundView.backgroundColor = [UIColor simplenoteLightBlueColor];
cell.textLabel.textColor = [UIColor simplenoteTextColor];
cell.detailTextLabel.textColor = [UIColor simplenoteSecondaryTextColor];
}
#pragma mark - Helpers
- (void)showDebugInformation
{
SPDebugViewController *debugViewController = [SPDebugViewController newDebugViewController];
[self.navigationController pushViewController:debugViewController animated:YES];
}
- (void)signOutAction:(id)sender
{
// Safety first: Check for unsynced notes before they are deleted!
Simperium *simperium = [[SPAppDelegate sharedDelegate] simperium];
if ([StatusChecker hasUnsentChanges:simperium] == false) {
[SPTracker trackUserSignedOut];
[[SPAppDelegate sharedDelegate] logoutAndReset:sender];
return;
}
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:NSLocalizedString(@"Unsynced Notes Detected", @"Alert title displayed in settings when an account has unsynced notes")
message:NSLocalizedString(@"Signing out will delete any unsynced notes. You can verify your synced notes by signing in to the Web App.", @"Alert message displayed when an account has unsynced notes")
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* signOutAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"Delete Notes", @"Verb: Delete notes and log out of the app")
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction * action) {
[SPTracker trackUserSignedOut];
[[SPAppDelegate sharedDelegate] logoutAndReset:sender];
}];
UIAlertAction* viewWebAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"Visit Web App", @"Visit app.simplenote.com in the browser")
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"path_to_url"] options:@{} completionHandler:nil];
}];
UIAlertAction* cancelAction = [UIAlertAction
actionWithTitle:NSLocalizedString(@"Cancel", @"Verb, cancel an alert dialog")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action) {
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:signOutAction];
[alert addAction:viewWebAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - Switches
- (void)condensedSwitchDidChangeValue:(UISwitch *)sender
{
BOOL isOn = [(UISwitch *)sender isOn];
[[Options shared] setCondensedNotesList:isOn];
[SPTracker trackSettingsListCondensedEnabled:isOn];
}
- (void)indexNotesSwitchDidChangeValue:(UISwitch *)sender
{
BOOL isOn = [(UISwitch *)sender isOn];
[[Options shared] setIndexNotesInSpotlight:isOn];
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[context setParentContext:SPAppDelegate.sharedDelegate.simperium.managedObjectContext];
if (isOn) {
[[CSSearchableIndex defaultSearchableIndex] indexSpotlightItemsIn:context];
} else {
[[CSSearchableIndex defaultSearchableIndex] deleteAllSearchableItemsWithCompletionHandler:^(NSError * _Nullable error) {
[self presentIndexRemovalAlert];
}];
}
}
- (void)tagSortSwitchDidChangeValue:(UISwitch *)sender
{
BOOL isOn = [(UISwitch *)sender isOn];
NSNumber *notificationObject = [NSNumber numberWithBool:isOn];
[[NSUserDefaults standardUserDefaults] setBool:isOn forKey:SPAlphabeticalTagSortPref];
[[NSNotificationCenter defaultCenter] postNotificationName:SPAlphabeticalTagSortPreferenceChangedNotification
object:notificationObject];
}
- (void)touchIdSwitchDidChangeValue:(UISwitch *)sender
{
if (![self isPinLockEnabled] && [self.biometrySwitch isOn]) {
UIAlertController* alert = [self pinLockRequiredAlert];
[self presentViewController:alert animated:YES completion:nil];
} else {
SPPinLockManager.shared.shouldUseBiometry = sender.on;
}
}
- (UIAlertController*)pinLockRequiredAlert
{
NSString *alertTitleTemplate = NSLocalizedString(@"To enable %1$@, you must have a passcode setup first.",
@"Prompt to setup passcode before biomtery lock. Parameters: %1$@ - biometry type (Face ID or Touch ID");
NSString *alertTitle = [NSString stringWithFormat:alertTitleTemplate, self.biometryTitle];
UIAlertController *alert = [UIAlertController alertControllerWithTitle:self.biometryTitle
message:alertTitle
preferredStyle:UIAlertControllerStyleAlert];
NSString *setupTitle = NSLocalizedString(@"Set up Passcode", @"Setup a passcode action button");
[alert addActionWithTitle:setupTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[self showPinLockViewController];
}];
NSString *cancelTitle = NSLocalizedString(@"Cancel", @"Cancel action button");
[alert addCancelActionWithTitle:cancelTitle handler:^(UIAlertAction * action) {
[self.biometrySwitch setOn:NO];
}];
return alert;
}
#pragma mark - Darkness
- (void)themeDidChange
{
[self refreshThemeStyles];
[self.tableView reloadData];
}
- (void)refreshThemeStyles
{
// Reload Switch Styles
NSArray *switches = @[ _condensedNoteListSwitch, _alphabeticalTagSortSwitch, _biometrySwitch ];
for (UISwitch *theSwitch in switches) {
theSwitch.onTintColor = [UIColor simplenoteSwitchOnTintColor];
theSwitch.tintColor = [UIColor simplenoteSwitchTintColor];
}
UIColor *tintColor = [UIColor simplenoteTintColor];
UIColor *backgroundColor = [UIColor simplenoteBackgroundColor];
[self.pinTimeoutPickerView setBackgroundColor:backgroundColor];
[self.doneToolbar setTintColor:tintColor];
[self.doneToolbar setBarTintColor:backgroundColor];
// Refresh the Table
[self.tableView applySimplenoteGroupedStyle];
}
#pragma mark - Preferences
- (BOOL)alphabeticalTagSortPref
{
return [[NSUserDefaults standardUserDefaults] boolForKey:SPAlphabeticalTagSortPref];
}
#pragma mark - Picker view delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [timeoutPickerOptions count];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
[self.pinTimeoutTextField setText:timeoutPickerOptions[row]];
[[NSUserDefaults standardUserDefaults] setInteger:row forKey:kPinTimeoutPreferencesKey];
[self.tableView reloadData];
}
- (void)pinTimeoutDoneAction:(id)sender
{
[self.pinTimeoutTextField resignFirstResponder];
}
- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
NSDictionary *attributes = @{
NSForegroundColorAttributeName: [UIColor simplenoteTextColor]
};
NSAttributedString *attributedTitle = [[NSAttributedString alloc] initWithString:timeoutPickerOptions[row] attributes:attributes];
return attributedTitle;
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPSettingsViewController.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 5,963 |
```swift
import Foundation
// MARK: - UIActivityItem With Special Treatment for WordPress iOS
//
class SimplenoteActivityItemSource: NSObject, UIActivityItemSource {
/// The Note that's about to be exported
///
private let content: String
private let targetURL: URL
/// Designated Initializer
///
init(content: String, identifier: String) {
self.content = content
self.targetURL = FileManager.default.temporaryDirectory.appendingPathComponent(identifier + ".txt")
super.init()
}
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return content
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
guard activityType?.isWordPressActivity == true else {
return content
}
return writeStringToURL(string: content, to: targetURL) ?? content
}
/// Writes a given String to the documents folder
///
private func writeStringToURL(string: String, to targetURL: URL) -> URL? {
do {
try string.write(to: targetURL, atomically: true, encoding: .utf8)
} catch {
NSLog("Note Exporter Failure: \(error)")
return nil
}
return targetURL
}
}
``` | /content/code_sandbox/Simplenote/Classes/SimplenoteActivityItemSource.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 287 |
```objective-c
//
// SPTableViewController.h
// Simplenote
//
// Created by Tom Witkin on 10/13/13.
//
#import <UIKit/UIKit.h>
@interface SPTableViewController : UITableViewController
@end
``` | /content/code_sandbox/Simplenote/Classes/SPTableViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 47 |
```swift
import UIKit
import SimplenoteEndpoints
// MARK: - Subscriber UI
//
// The methods in this extension are for showing and displaying the Sustainer banner in settings. We are discontinuing Sustainer,
// but we may still want to use the banner in the future, so marking these methods fileprivate and have removed their callers
fileprivate extension SPSettingsViewController {
@objc
func refreshTableHeaderView() {
guard let headerView = tableView.tableHeaderView as? BannerView else {
return
}
headerView.preferredWidth = tableView.frame.width
headerView.adjustSizeForCompressedLayout()
tableView.tableHeaderView = headerView
}
@objc
func restorePurchases() {
if StoreManager.shared.isActiveSubscriber {
presentPurchasesRestored(alert: .alreadySustainer)
return
}
StoreManager.shared.restorePurchases { isActiveSubscriber in
self.presentPurchasesRestored(alert: isActiveSubscriber ? .becameSustainer : .notFound)
}
}
private func presentPurchasesRestored(alert: RestorationAlert) {
let alertController = UIAlertController(title: alert.title, message: alert.message, preferredStyle: .alert)
alertController.addDefaultActionWithTitle(alert.action)
present(alertController, animated: true)
}
}
extension SPSettingsViewController {
@objc
var showSustainerSwitch: Bool {
let preferences = SPAppDelegate.shared().simperium.preferencesObject()
return preferences.isActiveSubscriber || preferences.wasSustainer
}
@objc
func sustainerSwitchDidChangeValue(sender: UISwitch) {
let isOn = sender.isOn
let iconName = isOn ? SPSustainerAppIconName : nil
UserDefaults.standard.set(isOn, forKey: .useSustainerIcon)
UIApplication.shared.setAlternateIconName(iconName)
}
}
// MARK: - Pin
//
extension SPSettingsViewController {
/// Show pin setup or pin remove view controller
@objc
func showPinLockViewController() {
let controller: PinLockController
if SPPinLockManager.shared.isEnabled {
controller = PinLockRemoveController(delegate: self)
} else {
controller = PinLockSetupController(delegate: self)
}
showPinLockViewController(with: controller)
}
private func showPinLockViewController(with controller: PinLockController) {
let viewController = PinLockViewController(controller: controller)
if traitCollection.verticalSizeClass != .compact {
viewController.modalPresentationStyle = .formSheet
}
navigationController?.present(viewController, animated: true, completion: nil)
}
}
// MARK: - PinLockSetupControllerDelegate
//
extension SPSettingsViewController: PinLockSetupControllerDelegate {
func pinLockSetupControllerDidComplete(_ controller: PinLockSetupController) {
SPTracker.trackSettingsPinlockEnabled(true)
dismissPresentedViewController()
SPPinLockManager.shared.shouldUseBiometry = true
}
func pinLockSetupControllerDidCancel(_ controller: PinLockSetupController) {
SPPinLockManager.shared.shouldUseBiometry = false
dismissPresentedViewController()
}
}
// MARK: - PinLockRemoveControllerDelegate
//
extension SPSettingsViewController: PinLockRemoveControllerDelegate {
func pinLockRemoveControllerDidComplete(_ controller: PinLockRemoveController) {
SPTracker.trackSettingsPinlockEnabled(false)
dismissPresentedViewController()
}
func pinLockRemoveControllerDidCancel(_ controller: PinLockRemoveController) {
dismissPresentedViewController()
}
}
// MARK: - Private
//
private extension SPSettingsViewController {
func dismissPresentedViewController() {
tableView.reloadData()
navigationController?.dismiss(animated: true, completion: nil)
}
}
// MARK: - Biometry
//
extension SPSettingsViewController {
@objc
var isBiometryAvailable: Bool {
SPPinLockManager.shared.availableBiometry != nil
}
@objc
var biometryTitle: String? {
SPPinLockManager.shared.availableBiometry?.title
}
}
// MARK: - BiometricAuthentication.Biometry
//
private extension BiometricAuthentication.Biometry {
var title: String {
switch self {
case .touchID:
return NSLocalizedString("Touch ID", comment: "Offer to enable Touch ID support if available and passcode is on.")
case .faceID:
return NSLocalizedString("Face ID", comment: "Offer to enable Face ID support if available and passcode is on.")
}
}
}
// MARK: - Account Deletion
extension SPSettingsViewController {
@objc
func deleteAccountWasPressed() {
guard let user = SPAppDelegate.shared().simperium.user,
let deletionController = SPAppDelegate.shared().accountDeletionController else {
return
}
SPTracker.trackDeleteAccountButttonTapped()
let spinnerViewController = SpinnerViewController()
presentAccountDeletionConfirmation(forEmail: user.email) { (_) in
self.present(spinnerViewController, animated: false, completion: nil)
deletionController.requestAccountDeletion(user) { [weak self] (result) in
spinnerViewController.dismiss(animated: false, completion: nil)
self?.handleDeletionResult(user: user, result)
}
}
}
private func handleDeletionResult(user: SPUser, _ result: Result<Data?, RemoteError>) {
switch result {
case .success:
presentSuccessAlert(for: user)
case .failure(let error):
handleError(error)
}
}
private func presentAccountDeletionConfirmation(forEmail email: String, onConfirm: @escaping ((UIAlertAction) -> Void)) {
let alert = UIAlertController(title: AccountDeletion.deleteAccount,
message: AccountDeletion.confirmAlertMessage(with: email),
preferredStyle: .alert)
let deleteAccountButton = UIAlertAction(title: AccountDeletion.deleteAccountButton, style: .destructive, handler: onConfirm)
alert.addAction(deleteAccountButton)
alert.addCancelActionWithTitle(AccountDeletion.cancel)
present(alert, animated: true, completion: nil)
}
private func handleError(_ error: RemoteError) {
presentRequestErrorAlert()
}
private func presentSuccessAlert(for user: SPUser) {
let alert = UIAlertController(title: AccountDeletion.succesAlertTitle, message: AccountDeletion.successMessage(email: user.email), preferredStyle: .alert)
alert.addCancelActionWithTitle(AccountDeletion.ok)
present(alert, animated: true, completion: nil)
}
private func presentRequestErrorAlert() {
let alert = UIAlertController(title: AccountDeletion.errorTitle, message: AccountDeletion.errorMessage, preferredStyle: .alert)
alert.addDefaultActionWithTitle(AccountDeletion.ok)
self.present(alert, animated: true, completion: nil)
}
@objc
func presentIndexRemovalAlert() {
DispatchQueue.main.async {
let alert = UIAlertController(title: IndexAlert.title, message: IndexAlert.message, preferredStyle: .alert)
alert.addDefaultActionWithTitle(IndexAlert.okay)
self.present(alert, animated: true, completion: nil)
}
}
}
private struct IndexAlert {
static let title = NSLocalizedString("Index Removed", comment: "Alert title letting user know their search index has been removed")
static let message = NSLocalizedString("Spotlight history may still appear in search results, but notes have be unindexed", comment: "Details that some results may still appear in searches on device")
static let okay = NSLocalizedString("Okay", comment: "confirm button title")
}
private struct AccountDeletion {
static func confirmAlertMessage(with email: String) -> String {
String(format: confirmAlertTemplate, email)
}
static let deleteAccount = NSLocalizedString("Delete Account", comment: "Delete account title and action")
static let confirmAlertTemplate = NSLocalizedString("By deleting the account for %@, all notes created with this account will be permanently deleted. This action is not reversible", comment: "Delete account confirmation alert message")
static let deleteAccountButton = NSLocalizedString("Request Account Deletion", comment: "Title for account deletion confirm button")
static let cancel = NSLocalizedString("Cancel", comment: "Cancel button title")
static let succesAlertTitle = NSLocalizedString("Check Your Email", comment: "Title for delete account succes alert")
static let successAlertMessage = NSLocalizedString("An email has been sent to %@. Check your inbox and follow the instructions to confirm account deletion.\n\nYour account won't be deleted until we receive your confirmation.", comment: "Delete account confirmation instructions")
static let ok = NSLocalizedString("Ok", comment: "Confirm alert message")
static let errorTitle = NSLocalizedString("Error", comment: "Deletion Error Title")
static let errorMessage = NSLocalizedString("An error occured. Please, try again. If the problem continues, contact us at support@simplenote.com for help.", comment: "Deletion error message")
static func successMessage(email: String) -> String {
String(format: successAlertMessage, email)
}
}
// MARK: - RestorationAlert
//
struct RestorationAlert {
let title: String
let message: String
let action: String
}
extension RestorationAlert {
static var notFound: RestorationAlert {
let title = NSLocalizedString("No purchases found", comment: "No purchases Found Title")
let message = NSLocalizedString("No previous valid purchases found, for the current period", comment: "No purchases Found Message")
let action = NSLocalizedString("Dismiss", comment: "Dismiss Alert")
return RestorationAlert(title: title, message: message, action: action)
}
static var becameSustainer: RestorationAlert {
let title = NSLocalizedString("Thank You!", comment: "Restoration Successful Title")
let message = NSLocalizedString("Sustainer subscription restored. Thank you for supporting Simplenote!", comment: "Restoration Successful Message")
let action = NSLocalizedString("Dismiss", comment: "Dismiss Alert")
return RestorationAlert(title: title, message: message, action: action)
}
static var alreadySustainer: RestorationAlert {
let title = NSLocalizedString("Simplenote Sustainer", comment: "Restoration Successful Title")
let message = NSLocalizedString("You're already a Sustainer. Thank you for supporting Simplenote!", comment: "Restoration Successful Message")
let action = NSLocalizedString("Dismiss", comment: "Dismiss Alert")
return RestorationAlert(title: title, message: message, action: action)
}
static var unsupported: RestorationAlert {
let title = NSLocalizedString("Unsupported", comment: "Upgrade Alert Title")
let message = NSLocalizedString("Please upgrade to the latest iOS release to restore purchases", comment: "Upgrade Alert Message")
let action = NSLocalizedString("Dismiss", comment: "Dismiss Alert")
return RestorationAlert(title: title, message: message, action: action)
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPSettingsViewController+Extensions.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 2,276 |
```objective-c
#import "SPAddCollaboratorsViewController.h"
#import "SPEntryListCell.h"
#import "SPEntryListAutoCompleteCell.h"
#import "NSString+Metadata.h"
#import "PersonTag.h"
#import <ContactsUI/ContactsUI.h>
#import "Simplenote-Swift.h"
#pragma mark - Private Helpers
@interface SPAddCollaboratorsViewController () <CNContactPickerDelegate>
@property (nonatomic, strong) SPContactsManager *contactsManager;
@end
#pragma mark - Implementation
@implementation SPAddCollaboratorsViewController
- (instancetype)init
{
self = [super init];
if (self) {
[self setupContactsManager];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.edgesForExtendedLayout = UIRectEdgeNone;
[self setupNavigationItem];
[self setupTextFields];
if (!self.dataSource) {
self.dataSource = [NSMutableArray arrayWithCapacity:3];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[primaryTableView reloadData];
[self.contactsManager requestAuthorizationIfNeededWithCompletion:nil];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.dataSource.count == 0) {
return;
}
// GDC is used to call becomeFirstResponder asynchronously to fix
// a layout issue on iPad in landscape. Views presented as a UIModalPresentationFormSheet
// and present a keyboard in viewDidAppear layout incorrectly
dispatch_async(dispatch_get_main_queue(), ^{
[self->entryTextField becomeFirstResponder];
});
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.view endEditing:YES];
}
#pragma mark - Private Helpers
- (void)setupNavigationItem
{
self.title = NSLocalizedString(@"Collaborators", @"Noun - collaborators are other Simplenote users who you chose to share a note with");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil)
style:UIBarButtonItemStyleDone
target:self
action:@selector(onDone)];
}
- (void)setupContactsManager
{
self.contactsManager = [SPContactsManager new];
}
- (void)setupTextFields
{
entryTextField.placeholder = NSLocalizedString(@"Add a new collaborator...", @"Noun - collaborators are other Simplenote users who you chose to share a note with");
}
- (void)setupWithCollaborators:(NSArray *)collaborators
{
NSMutableSet *merged = [NSMutableSet set];
for (NSString *tag in collaborators) {
NSArray *filtered = [self.contactsManager peopleWith:tag];
if (filtered.count == 0) {
PersonTag *person = [[PersonTag alloc] initWithName:nil email:tag];
[merged addObject:person];
continue;
}
[merged addObjectsFromArray:filtered];
}
self.dataSource = [[[merged allObjects] sortedArrayUsingSelector:@selector(compareName:)] mutableCopy];
[primaryTableView reloadData];
}
#pragma mark UITableViewDataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([tableView isEqual:primaryTableView]) {
return self.dataSource.count;
}
return [super tableView:tableView numberOfRowsInSection:section];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if ([tableView isEqual:primaryTableView]) {
return self.dataSource.count > 0 ? NSLocalizedString(@"Current Collaborators", nil) : nil;
}
return [super tableView:tableView titleForHeaderInSection:section];
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
if ([tableView isEqual:primaryTableView]) {
if (self.dataSource.count > 0) {
return nil;
} else {
return NSLocalizedString(@"Add an email address to share this note with someone. Then you can both make changes to it.", @"Description text for the screen that allows users to share notes with other users");
}
}
return [super tableView:tableView titleForFooterInSection:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SPEntryListCell *cell = (SPEntryListCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
PersonTag *personTag;
if ([tableView isEqual:primaryTableView]) {
personTag = self.dataSource[indexPath.row];
} else {
personTag = self.autoCompleteDataSource[indexPath.row];
}
BOOL hasName = personTag.name.length > 0;
NSString *primaryText = hasName ? personTag.name : personTag.email;
NSString *secondaryText = hasName ? personTag.email : nil;
[cell setupWithPrimaryText:primaryText secondaryText:secondaryText checkmarked:personTag.active];
return cell;
}
- (void)removeItemFromDataSourceAtIndexPath:(NSIndexPath *)indexPath
{
PersonTag *person = self.dataSource[indexPath.row];
[self.collaboratorDelegate collaboratorViewController:self didRemoveCollaborator:person.email];
[super removeItemFromDataSourceAtIndexPath:indexPath];
}
#pragma mark UITableViewDelegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.selected = NO;
if ([tableView isEqual:primaryTableView]) {
PersonTag *person = self.dataSource[indexPath.row];
person.active = !person.active;
if (person.active) {
[self.collaboratorDelegate collaboratorViewController:self didAddCollaborator:person.email];
} else {
[self.collaboratorDelegate collaboratorViewController:self didRemoveCollaborator:person.email];
}
[tableView reloadData];
} else if ([tableView isEqual:autoCompleteTableView]) {
PersonTag *person = self.autoCompleteDataSource[indexPath.row];
[self addPersonTag:person];
}
}
- (void)addPersonTag:(PersonTag *)person
{
// make sure email address is actually an email address
person.email = [person.email stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (![person.email isValidEmailAddress]) {
return;
}
// check to see from delegate if should add collaborator
if ([self.collaboratorDelegate collaboratorViewController:self shouldAddCollaborator:person.email]) {
[self.collaboratorDelegate collaboratorViewController:self didAddCollaborator:person.email];
person.active = YES;
[self.dataSource addObject:person];
entryTextField.text = @"";
[primaryTableView reloadSections:[NSIndexSet indexSetWithIndex:0]
withRowAnimation:UITableViewRowAnimationAutomatic];
[self updateAutoCompleteMatchesForString:nil];
}
}
- (void)processTextInField
{
NSString *email = entryTextField.text;
if (email.isValidEmailAddress == false) {
return;
}
NSArray *filtered = [self.contactsManager peopleWith:email];
PersonTag *person = filtered.firstObject ?: [[PersonTag alloc] initWithName:nil email:email];
[self addPersonTag:person];
}
- (void)updateAutoCompleteMatchesForString:(NSString *)string
{
if (self.contactsManager.authorized == false) {
return;
}
if (string.length > 0) {
NSArray *peopleFiltered = [self.contactsManager peopleWith:string];
NSSet *datasourceSet = [NSSet setWithArray:self.dataSource];
NSMutableSet *peopleSet = [NSMutableSet setWithArray:peopleFiltered];
[peopleSet minusSet:datasourceSet];
self.autoCompleteDataSource = [peopleSet.allObjects sortedArrayUsingSelector:@selector(compareName:)];
} else {
self.autoCompleteDataSource = nil;
}
[self updatedAutoCompleteMatches];
}
#pragma mark - Buttons
- (void)onDone
{
[self processTextInField];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark CNContactPickerDelegate Conformance
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
{
[self createPersonTagFromProperty:contactProperty];
}
#pragma mark - Helpers
- (void)createPersonTagFromProperty:(CNContactProperty *)property
{
NSString *name = [CNContactFormatter stringFromContact:property.contact style:CNContactFormatterStyleFullName];
NSString *email = property.value;
if (email.length == 0) {
return;
}
PersonTag *personTag = [[PersonTag alloc] initWithName:name email:email];
[self addPersonTag:personTag];
}
#pragma mark - Action Helpers
- (void)entryFieldPlusButtonTapped:(id)sender {
[self displayAddressPicker];
}
- (void)displayAddressPicker
{
CNContactPickerViewController *pickerViewController = [CNContactPickerViewController new];
pickerViewController.predicateForEnablingContact = [NSPredicate predicateWithFormat:@"emailAddresses.@count > 0"];
pickerViewController.displayedPropertyKeys = @[CNContactEmailAddressesKey];
pickerViewController.modalPresentationStyle = UIModalPresentationFormSheet;
pickerViewController.delegate = self;
[self presentViewController:pickerViewController animated:YES completion:nil];
}
@end
``` | /content/code_sandbox/Simplenote/Classes/SPAddCollaboratorsViewController.m | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,965 |
```swift
import Foundation
import UIKit
// MARK: - UIView's Animation Methods
//
extension UIView {
/// Animation for reloading the view
///
enum ReloadAnimation {
case slideLeading
case slideTrailing
case shake
}
/// Slide direction
///
enum SlideDirection {
case leading
case trailing
/// Direction considering user interface layout direction
///
var isLeft: Bool {
let left = self == .leading
if UIApplication.isRTL {
return !left
}
return left
}
/// Opposite direction
///
var opposite: SlideDirection {
return self == .leading ? .trailing : .leading
}
}
/// Animates a visibility switch, when applicable.
/// - Note: We're animating the Alpha property, and effectively switching the `isHidden` property onCompletion.
///
func animateVisibility(isHidden: Bool, duration: TimeInterval = UIKitConstants.animationQuickDuration) {
guard self.isHidden != isHidden else {
return
}
let animationAlpha = isHidden ? UIKitConstants.alpha0_0 : UIKitConstants.alpha1_0
UIView.animate(withDuration: duration) {
self.isHidden = isHidden
self.alpha = animationAlpha
}
}
/// Performs a FadeIn animation
///
func fadeIn(onCompletion: ((Bool) -> Void)? = nil) {
alpha = .zero
UIView.animate(withDuration: UIKitConstants.animationQuickDuration, animations: {
self.alpha = UIKitConstants.alpha1_0
}, completion: onCompletion)
}
/// Performs a FadeOut animation
///
func fadeOut(onCompletion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: UIKitConstants.animationQuickDuration, animations: {
self.alpha = UIKitConstants.alpha0_0
}, completion: onCompletion)
}
/// Reload the view with the specified animation
///
func reload(with animation: ReloadAnimation, in containerView: UIView, viewUpdateBlock: @escaping () -> Void) {
if animation == .shake {
shake() { _ in
viewUpdateBlock()
}
return
}
guard let superview = superview, let snapshot = snapshotView(afterScreenUpdates: true) else {
viewUpdateBlock()
return
}
superview.insertSubview(snapshot, aboveSubview: self)
pinSubviewToAllEdges(snapshot)
superview.setNeedsLayout()
superview.layoutIfNeeded()
viewUpdateBlock()
let slideDirection: SlideDirection = animation == .slideLeading ? .leading : .trailing
snapshot.slideOut(in: containerView, direction: slideDirection) { _ in
snapshot.removeFromSuperview()
}
slideIn(in: containerView, direction: slideDirection)
}
/// Slide the view out of the container view
///
func slideOut(in containerView: UIView, direction: SlideDirection, onCompletion: ((Bool) -> Void)? = nil) {
let targetTransform = slideTransformation(in: containerView, for: direction)
UIView.animate(withDuration: UIKitConstants.animationShortDuration, animations: {
self.transform = targetTransform
}, completion: onCompletion)
}
/// Slide the view in from the outside of container view
///
func slideIn(in containerView: UIView, direction: SlideDirection, onCompletion: ((Bool) -> Void)? = nil) {
let originalTransform = transform
transform = slideTransformation(in: containerView, for: direction.opposite)
UIView.animate(withDuration: UIKitConstants.animationShortDuration, animations: {
self.transform = originalTransform
}, completion: onCompletion)
}
private func slideTransformation(in containerView: UIView, for side: SlideDirection) -> CGAffineTransform {
let frameInContainer = convert(bounds, to: containerView)
if side.isLeft {
return transform.translatedBy(x: -frameInContainer.maxX, y: 0)
}
return transform.translatedBy(x: containerView.frame.width - frameInContainer.minX, y: 0)
}
/// Shake the view
///
func shake(onCompletion: ((Bool) -> Void)? = nil) {
let translation: CGFloat = 2.0
let leftTranslation = transform.translatedBy(x: translation, y: 0.0)
let rightTranslation = transform.translatedBy(x: -translation, y: 0.0)
let originalTransform = transform
transform = leftTranslation
UIView.animate(withDuration: 0.07, delay: 0.0, options: []) {
UIView.modifyAnimations(withRepeatCount: 5, autoreverses: true, animations: {
self.transform = rightTranslation
})
} completion: { (completed) in
self.transform = originalTransform
onCompletion?(completed)
}
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIView+Animations.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 1,022 |
```swift
import Foundation
// MARK: - Simplenote Constants!
//
@objcMembers
class SimplenoteConstants: NSObject {
/// Password Validation Rules
///
static let passwordRules = "minlength: 8; maxlength: 50;"
/// Simplenote: Scheme
///
static let simplenoteScheme = "simplenote"
/// Simplenote: Interlink Host
///
static let simplenoteInterlinkHost = "note"
/// Simplenote: Tag list Host
///
static let simplenoteInternalTagHost = "list"
/// Simplenote: Interlink Maximum Title Length
///
static let simplenoteInterlinkMaxTitleLength = 150
/// Simplenote: Published Notes base URL
///
static let simplenotePublishedBaseURL = "path_to_url"
/// Simplenote: Current Platform
///
static let simplenotePlatformName = "iOS"
/// Simplenote: Domain for shared group directory
///
static let sharedGroupDomain = "group.\(Bundle.main.rootBundleIdentifier ?? "com.codality.NotationalFlow")"
/// AppEngine: Base URL
///
static let currentEngineBaseURL = SPCredentials.defaultEngineURL as NSString
/// AppEngine: Endpoints
///
static let resetPasswordURL = currentEngineBaseURL.appendingPathComponent("/reset/?redirect=simplenote://launch&email=")
static let settingsURL = currentEngineBaseURL.appendingPathComponent("/settings")
static let loginRequestURL = currentEngineBaseURL.appendingPathComponent("/account/request-login")
static let loginCompletionURL = currentEngineBaseURL.appendingPathComponent("/account/complete-login")
static let signupURL = currentEngineBaseURL.appendingPathComponent("/account/request-signup")
static let verificationURL = currentEngineBaseURL.appendingPathComponent("/account/verify-email/")
static let accountDeletionURL = currentEngineBaseURL.appendingPathComponent("/account/request-delete/")
}
``` | /content/code_sandbox/Simplenote/Classes/SimplenoteConstants.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 434 |
```swift
import Foundation
import UIKit
// MARK: - UIKit Constants, so that we don't repeat ourselves forever!
//
@objcMembers
class UIKitConstants: NSObject {
static let alpha0_0 = CGFloat(0)
static let alpha0_1 = CGFloat(0.1)
static let alpha0_2 = CGFloat(0.2)
static let alpha0_4 = CGFloat(0.4)
static let alpha0_5 = CGFloat(0.5)
static let alpha0_6 = CGFloat(0.6)
static let alpha0_8 = CGFloat(0.8)
static let alpha1_0 = CGFloat(1)
static let animationDelayZero = TimeInterval(0)
static let animationDelayShort = TimeInterval(0.25)
static let animationDelayLong = TimeInterval(0.5)
static let animationQuickDuration = TimeInterval(0.1)
static let animationShortDuration = TimeInterval(0.25)
static let animationLongDuration = TimeInterval(0.5)
static let animationTightDampening = CGFloat(0.9)
/// Yes. This should be, potentially, an enum. But since we intend to use these constants in ObjC... oh well!
///
private override init() {
// NO-OP
}
}
``` | /content/code_sandbox/Simplenote/Classes/UIKitConstants.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 279 |
```objective-c
#import <UIKit/UIKit.h>
@class SPSidebarContainerViewController;
@protocol SPSidebarContainerDelegate <NSObject>
@required
- (BOOL)sidebarContainerShouldDisplaySidebar:(SPSidebarContainerViewController *)sidebarContainer;
- (void)sidebarContainerWillDisplaySidebar:(SPSidebarContainerViewController *)sidebarContainer;
- (void)sidebarContainerDidDisplaySidebar:(SPSidebarContainerViewController *)sidebarContainer;
- (void)sidebarContainerWillHideSidebar:(SPSidebarContainerViewController *)sidebarContainer;
- (void)sidebarContainerDidHideSidebar:(SPSidebarContainerViewController *)sidebarContainer;
@end
@interface SPSidebarContainerViewController : UIViewController
@property (nonatomic, strong, readonly) UIViewController *sidebarViewController;
@property (nonatomic, strong, readonly) UIViewController *mainViewController;
@property (nonatomic, assign, readonly) BOOL isSidebarVisible;
@property (nonatomic, assign) BOOL automaticallyMatchSidebarInsetsWithMainInsets;
@property (nonatomic, weak) id<SPSidebarContainerDelegate> delegate;
- (instancetype)initWithMainViewController:(UIViewController *)mainViewController
sidebarViewController:(UIViewController *)sidebarViewController;
- (void)toggleSidebar;
- (void)showSidebar;
- (void)hideSidebarWithAnimation:(BOOL)animated;
- (void)requirePanningToFail;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPSidebarContainerViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 260 |
```swift
import Foundation
// MARK: - NSMutableParagraphStyle
//
extension NSMutableParagraphStyle {
convenience init(lineSpacing: CGFloat) {
self.init()
self.lineSpacing = lineSpacing
}
}
``` | /content/code_sandbox/Simplenote/Classes/NSMutableParagraphStyle+Simplenote.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 42 |
```objective-c
#import <UIKit/UIKit.h>
typedef void(^SPNavigationControllerBlock)(void);
@interface SPNavigationController : UINavigationController
@property (nonatomic) BOOL displaysBlurEffect;
@property (nonatomic) BOOL disableRotation;
@property (nonatomic, copy) SPNavigationControllerBlock onWillDismiss;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPNavigationController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 57 |
```objective-c
//
// SPDebugViewController.h
// Simplenote
//
// Created by Jorge Leandro Perez on 6/3/14.
//
#import <UIKit/UIKit.h>
#import "SPTableViewController.h"
@interface SPDebugViewController : SPTableViewController
+ (instancetype)newDebugViewController;
@end
``` | /content/code_sandbox/Simplenote/Classes/SPDebugViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 64 |
```objective-c
#import <UIKit/UIKit.h>
#import "SPEntryListViewController.h"
NS_ASSUME_NONNULL_BEGIN
@class SPAddCollaboratorsViewController;
@protocol SPCollaboratorDelegate <NSObject>
@required
- (BOOL)collaboratorViewController:(SPAddCollaboratorsViewController *)viewController
shouldAddCollaborator:(NSString *)collaboratorEmail;
- (void)collaboratorViewController:(SPAddCollaboratorsViewController *)viewController
didAddCollaborator:(NSString *)collaboratorEmail;
- (void)collaboratorViewController:(SPAddCollaboratorsViewController *)viewController
didRemoveCollaborator:(NSString *)collaboratorEmail;
@end
@interface SPAddCollaboratorsViewController : SPEntryListViewController
@property (nonatomic, nullable, weak) id<SPCollaboratorDelegate> collaboratorDelegate;
- (void)setupWithCollaborators:(NSArray<NSString *> *)collaborators;
@end
NS_ASSUME_NONNULL_END
``` | /content/code_sandbox/Simplenote/Classes/SPAddCollaboratorsViewController.h | objective-c | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 198 |
```swift
import Foundation
import SafariServices
import SimplenoteEndpoints
// MARK: - SPAuthHandler
//
class SPAuthHandler {
/// Simperium Authenticator
///
private let simperiumService: SPAuthenticator
/// Designated Initializer.
///
/// - Parameter simperiumService: Reference to a valid SPAuthenticator instance.
///
init(simperiumService: SPAuthenticator) {
self.simperiumService = simperiumService
}
/// Authenticates against the Simperium Backend.
///
/// - Note: Errors are mapped into SPAuthError Instances
///
/// - Parameters:
/// - username: Simperium Username
/// - password: Simperium Password
/// - onCompletion: Closure to be executed on completion
///
func loginWithCredentials(username: String, password: String, onCompletion: @escaping (SPAuthError?) -> Void) {
simperiumService.authenticate(withUsername: username, password: password, success: {
onCompletion(nil)
}, failure: { (statusCode, response, error) in
let error = SPAuthError(loginErrorCode: statusCode, response: response, error: error)
onCompletion(error)
})
}
/// Validates a set of credentials against the Simperium Backend.
///
/// - Note: This API is meant to be used to verify an unsecured set of credentials, before presenting the Reset Password UI.
///
/// - Parameters:
/// - username: Simperium Username
/// - password: Simperium Password
/// - onCompletion: Closure to be executed on completion
///
func validateWithCredentials(username: String, password: String, onCompletion: @escaping (SPAuthError?) -> Void) {
simperiumService.validate(withUsername: username, password: password, success: {
onCompletion(nil)
}, failure: { (statusCode, response, error) in
let error = SPAuthError(loginErrorCode: statusCode, response: response, error: error)
onCompletion(error)
})
}
/// Requests an Authentication Email
///
@MainActor
func requestLoginEmail(username: String) async throws {
let remote = LoginRemote()
do {
try await remote.requestLoginEmail(email: username)
} catch let remoteError as RemoteError {
throw SPAuthError(loginRemoteError: remoteError)
}
}
/// Performs LogIn the User with an Authentication Code
///
@MainActor
func loginWithCode(username: String, code: String) async throws {
let remote = LoginRemote()
do {
let confirmation = try await remote.requestLoginConfirmation(email: username, authCode: code.uppercased())
simperiumService.authenticate(withUsername: confirmation.username, token: confirmation.syncToken)
} catch let remoteError as RemoteError {
throw SPAuthError(loginRemoteError: remoteError)
}
}
/// Registers a new user in the Simperium Backend.
///
/// - Note: Errors are mapped into SPAuthError Instances
///
/// - Parameters:
/// - username: Simperium Username
/// - onCompletion: Closure to be executed on completion
///
func signupWithCredentials(username: String, onCompletion: @escaping (SPAuthError?) -> Void) {
SignupRemote().requestSignup(email: username) { (result) in
switch result {
case .success:
onCompletion(nil)
case .failure(let remoteError):
let error = SPAuthError(signupRemoteError: remoteError)
onCompletion(error)
}
}
}
/// Presents the Password Reset (Web) Interface
///
func presentPasswordReset(from sourceViewController: UIViewController, username: String) {
let escapedUsername = username.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? username
guard let targetURL = URL(string: kSimperiumForgotPasswordURL + "?email=" + escapedUsername) else {
return
}
let safariViewController = SFSafariViewController(url: targetURL)
safariViewController.modalPresentationStyle = .overFullScreen
sourceViewController.present(safariViewController, animated: true, completion: nil)
}
}
``` | /content/code_sandbox/Simplenote/Classes/SPAuthHandler.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 913 |
```swift
//
// SPSortOrderViewController.swift
// Simplenote
//
//
import Foundation
import UIKit
// MARK: - Settings: Sort Order
//
class SPSortOrderViewController: UITableViewController {
/// Selected SortMode
///
@objc
var selectedMode: SortMode = .alphabeticallyAscending {
didSet {
updateSelectedCell(oldSortMode: oldValue, newSortMode: selectedMode)
onChange?(selectedMode)
}
}
/// Closure to be executed whenever a new Sort Mode is selected
///
@objc
var onChange: ((SortMode) -> Void)?
/// Indicates if an Action button should be attached to the navigationBar
///
var displaysDismissButton = false
/// Designated Initializer
///
init() {
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationItem()
setupTableView()
}
}
// MARK: - UITableViewDelegate Conformance
//
extension SPSortOrderViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return Constants.numberOfSections
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return SortMode.allCases.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SPDefaultTableViewCell.reusableIdentifier) ?? SPDefaultTableViewCell()
let mode = SortMode.allCases[indexPath.row]
setupCell(cell, with: mode)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedMode = SortMode.allCases[indexPath.row]
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - Private
//
private extension SPSortOrderViewController {
func setupNavigationItem() {
title = NSLocalizedString("Sort Order", comment: "Sort Order for the Notes List")
if displaysDismissButton {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done,
target: self,
action: #selector(dismissWasPressed))
}
}
func setupTableView() {
tableView.applySimplenoteGroupedStyle()
}
func setupCell(_ cell: UITableViewCell, with mode: SortMode) {
let selected = mode == selectedMode
cell.textLabel?.text = mode.description
cell.accessoryType = selected ? .checkmark : .none
}
func updateSelectedCell(oldSortMode: SortMode, newSortMode: SortMode) {
let oldIndexPath = indexPath(for: oldSortMode)
let newIndexPath = indexPath(for: newSortMode)
let oldSelectedCell = tableView.cellForRow(at: oldIndexPath)
let newSelectedCell = tableView.cellForRow(at: newIndexPath)
oldSelectedCell?.accessoryType = .none
newSelectedCell?.accessoryType = .checkmark
}
func indexPath(for mode: SortMode) -> IndexPath {
guard let selectedIndex = SortMode.allCases.firstIndex(of: mode) else {
fatalError()
}
return IndexPath(row: selectedIndex, section: Constants.firstSectionIndex)
}
}
extension SPSortOrderViewController {
@objc
func dismissWasPressed() {
dismiss(animated: true, completion: nil)
}
}
// MARK: - Constants
//
private enum Constants {
static let numberOfSections = 1
static let firstSectionIndex = 0
}
``` | /content/code_sandbox/Simplenote/Classes/SPSortOrderViewController.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 755 |
```swift
import UIKit
// MARK: - RoundedButton
//
class RoundedButton: UIButton {
override var bounds: CGRect {
didSet {
guard bounds.size != oldValue.size else {
return
}
updateCornerRadius()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
configure()
}
}
// MARK: - Private
//
private extension RoundedButton {
func configure() {
layer.masksToBounds = true
updateCornerRadius()
}
func updateCornerRadius() {
layer.cornerRadius = min(frame.height, frame.width) / 2
}
}
``` | /content/code_sandbox/Simplenote/Classes/RoundedButton.swift | swift | 2016-08-11T15:55:22 | 2024-08-14T02:42:22 | simplenote-ios | Automattic/simplenote-ios | 2,038 | 148 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.