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 // MARK: - Settings: Theme // class SPThemeViewController: UITableViewController { private var themes: [Theme] { return Theme.allThemes } /// Selected SortMode /// @objc var selectedTheme: Theme = .light { didSet { updateSelectedCell(oldSortMode: oldValue, newSortMode: selectedTheme) onChange?(selectedTheme) // TODO: Nuke this once iOS <13 support has been dropped refreshInterfaceStyle() } } /// Closure to be executed whenever a new Sort Mode is selected /// @objc var onChange: ((Theme) -> 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() refreshInterfaceStyle() } } // MARK: - UITableViewDelegate Conformance // extension SPThemeViewController { override func numberOfSections(in tableView: UITableView) -> Int { return Constants.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return themes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SPDefaultTableViewCell.reusableIdentifier) ?? SPDefaultTableViewCell() let mode = themes[indexPath.row] setupCell(cell, with: mode) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedTheme = themes[indexPath.row] tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Private // private extension SPThemeViewController { func setupNavigationItem() { title = NSLocalizedString("Themes", comment: "Simplenote Themes") if displaysDismissButton { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissWasPressed)) } } func setupCell(_ cell: UITableViewCell, with mode: Theme) { let selected = mode == selectedTheme cell.textLabel?.text = mode.description cell.textLabel?.textColor = .simplenoteTextColor cell.accessoryType = selected ? .checkmark : .none cell.backgroundColor = .simplenoteTableViewCellBackgroundColor } func refreshInterfaceStyle() { tableView.applySimplenoteGroupedStyle() tableView.reloadData() } func updateSelectedCell(oldSortMode: Theme, newSortMode: Theme) { 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: Theme) -> IndexPath { guard let selectedIndex = themes.firstIndex(of: mode) else { fatalError() } return IndexPath(row: selectedIndex, section: Constants.firstSectionIndex) } } extension SPThemeViewController { @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/SPThemeViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
776
```swift import Foundation // MARK: - NSRegularExpression (Checklists) // extension NSRegularExpression { /// Matches Checklists at the beginning of each line /// @objc static let regexForChecklists: NSRegularExpression = { try! NSRegularExpression(pattern: "^\\s*(-[ \t]+\\[[xX\\s]?\\])", options: .anchorsMatchLines) }() /// Matches Checklists patterns that can be ANYWHERE in the string, not necessarily at the beginning of the string. /// @objc static let regexForChecklistsEmbeddedAnywhere: NSRegularExpression = { try! NSRegularExpression(pattern: "\\s*(-[ \t]+\\[[xX\\s]?\\])", options: .anchorsMatchLines) }() /// Both our Checklist regexes look like this: `"^\\s*(EXPRESSION)"` /// This will produce two resulting NSRange(s): a top level one, including the full match, and a "capture group" /// By requesting the Range for `EXPRESSION` we'd be able to track **exactly** the location of our list marker `- [ ]` (disregarding, thus, the leading space). /// @objc static let regexForChecklistsExpectedNumberOfRanges = 2 /// Checklist's Match Marker Range /// @objc static let regexForChecklistsMarkerRangeIndex = 1 } ```
/content/code_sandbox/Simplenote/Classes/NSRegularExpression+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
299
```objective-c // // SPInteractivePushPopAnimationController.m // Simplenote // // Created by James Frost on 08/10/2015. // #import "SPInteractivePushPopAnimationController.h" #import "Simplenote-Swift.h" CGFloat const SPStandardInteractivePopGestureWidth = 20.0f; CGFloat const SPGestureTargetSwipeVelocity = 100.0f; CGFloat const SPGestureTargetPercentageComplete = 0.5f; CGFloat const SPPushAnimationDurationRegular = 0.5f; CGFloat const SPPushAnimationDurationCompact = 0.3f; @interface SPInteractivePushPopAnimationController ()<UIGestureRecognizerDelegate> @property (nonatomic, strong) UIPercentDrivenInteractiveTransition *interactiveTransition; @end @implementation SPInteractivePushPopAnimationController - (instancetype)initWithNavigationController:(UINavigationController *)navigationController { self = [super init]; if (self) { _navigationController = navigationController; [_navigationController.view addGestureRecognizer:[self interactivePanGestureRecognizer]]; } return self; } #pragma mark - Gesture Recognizer /// Gesture recognizer used to initiate an interactive push / pop - (UIPanGestureRecognizer *)interactivePanGestureRecognizer { UIPanGestureRecognizer *gestureRecogniser = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]; gestureRecogniser.delegate = self; gestureRecogniser.cancelsTouchesInView = NO; return gestureRecogniser; } - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if ([gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] == false) { return YES; } UIPanGestureRecognizer *panGestureRecognizer = (UIPanGestureRecognizer *)gestureRecognizer; UINavigationBar *navigationBar = self.navigationController.navigationBar; UIViewController *topViewController = self.navigationController.topViewController; CGPoint location = [panGestureRecognizer locationInView:navigationBar]; CGPoint translation = [panGestureRecognizer translationInView:navigationBar]; BOOL isLeftTranslation = translation.x < 0; BOOL isRightTranslation = translation.x > 0; BOOL isLTR = [UIView userInterfaceLayoutDirectionForSemanticContentAttribute: topViewController.view.semanticContentAttribute] == UIUserInterfaceLayoutDirectionLeftToRight; BOOL isSwipeTranslation = isLTR ? isLeftTranslation : isRightTranslation; // Ignore touches within the navigation bar if (CGRectContainsPoint(navigationBar.bounds, location)) { return NO; } // TopViewController conforms to SPInteractivePushViewControllerProvider AND We're Swiping Right to Left: Support Push! if ([topViewController conformsToProtocol:@protocol(SPInteractivePushViewControllerProvider)] && isSwipeTranslation) { UIViewController <SPInteractivePushViewControllerProvider> *pushProviderController = (UIViewController <SPInteractivePushViewControllerProvider> *)topViewController; CGPoint locationInView = [panGestureRecognizer locationInView:pushProviderController.view]; if (![pushProviderController interactivePushPopAnimationControllerShouldBeginPush:self touchPoint:locationInView]) { return NO; } // `StandardInteractivePopGestureWidth` is an estimate of how wide the standard navigation // controller interactive pop gesture recognizer's detection area is. return (location.x >= SPStandardInteractivePopGestureWidth); } // Pop Gesture: Let's leave `UINavigationController.interactivePopGestureRecognizer` deal with it. return NO; } - (void)handlePanGesture:(UIScreenEdgePanGestureRecognizer *)gesture { switch (gesture.state) { case UIGestureRecognizerStateBegan: [self beginTransition]; break; case UIGestureRecognizerStateChanged: [self updateTransitionWithGestureTranslation:[gesture translationInView:self.navigationController.view]]; break; case UIGestureRecognizerStateEnded: [self endTransitionWithGestureVelocity:[gesture velocityInView:self.navigationController.view]]; break; default: [self cancelTransition]; break; } } - (void)beginTransition { self.interactiveTransition = [UIPercentDrivenInteractiveTransition new]; // If the top view controller conforms to the protocol, we're doing a push if ([self.navigationController.topViewController conformsToProtocol:@protocol(SPInteractivePushViewControllerProvider)]) { self.navigationOperation = UINavigationControllerOperationPush; id<SPInteractivePushViewControllerProvider> topVC = (id<SPInteractivePushViewControllerProvider>)self.navigationController.topViewController; [topVC interactivePushPopAnimationControllerWillBeginPush:self]; UIViewController *nextViewController = [topVC nextViewControllerForInteractivePush]; [self.navigationController pushViewController:nextViewController animated:YES]; } else { self.navigationOperation = UINavigationControllerOperationPop; [self.navigationController popViewControllerAnimated:YES]; } } /// Updates the % completion of the `interactiveTransition` based on the translation of the user's touch within the view. - (void)updateTransitionWithGestureTranslation:(CGPoint)translation { CGFloat viewWidth = CGRectGetWidth(self.navigationController.view.bounds); CGFloat xTranslation = translation.x; if (self.navigationOperation == UINavigationControllerOperationPush) { xTranslation = MIN(xTranslation, 0); } else if (self.navigationOperation == UINavigationControllerOperationPop) { xTranslation = MAX(xTranslation, 0); } CGFloat percentage = fabs(xTranslation) / viewWidth; [self.interactiveTransition updateInteractiveTransition:MIN(MAX(percentage, 0), 1)]; } - (void)endTransitionWithGestureVelocity:(CGPoint)velocity { BOOL velocityExceedsTarget = NO; if (self.navigationOperation == UINavigationControllerOperationPush) { velocityExceedsTarget = velocity.x < -SPGestureTargetSwipeVelocity; } else if (self.navigationOperation == UINavigationControllerOperationPop) { velocityExceedsTarget = velocity.x > SPGestureTargetSwipeVelocity; } if (self.interactiveTransition.percentComplete > SPGestureTargetPercentageComplete || velocityExceedsTarget) { [self.interactiveTransition finishInteractiveTransition]; } else { [self.interactiveTransition cancelInteractiveTransition]; } [self cleanupTransition]; } - (void)cancelTransition { [self.interactiveTransition cancelInteractiveTransition]; [self cleanupTransition]; } - (void)cleanupTransition { _interactiveTransition = nil; self.navigationOperation = UINavigationControllerOperationNone; } #pragma mark - UIViewControllerAnimatedTransitioning - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext { // A fast animation looks a little odd when the editor is very wide, // so use a slightly longer duration for regular width UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey]; if ([fromView isHorizontallyCompact]) { return SPPushAnimationDurationCompact; } return SPPushAnimationDurationRegular; } - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext { UIView *containerView = [transitionContext containerView]; UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey]; UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey]; CGRect fromViewInitialFrame = [transitionContext initialFrameForViewController:fromViewController]; CGRect toViewFinalFrame = [transitionContext finalFrameForViewController:toViewController]; CGRect fromViewFinalFrame = toViewFinalFrame; CGRect toViewInitialFrame = fromViewInitialFrame; if (self.navigationOperation == UINavigationControllerOperationPush) { fromViewFinalFrame.origin.x -= fromViewInitialFrame.size.width; toViewInitialFrame.origin.x += fromViewInitialFrame.size.width; } else if (self.navigationOperation == UINavigationControllerOperationPop) { fromViewFinalFrame.origin.x += fromViewInitialFrame.size.width; toViewInitialFrame.origin.x -= fromViewInitialFrame.size.width; } [containerView insertSubview:toView aboveSubview:fromView]; fromView.frame = fromViewInitialFrame; toView.frame = toViewInitialFrame; toView.alpha = UIKitConstants.alpha0_0; void (^transition)() = ^void() { fromView.frame = fromViewFinalFrame; toView.frame = toViewFinalFrame; fromView.alpha = UIKitConstants.alpha0_0; toView.alpha = UIKitConstants.alpha1_0; }; void (^completion)(BOOL) = ^void(BOOL finished) { BOOL completed = ![transitionContext transitionWasCancelled]; if (!completed) { fromView.frame = fromViewInitialFrame; [toView removeFromSuperview]; } // We must restore fromView's alpha value. Otherwise `UINavigationController.interactivePopGestureRecognizer` // will end up displaying a blank UI. fromView.alpha = UIKitConstants.alpha1_0; [transitionContext completeTransition:completed]; }; UIViewAnimationOptions curve = ([transitionContext isInteractive]) ? UIViewAnimationOptionCurveLinear : UIViewAnimationOptionCurveEaseInOut; if ([transitionContext isAnimated]) { [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0 options:curve animations:transition completion:completion]; } else { transition(); completion(true); } } @end ```
/content/code_sandbox/Simplenote/Classes/SPInteractivePushPopAnimationController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,973
```swift import Foundation import UIKit // MARK: - UIBlurEffect Simplenote Methods // extension UIBlurEffect { /// Returns a UIBlurEffect instance matching the System preferences /// @objc static var simplenoteBlurEffect: UIBlurEffect { return UIBlurEffect(style: simplenoteBlurStyle) } /// Returns the UIBlurEffect.Style matching the System preferences /// @objc static var simplenoteBlurStyle: UIBlurEffect.Style { .regular } } ```
/content/code_sandbox/Simplenote/Classes/UIBlurEffect+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
119
```swift import Foundation // MARK: - ContentSlice // struct ContentSlice: Equatable { /// Original content /// let content: String /// Sliced range /// let range: Range<String.Index> /// Ranges of matched words /// let matches: [Range<String.Index>] /// NSRange version of `matches` /// var nsMatches: [NSRange] { return matches.map { NSRange($0, in: content) } } /// Content sliced to the range /// var slicedContent: String { return String(content[range]) } /// Constructor /// init(content: String, range: Range<String.Index>, matches: [Range<String.Index>]) { self.content = content self.range = range self.matches = matches } } ```
/content/code_sandbox/Simplenote/Classes/ContentSlice.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
180
```swift import Foundation // MARK: - NotesListFilter // enum NotesListFilter: Equatable { case everything case deleted case untagged case tag(name: String) } // MARK: - NotesListFilter: Public API // extension NotesListFilter { /// Initializes the ListFilter for a given `selectedTag` /// /// TODO: As of now, Simplenote keeps track of the selectedTag as a string, in the AppDelegate. /// Once we've Swifted enough (AppDelegate + TagListViewController), remove this initializer. /// init(selectedTag: String?) { guard let tag = selectedTag, !tag.isEmpty else { self = .everything return } switch selectedTag { case kSimplenoteTrashKey: self = .deleted case kSimplenoteUntaggedKey: self = .untagged default: self = .tag(name: tag) } } /// Filter's visible Title /// var title: String { switch self { case .everything: return NSLocalizedString("All Notes", comment: "Title: No filters applied") case .deleted: return NSLocalizedString("Trash", comment: "Title: Trash Tag is selected") case .untagged: return NSLocalizedString("Untagged", comment: "Title: Untagged Notes are onscreen") case .tag(let name): return name } } } ```
/content/code_sandbox/Simplenote/Classes/NotesListFilter.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
310
```objective-c #import "Simperium+Simplenote.h" #import "Simplenote-Swift.h" @implementation Simperium (Simplenote) - (Preferences *)preferencesObject { SPBucket *bucket = [self bucketForName:NSStringFromClass([Preferences class])]; Preferences *preferences = [bucket objectForKey:kSimperiumPreferencesObjectKey]; if (preferences != nil) { return preferences; } return [bucket insertNewObjectForKey:kSimperiumPreferencesObjectKey]; } @end ```
/content/code_sandbox/Simplenote/Classes/Simperium+Simplenote.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
109
```swift import Foundation // MARK: - Simplenote Methods // extension UIDevice { @objc static var isPad: Bool { UIDevice.current.userInterfaceIdiom == .pad } } ```
/content/code_sandbox/Simplenote/Classes/UIDevice+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
45
```swift import UIKit // MARK: - ActivityIndicatorButton // class ActivityIndicatorButton: UIButton { private lazy var activityIndicator = UIActivityIndicatorView() /// In Progress /// var inProgress: Bool = false { didSet { if inProgress { titleLabel?.alpha = UIKitConstants.alpha0_0 activityIndicator.startAnimating() } else { titleLabel?.alpha = UIKitConstants.alpha1_0 activityIndicator.stopAnimating() } isEnabled = !inProgress } } /// Activity indicator color /// var activityIndicatorColor: UIColor? { get { return activityIndicator.color } set { activityIndicator.color = newValue } } override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { super.init(coder: coder) configure() } } private extension ActivityIndicatorButton { func configure() { activityIndicator.hidesWhenStopped = true addSubview(activityIndicator) pinSubviewToCenter(activityIndicator) styleActivityIndicator() } func styleActivityIndicator() { activityIndicator.style = .medium } } ```
/content/code_sandbox/Simplenote/Classes/ActivityIndicatorButton.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
248
```objective-c // // NSManagedObjectContext+CoreDataExtensions.h // Castaway // // Created by Tom Witkin on 4/5/13. // #import <CoreData/CoreData.h> @interface NSManagedObjectContext (CoreDataExtensions) - (NSArray *)fetchAllObjectsForEntityName:(NSString *)entityName; - (NSArray *)fetchObjectsForEntityName:(NSString *)entityName withPredicate:(NSPredicate *)predicate; - (NSManagedObject *)fetchObjectForEntityName:(NSString *)entityName withPredicate:(NSPredicate *)predicate; - (NSManagedObject *)fetchObjectForEntityName:(NSString *)entityName withAttribute:(NSString *)attribute equalTo:(id)equalObject; - (NSManagedObject *)fetchObjectForEntityName:(NSString *)entityName withAttributes:(NSArray *)attributes equalToObjects:(NSArray *)equalObjects; - (NSInteger)countObjectsForEntityName:(NSString *)entityName withPredicate:(NSPredicate *)predicate; - (void)saveToParent:(void(^)(NSError *error))completion; @end ```
/content/code_sandbox/Simplenote/Classes/NSManagedObjectContext+CoreDataExtensions.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
207
```objective-c // // Tag.h // Simplenote // // Created by Michael Johnston on 10-04-19. // #import <Simperium/SPManagedObject.h> @interface Tag : SPManagedObject { NSString *name; NSMutableArray *recipients; int count; NSNumber *index; NSString *share; } @property (nonatomic, retain) NSString *name; @property (nonatomic, retain) NSMutableArray *recipients; @property (nonatomic) int count; @property (nonatomic, retain) NSNumber *index; @property (nonatomic, retain) NSString *share; - (id)initWithText:(NSString *)str; - (id)initWithText:(NSString *)str recipients:(NSArray *)emailList; - (NSString *)textWithPrefix; - (void)addRecipient:(NSString *)emailAddress; - (NSDictionary *)tagDictionary; @end ```
/content/code_sandbox/Simplenote/Classes/Tag.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
172
```objective-c // // WPAuthHandler.h // Simplenote // Handles oauth authentication with WordPress.com // #import <Simperium/Simperium.h> @interface WPAuthHandler : NSObject + (BOOL)isWPAuthenticationUrl:(NSURL*)url; + (void)presentWordPressSSOFromViewController:(UIViewController *)presenter; + (SPUser *)authorizeSimplenoteUserFromUrl:(NSURL*)url forAppId:(NSString *)appId; @end ```
/content/code_sandbox/Simplenote/Classes/WPAuthHandler.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
99
```swift import Foundation // MARK: - TagTextFieldInputValidator // struct TagTextFieldInputValidator { private var disallowedCharacterSet: CharacterSet { get { var whitespaceCharset = CharacterSet.whitespacesAndNewlines whitespaceCharset.insert(",") return whitespaceCharset } } /// Validation Result /// enum Result: Equatable { case valid case invalid case endingWithDisallowedCharacter(_ trimmedTag: String) } /// Validate text field input /// func validateInput(originalText: String, range: Range<String.Index>, replacement: String) -> Result { var isEndingWithDisallowedCharacter = false if let disallowedCharacterRange = replacement.rangeOfCharacter(from: disallowedCharacterSet) { if disallowedCharacterRange.upperBound == replacement.endIndex, range.upperBound == originalText.endIndex { isEndingWithDisallowedCharacter = true } else { return .invalid } } var tag = originalText.replacingCharacters(in: range, with: replacement) if isEndingWithDisallowedCharacter { tag = tag.trimmingCharacters(in: disallowedCharacterSet) } if validateLength(tag: tag) { if isEndingWithDisallowedCharacter { return .endingWithDisallowedCharacter(tag) } return .valid } return .invalid } /// Trim disallowed characters and return the first part before whitespace or newline /// func preprocessForPasting(tag: String) -> String? { return tag.components(separatedBy: disallowedCharacterSet) .filter({ !$0.isEmpty }) .first } /// Indicates if the receivers length is within allowed values /// - Important: `Tag.name` is used as the entity's `simperiumKey`, and the backend imposes a length. /// For that reason we must check on the `encoded` lenght (and not the actual raw string length) private func validateLength(tag: String) -> Bool { tag.byEncodingAsTagHash.count <= Constants.maximumTagLength } } // MARK: - Constants // private struct Constants { static let maximumTagLength = 256 } ```
/content/code_sandbox/Simplenote/Classes/TagTextFieldInputValidator.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
463
```swift import Foundation import LocalAuthentication // MARK: - BiometricAuthentication // class BiometricAuthentication { /// Biometry /// enum Biometry { case touchID case faceID } /// Available biometry type or nil if biometry is not supported or user disabled it in settings /// var availableBiometry: Biometry? { let context = LAContext() var error: NSError? guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else { return nil } switch context.biometryType { case .none: return nil case .touchID: return .touchID case .faceID: return .faceID default: return nil } } /// Evaluate biometry /// func evaluate(completion: @escaping (_ success: Bool) -> Void) { guard availableBiometry != nil else { completion(false) return } let context = LAContext() context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: Localization.biometryReason) { (success, _) in DispatchQueue.main.async { completion(success) } } } } // MARK: - Localization // private struct Localization { static let biometryReason = NSLocalizedString("To unlock the application", comment: "Touch ID reason/explanation") } ```
/content/code_sandbox/Simplenote/Classes/BiometricAuthentication.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
297
```swift import Foundation // MARK: - FileManager // extension FileManager { /// User's Document Directory /// var documentsURL: URL { guard let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { fatalError("Cannot Access User Documents Directory") } return url } /// URL for Simplenote's shared app group directory /// var sharedContainerURL: URL { containerURL(forSecurityApplicationGroupIdentifier: SimplenoteConstants.sharedGroupDomain)! } func recoveryDirectoryURL() -> URL? { let dir = sharedContainerURL.appendingPathComponent(Constants.recoveryDir) do { try createDirectoryIfNeeded(at: dir) } catch { NSLog("Could not create recovery directory because: $@", error.localizedDescription) return nil } return dir } func createDirectoryIfNeeded(at url: URL, withIntermediateDirectories: Bool = true) throws { if directoryExistsAtURL(url) { return } try createDirectory(at: url, withIntermediateDirectories: true) } func directoryExistsAtURL(_ url: URL) -> Bool { var isDir: ObjCBool = false let exists = self.fileExists(atPath: url.path, isDirectory: &isDir) return exists && isDir.boolValue } } private struct Constants { static let recoveryDir = "Recovery" } ```
/content/code_sandbox/Simplenote/Classes/FileManager+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
303
```swift import Foundation // MARK: - Simperium + Buckets // extension Simperium { var allBuckets: [SPBucket] { [ accountBucket, notesBucket, preferencesBucket, settingsBucket, tagsBucket ] } /// Bucket: Account /// - Note: Since it's **dynamic** (InMemory JSON Storage), we don't really have an Account class /// @objc var accountBucket: SPBucket { bucket(forName: Simperium.accountBucketName)! } /// Bucket: Notes /// @objc var notesBucket: SPBucket { bucket(forName: Note.classNameWithoutNamespaces)! } /// Bucket: Preferences /// @objc var preferencesBucket: SPBucket { bucket(forName: Preferences.classNameWithoutNamespaces)! } /// Bucket: Settings /// @objc var settingsBucket: SPBucket { bucket(forName: Settings.classNameWithoutNamespaces)! } /// Bucket: Tags /// @objc var tagsBucket: SPBucket { bucket(forName: Tag.classNameWithoutNamespaces)! } } // MARK: - Public API(s) // extension Simperium { /// Returns the Note with the specified SimperiumKey /// @objc(loadNoteWithSimperiumKey:) func loadNote(simperiumKey: String) -> Note? { return notesBucket.object(forKey: simperiumKey) as? Note } } // MARK: - Constants // extension Simperium { static let accountBucketName = "Account" static let preferencesLastChangedSignatureKey = "lastChangeSignature-Preferences" } ```
/content/code_sandbox/Simplenote/Classes/Simperium+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
357
```swift import Foundation // MARK: - SortMode List Methods // extension NSSortDescriptor { /// Returns a NSSortDescriptor, to be applied over Note collections, so that the resulting collection reflects the specified `SortMode` /// static func descriptorForNotes(sortMode: SortMode) -> NSSortDescriptor { let sortKeySelector: Selector var sortSelector: Selector? var ascending = true switch sortMode { case .alphabeticallyAscending: sortKeySelector = #selector(getter: Note.content) sortSelector = #selector(NSString.caseInsensitiveCompare) case .alphabeticallyDescending: sortKeySelector = #selector(getter: Note.content) sortSelector = #selector(NSString.caseInsensitiveCompare) ascending = false case .createdNewest: sortKeySelector = #selector(getter: Note.creationDate) ascending = false case .createdOldest: sortKeySelector = #selector(getter: Note.creationDate) case .modifiedNewest: sortKeySelector = #selector(getter: Note.modificationDate) ascending = false case .modifiedOldest: sortKeySelector = #selector(getter: Note.modificationDate) } return NSSortDescriptor(key: NSStringFromSelector(sortKeySelector), ascending: ascending, selector: sortSelector) } /// Returns a NSSortDescriptor that, when applied over a Tags collection, results in the Pinned Notes to be on top /// static func descriptorForPinnedNotes() -> NSSortDescriptor { return NSSortDescriptor(keyPath: \Note.pinned, ascending: false) } /// Returns a NSSortDescriptor, to be applied over Tag collections. Yields a sorted collection of Tags, by name, ascending /// static func descriptorForTags() -> NSSortDescriptor { let key = NSStringFromSelector(#selector(getter: Tag.name)) let selector = #selector(NSString.caseInsensitiveCompare) return NSSortDescriptor(key: key, ascending: true, selector: selector) } } ```
/content/code_sandbox/Simplenote/Classes/NSSortDescriptor+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
439
```swift import Foundation // MARK: - PassthruView: Doesn't capture tap events performed over itself! // class PassthruView: UIView { /// Callback is invoked when interacted with this view and not with subviews /// var onInteraction: (() -> Void)? override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let output = super.hitTest(point, with: event) if output == self { onInteraction?() return nil } return output } } ```
/content/code_sandbox/Simplenote/Classes/PassthruView.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
116
```swift import Foundation // MARK: - UIBarButtonItem + Appearance // extension UIBarButtonItem { /// Applies the Simplenote Appearance to `UIBarButtonItem` instances /// class func refreshAppearance() { let titleAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.preferredFont(forTextStyle: .body) ] let appearance = UIBarButtonItem.appearance() appearance.setTitleTextAttributes(titleAttributes, for: .normal) } } ```
/content/code_sandbox/Simplenote/Classes/UIBarButtonItem+Appearance.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
92
```objective-c #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface NSString (Condensing) /// Returns a version of the receiver with all of its newlines replaced with spaces. /// /// - Note: Multiple consecutive newlines will be replaced by a *single* space /// - (NSString *)stringByReplacingNewlinesWithSpaces; @end NS_ASSUME_NONNULL_END ```
/content/code_sandbox/Simplenote/Classes/NSString+Condensing.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
75
```objective-c // // SPMarkdownParser.h // Simplenote // // Created by James Frost on 01/10/2015. // #import <Foundation/Foundation.h> /** * @class SPMarkdownParser * @brief This is a simple wrapper around the 'hoedown' Markdown parser, * which produces HTML from a Markdown input string. */ @interface SPMarkdownParser : NSObject + (NSString *)renderHTMLFromMarkdownString:(NSString *)markdown; @end ```
/content/code_sandbox/Simplenote/Classes/SPMarkdownParser.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
110
```objective-c #import "SPTracker.h" #import "SPAutomatticTracker.h" #import "SPAppDelegate.h" #import "Simperium+Simplenote.h" @implementation SPTracker #pragma mark - Metadata + (void)refreshMetadataWithEmail:(NSString *)email { [[SPAutomatticTracker sharedInstance] refreshMetadataWithEmail:email]; } + (void)refreshMetadataForAnonymousUser { [[SPAutomatticTracker sharedInstance] refreshMetadataForAnonymousUser]; } #pragma mark - Application State + (void)trackApplicationOpened { [self trackAutomatticEventWithName:@"application_opened" properties:nil]; } + (void)trackApplicationClosed { [self trackAutomatticEventWithName:@"application_closed" properties:nil]; } #pragma mark - Note Editor + (void)trackEditorNoteCreated { [self trackAutomatticEventWithName:@"editor_note_created" properties:nil]; } + (void)trackEditorNoteDeleted { [self trackAutomatticEventWithName:@"editor_note_deleted" properties:nil]; } + (void)trackEditorNoteRestored { [self trackAutomatticEventWithName:@"editor_note_restored" properties:nil]; } + (void)trackEditorNotePublishEnabled:(BOOL)isOn { NSString *name = isOn ? @"editor_note_published" : @"editor_note_unpublished"; [self trackAutomatticEventWithName:name properties:nil]; } + (void)trackEditorNoteContentShared { [self trackAutomatticEventWithName:@"editor_note_content_shared" properties:nil]; } + (void)trackEditorNoteEdited { [self trackAutomatticEventWithName:@"editor_note_edited" properties:nil]; } + (void)trackEditorEmailTagAdded { [self trackAutomatticEventWithName:@"editor_email_tag_added" properties:nil]; } + (void)trackEditorEmailTagRemoved { [self trackAutomatticEventWithName:@"editor_email_tag_removed" properties:nil]; } + (void)trackEditorTagAdded { [self trackAutomatticEventWithName:@"editor_tag_added" properties:nil]; } + (void)trackEditorTagRemoved { [self trackAutomatticEventWithName:@"editor_tag_removed" properties:nil]; } + (void)trackEditorNotePinEnabled:(BOOL)isOn { NSString *name = isOn ? @"editor_note_pinned" : @"editor_note_unpinned"; [self trackAutomatticEventWithName:name properties:nil]; } + (void)trackEditorNoteMarkdownEnabled:(BOOL)isOn { NSString *name = isOn ? @"editor_note_markdown_enabled" : @"editor_note_markdown_disabled"; [self trackAutomatticEventWithName:name properties:nil]; } + (void)trackEditorActivitiesAccessed { [self trackAutomatticEventWithName:@"editor_activities_accessed" properties:nil]; } + (void)trackEditorChecklistInserted { [self trackAutomatticEventWithName:@"editor_checklist_inserted" properties:nil]; } + (void)trackEditorCollaboratorsAccessed { [self trackAutomatticEventWithName:@"editor_collaborators_accessed" properties:nil]; } + (void)trackEditorVersionsAccessed { [self trackAutomatticEventWithName:@"editor_versions_accessed" properties:nil]; } + (void)trackEditorCopiedInternalLink { [self trackAutomatticEventWithName:@"editor_copied_internal_link" properties:nil]; } + (void)trackEditorCopiedPublicLink { [self trackAutomatticEventWithName:@"editor_copied_public_link" properties:nil]; } + (void)trackEditorInterlinkAutocompleteViewed { [self trackAutomatticEventWithName:@"editor_interlink_autocomplete_viewed" properties:nil]; } #pragma mark - Note List + (void)trackListNoteCreated { [self trackAutomatticEventWithName:@"list_note_created" properties:nil]; } + (void)trackListNoteDeleted { [self trackAutomatticEventWithName:@"list_note_deleted" properties:nil]; } + (void)trackListNoteOpened { [self trackAutomatticEventWithName:@"list_note_opened" properties:nil]; } + (void)trackListTrashEmptied { [self trackAutomatticEventWithName:@"list_trash_emptied" properties:nil]; } + (void)trackListNotesSearched { [self trackAutomatticEventWithName:@"list_notes_searched" properties:nil]; } + (void)trackListPinToggled { [self trackAutomatticEventWithName:@"list_note_toggled_pin" properties:nil]; } + (void)trackListCopiedInternalLink { [self trackAutomatticEventWithName:@"list_copied_internal_link" properties:nil]; } + (void)trackListTagViewed { [self trackAutomatticEventWithName:@"list_tag_viewed" properties:nil]; } + (void)trackListUntaggedViewed { [self trackAutomatticEventWithName:@"list_untagged_viewed" properties:nil]; } + (void)trackTrashViewed { [self trackAutomatticEventWithName:@"list_trash_viewed" properties:nil]; } #pragma mark - Preferences + (void)trackSettingsPinlockEnabled:(BOOL)isOn { [self trackAutomatticEventWithName:@"settings_pinlock_enabled" properties:@{ @"enabled" : @(isOn) }]; } + (void)trackSettingsListCondensedEnabled:(BOOL)isOn { [self trackAutomatticEventWithName:@"settings_list_condensed_enabled" properties:@{ @"enabled" : @(isOn) }]; } + (void)trackSettingsNoteListSortMode:(NSString *)description { [self trackAutomatticEventWithName:@"settings_note_list_sort_mode" properties:@{ @"description" : description }]; } + (void)trackSettingsThemeUpdated:(NSString *)themeName { NSParameterAssert(themeName); [self trackAutomatticEventWithName:@"settings_theme_updated" properties:@{ @"name" : themeName }]; } #pragma mark - Sidebar + (void)trackSidebarSidebarPanned { [self trackAutomatticEventWithName:@"sidebar_sidebar_panned" properties:nil]; } + (void)trackSidebarButtonPresed { [self trackAutomatticEventWithName:@"sidebar_button_pressed" properties:nil]; } #pragma mark - Tag List + (void)trackTagRowRenamed { [self trackAutomatticEventWithName:@"tag_row_renamed" properties:nil]; } + (void)trackTagRowDeleted { [self trackAutomatticEventWithName:@"tag_row_deleted" properties:nil]; } + (void)trackTagCellPressed { [self trackAutomatticEventWithName:@"tag_cell_pressed" properties:nil]; } + (void)trackTagMenuRenamed { [self trackAutomatticEventWithName:@"tag_menu_renamed" properties:nil]; } + (void)trackTagMenuDeleted { [self trackAutomatticEventWithName:@"tag_menu_deleted" properties:nil]; } + (void)trackTagEditorAccessed { [self trackAutomatticEventWithName:@"tag_editor_accessed" properties:nil]; } #pragma mark - Ratings + (void)trackRatingsPromptSeen { [self trackAutomatticEventWithName:@"ratings_prompt_seen" properties:nil]; } + (void)trackRatingsAppRated { [self trackAutomatticEventWithName:@"ratings_app_rated" properties:nil]; } + (void)trackRatingsAppLiked { [self trackAutomatticEventWithName:@"ratings_app_liked" properties:nil]; } + (void)trackRatingsAppDisliked { [self trackAutomatticEventWithName:@"ratings_app_disliked" properties:nil]; } + (void)trackRatingsDeclinedToRate { [self trackAutomatticEventWithName:@"ratings_declined_to_rate_app" properties:nil]; } + (void)trackRatingsFeedbackScreenOpened { [self trackAutomatticEventWithName:@"ratings_feedback_screen_opened" properties:nil]; } + (void)trackRatingsFeedbackSent { [self trackAutomatticEventWithName:@"ratings_feedback_sent" properties:nil]; } + (void)trackRatingsFeedbackDeclined { [self trackAutomatticEventWithName:@"ratings_feedback_declined" properties:nil]; } #pragma mark - User + (void)trackUserAccountCreated { [self trackAutomatticEventWithName:@"user_account_created" properties:nil]; } + (void)trackUserSignedIn { [self trackAutomatticEventWithName:@"user_signed_in" properties:nil]; } + (void)trackUserSignedOut { [self trackAutomatticEventWithName:@"user_signed_out" properties:nil]; } #pragma mark - Login Links + (void)trackLoginLinkRequested { [self trackAutomatticEventWithName:@"login_link_requested" properties:nil]; } + (void)trackLoginLinkConfirmationSuccess { [self trackAutomatticEventWithName:@"login_link_confirmation_success" properties:nil]; } + (void)trackLoginLinkConfirmationFailure { [self trackAutomatticEventWithName:@"login_link_confirmation_failure" properties:nil]; } #pragma mark - WP.com Sign In + (void)trackWPCCButtonPressed { [self trackAutomatticEventWithName:@"wpcc_button_pressed" properties:nil]; } + (void)trackWPCCLoginSucceeded { [self trackAutomatticEventWithName:@"wpcc_login_succeeded" properties:nil]; } + (void)trackWPCCLoginFailed { [self trackAutomatticEventWithName:@"wpcc_login_failed" properties:nil]; } #pragma mark - Google Analytics Helpers + (void)trackAutomatticEventWithName:(NSString *)name properties:(NSDictionary *)properties { if ([self isTrackingDisabled]) { return; } [[SPAutomatticTracker sharedInstance] trackEventWithName:name properties:properties]; } #pragma mark - Automattic Tracks Helpers + (BOOL)isTrackingDisabled { Preferences *preferences = [[[SPAppDelegate sharedDelegate] simperium] preferencesObject]; NSNumber *enabled = [preferences analytics_enabled]; return [enabled boolValue] == false; } @end ```
/content/code_sandbox/Simplenote/Classes/SPTracker.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,198
```swift import Foundation import UIKit // MARK: - SPTagTableViewCell // @objcMembers class SPTagTableViewCell: UITableViewCell { /// Left UIImageView /// @IBOutlet private var leftImageView: UIImageView! /// Left UIImageView's Height Constraint /// @IBOutlet private var leftImageHeightConstraint: NSLayoutConstraint! /// Tag Name's Label /// @IBOutlet private var nameLabel: UILabel! /// Spacing Width Constraint: We're matching the Note Cell's Leading metrics /// @IBOutlet private var spacingViewWidthConstraint: NSLayoutConstraint! /// Left Image /// var leftImage: UIImage? { get { leftImageView.image } set { leftImageView.image = newValue } } /// Left Image's Tint Color /// var leftImageTintColor: UIColor { get { leftImageView.tintColor } set { leftImageView.tintColor = newValue } } /// Note's Title /// var titleText: String? { get { nameLabel?.text } set { nameLabel?.text = newValue } } /// 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() refreshStyle() refreshConstraints() } override func prepareForReuse() { super.prepareForReuse() refreshStyle() refreshConstraints() } } // MARK: - Private Methods // private extension SPTagTableViewCell { /// Setup: Layout Margins /// func setupMargins() { // Note: This one affects the TableView's separatorInsets layoutMargins = .zero } /// Refreshes the current Style current style /// func refreshStyle() { nameLabel.textColor = Style.textColor 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 assetHeight = Style.labelFont.inlineAssetHeight() // What's the spacing about? // We're matching NoteTableViewCell's Left Spacing (which is where the Pinned Indicator goes). // Our goal is to have the Left Image's PositionX to match the Note Cell's title label // spacingViewWidthConstraint.constant = max(min(assetHeight, Style.spacingMaximumSize), Style.spacingMinimumSize) leftImageHeightConstraint.constant = max(min(assetHeight, Style.imageMaximumSize), Style.imageMinimumSize) } } // MARK: - Notifications // private extension SPTagTableViewCell { /// 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: - Static! // extension SPTagTableViewCell { /// Returns the Height that the receiver would require to be rendered /// /// Note: Why these calculations? why not Autosizing cells?. Well... Performance. /// static var cellHeight: CGFloat { let lineHeight = UIFont.preferredFont(forTextStyle: .headline).lineHeight let padding = Style.padding let result = padding.top + lineHeight + padding.bottom return result.rounded(.up) } } // MARK: - Cell Styles // private enum Style { /// Accessory's Minimum Size /// static let imageMinimumSize = CGFloat(24) /// Accessory's Maximum Size (1.5 the asset's size) /// static let imageMaximumSize = CGFloat(36) /// Accessory's Minimum Size /// static let spacingMinimumSize = CGFloat(15) /// Accessory's Maximum Size (1.5 the asset's size) /// static let spacingMaximumSize = CGFloat(24) /// Tag(s) Cell Vertical Padding /// static let padding = UIEdgeInsets(top: 12, left: 0, bottom: 12, right: 0) /// Returns the Cell's Background Color /// static var backgroundColor: UIColor { .simplenoteBackgroundColor } /// Headline Font: To be applied over the first preview line /// static var labelFont: UIFont { .preferredFont(forTextStyle: .body) } /// Headline Color: To be applied over the first preview line /// static var textColor: UIColor { .simplenoteTextColor } /// Color to be applied over the cell upon selection /// static var selectionColor: UIColor { .simplenoteLightBlueColor } } ```
/content/code_sandbox/Simplenote/Classes/SPTagTableViewCell.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,097
```swift import Foundation // MARK: - UINavigationBar Simplenote Methods // extension UINavigationBar { /// Applies Simplenote's **LIGHT** Style /// @objc func applyLightStyle() { let bcColor = UIColor.white backgroundColor = bcColor barTintColor = bcColor let backgroundImage = UIImage() shadowImage = backgroundImage setBackgroundImage(backgroundImage, for: .default) setBackgroundImage(backgroundImage, for: .defaultPrompt) } } ```
/content/code_sandbox/Simplenote/Classes/UINavigationBar+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
104
```objective-c // // JSONKit+Simplenote.h // Simplenote-iOS // // Created by Jorge Leandro Perez on 1/4/14. // @interface NSArray (JSONKit) - (NSString *)JSONString; @end @interface NSDictionary (JSONKit) - (NSString *)JSONString; @end @interface NSString (JSONKit) - (id)objectFromJSONString; @end @interface NSData (JSONKit) - (id)objectFromJSONString; @end ```
/content/code_sandbox/Simplenote/Classes/JSONKit+Simplenote.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
101
```objective-c // // UITextView+Simplenote.h // Simplenote // // Created by Jorge Leandro Perez on 3/25/15. // #import <Foundation/Foundation.h> @interface UITextView (Simplenote) - (BOOL)applyAutoBulletsWithReplacementText:(NSString *)replacementText replacementRange:(NSRange)replacementRange; - (NSRange)visibleTextRange; @end ```
/content/code_sandbox/Simplenote/Classes/UITextView+Simplenote.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
85
```swift import Foundation import UIKit // MARK: - UIView: Image Representation Helpers // extension UIView { /// Returns a UIImage containing a rastrerized version of the receiver. /// @objc func imageRepresentation() -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { [unowned self] rendererContext in self.layer.render(in: rendererContext.cgContext) } } /// Returns the Image Representation of the receiver, contained within an UIImageView Instance. /// @objc func imageRepresentationWithinImageView() -> UIImageView { let output = UIImageView(image: imageRepresentation()) output.sizeToFit() return output } } ```
/content/code_sandbox/Simplenote/Classes/UIView+ImageRepresentation.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
145
```swift import Foundation import QuartzCore // MARK: - ViewSpinner: Spin a view // final class ViewSpinner { private let view: UIView private var displayLink: CADisplayLink? private var angle: Double = 0.0 private var velocity: Double = 0.0 /// Callback is invoked once max velocity is reached /// var onMaxVelocity: (() -> Void)? /// Init with a view to spin /// init(view: UIView) { self.view = view } /// Start spinning /// func start() { guard displayLink == nil else { return } view.layer.removeAllAnimations() velocity = 0.0 angle = 0.0 displayLink = CADisplayLink(target: self, selector: #selector(update(_:))) displayLink?.add(to: .current, forMode: .common) } /// Stop spinning /// func stop() { guard displayLink != nil else { return } displayLink?.invalidate() displayLink = nil let doublePi = 2 * Double.pi let targetAngle = ceil(angle / doublePi) * doublePi + doublePi view.layer.setAffineTransform(.init(rotationAngle: -CGFloat(targetAngle))) let spring = CASpringAnimation(keyPath: "transform.rotation") spring.damping = Constants.decelertaionDamping spring.initialVelocity = CGFloat((targetAngle - angle) / velocity) spring.fromValue = -angle spring.toValue = -targetAngle spring.duration = Constants.decelerationDuration spring.isRemovedOnCompletion = true view.layer.add(spring, forKey: "rotation") } @objc private func update(_ displayLink: CADisplayLink) { let timeDelta = displayLink.targetTimestamp - displayLink.timestamp let prevVelocity = velocity velocity = velocity + Constants.acceleration * timeDelta velocity = min(velocity, Constants.maxVelocity) angle = angle + velocity * timeDelta view.transform = .init(rotationAngle: -CGFloat(angle)) let shouldNotifyAboutMaxVelocity = prevVelocity < Constants.maxVelocity && velocity == Constants.maxVelocity if shouldNotifyAboutMaxVelocity { onMaxVelocity?() } } } // MARK: - Constants // private enum Constants { static let acceleration = Double(40.0) // Radians per sec static let maxVelocity = Double(50.0) // Radians per sec static let decelerationDuration = TimeInterval(1.5) static let decelertaionDamping = CGFloat(14.0) } ```
/content/code_sandbox/Simplenote/Classes/ViewSpinner.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
572
```objective-c // // SPTextField.h // Simplenote // // Created by Tom Witkin on 10/13/13. // #import <UIKit/UIKit.h> @interface SPTextField : UITextField @property (nonatomic, assign) NSDirectionalEdgeInsets rightViewInsets; @property (nonatomic, strong) UIColor *placeholdTextColor; @end ```
/content/code_sandbox/Simplenote/Classes/SPTextField.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
71
```objective-c #import "NSProcessInfo+Util.h" @implementation NSProcessInfo (Util) + (BOOL)isRunningTests { NSDictionary *environment = [[NSProcessInfo processInfo] environment]; NSString *injectBundle = environment[@"XCInjectBundle"]; BOOL result = [[injectBundle pathExtension] isEqualToString:@"xctest"] || [[injectBundle pathExtension] isEqualToString:@"octest"]; return result; } @end ```
/content/code_sandbox/Simplenote/Classes/NSProcessInfo+Util.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
86
```objective-c // // SPCollaboratorCompletionCell.h // Simplenote // // Created by Tom Witkin on 7/27/13. // #import "SPEntryListCell.h" @interface SPEntryListAutoCompleteCell : SPEntryListCell @end ```
/content/code_sandbox/Simplenote/Classes/SPEntryListAutoCompleteCell.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
59
```swift import Foundation // MARK: - NSURL + Interlink // extension NSURL { /// Indicates if the receiver' has the Simplenote Scheme /// @objc var isSimplenoteURL: Bool { scheme?.lowercased() == SimplenoteConstants.simplenoteScheme } /// Indicates if the receiver is a reference to a Note /// var isInterlinkURL: Bool { isSimplenoteURL && host?.lowercased() == SimplenoteConstants.simplenoteInterlinkHost } /// Extracts the Internal Note's SimperiumKey, whenever the receiver is an Interlink URL /// @objc var interlinkSimperiumKey: String? { guard isInterlinkURL else { return nil } return path?.replacingOccurrences(of: "/", with: "") } /// Indicates if the receiver is a reference to a tag /// @objc var isInternalTagURL: Bool { isSimplenoteURL && host?.lowercased() == SimplenoteConstants.simplenoteInternalTagHost } /// Extracts the tag, whenever the receiver is an internal tag url /// @objc var internalTagKey: String? { guard isInternalTagURL, let components = URLComponents(url: self as URL, resolvingAgainstBaseURL: false), let tagQuery = components.queryItems?.first(where: { $0.name == "tag" }) else { return nil } return tagQuery.value } } ```
/content/code_sandbox/Simplenote/Classes/NSURL+Links.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
340
```swift import Foundation import UIKit // MARK: - SPEditorTapRecognizerDelegate // Since the dawn of time, UITextView itself was set as (our own) TapGestureRecognizer delegate. // As per iOS 14, the new (superclass) implementation is not allowing our Tap recognizer to work simultaneously with its (internal) // recognizers. This is causing several undesired side effects. // // Ref. path_to_url // class SPEditorTapRecognizerDelegate: NSObject, UIGestureRecognizerDelegate { /// TextView in which we're listening to changes /// @objc weak var parentTextView: UITextView? /// View that, when interacted upon, should cause the recognizer to bail out /// @objc weak var excludedView: UIView? /// TextView only performs linkification when the `editable` flag is disabled. /// We're allowing Edition by means of a TapGestureRecognizer, which also allows us to deal with Tap events performed over TextAttachments /// /// Ref. path_to_url /// func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { guard let textView = parentTextView else { return true } if textView.isDragging { return false } let characterIndex = gestureRecognizer.characterIndex(in: textView) if textView.attachment(ofType: SPTextAttachment.self, at: characterIndex) != nil { return true } return textView.isFirstResponder == false } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard let excludedView = excludedView, let touchView = touch.view else { return true } return touchView.isDescendant(of: excludedView) == false } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } } ```
/content/code_sandbox/Simplenote/Classes/SPEditorTapRecognizerDelegate.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
403
```objective-c // // SPSimperiumManager.m // Simplenote // // Created by Tom Witkin on 7/26/13. // #import "SPObjectManager.h" #import "NSManagedObjectContext+CoreDataExtensions.h" #import <Simperium/Simperium.h> #import "SPAppDelegate.h" #import "Note.h" #import "Tag.h" #import "NSString+Metadata.h" #import "Simplenote-Swift.h" @implementation SPObjectManager + (SPObjectManager *)sharedManager { static SPObjectManager *sharedManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedManager = [[SPObjectManager alloc] init]; }); return sharedManager; } - (void)save { [[SPAppDelegate sharedDelegate] save]; } - (NSArray *)notes { return [[SPAppDelegate sharedDelegate].simperium.managedObjectContext fetchAllObjectsForEntityName:@"Note"]; } - (NSArray *)tags { // sort by index NSArray *allTags = [[SPAppDelegate sharedDelegate].simperium.managedObjectContext fetchAllObjectsForEntityName:@"Tag"]; NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"index" ascending:YES]; return [allTags sortedArrayUsingDescriptors:@[sortDescriptor]]; } - (BOOL)tagExists:(NSString *)tagName { return [self tagForName:tagName] != nil; } // This API performs `Tag` comparison by checking the `encoded tag hash`, in order to // normalize / isolate ourselves from potential Unicode-Y issues. // // Ref. path_to_url // - (Tag *)tagForName:(NSString *)tagName { NSString *targetTagHash = tagName.byEncodingAsTagHash; for (Tag *tag in self.tags) { if ([tag.name.byEncodingAsTagHash isEqualToString:targetTagHash]) { return tag; } } return nil; } - (void)editTag:(Tag *)tag title:(NSString *)newTitle { [self createTagFromString:newTitle atIndex:[self indexOfTag:tag]]; // Brute force renaming of all notes with this tag NSArray *notes = [self notesWithTag:tag]; for (Note *note in notes) { // Issue #311: Force the note to be loaded (this is a hack, yeah!) [note simperiumKey]; // Proceed renaming! [note stripTag: tag.name]; [note addTag: newTitle]; [note createPreview]; } NSManagedObjectContext *managedObjectContext = [[SPAppDelegate sharedDelegate] managedObjectContext]; [managedObjectContext deleteObject:tag]; [self save]; } - (BOOL)removeTagName:(NSString *)tagName { return [self removeTag:[self tagForName:tagName]]; } - (BOOL)removeTag:(Tag *)tag { NSArray *tagList = [self tags]; BOOL tagRemoved = NO; if (!tag) { NSLog(@"Critical error: tried to remove a tag that doesn't exist"); return tagRemoved; } NSArray *notes = [self notesWithTag: tag includeDeleted:YES]; // Strip this tag from all notes for (Note *note in notes) { [note stripTag: tag.name]; [note createPreview]; } NSInteger i = [tagList indexOfObject: tag] + 1; // Decrement the index of all tags after this one if (i != NSNotFound) { for (;i<[tagList count]; i++) { Tag *tagToUpdate = [tagList objectAtIndex: i]; int currentIndex = [tagToUpdate.index intValue]; tagToUpdate.index = [NSNumber numberWithInt:currentIndex-1]; } } NSManagedObjectContext *managedObjectContext = [[SPAppDelegate sharedDelegate] managedObjectContext]; [managedObjectContext deleteObject:tag]; tagRemoved = tag.isDeleted; [self save]; return tagRemoved; } - (Tag *)createTagFromString:(NSString *)tagName { // Add tag at end return [self createTagFromString:tagName atIndex:self.tags.count]; } - (Tag *)createTagFromString:(NSString *)tagName atIndex:(NSInteger)index { if (tagName == nil || tagName.length == 0 || [tagName isEqualToString:@" "]) { NSLog(@"Attempted to create empty tag"); return nil; } // Make sure email addresses don't get added as proper tags if ([tagName isValidEmailAddress]) { return nil; } // Ensure the new tag has no spaces NSString *newTagName = [[tagName componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString:@""]; // Check for duplicate if ([self tagExists:newTagName]) { return nil; } // Update indexes depending on where the tag will be inserted NSInteger tagIndex = index; NSArray *tagList = [self tags]; while (tagIndex < tagList.count) { Tag *updatedTag = [tagList objectAtIndex:tagIndex]; updatedTag.index = @(tagIndex+1); NSLog(@"Changed tag index at %ld to %d", (long)tagIndex, [updatedTag.index intValue]); tagIndex++; } // Finally Insert the new Tag SPBucket *tagBucket = [[SPAppDelegate sharedDelegate].simperium bucketForName:@"Tag"]; Tag *newTag = [tagBucket insertNewObjectForKey:newTagName.byEncodingAsTagHash]; newTag.index = @(index); newTag.name = newTagName; NSLog(@"Added new tag with index %d", [newTag.index intValue]); return newTag; } - (NSInteger)indexOfTag:(Tag *)tag { return [self.tags indexOfObject:tag]; } - (void)moveTagFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex { NSArray *tagList = [self tags]; NSMutableArray *tagListCopy = [tagList mutableCopy]; Tag *fromTag = [tagList objectAtIndex:fromIndex]; // Make arrays do the work of figuring out index changes (inefficient, but acceptable since this happens // infrequently) [tagListCopy insertObject:fromTag atIndex: toIndex+(fromIndex < toIndex ? 1:0)]; [tagListCopy removeObjectAtIndex:fromIndex + (fromIndex > toIndex ? 1:0)]; for (Tag *tag in tagList) { tag.index = @([tagListCopy indexOfObject:tag]); // yep, inefficient NSLog(@"index of tag %@ is now %d", tag.name, [tag.index intValue]); } [self save]; } - (void)trashNote:(Note *)note { note.deleted = YES; note.modificationDate = [NSDate date]; [self save]; } - (void)restoreNote:(Note *)note { note.deleted = NO; note.modificationDate = [NSDate date]; [self save]; } - (void)permenentlyDeleteNote:(Note *)note { NSManagedObjectContext *managedObjectContext = [[SPAppDelegate sharedDelegate] managedObjectContext]; [managedObjectContext deleteObject:note]; [self save]; } - (void)emptyTrash { NSManagedObjectContext *context = [[SPAppDelegate sharedDelegate] managedObjectContext]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"deleted == YES"]; NSArray *notesToDelete = [context fetchObjectsForEntityName:@"Note" withPredicate:predicate]; for (Note *note in notesToDelete) { [self permenentlyDeleteNote:note]; } [self save]; } #pragma mark - Sharing - (void)insertTagNamed:(NSString *)tagName note:(Note *)note { [note addTag:tagName]; note.modificationDate = [NSDate date]; [self save]; } - (void)removeTagNamed:(NSString *)tagName note:(Note *)note { [note stripTag:tagName]; note.modificationDate = [NSDate date]; [self save]; } #pragma mark - Updating Notes - (void)updateMarkdownState:(BOOL)markdown note:(Note *)note { if (note.markdown == markdown) { return; } note.markdown = markdown; note.modificationDate = [NSDate date]; [self save]; } - (void)updatePublishedState:(BOOL)published note:(Note *)note { if (note.published == published) { return; } note.published = published; note.modificationDate = [NSDate date]; [self save]; } - (void)updatePinnedState:(BOOL)pinned note:(Note *)note { if (note.pinned == pinned) { return; } note.pinned = pinned; note.modificationDate = [NSDate date]; [self save]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPObjectManager.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,916
```objective-c // // SPDebugViewController.m // Simplenote // // Created by Jorge Leandro Perez on 6/3/14. // #import "SPDebugViewController.h" #import "SPAppDelegate.h" #import "Note.h" #import "Simplenote-Swift.h" #import <Simperium/Simperium.h> #import <Simperium/SPBucket.h> static NSInteger const SPDebugSectionCount = 1; typedef NS_ENUM(NSInteger, SPDebugRow) { SPDebugRowWebsocket = 0, SPDebugRowTimestamp = 1, SPDebugRowAuthenticated = 2, SPDebugRowReachability = 3, SPDebugRowPendings = 4, SPDebugRowEnqueued = 5, SPDebugRowCount = 6 }; @interface SPDebugViewController () @property (nonatomic, assign) NSUInteger localPendingChanges; @property (nonatomic, assign) NSUInteger localEnqueuedChanges; @property (nonatomic, assign) NSUInteger localEnqueuedDeletions; @end @implementation SPDebugViewController - (void)viewDidLoad { [super viewDidLoad]; [self.tableView applySimplenoteGroupedStyle]; self.title = NSLocalizedString(@"Debug", @"Debug Screen Title"); Simperium *simperium = [[SPAppDelegate sharedDelegate] simperium]; SPBucket *bucket = [simperium bucketForName:NSStringFromClass([Note class])]; [bucket statsWithCallback:^(SPBucket *bucket, NSUInteger localPendingChanges, NSUInteger localEnqueuedChanges, NSUInteger localEnqueuedDeletions) { self.localPendingChanges = localPendingChanges; self.localEnqueuedChanges = localEnqueuedChanges; self.localEnqueuedDeletions = localEnqueuedDeletions; [self.tableView reloadData]; }]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return SPDebugSectionCount; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return SPDebugRowCount; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath]; Simperium *simperium = [[SPAppDelegate sharedDelegate] simperium]; switch (indexPath.row) { case SPDebugRowWebsocket: { cell.textLabel.text = NSLocalizedString(@"WebSocket", @"WebSocket Status"); cell.detailTextLabel.text = simperium.networkStatus; cell.selectionStyle = UITableViewCellSelectionStyleNone; break; } case SPDebugRowTimestamp: { NSString *timestamp = [NSDateFormatter localizedStringFromDate:simperium.networkLastSeenTime dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterLongStyle]; cell.textLabel.text = NSLocalizedString(@"LastSeen", @"Last Message timestamp"); cell.detailTextLabel.text = timestamp; cell.selectionStyle = UITableViewCellSelectionStyleNone; break; } case SPDebugRowReachability: { cell.textLabel.text = NSLocalizedString(@"Reachability", @"Reachs Internet"); cell.detailTextLabel.text = simperium.requiresConnection ? @"YES" : @"NO"; cell.selectionStyle = UITableViewCellSelectionStyleNone; break; } case SPDebugRowAuthenticated: { cell.textLabel.text = NSLocalizedString(@"Authenticated", @"User Authenticated"); cell.detailTextLabel.text = simperium.user.authenticated ? @"YES" : @"NO"; cell.selectionStyle = UITableViewCellSelectionStyleNone; break; } case SPDebugRowPendings: { cell.textLabel.text = NSLocalizedString(@"Pendings", @"Number of changes pending to be sent"); cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld", (long)self.localPendingChanges]; cell.selectionStyle = UITableViewCellSelectionStyleNone; break; } case SPDebugRowEnqueued: { cell.textLabel.text = NSLocalizedString(@"Enqueued", @"Number of objects enqueued for processing"); cell.detailTextLabel.text = [NSString stringWithFormat:@"%ld", (long)self.localEnqueuedChanges]; cell.selectionStyle = UITableViewCellSelectionStyleNone; break; } default: { break; } } return cell; } #pragma mark - Static Helpers + (instancetype)newDebugViewController { return [[SPDebugViewController alloc] initWithStyle:UITableViewStyleGrouped]; } @end ```
/content/code_sandbox/Simplenote/Classes/SPDebugViewController.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
944
```swift import Foundation import UIKit // MARK: - UIView's Simplenote Methods // extension UIView { /// Indicates if the receiver has the horizontal compact trait /// @objc func isHorizontallyCompact() -> Bool { return traitCollection.horizontalSizeClass == .compact } /// Adjusts the receiver's size for a compressed layout /// @objc func adjustSizeForCompressedLayout() { frame.size = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) } /// Returns all of the subviews of a given type /// func subviewsOfType<T: UIView>(_ type: T.Type) -> [T] { var output = [T]() for subview in subviews { output += subview.subviewsOfType(type) if let subview = subview as? T { output.append(subview) } } return output } /// Returns the enclosing TextView, if any /// @objc func enclosingTextView() -> UITextView? { if let textView = self as? UITextView { return textView } return superview?.enclosingTextView() } /// Returns the first subview in the receiver's hierarchy, downcasted as a UITableView. Returns nil, of course, if it's not a TableView! /// @objc func firstSubviewAsTableView() -> UITableView? { return subviews.first as? UITableView } /// Returns the Receiver's User Interface Direction /// @objc var userInterfaceLayoutDirection: UIUserInterfaceLayoutDirection { UIView.userInterfaceLayoutDirection(for: semanticContentAttribute) } } // MARK: - UIView Class Methods // extension UIView { /// Returns the Nib associated with the received: It's filename is expected to match the Class Name /// @objc class func loadNib() -> UINib { return UINib(nibName: classNameWithoutNamespaces, bundle: nil) } /// Returns the first Object contained within the nib with a name whose name matches with the receiver's type. /// Note: On error this method is expected to break, by design! /// class func instantiateFromNib<T>() -> T { return loadNib().instantiate(withOwner: nil, options: nil).first as! T } /// ObjC Convenience wrapper: Returns the first object contained within the receiver's nib. /// It's exactly the same as `instantiateFromNib`... but naming it differently to avoid collisions! /// @objc class func loadFromNib() -> Any? { return loadNib().instantiate(withOwner: nil, options: nil).first } } ```
/content/code_sandbox/Simplenote/Classes/UIView+Simplenote.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
578
```swift import Foundation import UIKit // MARK: - SwitchTableViewCell // class SwitchTableViewCell: UITableViewCell { /// Accessory View /// private(set) lazy var switchControl = UISwitch() /// Accessibility Hint to be applied over the control, whenever it's On /// var enabledAccessibilityHint: String? /// Accessibility Hint to be applied over the control, whenever it's Off /// var disabledAccessibilityHint: String? /// Wraps the TextLabel's Text Property /// var title: String? { get { textLabel?.text } set { textLabel?.text = newValue } } /// Indicates if the switch is On / Off /// var isOn: Bool { get { switchControl.isOn } set { switchControl.isOn = newValue switchControl.accessibilityHint = newValue ? enabledAccessibilityHint : disabledAccessibilityHint } } /// Listener: Receives the new State /// var onChange: ((Bool) -> Void)? // MARK: - Initializers override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupGestureRecognizer() setupSwitchControl() setupTableViewCell() refreshStyles() } required init?(coder: NSCoder) { super.init(coder: coder) } } // MARK: - Private API(s) // private extension SwitchTableViewCell { func setupGestureRecognizer() { let recognizer = UITapGestureRecognizer(target: self, action: #selector(contentWasPressed)) addGestureRecognizer(recognizer) } func setupSwitchControl() { switchControl.addTarget(self, action: #selector(switchDidChange), for: .valueChanged) } func setupTableViewCell() { accessoryView = switchControl selectionStyle = .none } func refreshStyles() { backgroundColor = .simplenoteTableViewCellBackgroundColor selectedBackgroundView?.backgroundColor = .simplenoteLightBlueColor switchControl.onTintColor = .simplenoteSwitchOnTintColor switchControl.tintColor = .simplenoteSwitchTintColor textLabel?.textColor = .simplenoteTextColor imageView?.tintColor = .simplenoteTextColor } } // MARK: - Action Handlers // extension SwitchTableViewCell { @IBAction func contentWasPressed() { let nextState = !switchControl.isOn switchControl.setOn(nextState, animated: true) notifyStateDidChangeAfterDelay() } @IBAction func switchDidChange() { notifyStateDidChangeAfterDelay() } /// Note: Why after a delay? /// Because this callback is expected to trigger a DB update, which might fire back into a `reloadData` call. /// This sequence is known to break animations. So we're deferring things up a bit! /// private func notifyStateDidChangeAfterDelay() { DispatchQueue.main.asyncAfter(deadline: .now() + UIKitConstants.animationQuickDuration) { [onChange, switchControl] in onChange?(switchControl.isOn) } } } ```
/content/code_sandbox/Simplenote/Classes/SwitchTableViewCell.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
657
```objective-c @interface NSString (Metadata) // Removes pin and tags - (NSArray *)stringArray; @end ```
/content/code_sandbox/Simplenote/Classes/NSString+Metadata.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
22
```objective-c // // SPTextField.m // Simplenote // // Created by Tom Witkin on 10/13/13. // #import "SPTextField.h" #import "Simplenote-Swift.h" @implementation SPTextField - (void)drawPlaceholderInRect:(CGRect)rect { if (self.placeholdTextColor == nil || self.placeholder.length == 0) { [super drawPlaceholderInRect:rect]; return; } [self.placeholder drawInRect:rect withAttributes:@{ NSFontAttributeName: self.font, NSForegroundColorAttributeName: self.placeholdTextColor }]; } - (CGRect)textRectForBounds:(CGRect)bounds { CGRect output = [super textRectForBounds:bounds]; return [self applyAccessoryInsetsToTextBounds:output]; } - (CGRect)editingRectForBounds:(CGRect)bounds { CGRect output = [super editingRectForBounds:bounds]; return [self applyAccessoryInsetsToTextBounds:output]; } - (CGRect)rightViewRectForBounds:(CGRect)bounds { // Invoked in LTR Mode. Let's not adjust the width, since it'd skew the Right Image CGRect output = [super rightViewRectForBounds:bounds]; if (CGRectGetWidth(output) > 0) { output.origin.x -= self.rightViewInsets.trailing; } return output; } - (CGRect)leftViewRectForBounds:(CGRect)bounds { // Invoked in RTL Mode. Let's not adjust the width, since it'd skew the Right Image CGRect output = [super leftViewRectForBounds:bounds]; if (CGRectGetWidth(output) > 0) { output.origin.x += self.rightViewInsets.leading; } return output; } - (CGRect)applyAccessoryInsetsToTextBounds:(CGRect)frame { if (self.userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionLeftToRight) { frame.size.width -= self.rightViewInsets.trailing; return frame; } frame.origin.x += self.rightViewInsets.leading; frame.size.width -= self.rightViewInsets.leading; return frame; } @end ```
/content/code_sandbox/Simplenote/Classes/SPTextField.m
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
461
```swift import Foundation // MARK: - PinLockVerifyControllerDelegate // protocol PinLockVerifyControllerDelegate: AnyObject { func pinLockVerifyControllerDidComplete(_ controller: PinLockVerifyController) } final class PinLockVerifyController: PinLockBaseController, PinLockController { var isCancellable: Bool { return false } private var attempts: Int = 1 private var hasShownBiometryVerification: Bool = false private let pinLockManager: SPPinLockManager private let application: ApplicationStateProvider private weak var delegate: PinLockVerifyControllerDelegate? private var onSuccesBlocks = [(() -> Void)]() init(pinLockManager: SPPinLockManager = .shared, application: ApplicationStateProvider = UIApplication.shared, delegate: PinLockVerifyControllerDelegate) { self.pinLockManager = pinLockManager self.application = application self.delegate = delegate super.init() configuration = PinLockControllerConfiguration(title: Localization.title, message: nil) } func handlePin(_ pin: String) { guard pinLockManager.validatePin(pin) else { switchToFailedAttempt(withTitle: Localization.title, attempts: attempts) attempts += 1 return } delegate?.pinLockVerifyControllerDidComplete(self) runOnSuccessBlocks() } func handleCancellation() { } func viewDidAppear() { verifyBiometry() } func applicationDidBecomeActive() { verifyBiometry() } private func runOnSuccessBlocks() { onSuccesBlocks.forEach({ $0() }) removeSuccesBlocks() } func addOnSuccesBlock(block: @escaping () -> Void) { onSuccesBlocks.append(block) } func removeSuccesBlocks() { onSuccesBlocks.removeAll() } } // MARK: - Biometry // private extension PinLockVerifyController { func verifyBiometry() { guard application.applicationState == .active, !hasShownBiometryVerification else { return } hasShownBiometryVerification = true pinLockManager.evaluateBiometry { [weak self] (success) in guard let self = self else { return } if success { self.delegate?.pinLockVerifyControllerDidComplete(self) self.runOnSuccessBlocks() } } } } // MARK: - Localization // private enum Localization { static let title = NSLocalizedString("Enter your passcode", comment: "Title on the PinLock screen asking to enter a passcode") } ```
/content/code_sandbox/Simplenote/Classes/PinLock/PinLockVerifyController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
558
```swift import Foundation // MARK: - PinLockBaseController: base functionality for pin lock controller // class PinLockBaseController { /// Current configuration /// var configuration = PinLockControllerConfiguration(title: "", message: nil) /// Configuration observer /// var configurationObserver: ((PinLockControllerConfiguration, UIView.ReloadAnimation?) -> Void)? { didSet { configurationObserver?(configuration, nil) } } /// Switch to another configuration with animation /// func switchTo(_ configuration: PinLockControllerConfiguration, with animation: UIView.ReloadAnimation) { self.configuration = configuration configurationObserver?(configuration, animation) } /// Switch to failed attempt configuration /// func switchToFailedAttempt(withTitle title: String, attempts: Int) { let configuration = PinLockControllerConfiguration(title: title, message: Localization.failedAttempts(attempts)) switchTo(configuration, with: .shake) } } // MARK: - Localization // private enum Localization { private static let failedAttemptsSingle = NSLocalizedString("%i Failed Passcode Attempt", comment: "Number of failed entries entering in passcode") private static let failedAttemptsPlural = NSLocalizedString("%i Failed Passcode Attempts", comment: "Number of failed entries entering in passcode") static func failedAttempts(_ attempts: Int) -> String { let template = attempts > 1 ? failedAttemptsPlural : failedAttemptsSingle return String(format: template, attempts) } } ```
/content/code_sandbox/Simplenote/Classes/PinLock/PinLockBaseController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
310
```swift import Foundation // MARK: - PinLockRemoveControllerDelegate // protocol PinLockRemoveControllerDelegate: AnyObject { func pinLockRemoveControllerDidComplete(_ controller: PinLockRemoveController) func pinLockRemoveControllerDidCancel(_ controller: PinLockRemoveController) } // MARK: - PinLockRemoveController // final class PinLockRemoveController: PinLockBaseController, PinLockController { var isCancellable: Bool { return true } private var attempts: Int = 1 private let pinLockManager: SPPinLockManager private weak var delegate: PinLockRemoveControllerDelegate? init(pinLockManager: SPPinLockManager = .shared, delegate: PinLockRemoveControllerDelegate) { self.pinLockManager = pinLockManager self.delegate = delegate super.init() configuration = PinLockControllerConfiguration(title: Localization.title, message: nil) } func handlePin(_ pin: String) { guard pinLockManager.validatePin(pin) else { switchToFailedAttempt(withTitle: Localization.title, attempts: attempts) attempts += 1 return } pinLockManager.removePin() delegate?.pinLockRemoveControllerDidComplete(self) } func handleCancellation() { delegate?.pinLockRemoveControllerDidCancel(self) } } // MARK: - Localization // private enum Localization { static let title = NSLocalizedString("Turn off Passcode", comment: "Prompt when disabling passcode") } ```
/content/code_sandbox/Simplenote/Classes/PinLock/PinLockRemoveController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
315
```swift import Foundation import CoreSpotlight import UIKit import SimplenoteSearch // MARK: - Components Initialization // extension SPNoteListViewController { /// Sets up the Feedback Generator! /// @objc func configureImpactGenerator() { feedbackGenerator = UIImpactFeedbackGenerator() feedbackGenerator.prepare() } /// Sets up the main TableView /// @objc func configureTableView() { assert(tableView == nil, "tableView is already initialized!") tableView = UITableView() tableView.delegate = self tableView.alwaysBounceVertical = true tableView.tableFooterView = UIView() tableView.layoutMargins = .zero tableView.separatorStyle = .none tableView.register(SPNoteTableViewCell.loadNib(), forCellReuseIdentifier: SPNoteTableViewCell.reuseIdentifier) tableView.register(SPTagTableViewCell.loadNib(), forCellReuseIdentifier: SPTagTableViewCell.reuseIdentifier) tableView.register(SPSectionHeaderView.self, forHeaderFooterViewReuseIdentifier: SPSectionHeaderView.reuseIdentifier) tableView.allowsMultipleSelectionDuringEditing = true } /// Sets up the Results Controller /// @objc func configureResultsController() { assert(notesListController == nil, "listController is already initialized!") notesListController = NotesListController(viewContext: SPAppDelegate.shared().managedObjectContext) notesListController.performFetch() } /// Sets up the Placeholder View /// @objc func configurePlaceholderView() { placeholderView = SPPlaceholderView() } /// Sets up the Search StackView /// - Note: We're embedding the SearchBar inside a StackView, to aid in the SearchBar-Hidden Mechanism /// @objc func configureSearchStackView() { assert(searchBar != nil, "searchBar must be initialized first!") searchBarStackView = UIStackView(arrangedSubviews: [searchBar]) searchBarStackView.axis = .vertical } /// Sets up the Root ViewController /// @objc func configureRootView() { navigationBarBackground.translatesAutoresizingMaskIntoConstraints = false placeholderView.translatesAutoresizingMaskIntoConstraints = false searchBarStackView.translatesAutoresizingMaskIntoConstraints = false tableView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tableView) view.addSubview(placeholderView) view.addSubview(navigationBarBackground) view.addSubview(searchBarStackView) NSLayoutConstraint.activate([ searchBarStackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), searchBarStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Constants.searchBarInsets.left), searchBarStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: Constants.searchBarInsets.right) ]) NSLayoutConstraint.activate([ navigationBarBackground.topAnchor.constraint(equalTo: view.topAnchor), navigationBarBackground.leftAnchor.constraint(equalTo: view.leftAnchor), navigationBarBackground.rightAnchor.constraint(equalTo: view.rightAnchor), navigationBarBackground.bottomAnchor.constraint(equalTo: searchBarStackView.bottomAnchor) ]) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) let placeholderVerticalCenterConstraint = placeholderView.centerYAnchor.constraint(equalTo: view.centerYAnchor) placeholderViewVerticalCenterConstraint = placeholderVerticalCenterConstraint let placeholderTopConstraint = placeholderView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: Constants.searchEmptyStateTopMargin) placeholderViewTopConstraint = placeholderTopConstraint NSLayoutConstraint.activate([ placeholderView.centerXAnchor.constraint(equalTo: view.centerXAnchor), placeholderVerticalCenterConstraint, placeholderView.leadingAnchor.constraint(greaterThanOrEqualTo: view.layoutMarginsGuide.leadingAnchor), placeholderView.trailingAnchor.constraint(lessThanOrEqualTo: view.layoutMarginsGuide.trailingAnchor), placeholderView.topAnchor.constraint(greaterThanOrEqualTo: view.layoutMarginsGuide.topAnchor), placeholderView.bottomAnchor.constraint(lessThanOrEqualTo: view.layoutMarginsGuide.bottomAnchor) ]) } /// Initializes the UITableView <> NoteListController Link. Should be called once both UITableView + ListController have been initialized /// @objc func startDisplayingEntities() { tableView.dataSource = self notesListController.onBatchChanges = { [weak self] (sectionsChangeset, objectsChangeset) in guard let `self` = self else { return } /// Note: /// 1. State Restoration might cause this ViewController not to be onScreen /// 2. When that happens, any remote change might cause a Batch Update /// 3. And the above yields a crash /// /// In this snipept we're preventing a beautiful `your_sha256_hash_Section` exception /// guard let _ = self.view.window else { self.reloadTableData() self.displayPlaceholdersIfNeeded() return } self.tableView.performBatchChanges(sectionsChangeset: sectionsChangeset, objectsChangeset: objectsChangeset) { _ in self.displayPlaceholdersIfNeeded() self.refreshEmptyTrashState() } self.updateCurrentSelection() } } } // MARK: - Internal Methods // extension SPNoteListViewController { /// Adjust the TableView's Insets, so that the content falls below the searchBar /// @objc func refreshTableViewTopInsets() { tableView.contentInset.top = searchBarStackView.frame.height / 1.75 tableView.verticalScrollIndicatorInsets.top = searchBarStackView.frame.height / 1.75 } /// Scrolls to the First Row whenever the flag `mustScrollToFirstRow` was set to true /// @objc func ensureFirstRowIsVisibleIfNeeded() { guard mustScrollToFirstRow else { return } ensureFirstRowIsVisible() mustScrollToFirstRow = false } /// Workaround: Scroll to the very first row. Expected to be called *just* once, right after the view has been laid out, and has been moved /// to its parent ViewController. /// /// Ref. Issue #452 /// @objc func ensureFirstRowIsVisible() { guard !tableView.isHidden else { return } tableView.contentOffset.y = tableView.adjustedContentInset.top * -1 } /// Refreshes the Notes ListController Filters + Sorting: We'll also update the UI (TableView + Title) to match the new parameters. /// @objc func refreshListController() { let selectedTag = SPAppDelegate.shared().selectedTag let filter = NotesListFilter(selectedTag: selectedTag) notesListController.filter = filter notesListController.sortMode = Options.shared.listSortMode notesListController.performFetch() reloadTableData() } /// Refreshes the receiver's Title, to match the current filter /// @objc func refreshTitle() { title = searchController.active ? NSLocalizedString("Search", comment: "Search Title") : notesListController.filter.title } /// Toggles the SearchBar's Visibility, based on the active Filter. /// /// - Note: We're marking `mustScrollToFirstRow`, which will cause the layout pass to run `ensureFirstRowIsVisible`. /// Changing the SearchBar Visibility triggers a layout pass, which updates the Table's Insets, and scrolls up to the first row. /// @objc func refreshSearchBar() { guard searchBar.isHidden != isDeletedFilterActive else { return } mustScrollToFirstRow = true searchBar.isHidden = isDeletedFilterActive } /// Refreshes the SearchBar's Text (and backfires the NoteListController filtering mechanisms!) /// func refreshSearchText(appendFilterFor tag: Tag) { let keyword = SearchQuerySettings.default.tagsKeyword + tag.name let updated = searchBar.text?.replaceLastWord(with: keyword) ?? keyword searchController.updateSearchText(searchText: updated + .space) } /// Displays the Emtpy State Placeholders, when / if needed /// @objc func displayPlaceholdersIfNeeded() { guard isListEmpty else { placeholderView.isHidden = true return } placeholderView.isHidden = false placeholderView.displayMode = placeholderDisplayMode updatePlaceholderPosition() } func refreshSelectAllLabels() { let numberOfSelectedRows = tableView.indexPathsForSelectedRows?.count ?? 0 let deselect = notesListController.numberOfObjects == numberOfSelectedRows selectAllButton.title = Localization.selectAllLabel(deselect: deselect) selectAllButton.isAccessibilityElement = true selectAllButton.accessibilityLabel = Localization.selectAllLabel(deselect: deselect) selectAllButton.accessibilityHint = Localization.selectAllAccessibilityHint } private var placeholderDisplayMode: SPPlaceholderView.DisplayMode { if isIndexingNotes || SPAppDelegate.shared().bSigningUserOut { return .generic } if let searchQuery = searchQuery, !searchQuery.isEmpty { let actionHandler: () -> Void = { [weak self] in self?.openNewNote(with: searchQuery.searchText) } return .text(text: Localization.EmptyState.searchTitle, actionText: Localization.EmptyState.searchAction(with: searchQuery.searchText), actionHandler: actionHandler) } switch notesListController.filter { case .everything: return .pictureAndText(imageName: .allNotes, text: Localization.EmptyState.allNotes) case .deleted: return .pictureAndText(imageName: .trash, text: Localization.EmptyState.trash) case .untagged: return .pictureAndText(imageName: .untagged, text: Localization.EmptyState.untagged) case .tag(name: let name): return .pictureAndText(imageName: .tag, text: Localization.EmptyState.tagged(with: name)) } } private func updatePlaceholderPosition() { if case .text = placeholderView.displayMode { placeholderViewVerticalCenterConstraint.isActive = false placeholderViewTopConstraint.isActive = true } else { placeholderViewTopConstraint.isActive = false placeholderViewVerticalCenterConstraint.isActive = true } } /// Indicates if the Deleted Notes are onScreen /// @objc var isDeletedFilterActive: Bool { return notesListController.filter == .deleted } /// Indicates if the List is Empty /// @objc var isListEmpty: Bool { return notesListController.numberOfObjects <= 0 } /// Indicates if we're in Search Mode /// @objc var isSearchActive: Bool { return searchController.active } /// Returns the SearchText /// @objc var searchQuery: SearchQuery? { guard case let .searching(query) = notesListController.state else { return nil } return query } /// Creates and opens new note with a given text /// func openNewNote(with content: String) { SPTracker.trackListNoteCreated() let note = SPObjectManager.shared().newDefaultNote() note.content = content if case let .tag(name) = notesListController.filter { note.addTag(name) } open(note, ignoringSearchQuery: true, animated: true) } /// Sets the state of the trash button /// @objc func refreshEmptyTrashState() { let isTrashOnScreen = self.isDeletedFilterActive let isNotEmpty = !self.isListEmpty emptyTrashButton.isEnabled = isTrashOnScreen && isNotEmpty } /// Delete selected notes /// @objc func trashSelectedNotes() { guard let notes = tableView.indexPathsForSelectedRows?.compactMap({ notesListController.object(at: $0) as? Note }) else { return } delete(notes: notes) setEditing(false, animated: true) } /// Setup Navigation toolbar buttons /// @objc func configureNavigationToolbarButton() { // TODO: When multi select is added to iPad, revist the conditionals here guard let trashButton = trashButton else { return } let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) setToolbarItems([flexibleSpace, trashButton], animated: true) } @objc func selectAllWasTapped() { if notesListController.numberOfObjects == tableView.indexPathsForSelectedRows?.count { tableView.deselectAllRows(inSection: .zero, animated: false) } else { tableView.selectAllRows(inSection: 0, animated: false) } refreshNavigationBarLabels() refreshTrashButton() } @objc func refreshNavigationBarLabels() { refreshListViewTitle() refreshSelectAllLabels() } @objc func refreshEditButtonTitle() { editButtonItem.title = isEditing ? Localization.cancelTitle : Localization.editTitle } func refreshTrashButton() { guard let selectedRows = tableView.indexPathsForSelectedRows else { trashButton.isEnabled = false return } trashButton.isEnabled = selectedRows.count > 0 } } // MARK: - UIScrollViewDelegate // extension SPNoteListViewController: UIScrollViewDelegate { public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { guard searchBar.isFirstResponder, searchBar.text?.isEmpty == false else { return } searchBar.resignFirstResponder() } } // MARK: - UITableViewDataSource // extension SPNoteListViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return notesListController.sections.count } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notesListController.sections[section].numberOfObjects } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch notesListController.object(at: indexPath) { case let note as Note: return dequeueAndConfigureCell(for: note, in: tableView, at: indexPath) case let tag as Tag: return dequeueAndConfigureCell(for: tag, in: tableView, at: indexPath) default: fatalError() } } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let section = notesListController.sections[section] guard section.displaysTitle else { return nil } return section.title } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard notesListController.sections[section].displaysTitle else { return nil } return tableView.dequeueReusableHeaderFooterView(ofType: SPSectionHeaderView.self) } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } } // MARK: - UITableViewDelegate // extension SPNoteListViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { // Notes: // 1. No need to estimate. We precalculate the Height elsewhere, and we can return the *Actual* value // 2. We always scroll to the first row whenever Search Results are updated. If we don't implement this method, // UITableView ends up jumping off elsewhere! // return self.tableView(tableView, heightForRowAt: indexPath) } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch notesListController.object(at: indexPath) { case is Note: return noteRowHeight case is Tag: return tagRowHeight default: return .zero } } public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { guard notesListController.sections[section].displaysTitle else { return .leastNormalMagnitude } return Constants.estimatedHeightForHeaderInSection } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard notesListController.sections[section].displaysTitle else { return .leastNormalMagnitude } return UITableView.automaticDimension } public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { // Swipeable Actions: Only enabled for Notes guard let note = notesListController.object(at: indexPath) as? Note else { return nil } return UISwipeActionsConfiguration(actions: contextActions(for: note)) } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if isEditing { refreshNavigationBarLabels() refreshTrashButton() return } selectedNote = nil switch notesListController.object(at: indexPath) { case let note as Note: SPRatingsHelper.sharedInstance()?.incrementSignificantEvent() open(note, animated: true) case let tag as Tag: refreshSearchText(appendFilterFor: tag) default: break } } public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { if isEditing { refreshNavigationBarLabels() refreshTrashButton() } } public func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? { guard isDeletedFilterActive == false, isEditing == false, let note = notesListController.object(at: indexPath) as? Note else { return nil } return UIContextMenuConfiguration(identifier: nil, previewProvider: { return self.previewingViewController(for: note) }, actionProvider: { suggestedActions in return self.contextMenu(for: note, at: indexPath) }) } public func tableView(_ tableView: UITableView, willPerformPreviewActionForMenuWith configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionCommitAnimating) { guard let editorViewController = animator.previewViewController as? SPNoteEditorViewController else { return } animator.addCompletion { editorViewController.isPreviewing = false self.show(editorViewController, sender: self) } } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { guard let cell = cell as? SPNoteTableViewCell else { return } var insets = SPNoteTableViewCell.separatorInsets insets.left -= cell.layoutMargins.left cell.separatorInset = insets cell.shouldDisplayBottomSeparator = indexPath.row < notesListController.numberOfObjects - 1 && !UIDevice.isPad } } // MARK: - TableViewCell(s) Initialization // private extension SPNoteListViewController { /// Returns a UITableViewCell configured to display the specified Note /// func dequeueAndConfigureCell(for note: Note, in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(ofType: SPNoteTableViewCell.self, for: indexPath) note.ensurePreviewStringsAreAvailable() cell.accessibilityLabel = note.titlePreview cell.accessibilityHint = NSLocalizedString("Open note", comment: "Select a note to view in the note editor") cell.accessoryLeftImage = note.pinned ? .image(name: .pinSmall) : nil cell.accessoryRightImage = note.published ? .image(name: .shared) : nil cell.accessoryLeftTintColor = .simplenoteNotePinStatusImageColor cell.accessoryRightTintColor = .simplenoteNoteShareStatusImageColor cell.rendersInCondensedMode = Options.shared.condensedNotesList cell.titleText = note.titlePreview cell.bodyText = note.bodyExcerpt(keywords: searchQuery?.keywords) cell.keywords = searchQuery?.keywords cell.keywordsTintColor = .simplenoteTintColor cell.prefixText = prefixText(for: note) cell.refreshAttributedStrings() return cell } /// Returns a UITableViewCell configured to display the specified Tag /// func dequeueAndConfigureCell(for tag: Tag, in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(ofType: SPTagTableViewCell.self, for: indexPath) cell.leftImage = .image(name: .tag) cell.leftImageTintColor = .simplenoteNoteShareStatusImageColor cell.titleText = SearchQuerySettings.default.tagsKeyword + tag.name return cell } /// Returns the Prefix for a given note: We'll prepend the (Creation / Modification) Date, whenever we're in Search, and the Sort Option is relevant /// func prefixText(for note: Note) -> String? { guard case .searching = notesListController.state, let date = note.date(for: notesListController.sortMode) else { return nil } return DateFormatter.listDateFormatter.string(from: date) } } // MARK: - Table // extension SPNoteListViewController { @objc func reloadTableData() { tableView.reloadData() updateCurrentSelection() } @objc func updateCurrentSelection() { tableView.deselectSelectedRow() if let note = selectedNote, let indexPath = notesListController.indexPath(forObject: note) { tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) } } private func updateSelectedNoteBasedOnSelectedIndexPath() { selectedNote = tableView.indexPathForSelectedRow.flatMap { indexPath in notesListController.object(at: indexPath) as? Note } } open override func setEditing(_ editing: Bool, animated: Bool) { ensureTableViewEditingIsInSync() super.setEditing(editing, animated: animated) tableView.setEditing(editing, animated: animated) refreshEditButtonTitle() refreshSelectAllLabels() tableView.deselectAllRows(inSection: .zero, animated: false) updateNavigationBar() configureNavigationToolbarButton() navigationController?.setToolbarHidden(!editing, animated: true) refreshListViewTitle() searchController.setEnabled(!editing) } private func ensureTableViewEditingIsInSync() { // If a swipe action is active, the tableView will already be set to isEditing == true // The edit button is still active while the swipe actions are active, if pressed // the VC and the tableview will get set to true, but since the tableView is already // editing nothind will happen. // This method ensures the tableview and VC are in sync when the edit button is tapped guard tableView.isEditing != isEditing else { return } tableView.setEditing(isEditing, animated: false) } private func refreshListViewTitle() { title = { guard isEditing else { return notesListController.filter.title } let count = tableView.indexPathsForSelectedRows?.count ?? .zero return count > 0 ? Localization.selectedTitle(with: count) : notesListController.filter.title }() } @objc func restoreSelectedRowsAfterBackgrounding() { guard let selectedNotesEnteringBackground, selectedNotesEnteringBackground.isEmpty == false else { return } selectRows(with: selectedNotesEnteringBackground) self.selectedNotesEnteringBackground = [] } func selectRows(with indexPaths: [IndexPath]) { guard isEditing else { return } indexPaths.forEach({ tableView.selectRow(at: $0, animated: false, scrollPosition: .none) }) } } // MARK: - Row Actions // private extension SPNoteListViewController { func contextActions(for note: Note) -> [UIContextualAction] { if note.deleted { return deletedContextActions(for: note) } return regularContextActions(for: note) } func deletedContextActions(for note: Note) -> [UIContextualAction] { let restoreAction = UIContextualAction(style: .normal, image: .image(name: .restore), backgroundColor: .simplenoteRestoreActionColor) { (_, _, completion) in SPObjectManager.shared().restoreNote(note) CSSearchableIndex.default().indexSearchableNote(note) completion(true) } restoreAction.accessibilityLabel = ActionTitle.restore let deleteAction = UIContextualAction(style: .destructive, image: .image(name: .trash), backgroundColor: .simplenoteDestructiveActionColor) { (_, _, completion) in SPTracker.trackListNoteDeleted() SPObjectManager.shared().permenentlyDeleteNote(note) completion(true) } deleteAction.accessibilityLabel = ActionTitle.delete return [restoreAction, deleteAction] } func regularContextActions(for note: Note) -> [UIContextualAction] { let pinImageName: UIImageName = note.pinned ? .unpin : .pin let pinActionTitle: String = note.pinned ? ActionTitle.unpin : ActionTitle.pin let trashAction = UIContextualAction(style: .destructive, title: nil, image: .image(name: .trash), backgroundColor: .simplenoteDestructiveActionColor) { [weak self] (_, _, completion) in self?.delete(note: note) NoticeController.shared.present(NoticeFactory.noteTrashed(onUndo: { SPObjectManager.shared().restoreNote(note) SPTracker.trackPreformedNoticeAction(ofType: .noteTrashed, noticeType: .undo) self?.tableView.reloadData() })) SPTracker.trackPresentedNotice(ofType: .noteTrashed) completion(true) } trashAction.accessibilityLabel = ActionTitle.trash let pinAction = UIContextualAction(style: .normal, title: nil, image: .image(name: pinImageName), backgroundColor: .simplenoteSecondaryActionColor) { [weak self] (_, _, completion) in self?.togglePinnedState(note: note) completion(true) } pinAction.accessibilityLabel = pinActionTitle let copyAction = UIContextualAction(style: .normal, title: nil, image: .image(name: .link), backgroundColor: .simplenoteTertiaryActionColor) { [weak self] (_, _, completion) in self?.copyInternalLink(to: note) NoticeController.shared.present(NoticeFactory.linkCopied()) SPTracker.trackPresentedNotice(ofType: .internalLinkCopied) completion(true) } copyAction.accessibilityLabel = ActionTitle.copyLink let shareAction = UIContextualAction(style: .normal, title: nil, image: .image(name: .share), backgroundColor: .simplenoteQuaternaryActionColor) { [weak self] (_, _, completion) in self?.share(note: note) completion(true) } shareAction.accessibilityLabel = ActionTitle.share return [trashAction, pinAction, copyAction, shareAction] } } // MARK: - UIMenu // private extension SPNoteListViewController { /// Invoked by the Long Press UITableView Mechanism (ex 3d Touch) /// func contextMenu(for note: Note, at indexPath: IndexPath) -> UIMenu { let copy = UIAction(title: ActionTitle.copyLink, image: .image(name: .link)) { [weak self] _ in self?.copyInternalLink(to: note) NoticeController.shared.present(NoticeFactory.linkCopied()) SPTracker.trackPresentedNotice(ofType: .internalLinkCopied) } let share = UIAction(title: ActionTitle.share, image: .image(name: .share)) { [weak self] _ in self?.share(note: note) } let pinTitle = note.pinned ? ActionTitle.unpin : ActionTitle.pin let pin = UIAction(title: pinTitle, image: .image(name: .pin)) { [weak self] _ in self?.togglePinnedState(note: note) } let select = UIAction(title: ActionTitle.select, image: .image(name: .success)) { [weak self] _ in self?.setEditing(true, animated: true) self?.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) self?.tableView.scrollToNearestSelectedRow(at: .none, animated: false) self?.refreshListViewTitle() self?.refreshTrashButton() self?.refreshSelectAllLabels() } if isSearchActive { select.attributes = .disabled } let delete = UIAction(title: ActionTitle.delete, image: .image(name: .trash), attributes: .destructive) { [weak self] _ in self?.delete(note: note) NoticeController.shared.present(NoticeFactory.noteTrashed(onUndo: { SPObjectManager.shared().restoreNote(note) SPTracker.trackPreformedNoticeAction(ofType: .noteTrashed, noticeType: .undo) self?.tableView.reloadData() })) SPTracker.trackPresentedNotice(ofType: .noteTrashed) } return UIMenu(title: "", children: [select, share, copy, pin, delete]) } } // MARK: - Services // private extension SPNoteListViewController { func delete(note: Note) { SPTracker.trackListNoteDeleted() SPObjectManager.shared().trashNote(note) CSSearchableIndex.default().deleteSearchableNote(note) } func copyInternalLink(to note: Note) { SPTracker.trackListCopiedInternalLink() UIPasteboard.general.copyInternalLink(to: note) } func togglePinnedState(note: Note) { SPTracker.trackListPinToggled() SPObjectManager.shared().updatePinnedState(!note.pinned, note: note) } func share(note: Note) { guard let _ = note.content, let activityController = UIActivityViewController(note: note) else { return } SPTracker.trackEditorNoteContentShared() guard UIDevice.sp_isPad(), let indexPath = notesListController.indexPath(forObject: note) else { present(activityController, animated: true, completion: nil) return } activityController.modalPresentationStyle = .popover let presentationController = activityController.popoverPresentationController presentationController?.permittedArrowDirections = .any presentationController?.sourceRect = tableView.rectForRow(at: indexPath) presentationController?.sourceView = tableView present(activityController, animated: true, completion: nil) } func previewingViewController(for note: Note) -> SPNoteEditorViewController { let editorViewController = EditorFactory.shared.build(with: note) editorViewController.isPreviewing = true editorViewController.update(withSearchQuery: searchQuery) return editorViewController } func delete(notes: [Note]) { for note in notes { delete(note: note) } NoticeController.shared.present(NoticeFactory.notesTrashed(notes, onUndo: { for note in notes { SPObjectManager.shared().restoreNote(note) } SPTracker.trackPreformedNoticeAction(ofType: .multipleNotesTrashed, noticeType: .undo) })) SPTracker.trackPresentedNotice(ofType: .multipleNotesTrashed) setEditing(false, animated: true) } } // MARK: - Services (Internal) // extension SPNoteListViewController { @objc func createNewNote() { SPTracker.trackListNoteCreated() // the editor view will create a note. Passing no note ensures that an emty note isn't added // to the FRC before the animation occurs tableView.setEditing(false, animated: false) open(nil, animated: true) } } // MARK: - Keyboard Handling // extension SPNoteListViewController { @objc(keyboardWillChangeFrame:) func keyboardWillChangeFrame(note: Notification) { guard let _ = view.window else { // No window means we aren't in the view hierarchy. // Asking UITableView to refresh layout when not in the view hierarcy results in console warnings. return } guard let keyboardFrame = (note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } keyboardHeight = keyboardFrame.intersection(view.frame).height refreshTableViewBottomInsets(animated: true) } func refreshTableViewBottomInsets(animated: Bool = false) { let bottomInsets = bottomInsetsForTableView let updates = { self.tableView.contentInset.bottom = bottomInsets self.tableView.verticalScrollIndicatorInsets.bottom = bottomInsets self.view.layoutIfNeeded() } if animated { UIView.animate(withDuration: UIKitConstants.animationShortDuration, animations: updates) } else { updates() } } var bottomInsetsForTableView: CGFloat { // Keyboard offScreen + Search Active: Seriously, consider the Search Bar guard keyboardHeight > .zero else { return .zero } // Keyboard onScreen: the SortBar falls below the keyboard return keyboardHeight } } // MARK: - Search Action Handlers // extension SPNoteListViewController { private var popoverPresenter: PopoverPresenter { let viewportProvider: () -> CGRect = { [weak self] in guard let self = self else { return .zero } let bounds = self.view.bounds.inset(by: self.view.safeAreaInsets) return self.view.convert(bounds, to: nil) } let presenter = PopoverPresenter(containerViewController: self, viewportProvider: viewportProvider) presenter.dismissOnInteractionWithPassthruView = true presenter.dismissOnContainerFrameChange = true presenter.centerContentRelativeToAnchor = view.frame.width > Constants.centeredSortPopoverThreshold return presenter } } // MARK: - Keyboard // extension SPNoteListViewController { open override var canBecomeFirstResponder: Bool { return true } open override var keyCommands: [UIKeyCommand]? { var commands = tableCommands if isSearchActive { commands.append(UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(keyboardStopSearching))) // We add this shortcut only when search bar is first responder because when it's not we don't want to clear the search. // The shortcut that actually focuses on the searchbar is located in `SPSidebarContainerViewController`. This is done to make shortcut work from multiple screens if searchBar.isFirstResponder { commands.append(UIKeyCommand(input: "f", modifierFlags: [.command, .shift], action: #selector(keyboardStopSearching))) } } return commands } @objc private func keyboardStopSearching() { endSearching() } } // MARK: - Keyboard (List) // private extension SPNoteListViewController { var tableCommands: [UIKeyCommand] { var commands = [ UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags: [], action: #selector(keyboardUp)), UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags: [], action: #selector(keyboardDown)), UIKeyCommand(input: UIKeyCommand.inputReturn, modifierFlags: [], action: #selector(keyboardSelect)) ] if isFirstResponder { commands.append(UIKeyCommand(input: UIKeyCommand.inputTrailingArrow, modifierFlags: [], action: #selector(keyboardSelect))) } return commands } @objc func keyboardUp() { navigatingUsingKeyboard = true tableView?.selectPrevRow() updateSelectedNoteBasedOnSelectedIndexPath() } @objc func keyboardDown() { navigatingUsingKeyboard = true tableView?.selectNextRow() updateSelectedNoteBasedOnSelectedIndexPath() } @objc func keyboardSelect() { navigatingUsingKeyboard = true tableView?.executeSelection() } } // MARK: - Private Types // private enum ActionTitle { static let cancel = NSLocalizedString("Cancel", comment: "Dismissing an interface") static let copyLink = NSLocalizedString("Copy Internal Link", comment: "Copies Link to a Note") static let trash = NSLocalizedString("Move to Trash", comment: "Deletes a note") static let pin = NSLocalizedString("Pin to Top", comment: "Pins a note") static let share = NSLocalizedString("Share...", comment: "Shares a note") static let unpin = NSLocalizedString("Unpin", comment: "Unpins a note") static let restore = NSLocalizedString("Restore Note", comment: "Restore a note from trash") static let delete = NSLocalizedString("Delete Note", comment: "Delete a note from trash") static let select = NSLocalizedString("Select", comment: "Select multiple notes at once") } private enum Constants { /// Section Header's Estimated Height /// static let estimatedHeightForHeaderInSection = CGFloat(30) /// Where do these insets come from? /// `For other subviews in your view hierarchy, the default layout margins are normally 8 points on each side` /// /// We're replicating the (old) view herarchy's behavior, in which the SearchBar would actually be contained within a view with 8pt margins on each side. /// This won't be required anymore *soon*, and it's just a temporary workaround. /// /// Ref. path_to_url /// static let searchBarInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: -8) static let searchEmptyStateTopMargin = CGFloat(128) static let centeredSortPopoverThreshold = CGFloat(500) } private enum Localization { enum EmptyState { static let allNotes = NSLocalizedString("Create your first note", comment: "Message shown in note list when no notes are in the current view") static let trash = NSLocalizedString("Your trash is empty", comment: "Message shown in note list when no notes are in the trash") static let untagged = NSLocalizedString("No untagged notes", comment: "Message shown in note list when no notes are untagged") static func tagged(with tag: String) -> String { return String(format: NSLocalizedString("No notes tagged %@", comment: "Message shown in note list when no notes are tagged with the provided tag. Parameter: %@ - tag"), tag) } static let searchTitle = NSLocalizedString("No Results", comment: "Message shown when no notes match a search string") static func searchAction(with searchTerm: String) -> String { return String(format: NSLocalizedString("Create a new note titled %@", comment: "Tappable message shown when no notes match a search string. Parameter: %@ - search term"), searchTerm) } } static func selectedTitle(with count: Int) -> String { let string = NSLocalizedString("%i Selected", comment: "Count of currently selected notes") return String(format: string, count) } static func selectAllLabel(deselect: Bool) -> String { let selectLabel = NSLocalizedString("Select All", comment: "Select all Button Label") let deselectLabel = NSLocalizedString("Deselect All", comment: "Deselect all Button Label") return deselect ? deselectLabel : selectLabel } static let selectAllAccessibilityHint = NSLocalizedString("Tap button to select or deselect all notes", comment: "Accessibility hint for the select/deselect all button") static let editTitle = NSLocalizedString("Edit", comment: "Edit button title") static let cancelTitle = NSLocalizedString("Cancel", comment: "Cancel button title") } ```
/content/code_sandbox/Simplenote/Classes/SPNoteListViewController+Extensions.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
8,402
```swift import Foundation // MARK: - PinLockSetupControllerDelegate // protocol PinLockSetupControllerDelegate: AnyObject { func pinLockSetupControllerDidComplete(_ controller: PinLockSetupController) func pinLockSetupControllerDidCancel(_ controller: PinLockSetupController) } // MARK: - PinLockSetupController // final class PinLockSetupController: PinLockBaseController, PinLockController { var isCancellable: Bool { return true } private var pin: String? private let pinLockManager: SPPinLockManager private weak var delegate: PinLockSetupControllerDelegate? init(pinLockManager: SPPinLockManager = .shared, delegate: PinLockSetupControllerDelegate) { self.pinLockManager = pinLockManager self.delegate = delegate super.init() configuration = PinLockControllerConfiguration(title: Localization.createPasscode, message: nil) } func handlePin(_ pin: String) { guard !pin.isEmpty else { self.pin = nil switchTo(PinLockControllerConfiguration(title: Localization.createPasscode, message: nil), with: .shake) return } guard let firstPin = self.pin else { self.pin = pin switchToPinConfirmation() return } guard pin == firstPin else { self.pin = nil switchTo(PinLockControllerConfiguration(title: Localization.createPasscode, message: Localization.passcodesDontMatch), with: .slideTrailing) return } pinLockManager.setPin(pin) delegate?.pinLockSetupControllerDidComplete(self) } func handleCancellation() { delegate?.pinLockSetupControllerDidCancel(self) } } // MARK: - Private // private extension PinLockSetupController { func switchToPinConfirmation() { let configuration = PinLockControllerConfiguration(title: Localization.confirmPasscode, message: nil) switchTo(configuration, with: .slideLeading) } } // MARK: - Localization // private enum Localization { static let createPasscode = NSLocalizedString("Choose a 4 digit passcode", comment: "Title on the PinLock screen asking to create a passcode") static let confirmPasscode = NSLocalizedString("Confirm your passcode", comment: "Title on the PinLock screen asking to confirm a passcode") static let passcodesDontMatch = NSLocalizedString("Passcodes did not match. Try again.", comment: "Pin Lock") } ```
/content/code_sandbox/Simplenote/Classes/PinLock/PinLockSetupController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
522
```swift import Foundation // MARK: - PinLockControllerConfiguration // struct PinLockControllerConfiguration: Equatable { /// PinLock screen title let title: String /// PinLock screen message /// let message: String? } // MARK: - PinLockController // protocol PinLockController: AnyObject { /// Observer for configuration changes. Provides updated configuration and optional animation /// var configurationObserver: ((PinLockControllerConfiguration, UIView.ReloadAnimation?) -> Void)? { get set } /// Is the flow cancellable? If cancellable VC should show `cancel` button to dismiss the flow /// var isCancellable: Bool { get } /// Handle pin entered in VC /// func handlePin(_ pin: String) /// Handle tap on `cancel` button in VC /// func handleCancellation() /// Handle view did appear event /// func viewDidAppear() /// Handle application become active /// func applicationDidBecomeActive() } /// Default impementation /// extension PinLockController { func viewDidAppear() {} func applicationDidBecomeActive() {} } ```
/content/code_sandbox/Simplenote/Classes/PinLock/PinLockController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
239
```swift import UIKit // MARK: - PinLockViewController // class PinLockViewController: UIViewController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var messageLabel: UILabel! @IBOutlet private weak var cancelButton: UIButton! @IBOutlet private weak var progressView: PinLockProgressView! @IBOutlet private weak var headerStackView: UIStackView! @IBOutlet private var keypadButtons: [UIButton] = [] let controller: PinLockController private var inputValues: [Int] = [] { didSet { progressView.progress = inputValues.count updateCancelButton() } } private let feedbackGenerator = UINotificationFeedbackGenerator() init(controller: PinLockController) { self.controller = controller super.init(nibName: nil, bundle: nil) isModalInPresentation = true modalPresentationStyle = .fullScreen } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { removeNotificationListeners() } override func viewDidLoad() { super.viewDidLoad() setup() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) controller.configurationObserver = { [weak self] (configuration, animation) in self?.update(with: configuration, animation: animation) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) controller.viewDidAppear() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) controller.configurationObserver = nil } } // MARK: - Orientation // extension PinLockViewController { override public var shouldAutorotate: Bool { if UIDevice.isPad { return super.shouldAutorotate } return false } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.isPad { return super.supportedInterfaceOrientations } return [.portrait, .portraitUpsideDown] } override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if UIDevice.isPad { return super.preferredInterfaceOrientationForPresentation } return .portrait } } // MARK: - Setup // private extension PinLockViewController { func setup() { view.backgroundColor = .simplenoteLockScreenBackgroudColor setupMessageLabel() setupCancelButton() setupProgressView() setupKeypadButtons() setupNotificationListeners() } func setupCancelButton() { cancelButton.setTitleColor(.white, for: .normal) updateCancelButton() } func setupProgressView() { progressView.length = Constants.pinLength } func setupKeypadButtons() { for button in keypadButtons { button.setBackgroundImage(UIColor.simplenoteLockScreenButtonColor.dynamicImageRepresentation(), for: .normal) button.setBackgroundImage(UIColor.simplenoteLockScreenHighlightedButtonColor.dynamicImageRepresentation(), for: .highlighted) button.addTarget(self, action: #selector(handleTapOnKeypadButton(_:)), for: .touchUpInside) } } func setupMessageLabel() { messageLabel.textColor = .simplenoteLockScreenMessageColor } func update(with configuration: PinLockControllerConfiguration, animation: UIView.ReloadAnimation?) { guard let animation = animation else { update(with: configuration) return } headerStackView.reload(with: animation, in: view) { [weak self] in self?.update(with: configuration) } announceUpdate(with: configuration) if animation == .shake { feedbackGenerator.notificationOccurred(.error) } } func update(with configuration: PinLockControllerConfiguration) { inputValues = [] updateTitleLabel(with: configuration) updateMessageLabel(with: configuration) } func updateTitleLabel(with configuration: PinLockControllerConfiguration) { titleLabel.text = configuration.title } func updateMessageLabel(with configuration: PinLockControllerConfiguration) { // Use `space` to preserve the height of `messageLabel` even if it's empty let text = configuration.message ?? " " messageLabel.text = text } func updateCancelButton() { if inputValues.isEmpty { cancelButton.setTitle(Localization.cancelButton, for: .normal) cancelButton.isHidden = !controller.isCancellable return } cancelButton.isHidden = false cancelButton.setTitle(Localization.deleteButton, for: .normal) } } // MARK: - Pincode // private extension PinLockViewController { func addDigit(_ digit: Int) { guard inputValues.count < Constants.pinLength else { return } inputValues.append(digit) if inputValues.count == Constants.pinLength { let pin = inputValues.compactMap(String.init).joined() controller.handlePin(pin) } } @discardableResult func removeLastDigit() -> Bool { guard !inputValues.isEmpty else { return false } inputValues.removeLast() return true } } // MARK: - Buttons // private extension PinLockViewController { @objc func handleTapOnKeypadButton(_ button: UIButton) { guard let index = keypadButtons.firstIndex(of: button) else { return } addDigit(index) } @IBAction private func handleTapOnCancelButton() { if !removeLastDigit() { controller.handleCancellation() } } } // MARK: - External keyboard // extension PinLockViewController { override var canBecomeFirstResponder: Bool { return true } override var keyCommands: [UIKeyCommand]? { var commands = (0..<10).map { UIKeyCommand(input: String($0), modifierFlags: [], action: #selector(handleKeypress(_:))) } let backspaceCommand = UIKeyCommand(input: "\u{8}", modifierFlags: [], action: #selector(handleBackspace)) commands.append(backspaceCommand) return commands } @objc private func handleKeypress(_ keyCommand: UIKeyCommand) { guard let digit = Int(keyCommand.input ?? "") else { return } addDigit(digit) } @objc private func handleBackspace() { removeLastDigit() } } // MARK: - Notifications // private extension PinLockViewController { func setupNotificationListeners() { NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) } func removeNotificationListeners() { NotificationCenter.default.removeObserver(self) } @objc func applicationDidBecomeActive() { controller.applicationDidBecomeActive() } } // MARK: - Accessibility // extension PinLockViewController { override func accessibilityPerformEscape() -> Bool { controller.handleCancellation() return true } private func announceUpdate(with configuration: PinLockControllerConfiguration) { let message = [configuration.message, configuration.title] .compactMap({ $0 }) .joined(separator: "\n") // The message wasn't playing without using a delay :shrug: DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { UIAccessibility.post(notification: .announcement, argument: message) } } } // MARK: - Localization // private enum Localization { static let deleteButton = NSLocalizedString("Delete", comment: "PinLock screen \"delete\" button") static let cancelButton = NSLocalizedString("Cancel", comment: "PinLock screen \"cancel\" button") } // MARK: - Constants // private enum Constants { static let pinLength: Int = 4 } ```
/content/code_sandbox/Simplenote/Classes/PinLock/PinLockViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,654
```css html { background: #FFFFFF; color: #111111; } ::-webkit-scrollbar-thumb { background: #84878a; } .note-detail-markdown a { color: #3361cc; } .note-detail-markdown hr { color: #4895d9; } .note-detail-markdown code { color: #899199; } .note-detail-markdown pre { background: #f6f7f8; } .note-detail-markdown pre code { color: #616870; } .note-detail-markdown table tr:nth-child(2n) { background-color: #f6f7f8; } .note-detail-markdown table th, .note-detail-markdown table td { border-color: #c0c4c8; } ```
/content/code_sandbox/Simplenote/Resources/markdown-light.css
css
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
164
```css /* Accessibility high contrast blue */ .note-detail-markdown a { color: #85aaff !important; } ```
/content/code_sandbox/Simplenote/Resources/markdown-dark-contrast.css
css
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
25
```css /* Accessibility high contrast blue */ .note-detail-markdown a { color: #284da2 !important; } ```
/content/code_sandbox/Simplenote/Resources/markdown-default-contrast.css
css
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
25
```css html { background: 1f2123; color: #DDDDDD; } ::-webkit-scrollbar-thumb { background: #84878a; } .note-detail-markdown a { color: #618df2; } .note-detail-markdown hr { color: #4895d9; } .note-detail-markdown code { color: #84878a; } .note-detail-markdown pre { background: #002b36; } .note-detail-markdown pre code { color: #84878a; } .note-detail-markdown table tr:nth-child(2n) { background-color: #383d41; } .note-detail-markdown table th, .note-detail-markdown table td { border-color: #575e65; } ```
/content/code_sandbox/Simplenote/Resources/markdown-dark.css
css
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
160
```css @charset "UTF-8"; * , body { margin: 0; padding: 0; } body { background: transparent; } img { border: 0; } * :focus { outline: none; } html { margin: 0; padding: 0; text-rendering: optimizeLegibility; } ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background-color: transparent; } ::-webkit-scrollbar-thumb { border-radius: 6px; } /* Same styles as app.simplenote.com/publish */ .note-detail-markdown { user-select: auto; font-family: 'Noto Serif', serif; font-size: 18px; line-height: 1.7; word-wrap: break-word; padding: 20px 20px 20px 24px; } .note-detail-markdown h1, .note-detail-markdown h2, .note-detail-markdown h3, .note-detail-markdown h4, .note-detail-markdown h5, .note-detail-markdown h6, .note-detail-markdown #title { line-height: 1.15; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; margin: 1.7em 0 1em 0; } .note-detail-markdown h1, .note-detail-markdown #title { font-size: 2em; } .note-detail-markdown h1:first-of-type, .note-detail-markdown #title:first-of-type { margin-top: 0; } .note-detail-markdown h2 { font-size: 1.8em; } .note-detail-markdown h3 { font-size: 1.4em; } .note-detail-markdown h4 { font-size: 1.2em; } .note-detail-markdown h5, .note-detail-markdown h6 { font-size: 1em; } .note-detail-markdown #title { margin-bottom: 0.5em; font-weight: bold; } .note-detail-markdown p, .note-detail-markdown ul, .note-detail-markdown ol, .note-detail-markdown blockquote, .note-detail-markdown pre, .note-detail-markdown table, .note-detail-markdown code, .note-detail-markdown img { margin-bottom: 1.7em; box-sizing: border-box; } .note-detail-markdown ul, .note-detail-markdown ol { margin-left: 2em; } .note-detail-markdown img { display: block; margin: 0 auto; max-width: 100%; height: auto; } .note-detail-markdown hr { border: 0; margin: 3.4em 0; height: 1em; } .note-detail-markdown hr:before { content: '...'; display: block; width: 100%; letter-spacing: 2em; text-indent: 2em; z-index: 1; line-height: .5; text-align: center; } .note-detail-markdown blockquote { font-style: italic; border-left: 4px solid currentColor; margin-left: 0; padding-left: 1.7em; } .note-detail-markdown pre { padding: 1em; border-radius: 3px; } .note-detail-markdown pre code { font-size: 85%; background: transparent; width: 100%; overflow-x: auto; display: block; margin-bottom: 0; } .note-detail-markdown table { border-collapse: collapse; border-spacing: 0; display: block; width: 100%; } .note-detail-markdown table th, .note-detail-markdown table td { border: 1px solid; padding: 6px 13px; } .note-detail-markdown table th { font-weight: 600; } .note-detail-markdown input { pointer-events: none; } .note-detail-markdown .task-list { list-style-type: none; margin-left: 0; } .note-detail-markdown .task-list li input { margin-right: 6px; } @media only screen and (max-width: 480px) { .note-detail-markdown { font-size: 16px; } .note-detail-markdown h1, .note-detail-markdown h2, .note-detail-markdown h3, .note-detail-markdown h4, .note-detail-markdown h5, .note-detail-markdown h6, .note-detail-markdown #title { margin: 1.19em 0 0.7em 0; } .note-detail-markdown #title { margin-bottom: 0; } } ```
/content/code_sandbox/Simplenote/Resources/markdown-default.css
css
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,051
```swift import Foundation import SimplenoteEndpoints // MARK: - AccountVerificationController // @objc class AccountVerificationController: NSObject { /// Possible verification states /// enum State { case unknown case unverified case verificationInProgress case verified } /// Current verification state /// private(set) var state: State = .unknown { didSet { guard oldValue != state else { return } onStateChange?(oldValue, state) } } /// User's email /// let email: String /// Callback is invoked when state changes /// var onStateChange: ((_ oldState: State, _ state: State) -> Void)? /// Remote service /// private let remote: AccountRemote /// Initialize with user's email /// init(email: String, remote: AccountRemote = .init()) { self.email = email self.remote = remote super.init() } /// Update verification state with data from `email-verification` entity /// @objc func update(with rawData: Any?) { guard !email.isEmpty else { return } guard let rawData = rawData as? [AnyHashable: Any] else { state = .unverified return } let emailVerification = EmailVerification(payload: rawData) if emailVerification.token?.username.lowercased() == email.lowercased() { state = .verified } else if emailVerification.sentTo != nil { state = .verificationInProgress } else { state = .unverified } } /// Send verification request /// func verify(completion: @escaping (_ result: Result<Data?, RemoteError>) -> Void) { remote.verify(email: email, completion: completion) } } ```
/content/code_sandbox/Simplenote/Verification/AccountVerificationController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
392
```swift import UIKit // MARK: - AccountVerificationViewController // class AccountVerificationViewController: UIViewController { /// Configuration /// struct Configuration: Equatable { static let review = Configuration(iconName: .warning, title: Localization.Review.title, messageTemplate: Localization.Review.messageTemplate, primaryButton: Localization.Review.confirm, secondaryButton: Localization.Review.changeEmail, errorMessageTitle: Localization.Review.errorMessageTitle) static let verify = Configuration(iconName: .mail, title: Localization.Verify.title, messageTemplate: Localization.Verify.messageTemplate, primaryButton: nil, secondaryButton: Localization.Verify.resendEmail, errorMessageTitle: Localization.Verify.errorMessageTitle) let iconName: UIImageName let title: String let messageTemplate: String let primaryButton: String? let secondaryButton: String let errorMessageTitle: String private init(iconName: UIImageName, title: String, messageTemplate: String, primaryButton: String?, secondaryButton: String, errorMessageTitle: String) { self.iconName = iconName self.title = title self.messageTemplate = messageTemplate self.primaryButton = primaryButton self.secondaryButton = secondaryButton self.errorMessageTitle = errorMessageTitle } } @IBOutlet private weak var iconView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var textLabel: UILabel! @IBOutlet private weak var primaryButton: ActivityIndicatorButton! @IBOutlet private weak var secondaryButton: ActivityIndicatorButton! @IBOutlet private weak var dismissButton: UIButton! @IBOutlet private weak var contentStackView: UIStackView! @IBOutlet private weak var scrollView: UIScrollView! private var configuration: Configuration { didSet { refreshStyle() refreshContent() trackScreen() } } private let controller: AccountVerificationController init(configuration: Configuration, controller: AccountVerificationController) { self.configuration = configuration self.controller = controller super.init(nibName: nil, bundle: nil) isModalInPresentation = true modalPresentationStyle = .fullScreen } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() refreshStyle() refreshContent() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) trackScreen() } } // MARK: - Private // private extension AccountVerificationViewController { func verifyEmail(onSuccess: (() -> Void)? = nil) { let button = primaryButton.isHidden ? secondaryButton : primaryButton button?.inProgress = true updateButtons(isEnabled: false) controller.verify { [weak self] (result) in switch result { case .success: onSuccess?() case .failure: self?.showErrorMessage() } button?.inProgress = false self?.updateButtons(isEnabled: true) } } func showErrorMessage() { let alertController = UIAlertController(title: configuration.errorMessageTitle, message: Localization.errorMessage, preferredStyle: .alert) alertController.addDefaultActionWithTitle(Localization.okButton) present(alertController, animated: true, completion: nil) } } // MARK: - Buttons // extension AccountVerificationViewController { @IBAction private func handleTapOnDismissButton() { dismiss() SPTracker.trackVerificationDismissed() } @IBAction private func handleTapOnPrimaryButton() { guard configuration == .review else { return } verifyEmail(onSuccess: { [weak self] in self?.transitionToVerificationScreen() }) SPTracker.trackVerificationConfirmButtonTapped() } @IBAction private func handleTapOnSecondaryButton() { switch configuration { case .review: if let url = URL(string: SimplenoteConstants.settingsURL) { UIApplication.shared.open(url, options: [:], completionHandler: nil) dismiss() } SPTracker.trackVerificationChangeEmailButtonTapped() case .verify: verifyEmail() SPTracker.trackVerificationResendEmailButtonTapped() default: return } } private func updateButtons(isEnabled: Bool) { [primaryButton, secondaryButton].forEach { $0?.isEnabled = isEnabled } } } // MARK: - Transitions // private extension AccountVerificationViewController { func transitionToVerificationScreen() { contentStackView.reload(with: .slideLeading, in: view) { self.configuration = .verify self.primaryButton.inProgress = false self.secondaryButton.inProgress = false self.updateButtons(isEnabled: true) } } func dismiss() { dismiss(animated: true, completion: nil) } } // MARK: - Style // private extension AccountVerificationViewController { func refreshStyle() { view.backgroundColor = .simplenoteVerificationScreenBackgroundColor iconView.tintColor = .simplenoteTitleColor titleLabel.textColor = .simplenoteTextColor titleLabel.font = UIFont.preferredFont(for: .largeTitle, weight: .bold) textLabel.textColor = .simplenoteTextColor primaryButton.backgroundColor = .simplenoteBlue50Color primaryButton.setTitleColor(.white, for: .normal) primaryButton.activityIndicatorColor = .white primaryButton.layer.cornerRadius = Constants.primaryButtonCornerRadius primaryButton.titleLabel?.adjustsFontForContentSizeCategory = true secondaryButton.backgroundColor = .clear secondaryButton.setTitleColor(.simplenoteTintColor, for: .normal) secondaryButton.titleLabel?.adjustsFontForContentSizeCategory = true scrollView.contentInset = Constants.scrollContentInset } } // MARK: - Content // private extension AccountVerificationViewController { func refreshContent() { let message = String(format: configuration.messageTemplate, controller.email) iconView.image = UIImage.image(name: configuration.iconName) titleLabel.text = configuration.title textLabel.attributedText = attributedText(message, highlighting: controller.email) primaryButton.setTitle(configuration.primaryButton, for: .normal) secondaryButton.setTitle(configuration.secondaryButton, for: .normal) primaryButton.isHidden = configuration.primaryButton == nil } func attributedText(_ text: String, highlighting term: String) -> NSAttributedString { let attributedMessage = NSMutableAttributedString(string: text, attributes: [ .foregroundColor: UIColor.simplenoteTextColor, .font: UIFont.preferredFont(forTextStyle: .body) ]) if let range = text.range(of: term) { attributedMessage.addAttribute(.font, value: UIFont.preferredFont(forTextStyle: .headline), range: NSRange(range, in: text)) } return attributedMessage } } // MARK: - Tracks // private extension AccountVerificationViewController { func trackScreen() { switch configuration { case .review: SPTracker.trackVerificationReviewScreenViewed() case .verify: SPTracker.trackVerificationVerifyScreenViewed() default: break } } } // MARK: - Orientation // extension AccountVerificationViewController { override public var shouldAutorotate: Bool { if UIDevice.isPad { return super.shouldAutorotate } return false } override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.isPad { return super.supportedInterfaceOrientations } return [.portrait, .portraitUpsideDown] } override public var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if UIDevice.isPad { return super.preferredInterfaceOrientationForPresentation } return .portrait } } // MARK: - Constants // private struct Constants { static let scrollContentInset = UIEdgeInsets(top: 72, left: 0, bottom: 20, right: 0) static let primaryButtonCornerRadius: CGFloat = 8 } // MARK: - Localization // private struct Localization { static let errorMessage = NSLocalizedString("Please check your network settings and try again.", comment: "Error message. Account verification") static let okButton = NSLocalizedString("OK", comment: "Dismisses an AlertController") struct Review { static let title = NSLocalizedString("Review Your Account", comment: "Title -> Review you account screen") static let messageTemplate = NSLocalizedString("You are registered with Simplenote using the email %1$@.\n\nImprovements to account security may result in account loss if you no longer have access to this email address.", comment: "Message -> Review you account screen. Parameter: %1$@ - email address") static let confirm = NSLocalizedString("Confirm", comment: "Confirm button -> Review you account screen") static let changeEmail = NSLocalizedString("Change Email", comment: "Change email button -> Review you account screen") static let errorMessageTitle = NSLocalizedString("Cannot Confirm Account", comment: "Error message title. Review you account screen") } struct Verify { static let title = NSLocalizedString("Verify Your Email", comment: "Title -> Verify your email screen") static let messageTemplate = NSLocalizedString("Weve sent a verification email to %1$@. Please check your inbox and follow the instructions.", comment: "Message -> Verify your email screen. Parameter: %1$@ - email address") static let resendEmail = NSLocalizedString("Resend Email", comment: "Resend email button -> Verify your email screen") static let errorMessageTitle = NSLocalizedString("Cannot Send Verification Email", comment: "Error message title. Verify your email screen") } } ```
/content/code_sandbox/Simplenote/Verification/AccountVerificationViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,028
```swift import UIKit // MARK: - NoteEditorTagListViewControllerDelegate // protocol NoteEditorTagListViewControllerDelegate: AnyObject { func tagListDidUpdate(_ tagList: NoteEditorTagListViewController) func tagListIsEditing(_ tagList: NoteEditorTagListViewController) } // MARK: - NoteEditorTagListViewController // @objc class NoteEditorTagListViewController: UIViewController { @IBOutlet private weak var tagView: TagView! { didSet { tagView.delegate = self tagView.backgroundColor = .clear tagView.keyboardAppearance = .simplenoteKeyboardAppearance } } private let note: Note private let objectManager = SPObjectManager.shared() private let popoverPresenter: PopoverPresenter // if a newly created tag is deleted within a certain time span, // the tag will be completely deleted - note just removed from the // current note. This helps prevent against tag spam by mistyping private var recentlyCreatedTag: String? private var recentlyCreatedTagTimer: Timer? { didSet { oldValue?.invalidate() } } private lazy var suggestionsViewController: NoteEditorTagSuggestionsViewController = { let viewController = NoteEditorTagSuggestionsViewController(note: note) viewController.onSelectionCallback = { [weak self] tagName in guard let self = self else { return } self.tagView.addTagFieldText = nil self.tagView(self.tagView, wantsToCreateTagWithName: tagName) } return viewController }() weak var delegate: NoteEditorTagListViewControllerDelegate? init(note: Note, popoverPresenter: PopoverPresenter) { self.note = note self.popoverPresenter = popoverPresenter super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() reload() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { popoverPresenter.dismiss() } @objc func reload() { let tags = note.tagsArray? .compactMap({ $0 as? String }) .filter({ ($0 as NSString).isValidEmailAddress == false }) tagView.setup(withTagNames: tags ?? []) } @objc(scrollEntryFieldToVisibleAnimated:) func scrollEntryFieldToVisible(animated: Bool) { tagView.scrollEntryFieldToVisible(animated: animated) } } // MARK: - First Responder // extension NoteEditorTagListViewController { override var isFirstResponder: Bool { return tagView.isFirstResponder } override func becomeFirstResponder() -> Bool { tagView.becomeFirstResponder() } override func resignFirstResponder() -> Bool { tagView.resignFirstResponder() } } // MARK: - Object Manager // private extension NoteEditorTagListViewController { func createTagIfNotExists(tagName: String) { guard !objectManager.tagExists(tagName) else { return } objectManager.createTag(from: tagName) recentlyCreatedTag = tagName recentlyCreatedTagTimer = Timer.scheduledTimer(withTimeInterval: Constants.clearRecentlyCreatedTagTimeout, repeats: false) { [weak self] (_) in self?.recentlyCreatedTagTimer = nil self?.recentlyCreatedTag = nil } } func deleteTagIfCreatedRecently(tagName: String) { guard let recentlyCreatedTag = recentlyCreatedTag, recentlyCreatedTag == tagName else { return } self.recentlyCreatedTag = nil self.recentlyCreatedTagTimer = nil objectManager.removeTagName(recentlyCreatedTag) } } // MARK: - SPTagViewDelegate // extension NoteEditorTagListViewController: TagViewDelegate { func tagView(_ tagView: TagView, wantsToCreateTagWithName tagName: String) { guard !note.hasTag(tagName) else { return } let isEmailAddress = (tagName as NSString).isValidEmailAddress guard !isEmailAddress else { let alertController = UIAlertController(title: Localization.CollaborationAlert.title, message: Localization.CollaborationAlert.message, preferredStyle: .alert) alertController.addCancelActionWithTitle(Localization.CollaborationAlert.cancelAction) present(alertController, animated: true, completion: nil) return } createTagIfNotExists(tagName: tagName) note.addTag(tagName) tagView.add(tag: tagName) delegate?.tagListDidUpdate(self) SPTracker.trackEditorTagAdded() updateSuggestions() } func tagView(_ tagView: TagView, wantsToRemoveTagWithName tagName: String) { note.stripTag(tagName) deleteTagIfCreatedRecently(tagName: tagName) tagView.remove(tag: tagName) delegate?.tagListDidUpdate(self) SPTracker.trackEditorTagRemoved() updateSuggestions() } func tagViewDidBeginEditing(_ tagView: TagView) { delegate?.tagListIsEditing(self) updateSuggestions() } func tagViewDidChange(_ tagView: TagView) { delegate?.tagListIsEditing(self) updateSuggestions() } private func updateSuggestions() { suggestionsViewController.update(with: tagView.addTagFieldText) if suggestionsViewController.isEmpty { popoverPresenter.dismiss() return } if popoverPresenter.isPresented { popoverPresenter.relocate(around: tagView.addTagFieldFrameInWindow) } else { popoverPresenter.show(suggestionsViewController, around: tagView.addTagFieldFrameInWindow) } } } // MARK: - Constants // private struct Constants { static let clearRecentlyCreatedTagTimeout: TimeInterval = 3.5 } // MARK: - Localization // private struct Localization { enum CollaborationAlert { static let title = NSLocalizedString("Collaboration has moved", comment: "Alert title that collaboration has moved") static let message = NSLocalizedString("Sharing notes is now accessed through the action menu from the toolbar.", comment: "Alert message that collaboration has moved") static let cancelAction = NSLocalizedString("OK", comment: "Alert confirmation button title") } } ```
/content/code_sandbox/Simplenote/Tags/NoteEditorTagListViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,323
```swift import UIKit // MARK: - NoteEditorTagSuggestionsViewController // class NoteEditorTagSuggestionsViewController: 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 tableView.maxNumberOfVisibleRows = Metrics.maxNumberOfVisibleRows } } private let note: Note private let objectManager = SPObjectManager.shared() private var data: [String] = [] /// Called when row is selected /// var onSelectionCallback: ((String) -> Void)? /// Is empty /// var isEmpty: Bool { return data.isEmpty } /// Init /// init(note: Note) { self.note = note 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 } /// Update with keywords. Tags containing keywords that are not already in the note will be suggested /// func update(with keywords: String?) { let keywords = (keywords ?? "").trimmingCharacters(in: .whitespacesAndNewlines) guard !keywords.isEmpty else { reload(with: []) return } let tags = objectManager.tags() .filter { tag in !note.hasTag(tag.name) && tag.name.range(of: keywords, options: [.caseInsensitive, .diacriticInsensitive]) != nil } .compactMap { tag in tag.name } reload(with: tags) } private func reload(with data: [String]) { self.data = data // Can be called before view is loaded tableView?.reloadData() } } // MARK: - UITableViewDelegate // extension NoteEditorTagSuggestionsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) onSelectionCallback?(data[indexPath.row]) } } // MARK: - UITableViewDataSource // extension NoteEditorTagSuggestionsViewController: 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) cell.title = data[indexPath.row] cell.backgroundColor = .clear cell.separatorInset = .zero return cell } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // "Drops" the last separator! .leastNonzeroMagnitude } } // MARK: - Metrics // private struct Metrics { static let maxNumberOfVisibleRows: CGFloat = 3.5 } ```
/content/code_sandbox/Simplenote/Tags/NoteEditorTagSuggestionsViewController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
655
```swift import Foundation @objc class PublishController: NSObject { private var observedNotes = [String: Note]() var onUpdate: ((Note) -> Void)? func updatePublishState(for note: Note, to published: Bool) { if note.published == published { return } changePublishState(for: note, to: published) beginListeningForChanges(to: note, timeOut: Constants.timeOut) publishStateChanged(for: note) } private func changePublishState(for note: Note, to published: Bool) { note.published = published note.modificationDate = Date() SPAppDelegate.shared().save() } private func publishStateChanged(for note: Note) { onUpdate?(note) } } extension PublishController { // MARK: Listeners private func beginListeningForChanges(to note: Note, timeOut: TimeInterval) { observedNotes[note.simperiumKey] = note DispatchQueue.main.asyncAfter(deadline: .now() + timeOut) { self.endListeningForChanges(to: note) } } private func endListeningForChanges(to note: Note) { observedNotes.removeValue(forKey: note.simperiumKey) } // MARK: Listener Notifications @objc(didReceiveUpdateNotificationForKey:withMemberNames:) func didReceiveUpdateNotification(for key: String, with memberNames: NSArray) { guard memberNames.contains(Constants.observedProperty), let note = observedNotes[key] else { return } publishStateChanged(for: note) endListeningForChanges(to: note) } @objc(didReceiveDeleteNotificationsForKey:) func didReceiveDeleteNotification(for key: String) { guard let note = observedNotes[key] else { return } endListeningForChanges(to: note) } } private struct Constants { static let timeOut = TimeInterval(5) static let observedProperty = "publishURL" } ```
/content/code_sandbox/Simplenote/Controllers/PublishController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
416
```swift import Foundation import SimplenoteEndpoints @objc class AccountDeletionController: NSObject { private var accountDeletionRequestDate: Date? var hasValidDeletionRequest: Bool { guard let expirationDate = accountDeletionRequestDate?.increased(byDays: 1) else { return false } return Date() < expirationDate } func requestAccountDeletion(_ user: SPUser, completion: @escaping (_ result: Result<Data?, RemoteError>) -> Void) { AccountRemote().requestDelete(user) { [weak self] (result) in if case .success = result { self?.accountDeletionRequestDate = Date() } completion(result) } } @objc func clearRequestToken() { accountDeletionRequestDate = nil } } ```
/content/code_sandbox/Simplenote/Controllers/AccountDeletionController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
179
```swift import Foundation // MARK: - VersionsController // class VersionsController: NSObject { private let bucket: SPBucket /// Map of event listeners. /// private let callbackMap = NSMapTable<NSString, ListenerWrapper>(keyOptions: .copyIn, valueOptions: .weakMemory) /// Designated Initializer /// /// - Parameters: /// - bucket: Simperium bucket /// init(bucket: SPBucket) { self.bucket = bucket super.init() } /// Requests the specified number of versions of Notes for a given SimperiumKey. /// /// - Parameters: /// - simperiumKey: Identifier of the entity /// - currentVersion: Current version of Object. Used to calculate the amount of available versions to load /// - onResponse: Closure to be executed whenever a new version is received. This closure might be invoked `N` times. /// /// - Returns: An opaque entity, which should be retained by the callback handler. /// /// - Note: Whenever the returned entity is released, no further events will be relayed to the `onResponse` closure. /// - Warning: By design, there can be only *one* listener for changes associated to a SimperiumKey. /// func requestVersions(for simperiumKey: String, currentVersion: Int, onResponse: @escaping (SPHistoryVersion) -> Void) -> Any { // Keep a reference to the closure let wrapper = ListenerWrapper(block: onResponse) callbackMap.setObject(wrapper, forKey: simperiumKey as NSString) let versionRange = VersionsController.range(forCurrentVersion: currentVersion) bucket.requestVersions(Int32(versionRange.count), key: simperiumKey) // We'll return the wrapper as receipt return wrapper } } // MARK: - Simperium // extension VersionsController { /// Notifies all of the subscribers a new Version has been retrieved from Simperium. /// - Note: This API should be (manually) invoked everytime SPBucket's delegate receives a new Version (!) /// @objc(didReceiveObjectForSimperiumKey:version:data:) func didReceiveObject(for simperiumKey: String, version: Int, data: NSDictionary) { guard let wrapper = callbackMap.object(forKey: simperiumKey as NSString) else { return } guard let payload = data as? [AnyHashable: Any], let item = SPHistoryVersion(version: version, payload: payload) else { return } wrapper.block(item) } } // MARK: - Helpers // extension VersionsController { /// Returns an range of versions which can be requested /// /// - Parameters: /// - version: Current version of the entity /// /// - Returns: Range of versions /// static func range(forCurrentVersion version: Int) -> ClosedRange<Int> { let upperBound = max(version, Constants.minVersion) let lowerBound = max(upperBound - Constants.maxNumberOfVersions + 1, Constants.minVersion) return lowerBound...upperBound } } // MARK: - ListenerWrapper // private class ListenerWrapper: NSObject { let block: (SPHistoryVersion) -> Void init(block: @escaping (SPHistoryVersion) -> Void) { self.block = block } } // MARK: - Constants // private struct Constants { static let minVersion = 1 static let maxNumberOfVersions = 30 } ```
/content/code_sandbox/Simplenote/Controllers/VersionsController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
757
```swift import Foundation class PublishNoticePresenter { static func presentNotice(for note: Note) { switch note.publishState { case .publishing: NoticeController.shared.present(NoticeFactory.publishing()) SPTracker.trackPresentedNotice(ofType: .publishing) case .published: let notice = NoticeFactory.published(note, onCopy: { UIPasteboard.general.copyPublicLink(to: note) NoticeController.shared.present(NoticeFactory.linkCopied()) SPTracker.trackPreformedNoticeAction(ofType: .published, noticeType: .copyLink) }) NoticeController.shared.present(notice) SPTracker.trackPresentedNotice(ofType: .published) case .unpublishing: NoticeController.shared.present(NoticeFactory.unpublishing()) SPTracker.trackPresentedNotice(ofType: .unpublishing) case .unpublished: let notice = NoticeFactory.unpublished(note, onUndo: { SPAppDelegate.shared().publishController.updatePublishState(for: note, to: true) SPTracker.trackPreformedNoticeAction(ofType: .unpublished, noticeType: .undo) }) NoticeController.shared.present(notice) SPTracker.trackPresentedNotice(ofType: .unpublished) } } } ```
/content/code_sandbox/Simplenote/Controllers/PublishNoticePresenter.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
265
```swift import WidgetKit import Intents struct WidgetController { @available(iOS 14.0, *) static func resetWidgetTimelines() { WidgetCenter.shared.getCurrentConfigurations { result in guard case .success(let widgets) = result else { return } if widgets.contains(where: { widget in /// Note: /// We *used to* check if `widget.configuration` was of the `NoteWidgetIntent` / `ListWidgetIntent`. /// This caused (a million) Swift compiler errors in Xcode 13. /// In order to remediate this, we're disabling `codegen` in the `intentdefinition` file, and simply checking if there's /// an Intent set up there. /// The only scenario in which we wouldn't wanna reload the Timelines is the `New Note` widget (which does not display any dynamic content). /// return widget.configuration != nil }) { WidgetCenter.shared.reloadAllTimelines() } } } static func syncWidgetDefaults(authenticated: Bool, sortMode: SortMode) { let widgetDefaults = WidgetDefaults.shared widgetDefaults.sortMode = sortMode widgetDefaults.loggedIn = authenticated } } ```
/content/code_sandbox/Simplenote/Controllers/WidgetController.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
260
```c #include "context_test.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> /******************** * GENERIC RENDERER * ********************/ static void rndr_blockcode(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *lang, const hoedown_buffer *attr, const hoedown_renderer_data *data) { uint8_t c = hoedown_document_fencedcode_char(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (c) hoedown_buffer_putc(ob, c); else hoedown_buffer_puts(ob, "unfenced blockcode"); hoedown_buffer_putc(ob, ' '); } static void rndr_blockquote(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (content) hoedown_buffer_put(ob, content->data, content->size); } static void rndr_header(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, int level, const hoedown_renderer_data *data) { hoedown_header_type header_type = hoedown_document_header_type(((hoedown_context_test_renderer_state*) data->opaque)->doc); switch (header_type) { case HOEDOWN_HEADER_ATX: hoedown_buffer_puts(ob, "HOEDOWN_HEADER_ATX"); break; case HOEDOWN_HEADER_SETEXT: hoedown_buffer_puts(ob, "HOEDOWN_HEADER_SETEXT"); break; default: break; } hoedown_buffer_putc(ob, ' '); } static int rndr_link(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *attr, const hoedown_renderer_data *data) { const hoedown_buffer *id, *ref_attr, *inline_attr; hoedown_link_type link_type; id = hoedown_document_link_id(((hoedown_context_test_renderer_state*) data->opaque)->doc); hoedown_buffer_puts(ob, "id: "); if (id) hoedown_buffer_put(ob, id->data, id->size); else hoedown_buffer_puts(ob, "no id"); hoedown_buffer_putc(ob, ' '); link_type = hoedown_document_link_type(((hoedown_context_test_renderer_state*) data->opaque)->doc); switch (link_type) { case HOEDOWN_LINK_INLINE: hoedown_buffer_puts(ob, "HOEDOWN_LINK_INLINE"); break; case HOEDOWN_LINK_REFERENCE: hoedown_buffer_puts(ob, "HOEDOWN_LINK_REFERENCE"); break; case HOEDOWN_LINK_EMPTY_REFERENCE: hoedown_buffer_puts(ob, "HOEDOWN_LINK_EMPTY_REFERENCE"); break; case HOEDOWN_LINK_SHORTCUT: hoedown_buffer_puts(ob, "HOEDOWN_LINK_SHORTCUT"); break; default: break; } ref_attr = hoedown_document_link_ref_attr(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (ref_attr && ref_attr->size > 0) { hoedown_buffer_puts(ob, " ref_attr: "); hoedown_buffer_put(ob, ref_attr->data, ref_attr->size); } inline_attr = hoedown_document_link_inline_attr(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (inline_attr && inline_attr->size > 0) { hoedown_buffer_puts(ob, " inline_attr: "); hoedown_buffer_put(ob, inline_attr->data, inline_attr->size); } return 1; } static void rndr_list(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, unsigned int flags, const hoedown_renderer_data *data) { if (content) hoedown_buffer_put(ob, content->data, content->size); } static void rndr_listitem(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, hoedown_list_flags *flags, const hoedown_renderer_data *data) { uint8_t c; const hoedown_buffer* ol_numeral; ol_numeral = hoedown_document_ol_numeral(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (ol_numeral) { hoedown_buffer_put(ob, ol_numeral->data, ol_numeral->size); hoedown_buffer_puts(ob, ". "); } else { c = hoedown_document_ul_item_char(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (c) { hoedown_buffer_putc(ob, c); hoedown_buffer_putc(ob, ' '); } } if (content) hoedown_buffer_put(ob, content->data, content->size); } static void rndr_paragraph(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, const hoedown_renderer_data *data) { int list_depth, blockquote_depth; list_depth = hoedown_document_list_depth(((hoedown_context_test_renderer_state*) data->opaque)->doc); blockquote_depth = hoedown_document_blockquote_depth(((hoedown_context_test_renderer_state*) data->opaque)->doc); hoedown_buffer_printf(ob, "list depth: %d blockquote depth: %d ", list_depth, blockquote_depth); if (content) { hoedown_buffer_puts(ob, "paragraph: "); hoedown_buffer_put(ob, content->data, content->size); } hoedown_buffer_putc(ob, '\n'); } static void rndr_hrule(hoedown_buffer *ob, const hoedown_renderer_data *data) { uint8_t c = hoedown_document_hrule_char(((hoedown_context_test_renderer_state*) data->opaque)->doc); hoedown_buffer_putc(ob, c); hoedown_buffer_putc(ob, ' '); } static int rndr_image(hoedown_buffer *ob, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *alt, const hoedown_buffer *attr, const hoedown_renderer_data *data) { const hoedown_buffer *id, *ref_attr, *inline_attr; hoedown_link_type link_type; id = hoedown_document_link_id(((hoedown_context_test_renderer_state*) data->opaque)->doc); hoedown_buffer_puts(ob, "id: "); if (id) hoedown_buffer_put(ob, id->data, id->size); else hoedown_buffer_puts(ob, "no id"); hoedown_buffer_putc(ob, ' '); link_type = hoedown_document_link_type(((hoedown_context_test_renderer_state*) data->opaque)->doc); switch (link_type) { case HOEDOWN_LINK_INLINE: hoedown_buffer_puts(ob, "HOEDOWN_LINK_INLINE"); break; case HOEDOWN_LINK_REFERENCE: hoedown_buffer_puts(ob, "HOEDOWN_LINK_REFERENCE"); break; case HOEDOWN_LINK_EMPTY_REFERENCE: hoedown_buffer_puts(ob, "HOEDOWN_LINK_EMPTY_REFERENCE"); break; case HOEDOWN_LINK_SHORTCUT: hoedown_buffer_puts(ob, "HOEDOWN_LINK_SHORTCUT"); break; default: break; } ref_attr = hoedown_document_link_ref_attr(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (ref_attr && ref_attr->size > 0) { hoedown_buffer_puts(ob, " ref_attr: "); hoedown_buffer_put(ob, ref_attr->data, ref_attr->size); } inline_attr = hoedown_document_link_inline_attr(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (inline_attr && inline_attr->size > 0) { hoedown_buffer_puts(ob, " inline_attr: "); hoedown_buffer_put(ob, inline_attr->data, inline_attr->size); } return 1; } static void rndr_normal_text(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { int escaped = hoedown_document_is_escaped(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (escaped) { hoedown_buffer_putc(ob, '\\'); } if (content) hoedown_buffer_put(ob, content->data, content->size); } static void rndr_footnotes(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (content) hoedown_buffer_put(ob, content->data, content->size); } static void rndr_footnote_def(hoedown_buffer *ob, const hoedown_buffer *content, unsigned int num, const hoedown_renderer_data *data) { const hoedown_buffer *id; id = hoedown_document_footnote_id(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (id) { hoedown_buffer_puts(ob, "id: "); hoedown_buffer_put(ob, id->data, id->size); } hoedown_buffer_putc(ob, ' '); if (content) hoedown_buffer_put(ob, content->data, content->size); } static int rndr_footnote_ref(hoedown_buffer *ob, unsigned int num, const hoedown_renderer_data *data) { const hoedown_buffer *id; id = hoedown_document_link_id(((hoedown_context_test_renderer_state*) data->opaque)->doc); if (id) { hoedown_buffer_puts(ob, "id: "); hoedown_buffer_put(ob, id->data, id->size); } hoedown_buffer_putc(ob, ' '); return 1; } static void rndr_ref(hoedown_buffer *orig, const hoedown_renderer_data *data) { /* this is a little dirty, but it is simpler than maintaining this state in the renderer */ hoedown_buffer *copy; copy = hoedown_buffer_new(64); hoedown_buffer_grow(copy, orig->size); memcpy(copy->data, orig->data, orig->size); copy->size = orig->size; printf("Reference Definition: %s\n", hoedown_buffer_cstr(copy)); hoedown_buffer_free(copy); } static void rndr_footnote_ref_def(hoedown_buffer *orig, const hoedown_renderer_data *data) { /* this is a little dirty, but it is simpler than maintaining this state in the renderer */ hoedown_buffer *copy; copy = hoedown_buffer_new(64); hoedown_buffer_grow(copy, orig->size); memcpy(copy->data, orig->data, orig->size); copy->size = orig->size; printf("Footnote Reference Definition: %s\n", hoedown_buffer_cstr(copy)); hoedown_buffer_free(copy); } static int rndr_dummy_span(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { return 1; } hoedown_renderer * hoedown_context_test_renderer_new(hoedown_document *doc) { static const hoedown_renderer cb_default = { NULL, rndr_blockcode, rndr_blockquote, rndr_header, rndr_hrule, rndr_list, rndr_listitem, rndr_paragraph, NULL, NULL, NULL, NULL, NULL, rndr_footnotes, rndr_footnote_def, NULL, NULL, NULL, rndr_dummy_span, rndr_dummy_span, rndr_dummy_span, rndr_dummy_span, rndr_dummy_span, rndr_image, NULL, rndr_link, rndr_dummy_span, rndr_dummy_span, NULL, rndr_footnote_ref, NULL, NULL, NULL, rndr_normal_text, NULL, NULL, NULL, rndr_ref, rndr_footnote_ref_def, }; hoedown_context_test_renderer_state *state; hoedown_renderer *renderer; /* Prepare the state pointer */ state = hoedown_malloc(sizeof(hoedown_context_test_renderer_state)); memset(state, 0x0, sizeof(hoedown_context_test_renderer_state)); state->doc = doc; /* Prepare the renderer */ renderer = hoedown_malloc(sizeof(hoedown_renderer)); memcpy(renderer, &cb_default, sizeof(hoedown_renderer)); renderer->opaque = state; return renderer; } void hoedown_context_test_renderer_free(hoedown_renderer *renderer) { free(renderer->opaque); free(renderer); } ```
/content/code_sandbox/External/Hoextdown/context_test.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,883
```objective-c /* hash.h - generic markdown parser */ #ifndef HOEDOWN_HASH_H #define HOEDOWN_HASH_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif typedef struct hoedown_hash_item hoedown_hash_item; typedef struct hoedown_hash hoedown_hash; typedef void (hoedown_hash_value_destruct) (void *data); struct hoedown_hash_item { char *key; void *value; hoedown_hash_value_destruct *destruct; hoedown_hash_item *next; hoedown_hash_item *tail; }; struct hoedown_hash { hoedown_hash_item **items; size_t asize; }; hoedown_hash * hoedown_hash_new(size_t size); void hoedown_hash_free(hoedown_hash *hash); int hoedown_hash_add(hoedown_hash *hash, const char *key, size_t key_len, void *value, hoedown_hash_value_destruct *destruct); void * hoedown_hash_find(hoedown_hash *hash, char *key, size_t key_len); #ifdef __cplusplus } #endif #endif /** HOEDOWN_HASH_H **/ ```
/content/code_sandbox/External/Hoextdown/hash.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
253
```c #include "escape.h" #include <assert.h> #include <stdio.h> #include <string.h> #define likely(x) __builtin_expect((x),1) #define unlikely(x) __builtin_expect((x),0) /* * The following characters will not be escaped: * * -_.+!*'(),%#@?=;:/,+&$ alphanum * * Note that this character set is the addition of: * * - The characters which are safe to be in an URL * - The characters which are *not* safe to be in * an URL because they are RESERVED characters. * * We assume (lazily) that any RESERVED char that * appears inside an URL is actually meant to * have its native function (i.e. as an URL * component/separator) and hence needs no escaping. * * There are two exceptions: the chacters & (amp) * and ' (single quote) do not appear in the table. * They are meant to appear in the URL as components, * yet they require special HTML-entity escaping * to generate valid HTML markup. * * All other characters will be escaped to %XX. * */ static const uint8_t HREF_SAFE[UINT8_MAX+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; void hoedown_escape_href(hoedown_buffer *ob, const uint8_t *data, size_t size) { static const char hex_chars[] = "0123456789ABCDEF"; size_t i = 0, mark; char hex_str[3]; hex_str[0] = '%'; while (i < size) { mark = i; while (i < size && HREF_SAFE[data[i]]) i++; /* Optimization for cases where there's nothing to escape */ if (mark == 0 && i >= size) { hoedown_buffer_put(ob, data, size); return; } if (likely(i > mark)) { hoedown_buffer_put(ob, data + mark, i - mark); } /* escaping */ if (i >= size) break; switch (data[i]) { /* amp appears all the time in URLs, but needs * HTML-entity escaping to be inside an href */ case '&': HOEDOWN_BUFPUTSL(ob, "&amp;"); break; /* the single quote is a valid URL character * according to the standard; it needs HTML * entity escaping too */ case '\'': HOEDOWN_BUFPUTSL(ob, "&#x27;"); break; /* the space can be escaped to %20 or a plus * sign. we're going with the generic escape * for now. the plus thing is more commonly seen * when building GET strings */ #if 0 case ' ': hoedown_buffer_putc(ob, '+'); break; #endif /* every other character goes with a %XX escaping */ default: hex_str[1] = hex_chars[(data[i] >> 4) & 0xF]; hex_str[2] = hex_chars[data[i] & 0xF]; hoedown_buffer_put(ob, (uint8_t *)hex_str, 3); } i++; } } /** * According to the OWASP rules: * * & --> &amp; * < --> &lt; * > --> &gt; * " --> &quot; * ' --> &#x27; &apos; is not recommended * / --> &#x2F; forward slash is included as it helps end an HTML entity * */ static const uint8_t HTML_ESCAPE_TABLE[UINT8_MAX+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static const char *HTML_ESCAPES[] = { "", "&quot;", "&amp;", "&#39;", "&#47;", "&lt;", "&gt;" }; void hoedown_escape_html(hoedown_buffer *ob, const uint8_t *data, size_t size, int secure) { size_t i = 0, mark; while (1) { mark = i; while (i < size && HTML_ESCAPE_TABLE[data[i]] == 0) i++; /* Optimization for cases where there's nothing to escape */ if (mark == 0 && i >= size) { hoedown_buffer_put(ob, data, size); return; } if (likely(i > mark)) hoedown_buffer_put(ob, data + mark, i - mark); if (i >= size) break; /* The forward slash is only escaped in secure mode */ if (!secure && data[i] == '/') { hoedown_buffer_putc(ob, '/'); } else { hoedown_buffer_puts(ob, HTML_ESCAPES[HTML_ESCAPE_TABLE[data[i]]]); } i++; } } ```
/content/code_sandbox/External/Hoextdown/escape.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
2,593
```c #include "stack.h" #include "buffer.h" #include <stdlib.h> #include <string.h> #include <assert.h> void hoedown_stack_init(hoedown_stack *st, size_t initial_size) { assert(st); st->item = NULL; st->size = st->asize = 0; if (!initial_size) initial_size = 8; hoedown_stack_grow(st, initial_size); } void hoedown_stack_uninit(hoedown_stack *st) { assert(st); free(st->item); } void hoedown_stack_grow(hoedown_stack *st, size_t neosz) { assert(st); if (st->asize >= neosz) return; st->item = hoedown_realloc(st->item, neosz * sizeof(void *)); memset(st->item + st->asize, 0x0, (neosz - st->asize) * sizeof(void *)); st->asize = neosz; if (st->size > neosz) st->size = neosz; } void hoedown_stack_push(hoedown_stack *st, void *item) { assert(st); if (st->size >= st->asize) hoedown_stack_grow(st, st->size * 2); st->item[st->size++] = item; } void * hoedown_stack_pop(hoedown_stack *st) { assert(st); if (!st->size) return NULL; return st->item[--st->size]; } void * hoedown_stack_top(const hoedown_stack *st) { assert(st); if (!st->size) return NULL; return st->item[st->size - 1]; } ```
/content/code_sandbox/External/Hoextdown/stack.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
382
```c #include "autolink.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #ifndef _MSC_VER #include <strings.h> #else #define strncasecmp _strnicmp #endif int hoedown_autolink_is_safe(const uint8_t *data, size_t size) { static const size_t valid_uris_count = 6; static const char *valid_uris[] = { "http://", "https://", "/", "#", "ftp://", "mailto:" }; static const size_t valid_uris_size[] = { 7, 8, 1, 1, 6, 7 }; size_t i; for (i = 0; i < valid_uris_count; ++i) { size_t len = valid_uris_size[i]; if (size > len && strncasecmp((char *)data, valid_uris[i], len) == 0 && isalnum(data[len])) return 1; } return 0; } static size_t autolink_delim(uint8_t *data, size_t link_end, size_t max_rewind, size_t size) { uint8_t cclose, copen = 0; size_t i; for (i = 0; i < link_end; ++i) if (data[i] == '<') { link_end = i; break; } while (link_end > 0) { if (strchr("?!.,:", data[link_end - 1]) != NULL) link_end--; else if (data[link_end - 1] == ';') { size_t new_end = link_end - 2; while (new_end > 0 && isalpha(data[new_end])) new_end--; if (new_end < link_end - 2 && data[new_end] == '&') link_end = new_end; else link_end--; } else break; } if (link_end == 0) return 0; cclose = data[link_end - 1]; switch (cclose) { case '"': copen = '"'; break; case '\'': copen = '\''; break; case ')': copen = '('; break; case ']': copen = '['; break; case '}': copen = '{'; break; } if (copen != 0) { size_t closing = 0; size_t opening = 0; size_t i = 0; /* Try to close the final punctuation sign in this same line; * if we managed to close it outside of the URL, that means that it's * not part of the URL. If it closes inside the URL, that means it * is part of the URL. * * Examples: * * foo path_to_url bar * => path_to_url * * foo (path_to_url bar * => path_to_url * * foo path_to_url bar * => path_to_url * * (foo path_to_url bar * => foo path_to_url */ while (i < link_end) { if (data[i] == copen) opening++; else if (data[i] == cclose) closing++; i++; } if (closing != opening) link_end--; } return link_end; } static size_t check_domain(uint8_t *data, size_t size, int allow_short) { size_t i, np = 0; if (!isalnum(data[0])) return 0; for (i = 1; i < size - 1; ++i) { if (strchr(".:", data[i]) != NULL) np++; else if (!isalnum(data[i]) && data[i] != '-') break; } if (allow_short) { /* We don't need a valid domain in the strict sense (with * least one dot; so just make sure it's composed of valid * domain characters and return the length of the the valid * sequence. */ return i; } else { /* a valid domain needs to have at least a dot. * that's as far as we get */ return np ? i : 0; } } size_t hoedown_autolink__www( size_t *rewind_p, hoedown_buffer *link, uint8_t *data, size_t max_rewind, size_t size, unsigned int flags) { size_t link_end; if (max_rewind > 0 && !ispunct(data[-1]) && !isspace(data[-1])) return 0; if (size < 4 || memcmp(data, "www.", strlen("www.")) != 0) return 0; link_end = check_domain(data, size, 0); if (link_end == 0) return 0; while (link_end < size && !isspace(data[link_end])) link_end++; link_end = autolink_delim(data, link_end, max_rewind, size); if (link_end == 0) return 0; hoedown_buffer_put(link, data, link_end); *rewind_p = 0; return (int)link_end; } size_t hoedown_autolink__email( size_t *rewind_p, hoedown_buffer *link, uint8_t *data, size_t max_rewind, size_t size, unsigned int flags) { size_t link_end, rewind; int nb = 0, np = 0; for (rewind = 0; rewind < max_rewind; ++rewind) { uint8_t c = data[-1 - rewind]; if (isalnum(c)) continue; if (strchr(".+-_", c) != NULL) continue; break; } if (rewind == 0) return 0; for (link_end = 0; link_end < size; ++link_end) { uint8_t c = data[link_end]; if (isalnum(c)) continue; if (c == '@') nb++; else if (c == '.' && link_end < size - 1) np++; else if (c != '-' && c != '_') break; } if (link_end < 2 || nb != 1 || np == 0 || !isalpha(data[link_end - 1])) return 0; link_end = autolink_delim(data, link_end, max_rewind, size); if (link_end == 0) return 0; hoedown_buffer_put(link, data - rewind, link_end + rewind); *rewind_p = rewind; return link_end; } size_t hoedown_autolink__url( size_t *rewind_p, hoedown_buffer *link, uint8_t *data, size_t max_rewind, size_t size, unsigned int flags) { size_t link_end, rewind = 0, domain_len; if (size < 4 || data[1] != '/' || data[2] != '/') return 0; while (rewind < max_rewind && isalpha(data[-1 - rewind])) rewind++; if (!hoedown_autolink_is_safe(data - rewind, size + rewind)) return 0; link_end = strlen("://"); domain_len = check_domain( data + link_end, size - link_end, flags & HOEDOWN_AUTOLINK_SHORT_DOMAINS); if (domain_len == 0) return 0; link_end += domain_len; while (link_end < size && !isspace(data[link_end])) link_end++; link_end = autolink_delim(data, link_end, max_rewind, size); if (link_end == 0) return 0; hoedown_buffer_put(link, data - rewind, link_end + rewind); *rewind_p = rewind; return link_end; } ```
/content/code_sandbox/External/Hoextdown/autolink.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,763
```objective-c /* html.h - HTML renderer and utilities */ #ifndef HOEDOWN_HTML_H #define HOEDOWN_HTML_H #include "document.h" #include "buffer.h" #include "hash.h" #ifdef __cplusplus extern "C" { #endif /************* * CONSTANTS * *************/ typedef enum hoedown_html_flags { HOEDOWN_HTML_SKIP_HTML = (1 << 0), HOEDOWN_HTML_ESCAPE = (1 << 1), HOEDOWN_HTML_HARD_WRAP = (1 << 2), HOEDOWN_HTML_USE_XHTML = (1 << 3), HOEDOWN_HTML_USE_TASK_LIST = (1 << 4), HOEDOWN_HTML_LINE_CONTINUE = (1 << 5), HOEDOWN_HTML_HEADER_ID = (1 << 6), HOEDOWN_HTML_FENCED_CODE_SCRIPT = (1 << 7) } hoedown_html_flags; typedef enum hoedown_html_tag { HOEDOWN_HTML_TAG_NONE = 0, HOEDOWN_HTML_TAG_OPEN, HOEDOWN_HTML_TAG_CLOSE } hoedown_html_tag; /********* * TYPES * *********/ struct hoedown_html_renderer_state { void *opaque; struct { int header_count; int current_level; int level_offset; int nesting_level; char *header; char *footer; } toc_data; struct { hoedown_hash *header_id; } hash; hoedown_html_flags flags; /* extra callbacks */ void (*link_attributes)(hoedown_buffer *ob, const hoedown_buffer *url, const hoedown_renderer_data *data); }; typedef struct hoedown_html_renderer_state hoedown_html_renderer_state; /************* * FUNCTIONS * *************/ /* hoedown_html_smartypants: process an HTML snippet using SmartyPants for smart punctuation */ void hoedown_html_smartypants(hoedown_buffer *ob, const uint8_t *data, size_t size); /* hoedown_html_is_tag: checks if data starts with a specific tag, returns the tag type or NONE */ hoedown_html_tag hoedown_html_is_tag(const uint8_t *data, size_t size, const char *tagname); /* hoedown_html_renderer_new: allocates a regular HTML renderer */ hoedown_renderer *hoedown_html_renderer_new( hoedown_html_flags render_flags, int nesting_level ) __attribute__ ((malloc)); /* hoedown_html_toc_renderer_new: like hoedown_html_renderer_new, but the returned renderer produces the Table of Contents */ hoedown_renderer *hoedown_html_toc_renderer_new( int nesting_level ) __attribute__ ((malloc)); /* hoedown_html_renderer_free: deallocate an HTML renderer */ void hoedown_html_renderer_free(hoedown_renderer *renderer); #ifdef __cplusplus } #endif #endif /** HOEDOWN_HTML_H **/ ```
/content/code_sandbox/External/Hoextdown/html.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
612
```objective-c /* context_test.h - context test renderer used to test parser state functions */ #ifndef CONTEXT_TEST_H #define CONTEXT_TEST_H #include "document.h" #include "buffer.h" #include "hash.h" #ifdef __cplusplus extern "C" { #endif /********* * TYPES * *********/ struct hoedown_context_test_renderer_state { hoedown_document *doc; }; typedef struct hoedown_context_test_renderer_state hoedown_context_test_renderer_state; /************* * FUNCTIONS * *************/ /* hoedown_context_test_renderer_new: allocates a context test renderer */ hoedown_renderer *hoedown_context_test_renderer_new() __attribute__ ((malloc)); /* hoedown_context_test_renderer_free: deallocate a context test renderer */ void hoedown_context_test_renderer_free(hoedown_renderer *renderer); #ifdef __cplusplus } #endif #endif /** CONTEXT_TEST_H **/ ```
/content/code_sandbox/External/Hoextdown/context_test.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
182
```c #include "hash.h" #include <stdlib.h> #include <string.h> #define HOEDOWN_HASH_ITEM_SIZE 255 #define HOEDOWN_HASH_FNV_PRIME 0x01000193 #define HOEDOWN_HASH_FNV_OFFSET_BASIS 0x811c9dc5 static char * hoedown_hash_strndup(const char* str, size_t n) { if (str) { char *s = (char *)malloc(sizeof(char) * (n + 1)); if (s) { memcpy(s, str, n); s[n] = '\0'; } return s; } return NULL; } static char * hoedown_hash_strdup(const char* str) { if (str) { return hoedown_hash_strndup(str, strlen(str)); } return NULL; } static unsigned int hoedown_hash_fnv(const char *key, const char *max, size_t limit) { unsigned int hash = HOEDOWN_HASH_FNV_OFFSET_BASIS; if (max == NULL) { if (key) { max = key + strlen(key); } else { max = key; } } while (key < max) { hash *= HOEDOWN_HASH_FNV_PRIME; hash ^= *key; key++; } hash %= limit; return hash; } static hoedown_hash_item * hoedown_hash_item_new(void) { hoedown_hash_item *item; item = (hoedown_hash_item *)malloc(sizeof(hoedown_hash_item)); if (!item) { return NULL; } item->key = NULL; item->value = NULL; item->destruct = NULL; item->next = NULL; item->tail = NULL; return item; } static void hoedown_hash_item_free(hoedown_hash_item *item) { if (item) { if (item->next) { hoedown_hash_item_free(item->next); } if (item->key) { free(item->key); } if (item->destruct) { (item->destruct)(item->value); } free(item); } } static int hoedown_hash_item_push(hoedown_hash_item *item, const char *key, size_t key_len, void *value, hoedown_hash_value_destruct *destruct) { hoedown_hash_item *entry; if (!item || !key || !value) { return 1; } if (item->key != NULL) { entry = hoedown_hash_item_new(); if (!entry) { return 1; } } else { entry = item; } if (key_len > 0) { entry->key = hoedown_hash_strndup(key, key_len); } else { entry->key = hoedown_hash_strdup(key); } entry->value = value; entry->destruct = destruct; if (item->tail) { item->tail->next = entry; } else if (item != entry) { item->next = entry; } item->tail = entry; return 0; } hoedown_hash * hoedown_hash_new(size_t size) { hoedown_hash *hash; size_t items_size; hash = (hoedown_hash *)malloc(sizeof(hoedown_hash)); if (!hash) { return NULL; } if (size == 0) { size = HOEDOWN_HASH_ITEM_SIZE; } items_size = sizeof(hoedown_hash_item *) * size; hash->items = (hoedown_hash_item **)malloc(items_size); if (!hash->items) { free(hash); return NULL; } memset(hash->items, 0, items_size); hash->asize = size; return hash; } void hoedown_hash_free(hoedown_hash *hash) { if (hash) { if (hash->items) { size_t i = 0; while (i < hash->asize) { if (hash->items[i]) { hoedown_hash_item_free(hash->items[i]); } ++i; } free(hash->items); } free(hash); } } int hoedown_hash_add(hoedown_hash *hash, const char *key, size_t key_len, void *value, hoedown_hash_value_destruct *destruct) { unsigned int h; if (!hash || !key || !value) { return 1; } h = hoedown_hash_fnv(key, key + key_len, hash->asize); if (!hash->items[h]) { hash->items[h] = hoedown_hash_item_new(); if (!hash->items[h]) { return 1; } } if (hoedown_hash_item_push(hash->items[h], key, key_len, value, destruct) != 0) { return 1; } return 0; } void * hoedown_hash_find(hoedown_hash *hash, char *key, size_t key_len) { unsigned int h; if (!hash || !key) { return NULL; } h = hoedown_hash_fnv(key, key + key_len, hash->asize); if (hash->items[h]) { hoedown_hash_item *item = hash->items[h]; while (item != NULL) { if (item->key && strncmp(item->key, key, key_len) == 0) { return item->value; } item = item->next; } } return NULL; } ```
/content/code_sandbox/External/Hoextdown/hash.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,267
```objective-c /* document.h - generic markdown parser */ #ifndef HOEDOWN_DOCUMENT_H #define HOEDOWN_DOCUMENT_H #include "buffer.h" #include "autolink.h" #ifdef __cplusplus extern "C" { #endif /************* * CONSTANTS * *************/ /* Next offset: 22 */ typedef enum hoedown_extensions { /* block-level extensions */ HOEDOWN_EXT_TABLES = (1 << 0), HOEDOWN_EXT_MULTILINE_TABLES = (1 << 18), HOEDOWN_EXT_FENCED_CODE = (1 << 1), HOEDOWN_EXT_FOOTNOTES = (1 << 2), HOEDOWN_EXT_DEFINITION_LISTS = (1 << 19), HOEDOWN_EXT_BLOCKQUOTE_EMPTY_LINE = (1 << 21), /* span-level extensions */ HOEDOWN_EXT_AUTOLINK = (1 << 3), HOEDOWN_EXT_STRIKETHROUGH = (1 << 4), HOEDOWN_EXT_UNDERLINE = (1 << 5), HOEDOWN_EXT_HIGHLIGHT = (1 << 6), HOEDOWN_EXT_QUOTE = (1 << 7), HOEDOWN_EXT_SUPERSCRIPT = (1 << 8), HOEDOWN_EXT_MATH = (1 << 9), /* other flags */ HOEDOWN_EXT_NO_INTRA_EMPHASIS = (1 << 11), HOEDOWN_EXT_SPACE_HEADERS = (1 << 12), HOEDOWN_EXT_MATH_EXPLICIT = (1 << 13), HOEDOWN_EXT_HTML5_BLOCKS = (1 << 20), HOEDOWN_EXT_NO_INTRA_UNDERLINE_EMPHASIS = (1 << 21), /* negative flags */ HOEDOWN_EXT_DISABLE_INDENTED_CODE = (1 << 14), /* special attribute */ HOEDOWN_EXT_SPECIAL_ATTRIBUTE = (1 << 15), /* script tags */ HOEDOWN_EXT_SCRIPT_TAGS = (1 << 16), /* meta block */ HOEDOWN_EXT_META_BLOCK = (1 << 17) } hoedown_extensions; #define HOEDOWN_EXT_BLOCK (\ HOEDOWN_EXT_TABLES |\ HOEDOWN_EXT_MULTILINE_TABLES |\ HOEDOWN_EXT_FENCED_CODE |\ HOEDOWN_EXT_FOOTNOTES |\ HOEDOWN_EXT_DEFINITION_LISTS |\ HOEDOWN_EXT_BLOCKQUOTE_EMPTY_LINE ) #define HOEDOWN_EXT_SPAN (\ HOEDOWN_EXT_AUTOLINK |\ HOEDOWN_EXT_STRIKETHROUGH |\ HOEDOWN_EXT_UNDERLINE |\ HOEDOWN_EXT_HIGHLIGHT |\ HOEDOWN_EXT_QUOTE |\ HOEDOWN_EXT_SUPERSCRIPT |\ HOEDOWN_EXT_MATH ) #define HOEDOWN_EXT_FLAGS (\ HOEDOWN_EXT_NO_INTRA_EMPHASIS |\ HOEDOWN_EXT_SPACE_HEADERS |\ HOEDOWN_EXT_MATH_EXPLICIT |\ HOEDOWN_EXT_SPECIAL_ATTRIBUTE |\ HOEDOWN_EXT_SCRIPT_TAGS |\ HOEDOWN_EXT_META_BLOCK |\ HOEDOWN_EXT_HTML5_BLOCKS) #define HOEDOWN_EXT_NEGATIVE (\ HOEDOWN_EXT_DISABLE_INDENTED_CODE ) typedef enum hoedown_list_flags { HOEDOWN_LIST_ORDERED = (1 << 0), HOEDOWN_LI_BLOCK = (1 << 1), /* <li> containing block data */ HOEDOWN_LI_TASK = (1 << 2), HOEDOWN_LI_END = (1 << 3), /* internal list flag */ HOEDOWN_LIST_DEFINITION = (1 << 4), HOEDOWN_LI_DT = (1 << 5), HOEDOWN_LI_DD = (1 << 6) } hoedown_list_flags; typedef enum hoedown_table_flags { HOEDOWN_TABLE_ALIGN_LEFT = 1, HOEDOWN_TABLE_ALIGN_RIGHT = 2, HOEDOWN_TABLE_ALIGN_CENTER = 3, HOEDOWN_TABLE_ALIGNMASK = 3, HOEDOWN_TABLE_HEADER = 4 } hoedown_table_flags; typedef enum hoedown_autolink_type { HOEDOWN_AUTOLINK_NONE, /* used internally when it is not an autolink*/ HOEDOWN_AUTOLINK_NORMAL, /* normal http/http/ftp/mailto/etc link */ HOEDOWN_AUTOLINK_EMAIL /* e-mail link without explit mailto: */ } hoedown_autolink_type; typedef enum hoedown_header_type { HOEDOWN_HEADER_NONE, /* not a header */ HOEDOWN_HEADER_ATX, /* e.g. "# Foo" */ HOEDOWN_HEADER_SETEXT /* e.g. "Foo\n---" or "Foo\n===" */ } hoedown_header_type; typedef enum hoedown_link_type { HOEDOWN_LINK_NONE, /* not in a link */ HOEDOWN_LINK_INLINE, /* e.g. [foo](/bar/) */ HOEDOWN_LINK_REFERENCE, /* e.g. [foo][bar] */ HOEDOWN_LINK_EMPTY_REFERENCE, /* e.g. [foo][] */ HOEDOWN_LINK_SHORTCUT /* e.g. [foo] */ } hoedown_link_type; /********* * TYPES * *********/ struct hoedown_document; typedef struct hoedown_document hoedown_document; struct hoedown_renderer_data { void *opaque; }; typedef struct hoedown_renderer_data hoedown_renderer_data; /* hoedown_renderer - functions for rendering parsed data */ struct hoedown_renderer { /* state object */ void *opaque; /* block level callbacks - NULL skips the block */ void (*blockcode)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *lang, const hoedown_buffer *attr, const hoedown_renderer_data *data); void (*blockquote)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); void (*header)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *attr, int level, const hoedown_renderer_data *data); void (*hrule)(hoedown_buffer *ob, const hoedown_renderer_data *data); void (*list)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, hoedown_list_flags flags, const hoedown_renderer_data *data); void (*listitem)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, hoedown_list_flags *flags, const hoedown_renderer_data *data); void (*paragraph)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, const hoedown_renderer_data *data); void (*table)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, const hoedown_renderer_data *data); void (*table_header)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); void (*table_body)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); void (*table_row)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); void (*table_cell)(hoedown_buffer *ob, const hoedown_buffer *content, hoedown_table_flags flags, const hoedown_renderer_data *data); void (*footnotes)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); void (*footnote_def)(hoedown_buffer *ob, const hoedown_buffer *content, unsigned int num, const hoedown_renderer_data *data); void (*blockhtml)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data); /* span level callbacks - NULL or return 0 prints the span verbatim */ int (*autolink)(hoedown_buffer *ob, const hoedown_buffer *link, hoedown_autolink_type type, const hoedown_renderer_data *data); int (*codespan)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *attr, const hoedown_renderer_data *data); int (*double_emphasis)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*emphasis)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*underline)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*highlight)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*quote)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*image)(hoedown_buffer *ob, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *alt, const hoedown_buffer *attr, const hoedown_renderer_data *data); int (*linebreak)(hoedown_buffer *ob, const hoedown_renderer_data *data); int (*link)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *attr, const hoedown_renderer_data *data); int (*triple_emphasis)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*strikethrough)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*superscript)(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data); int (*footnote_ref)(hoedown_buffer *ob, unsigned int num, const hoedown_renderer_data *data); int (*math)(hoedown_buffer *ob, const hoedown_buffer *text, int displaymode, const hoedown_renderer_data *data); int (*raw_html)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data); /* low level callbacks - NULL copies input directly into the output */ void (*entity)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data); void (*normal_text)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data); /* miscellaneous callbacks */ void (*doc_header)(hoedown_buffer *ob, int inline_render, const hoedown_renderer_data *data); void (*doc_footer)(hoedown_buffer *ob, int inline_render, const hoedown_renderer_data *data); /* user block */ void (*user_block)(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data); /* reference callbacks */ /* called when a link reference definition is parsed */ void (*ref)(hoedown_buffer *orig, const hoedown_renderer_data *data); /* called when a footnote reference definition is parsed */ void (*footnote_ref_def)(hoedown_buffer *orig, const hoedown_renderer_data *data); }; typedef struct hoedown_renderer hoedown_renderer; /************* * FUNCTIONS * *************/ typedef size_t (*hoedown_user_block)(uint8_t *context, size_t size, const hoedown_renderer_data *data); /* hoedown_document_new: allocate a new document processor instance */ hoedown_document *hoedown_document_new( const hoedown_renderer *renderer, hoedown_extensions extensions, size_t max_nesting, uint8_t attr_activation, hoedown_user_block user_block, hoedown_buffer *meta ) __attribute__ ((malloc)); /* hoedown_document_render: render regular Markdown using the document processor */ void hoedown_document_render(hoedown_document *doc, hoedown_buffer *ob, const uint8_t *data, size_t size); /* hoedown_document_render_inline: render inline Markdown using the document processor */ void hoedown_document_render_inline(hoedown_document *doc, hoedown_buffer *ob, const uint8_t *data, size_t size); /* hoedown_document_free: deallocate a document processor instance */ void hoedown_document_free(hoedown_document *doc); /* returns a hoedown buffer containing the id of link or footnote reference being processed, or NULL if no link or footnote is being processed */ const hoedown_buffer *hoedown_document_link_id(hoedown_document* document); /* returns a hoedown buffer containing the reference attr of link being * processed, or NULL or empty if none exists */ const hoedown_buffer *hoedown_document_link_ref_attr( hoedown_document *document); /* returns a hoedown buffer containing the inline attr of link being processed, * or NULL or empty if none exists */ const hoedown_buffer *hoedown_document_link_inline_attr( hoedown_document *document); /* returns the id of the footnote definition currently processed, or NULL if not processing a footnote */ const hoedown_buffer *hoedown_document_footnote_id(hoedown_document *document); /* returns 1 if the currently processed buffer in normal text was escaped in the original document */ int hoedown_document_is_escaped(hoedown_document* document); /* returns the header type of the currently processed header, or HOEDOWN_HEADER_NONE if not processing a header */ hoedown_header_type hoedown_document_header_type(hoedown_document* document); /* returns the link type of the currently processed link, or HOEDOWN_LINK_NONE if not processing a link */ hoedown_link_type hoedown_document_link_type(hoedown_document *document); /* returns the list depth of the currently processed element, 1 per level */ int hoedown_document_list_depth(hoedown_document* document); /* returns the blockquote depth of the currently processed element, 1 per level */ int hoedown_document_blockquote_depth(hoedown_document* document); /* returns the character used for the currently processing unordered list (+, *, or -), or 0 if not processing an unordered list */ uint8_t hoedown_document_ul_item_char(hoedown_document* document); /* returns the character used for the currently processing hrule (-, *, or _), or 0 if not processing an hrule */ uint8_t hoedown_document_hrule_char(hoedown_document* document); /* returns the character used for the currently processing fenced code block (` or ~), or 0 if not processing a fenced code block */ uint8_t hoedown_document_fencedcode_char(hoedown_document* document); /* returns the text of the numeral that begins an ordered list item, or NULL if not processing an ordered list item */ const hoedown_buffer* hoedown_document_ol_numeral(hoedown_document* document); #ifdef __cplusplus } #endif #endif /** HOEDOWN_DOCUMENT_H **/ ```
/content/code_sandbox/External/Hoextdown/document.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
3,308
```objective-c /* autolink.h - versatile autolinker */ #ifndef HOEDOWN_AUTOLINK_H #define HOEDOWN_AUTOLINK_H #include "buffer.h" #ifdef __cplusplus extern "C" { #endif /************* * CONSTANTS * *************/ typedef enum hoedown_autolink_flags { HOEDOWN_AUTOLINK_SHORT_DOMAINS = (1 << 0) } hoedown_autolink_flags; /************* * FUNCTIONS * *************/ /* hoedown_autolink_is_safe: verify that a URL has a safe protocol */ int hoedown_autolink_is_safe(const uint8_t *data, size_t size); /* hoedown_autolink__www: search for the next www link in data */ size_t hoedown_autolink__www(size_t *rewind_p, hoedown_buffer *link, uint8_t *data, size_t offset, size_t size, hoedown_autolink_flags flags); /* hoedown_autolink__email: search for the next email in data */ size_t hoedown_autolink__email(size_t *rewind_p, hoedown_buffer *link, uint8_t *data, size_t offset, size_t size, hoedown_autolink_flags flags); /* hoedown_autolink__url: search for the next URL in data */ size_t hoedown_autolink__url(size_t *rewind_p, hoedown_buffer *link, uint8_t *data, size_t offset, size_t size, hoedown_autolink_flags flags); #ifdef __cplusplus } #endif #endif /** HOEDOWN_AUTOLINK_H **/ ```
/content/code_sandbox/External/Hoextdown/autolink.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
350
```objective-c /* buffer.h - simple, fast buffers */ #ifndef HOEDOWN_BUFFER_H #define HOEDOWN_BUFFER_H #include <stdio.h> #include <stddef.h> #include <stdarg.h> #include <stdint.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif #if defined(_MSC_VER) #define __attribute__(x) #define inline __inline #define __builtin_expect(x,n) x #endif /********* * TYPES * *********/ typedef void *(*hoedown_realloc_callback)(void *, size_t); typedef void (*hoedown_free_callback)(void *); struct hoedown_buffer { uint8_t *data; /* actual character data */ size_t size; /* size of the string */ size_t asize; /* allocated size (0 = volatile buffer) */ size_t unit; /* reallocation unit size (0 = read-only buffer) */ hoedown_realloc_callback data_realloc; hoedown_free_callback data_free; hoedown_free_callback buffer_free; }; typedef struct hoedown_buffer hoedown_buffer; /************* * FUNCTIONS * *************/ /* allocation wrappers */ void *hoedown_malloc(size_t size) __attribute__ ((malloc)); void *hoedown_calloc(size_t nmemb, size_t size) __attribute__ ((malloc)); void *hoedown_realloc(void *ptr, size_t size) __attribute__ ((malloc)); /* hoedown_buffer_init: initialize a buffer with custom allocators */ void hoedown_buffer_init( hoedown_buffer *buffer, size_t unit, hoedown_realloc_callback data_realloc, hoedown_free_callback data_free, hoedown_free_callback buffer_free ); /* hoedown_buffer_uninit: uninitialize an existing buffer */ void hoedown_buffer_uninit(hoedown_buffer *buf); /* hoedown_buffer_new: allocate a new buffer */ hoedown_buffer *hoedown_buffer_new(size_t unit) __attribute__ ((malloc)); /* hoedown_buffer_reset: free internal data of the buffer */ void hoedown_buffer_reset(hoedown_buffer *buf); /* hoedown_buffer_grow: increase the allocated size to the given value */ void hoedown_buffer_grow(hoedown_buffer *buf, size_t neosz); /* hoedown_buffer_put: append raw data to a buffer */ void hoedown_buffer_put(hoedown_buffer *buf, const uint8_t *data, size_t size); /* hoedown_buffer_puts: append a NUL-terminated string to a buffer */ void hoedown_buffer_puts(hoedown_buffer *buf, const char *str); /* hoedown_buffer_putc: append a single char to a buffer */ void hoedown_buffer_putc(hoedown_buffer *buf, uint8_t c); /* hoedown_buffer_putf: read from a file and append to a buffer, until EOF or error */ int hoedown_buffer_putf(hoedown_buffer *buf, FILE* file); /* hoedown_buffer_set: replace the buffer's contents with raw data */ void hoedown_buffer_set(hoedown_buffer *buf, const uint8_t *data, size_t size); /* hoedown_buffer_sets: replace the buffer's contents with a NUL-terminated string */ void hoedown_buffer_sets(hoedown_buffer *buf, const char *str); /* hoedown_buffer_eq: compare a buffer's data with other data for equality */ int hoedown_buffer_eq(const hoedown_buffer *buf, const uint8_t *data, size_t size); /* hoedown_buffer_eq: compare a buffer's data with NUL-terminated string for equality */ int hoedown_buffer_eqs(const hoedown_buffer *buf, const char *str); /* hoedown_buffer_prefix: compare the beginning of a buffer with a string */ int hoedown_buffer_prefix(const hoedown_buffer *buf, const char *prefix); /* hoedown_buffer_slurp: remove a given number of bytes from the head of the buffer */ void hoedown_buffer_slurp(hoedown_buffer *buf, size_t size); /* hoedown_buffer_cstr: NUL-termination of the string array (making a C-string) */ const char *hoedown_buffer_cstr(hoedown_buffer *buf); /* hoedown_buffer_printf: formatted printing to a buffer */ void hoedown_buffer_printf(hoedown_buffer *buf, const char *fmt, ...) __attribute__ ((format (printf, 2, 3))); /* hoedown_buffer_put_utf8: put a Unicode character encoded as UTF-8 */ void hoedown_buffer_put_utf8(hoedown_buffer *buf, unsigned int codepoint); /* hoedown_buffer_free: free the buffer */ void hoedown_buffer_free(hoedown_buffer *buf); /* HOEDOWN_BUFPUTSL: optimized hoedown_buffer_puts of a string literal */ #define HOEDOWN_BUFPUTSL(output, literal) \ hoedown_buffer_put(output, (const uint8_t *)literal, sizeof(literal) - 1) /* HOEDOWN_BUFSETSL: optimized hoedown_buffer_sets of a string literal */ #define HOEDOWN_BUFSETSL(output, literal) \ hoedown_buffer_set(output, (const uint8_t *)literal, sizeof(literal) - 1) /* HOEDOWN_BUFEQSL: optimized hoedown_buffer_eqs of a string literal */ #define HOEDOWN_BUFEQSL(output, literal) \ hoedown_buffer_eq(output, (const uint8_t *)literal, sizeof(literal) - 1) #ifdef __cplusplus } #endif #endif /** HOEDOWN_BUFFER_H **/ ```
/content/code_sandbox/External/Hoextdown/buffer.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,218
```objective-c /* stack.h - simple stacking */ #ifndef HOEDOWN_STACK_H #define HOEDOWN_STACK_H #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /********* * TYPES * *********/ struct hoedown_stack { void **item; size_t size; size_t asize; }; typedef struct hoedown_stack hoedown_stack; /************* * FUNCTIONS * *************/ /* hoedown_stack_init: initialize a stack */ void hoedown_stack_init(hoedown_stack *st, size_t initial_size); /* hoedown_stack_uninit: free internal data of the stack */ void hoedown_stack_uninit(hoedown_stack *st); /* hoedown_stack_grow: increase the allocated size to the given value */ void hoedown_stack_grow(hoedown_stack *st, size_t neosz); /* hoedown_stack_push: push an item to the top of the stack */ void hoedown_stack_push(hoedown_stack *st, void *item); /* hoedown_stack_pop: retrieve and remove the item at the top of the stack */ void *hoedown_stack_pop(hoedown_stack *st); /* hoedown_stack_top: retrieve the item at the top of the stack */ void *hoedown_stack_top(const hoedown_stack *st); #ifdef __cplusplus } #endif #endif /** HOEDOWN_STACK_H **/ ```
/content/code_sandbox/External/Hoextdown/stack.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
298
```c #include "buffer.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> void * hoedown_malloc(size_t size) { void *ret = malloc(size); if (!ret) { fprintf(stderr, "Allocation failed.\n"); abort(); } return ret; } void * hoedown_calloc(size_t nmemb, size_t size) { void *ret = calloc(nmemb, size); if (!ret) { fprintf(stderr, "Allocation failed.\n"); abort(); } return ret; } void * hoedown_realloc(void *ptr, size_t size) { void *ret = realloc(ptr, size); if (!ret) { fprintf(stderr, "Allocation failed.\n"); abort(); } return ret; } void hoedown_buffer_init( hoedown_buffer *buf, size_t unit, hoedown_realloc_callback data_realloc, hoedown_free_callback data_free, hoedown_free_callback buffer_free) { assert(buf); buf->data = NULL; buf->size = buf->asize = 0; buf->unit = unit; buf->data_realloc = data_realloc; buf->data_free = data_free; buf->buffer_free = buffer_free; } void hoedown_buffer_uninit(hoedown_buffer *buf) { assert(buf && buf->unit); buf->data_free(buf->data); } hoedown_buffer * hoedown_buffer_new(size_t unit) { hoedown_buffer *ret = hoedown_malloc(sizeof (hoedown_buffer)); hoedown_buffer_init(ret, unit, hoedown_realloc, free, free); return ret; } void hoedown_buffer_free(hoedown_buffer *buf) { if (!buf) return; assert(buf && buf->unit); buf->data_free(buf->data); if (buf->buffer_free) buf->buffer_free(buf); } void hoedown_buffer_reset(hoedown_buffer *buf) { assert(buf && buf->unit); buf->data_free(buf->data); buf->data = NULL; buf->size = buf->asize = 0; } void hoedown_buffer_grow(hoedown_buffer *buf, size_t neosz) { size_t neoasz; assert(buf && buf->unit); if (buf->asize >= neosz) return; neoasz = buf->asize + buf->unit; while (neoasz < neosz) neoasz += buf->unit; buf->data = buf->data_realloc(buf->data, neoasz); buf->asize = neoasz; } void hoedown_buffer_put(hoedown_buffer *buf, const uint8_t *data, size_t size) { assert(buf && buf->unit); if (buf->size + size > buf->asize) hoedown_buffer_grow(buf, buf->size + size); memcpy(buf->data + buf->size, data, size); buf->size += size; } void hoedown_buffer_puts(hoedown_buffer *buf, const char *str) { hoedown_buffer_put(buf, (const uint8_t *)str, strlen(str)); } void hoedown_buffer_putc(hoedown_buffer *buf, uint8_t c) { assert(buf && buf->unit); if (buf->size >= buf->asize) hoedown_buffer_grow(buf, buf->size + 1); buf->data[buf->size] = c; buf->size += 1; } int hoedown_buffer_putf(hoedown_buffer *buf, FILE *file) { assert(buf && buf->unit); while (!(feof(file) || ferror(file))) { hoedown_buffer_grow(buf, buf->size + buf->unit); buf->size += fread(buf->data + buf->size, 1, buf->unit, file); } return ferror(file); } void hoedown_buffer_set(hoedown_buffer *buf, const uint8_t *data, size_t size) { assert(buf && buf->unit); if (size > buf->asize) hoedown_buffer_grow(buf, size); memcpy(buf->data, data, size); buf->size = size; } void hoedown_buffer_sets(hoedown_buffer *buf, const char *str) { hoedown_buffer_set(buf, (const uint8_t *)str, strlen(str)); } int hoedown_buffer_eq(const hoedown_buffer *buf, const uint8_t *data, size_t size) { if (buf->size != size) return 0; return memcmp(buf->data, data, size) == 0; } int hoedown_buffer_eqs(const hoedown_buffer *buf, const char *str) { return hoedown_buffer_eq(buf, (const uint8_t *)str, strlen(str)); } int hoedown_buffer_prefix(const hoedown_buffer *buf, const char *prefix) { size_t i; for (i = 0; i < buf->size; ++i) { if (prefix[i] == 0) return 0; if (buf->data[i] != prefix[i]) return buf->data[i] - prefix[i]; } return 0; } void hoedown_buffer_slurp(hoedown_buffer *buf, size_t size) { assert(buf && buf->unit); if (size >= buf->size) { buf->size = 0; return; } buf->size -= size; memmove(buf->data, buf->data + size, buf->size); } const char * hoedown_buffer_cstr(hoedown_buffer *buf) { assert(buf && buf->unit); if (buf->size < buf->asize && buf->data[buf->size] == 0) return (char *)buf->data; hoedown_buffer_grow(buf, buf->size + 1); buf->data[buf->size] = 0; return (char *)buf->data; } void hoedown_buffer_printf(hoedown_buffer *buf, const char *fmt, ...) { va_list ap; int n; assert(buf && buf->unit); if (buf->size >= buf->asize) hoedown_buffer_grow(buf, buf->size + 1); va_start(ap, fmt); n = vsnprintf((char *)buf->data + buf->size, buf->asize - buf->size, fmt, ap); va_end(ap); if (n < 0) { #ifndef _MSC_VER return; #else va_start(ap, fmt); n = _vscprintf(fmt, ap); va_end(ap); #endif } if ((size_t)n >= buf->asize - buf->size) { hoedown_buffer_grow(buf, buf->size + n + 1); va_start(ap, fmt); n = vsnprintf((char *)buf->data + buf->size, buf->asize - buf->size, fmt, ap); va_end(ap); } if (n < 0) return; buf->size += n; } void hoedown_buffer_put_utf8(hoedown_buffer *buf, unsigned int c) { unsigned char unichar[4]; assert(buf && buf->unit); if (c < 0x80) { hoedown_buffer_putc(buf, c); } else if (c < 0x800) { unichar[0] = 192 + (c / 64); unichar[1] = 128 + (c % 64); hoedown_buffer_put(buf, unichar, 2); } else if (c - 0xd800u < 0x800) { HOEDOWN_BUFPUTSL(buf, "\xef\xbf\xbd"); } else if (c < 0x10000) { unichar[0] = 224 + (c / 4096); unichar[1] = 128 + (c / 64) % 64; unichar[2] = 128 + (c % 64); hoedown_buffer_put(buf, unichar, 3); } else if (c < 0x110000) { unichar[0] = 240 + (c / 262144); unichar[1] = 128 + (c / 4096) % 64; unichar[2] = 128 + (c / 64) % 64; unichar[3] = 128 + (c % 64); hoedown_buffer_put(buf, unichar, 4); } else { HOEDOWN_BUFPUTSL(buf, "\xef\xbf\xbd"); } } ```
/content/code_sandbox/External/Hoextdown/buffer.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
1,944
```c #include "html.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include "escape.h" #include "hash.h" #ifdef _MSC_VER #define strncasecmp _strnicmp #endif #define USE_XHTML(opt) (opt->flags & HOEDOWN_HTML_USE_XHTML) #define USE_TASK_LIST(opt) (opt->flags & HOEDOWN_HTML_USE_TASK_LIST) hoedown_html_tag hoedown_html_is_tag(const uint8_t *data, size_t size, const char *tagname) { size_t i; int closed = 0; if (size < 3 || data[0] != '<') return HOEDOWN_HTML_TAG_NONE; i = 1; if (data[i] == '/') { closed = 1; i++; } for (; i < size; ++i, ++tagname) { if (*tagname == 0) break; if (data[i] != *tagname) return HOEDOWN_HTML_TAG_NONE; } if (i == size) return HOEDOWN_HTML_TAG_NONE; if (isspace(data[i]) || data[i] == '>') return closed ? HOEDOWN_HTML_TAG_CLOSE : HOEDOWN_HTML_TAG_OPEN; return HOEDOWN_HTML_TAG_NONE; } static void escape_html(hoedown_buffer *ob, const uint8_t *source, size_t length) { hoedown_escape_html(ob, source, length, 0); } static void escape_href(hoedown_buffer *ob, const uint8_t *source, size_t length) { hoedown_escape_href(ob, source, length); } /******************** * GENERIC RENDERER * ********************/ static int rndr_attributes(struct hoedown_buffer *ob, const uint8_t *buf, const size_t size, hoedown_buffer *class, const hoedown_renderer_data *data) { /* i keeps track of how much we've parsed so far. */ size_t i = 0; int rendered_id = 0; int must_free_class = 0; while (i < size) { /* An attribute can come in a variety of shapes: * - #id, where "id" is a sequence of non-space characters * - .cls, where "cls" is a sequence of non-space characters * - key=val, where "key" and "val" are sequences of non-space characters * - key="quoted val", where "quoted val" may not contain a quote. * We look for each case and set the key and val variables. We ignore text * that does not match the patterns above (e.g., single words). * */ int is_id = 0; int is_class = 0; size_t key_start = 0, key_end = 0, val_start = 0, val_end = 0; /* Skip to the first non-space character */ for (; i < size && buf[i] == ' '; ++i) {} if (i >= size) break; if (buf[i] == '#') { /* #id */ is_id = 1; ++i; } else if (buf[i] == '.') { /* .cls */ is_class = 1; ++i; } if (is_id || is_class) { val_start = i; for (val_end = val_start; val_end < size && buf[val_end] != ' '; ++val_end) {} i = val_end; } else { /* key=... */ key_start = i; for (key_end = key_start; key_end < size && buf[key_end] != ' ' && buf[key_end] != '='; ++key_end) {} i = key_end; if (i >= size) break; ++i; if (buf[key_end] != '=') continue; if (strncasecmp((char *)buf + key_start, "id", key_end - key_start) == 0) { is_id = 1; } else if (strncasecmp((char *)buf + key_start, "class", key_end - key_start) == 0) { is_class = 1; } val_start = i; if (val_start < size && (buf[val_start] == '"' || buf[val_start] == '\'')) { /* key="quoted val" */ val_start += 1; for (val_end = val_start; val_end < size && buf[val_end] != buf[val_start - 1]; ++val_end) {} i = val_end; if (i >= size) break; ++i; } else { /* key=val */ for (val_end = val_start; val_end < size && buf[val_end] != ' '; ++val_end) {} i = val_end; } } /* Now that we found our keys and values, let's render the attribute. */ if (is_id) { if (rendered_id) continue; if (val_end == val_start) continue; rendered_id = 1; HOEDOWN_BUFPUTSL(ob, " id=\""); escape_html(ob, buf + val_start, val_end - val_start); hoedown_buffer_putc(ob, '"'); } else if (is_class) { if (val_end == val_start) continue; if (!class) { class = hoedown_buffer_new(size); must_free_class = 1; } escape_html(class, buf + val_start, val_end - val_start); hoedown_buffer_putc(class, ' '); } else { if (key_end == key_start) continue; hoedown_buffer_putc(ob, ' '); escape_html(ob, buf + key_start, key_end - key_start); HOEDOWN_BUFPUTSL(ob, "=\""); escape_html(ob, buf + val_start, val_end - val_start); hoedown_buffer_putc(ob, '"'); } } if (class) { if (class->size > 0) { HOEDOWN_BUFPUTSL(ob, " class=\""); hoedown_buffer_put(ob, class->data, class->size-1); hoedown_buffer_putc(ob, '"'); } if (must_free_class) { hoedown_buffer_free(class); } } return 1; } static int rndr_autolink(hoedown_buffer *ob, const hoedown_buffer *link, hoedown_autolink_type type, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (!link || !link->size) return 0; HOEDOWN_BUFPUTSL(ob, "<a href=\""); if (type == HOEDOWN_AUTOLINK_EMAIL) HOEDOWN_BUFPUTSL(ob, "mailto:"); escape_href(ob, link->data, link->size); if (state->link_attributes) { hoedown_buffer_putc(ob, '\"'); state->link_attributes(ob, link, data); hoedown_buffer_putc(ob, '>'); } else { HOEDOWN_BUFPUTSL(ob, "\">"); } /* * Pretty printing: if we get an email address as * an actual URI, e.g. `mailto:foo@bar.com`, we don't * want to print the `mailto:` prefix */ if (hoedown_buffer_prefix(link, "mailto:") == 0) { escape_html(ob, link->data + 7, link->size - 7); } else { escape_html(ob, link->data, link->size); } HOEDOWN_BUFPUTSL(ob, "</a>"); return 1; } static void rndr_blockcode(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *lang, const hoedown_buffer *attr, const hoedown_renderer_data *data) { if (ob->size) hoedown_buffer_putc(ob, '\n'); if (lang) { hoedown_html_renderer_state *state = data->opaque; if ((state->flags & HOEDOWN_HTML_FENCED_CODE_SCRIPT) && lang->size > 7 && memcmp(lang->data, "script@", 7) == 0 && text) { HOEDOWN_BUFPUTSL(ob, "<script type=\""); escape_html(ob, lang->data + 7, lang->size - 7); HOEDOWN_BUFPUTSL(ob, "\">\n"); hoedown_buffer_put(ob, text->data, text->size); HOEDOWN_BUFPUTSL(ob, "</script>\n"); return; } HOEDOWN_BUFPUTSL(ob, "<pre><code"); if (attr && attr->size) { hoedown_buffer *lang_class = hoedown_buffer_new(lang->size + 9); if (lang->size) { HOEDOWN_BUFPUTSL(lang_class, "language-"); escape_html(lang_class, lang->data, lang->size); if (lang_class->data[lang_class->size-1] != ' ') { hoedown_buffer_putc(lang_class, ' '); } } rndr_attributes(ob, attr->data, attr->size, lang_class, data); hoedown_buffer_free(lang_class); } else { HOEDOWN_BUFPUTSL(ob, " class=\"language-"); escape_html(ob, lang->data, lang->size); hoedown_buffer_putc(ob, '"'); } hoedown_buffer_putc(ob, '>'); } else if (attr && attr->size) { HOEDOWN_BUFPUTSL(ob, "<pre><code"); rndr_attributes(ob, attr->data, attr->size, NULL, data); hoedown_buffer_putc(ob, '>'); } else { HOEDOWN_BUFPUTSL(ob, "<pre><code>"); } if (text) escape_html(ob, text->data, text->size); HOEDOWN_BUFPUTSL(ob, "</code></pre>\n"); } static void rndr_blockquote(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (ob->size) hoedown_buffer_putc(ob, '\n'); HOEDOWN_BUFPUTSL(ob, "<blockquote>\n"); if (content) hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</blockquote>\n"); } static int rndr_codespan(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_buffer *attr, const hoedown_renderer_data *data) { HOEDOWN_BUFPUTSL(ob, "<code"); if (attr && attr->size) { rndr_attributes(ob, attr->data, attr->size, NULL, data); } hoedown_buffer_putc(ob, '>'); if (text) escape_html(ob, text->data, text->size); HOEDOWN_BUFPUTSL(ob, "</code>"); return 1; } static int rndr_strikethrough(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<del>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</del>"); return 1; } static int rndr_double_emphasis(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<strong>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</strong>"); return 1; } static int rndr_emphasis(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<em>"); if (content) hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</em>"); return 1; } static int rndr_underline(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<u>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</u>"); return 1; } static int rndr_highlight(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<mark>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</mark>"); return 1; } static int rndr_quote(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<q>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</q>"); return 1; } static int rndr_linebreak(hoedown_buffer *ob, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; hoedown_buffer_puts(ob, USE_XHTML(state) ? "<br/>\n" : "<br>\n"); return 1; } static void rndr_header_id(hoedown_buffer *ob, const uint8_t *source, size_t length, int escape, const hoedown_renderer_data *data) { size_t i = 0, n = 0; hoedown_html_renderer_state *state = data->opaque; hoedown_hash *hash = state->hash.header_id; while (i < length) { if (isalnum(source[i])) { hoedown_buffer_putc(ob, tolower(source[i])); } else if (source[i] == ' ') { hoedown_buffer_putc(ob, '-'); } else if (source[i] == '-' || source[i] == '_') { hoedown_buffer_putc(ob, source[i]); } else if (!isascii(source[i])) { if (escape) { hoedown_buffer_printf(ob, "%%%02X", source[i]); } else { hoedown_buffer_putc(ob, source[i]); } } else if (source[i] == '&') { while (i < length && source[i] != ';') { ++i; } } else if (source[i] == '<') { while (i < length && source[i] != '>') { ++i; } } ++i; } if (hash) { void *value = hoedown_hash_find(hash, (char *)source, length); if (value) { size_t *p = (size_t *)value; ++(*p); n = *p; } if (n > 0) { hoedown_buffer_printf(ob, "-%ld", n); } else if (hash) { size_t *p = (size_t *)malloc(sizeof(size_t)); if (p) { *p = 0; hoedown_hash_add(hash, (char *)source, length, (void *)p, free); } } } } static void rndr_header(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, int level, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (ob->size) hoedown_buffer_putc(ob, '\n'); hoedown_buffer *merged_attr = hoedown_buffer_new(sizeof(hoedown_buffer)); if (attr && attr->size) { hoedown_buffer_put(merged_attr, attr->data, attr->size); } if (content && content->size && ((state->flags & HOEDOWN_HTML_HEADER_ID) || (level <= state->toc_data.nesting_level))) { hoedown_buffer_puts(merged_attr, " #"); rndr_header_id(merged_attr, content->data, content->size, 0, data); } if (merged_attr && merged_attr->size) { hoedown_buffer_printf(ob, "<h%d", level); rndr_attributes(ob, merged_attr->data, merged_attr->size, NULL, data); hoedown_buffer_putc(ob, '>'); } else { hoedown_buffer_printf(ob, "<h%d>", level); } hoedown_buffer_free(merged_attr); if (content) hoedown_buffer_put(ob, content->data, content->size); hoedown_buffer_printf(ob, "</h%d>\n", level); } static int rndr_link(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *attr, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; HOEDOWN_BUFPUTSL(ob, "<a href=\""); if (link && link->size) { escape_href(ob, link->data, link->size); } if (title && title->size) { HOEDOWN_BUFPUTSL(ob, "\" title=\""); escape_html(ob, title->data, title->size); } hoedown_buffer_putc(ob, '"'); if (state->link_attributes) { state->link_attributes(ob, link, data); } if (attr && attr->size) { rndr_attributes(ob, attr->data, attr->size, NULL, data); } hoedown_buffer_putc(ob, '>'); if (content && content->size) hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</a>"); return 1; } static void rndr_list(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, unsigned int flags, const hoedown_renderer_data *data) { if (ob->size) hoedown_buffer_putc(ob, '\n'); if (flags & HOEDOWN_LIST_ORDERED) { HOEDOWN_BUFPUTSL(ob, "<ol"); } else if (flags & HOEDOWN_LIST_DEFINITION) { HOEDOWN_BUFPUTSL(ob, "<dl"); } else { if (flags & HOEDOWN_LI_TASK) { HOEDOWN_BUFPUTSL(ob, "<ul class=\"task-list\""); } else { HOEDOWN_BUFPUTSL(ob, "<ul"); } } if (attr && attr->size) { rndr_attributes(ob, attr->data, attr->size, NULL, data); } HOEDOWN_BUFPUTSL(ob, ">\n"); if (content) hoedown_buffer_put(ob, content->data, content->size); if (flags & HOEDOWN_LIST_ORDERED) { HOEDOWN_BUFPUTSL(ob, "</ol>\n"); } else if (flags & HOEDOWN_LIST_DEFINITION) { HOEDOWN_BUFPUTSL(ob, "</dl>\n"); } else { HOEDOWN_BUFPUTSL(ob, "</ul>\n"); } } static void rndr_listitem(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, hoedown_list_flags *flags, const hoedown_renderer_data *data) { if (content) { hoedown_html_renderer_state *state = data->opaque; size_t prefix = 0; size_t size = content->size; int is_li_tag = 0; while (size && content->data[size - 1] == '\n') size--; if (*flags & HOEDOWN_LI_DD) { HOEDOWN_BUFPUTSL(ob, "<dd"); } else if (*flags & HOEDOWN_LI_DT) { HOEDOWN_BUFPUTSL(ob, "<dt"); } else { HOEDOWN_BUFPUTSL(ob, "<li"); is_li_tag = 1; } if (attr && attr->size) { rndr_attributes(ob, attr->data, attr->size, NULL, data); } hoedown_buffer_putc(ob, '>'); if (USE_TASK_LIST(state) && is_li_tag && size >= 3) { /* Block list items are wrapped in <p> tags. Output the opening tag now, * then check for a task list. */ if (*flags & HOEDOWN_LI_BLOCK) { prefix = 3; hoedown_buffer_put(ob, content->data, prefix); } if (size >= prefix + 3) { if (strncmp((char *)content->data + prefix, "[ ]", 3) == 0) { HOEDOWN_BUFPUTSL(ob, "<input type=\"checkbox\""); hoedown_buffer_puts(ob, USE_XHTML(state) ? "/>" : ">"); prefix += 3; *flags |= HOEDOWN_LI_TASK; } else if (strncasecmp((char *)content->data + prefix, "[x]", 3) == 0) { HOEDOWN_BUFPUTSL(ob, "<input checked=\"\" type=\"checkbox\""); hoedown_buffer_puts(ob, USE_XHTML(state) ? "/>" : ">"); prefix += 3; *flags |= HOEDOWN_LI_TASK; } } } hoedown_buffer_put(ob, content->data+prefix, size-prefix); } else { if (*flags & HOEDOWN_LI_DD) { HOEDOWN_BUFPUTSL(ob, "<dd>"); } else if (*flags & HOEDOWN_LI_DT) { HOEDOWN_BUFPUTSL(ob, "<dt>"); } else { HOEDOWN_BUFPUTSL(ob, "<li>"); } } if (*flags & HOEDOWN_LI_DD) { HOEDOWN_BUFPUTSL(ob, "</dd>\n"); } else if (*flags & HOEDOWN_LI_DT) { HOEDOWN_BUFPUTSL(ob, "</dt>\n"); } else { HOEDOWN_BUFPUTSL(ob, "</li>\n"); } } static void rndr_paragraph(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; size_t i = 0; if (ob->size) hoedown_buffer_putc(ob, '\n'); if (!content || !content->size) return; while (i < content->size && isspace(content->data[i])) i++; if (i == content->size) return; HOEDOWN_BUFPUTSL(ob, "<p"); if (attr && attr->size) { rndr_attributes(ob, attr->data, attr->size, NULL, data); } HOEDOWN_BUFPUTSL(ob, ">"); if (state->flags & HOEDOWN_HTML_HARD_WRAP) { size_t org; while (i < content->size) { org = i; while (i < content->size && content->data[i] != '\n') i++; if (i > org) hoedown_buffer_put(ob, content->data + org, i - org); /* * do not insert a line break if this newline * is the last character on the paragraph */ if (i >= content->size - 1) break; rndr_linebreak(ob, data); i++; } } else if (state->flags & HOEDOWN_HTML_LINE_CONTINUE) { size_t org; while (i < content->size) { org = i; while (i < content->size && content->data[i] != '\n') { ++i; } if (i > org) { hoedown_buffer_put(ob, content->data + org, i - org); } if (i >= content->size - 1) { break; } if (content->data[i] == '\n' && (isascii(content->data[i-1]) || isascii(content->data[i+1]))) { if (i < 5 || strncmp((char *)content->data+i-5, "<br/>", 5) != 0 || strncmp((char *)content->data+i-4, "<br>", 4) != 0) { HOEDOWN_BUFPUTSL(ob, " "); } } ++i; } } else { hoedown_buffer_put(ob, content->data + i, content->size - i); } HOEDOWN_BUFPUTSL(ob, "</p>\n"); } static void rndr_raw_block(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data) { size_t org, sz; if (!text) return; /* FIXME: Do we *really* need to trim the HTML? How does that make a difference? */ sz = text->size; while (sz > 0 && text->data[sz - 1] == '\n') sz--; org = 0; while (org < sz && text->data[org] == '\n') org++; if (org >= sz) return; if (ob->size) hoedown_buffer_putc(ob, '\n'); hoedown_buffer_put(ob, text->data + org, sz - org); hoedown_buffer_putc(ob, '\n'); } static int rndr_triple_emphasis(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<strong><em>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</em></strong>"); return 1; } static void rndr_hrule(hoedown_buffer *ob, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (ob->size) hoedown_buffer_putc(ob, '\n'); hoedown_buffer_puts(ob, USE_XHTML(state) ? "<hr/>\n" : "<hr>\n"); } static int rndr_image(hoedown_buffer *ob, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *alt, const hoedown_buffer *attr, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (!link || !link->size) return 0; HOEDOWN_BUFPUTSL(ob, "<img src=\""); escape_href(ob, link->data, link->size); HOEDOWN_BUFPUTSL(ob, "\" alt=\""); if (alt && alt->size) escape_html(ob, alt->data, alt->size); if (title && title->size) { HOEDOWN_BUFPUTSL(ob, "\" title=\""); escape_html(ob, title->data, title->size); } hoedown_buffer_putc(ob, '"'); if (attr && attr->size) { rndr_attributes(ob, attr->data, attr->size, NULL, data); } hoedown_buffer_puts(ob, USE_XHTML(state) ? "/>" : ">"); return 1; } static int rndr_raw_html(hoedown_buffer *ob, const hoedown_buffer *text, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; /* ESCAPE overrides SKIP_HTML. It doesn't look to see if * there are any valid tags, just escapes all of them. */ if((state->flags & HOEDOWN_HTML_ESCAPE) != 0) { escape_html(ob, text->data, text->size); return 1; } if ((state->flags & HOEDOWN_HTML_SKIP_HTML) != 0) return 1; hoedown_buffer_put(ob, text->data, text->size); return 1; } static void rndr_table(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, const hoedown_renderer_data *data) { if (ob->size) hoedown_buffer_putc(ob, '\n'); HOEDOWN_BUFPUTSL(ob, "<table"); if (attr) rndr_attributes(ob, attr->data, attr->size, NULL, data); HOEDOWN_BUFPUTSL(ob, ">\n"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</table>\n"); } static void rndr_table_header(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (ob->size) hoedown_buffer_putc(ob, '\n'); HOEDOWN_BUFPUTSL(ob, "<thead>\n"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</thead>\n"); } static void rndr_table_body(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (ob->size) hoedown_buffer_putc(ob, '\n'); HOEDOWN_BUFPUTSL(ob, "<tbody>\n"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</tbody>\n"); } static void rndr_tablerow(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { HOEDOWN_BUFPUTSL(ob, "<tr>\n"); if (content) hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</tr>\n"); } static void rndr_tablecell(hoedown_buffer *ob, const hoedown_buffer *content, hoedown_table_flags flags, const hoedown_renderer_data *data) { if (flags & HOEDOWN_TABLE_HEADER) { HOEDOWN_BUFPUTSL(ob, "<th"); } else { HOEDOWN_BUFPUTSL(ob, "<td"); } switch (flags & HOEDOWN_TABLE_ALIGNMASK) { case HOEDOWN_TABLE_ALIGN_CENTER: HOEDOWN_BUFPUTSL(ob, " style=\"text-align: center\">"); break; case HOEDOWN_TABLE_ALIGN_LEFT: HOEDOWN_BUFPUTSL(ob, " style=\"text-align: left\">"); break; case HOEDOWN_TABLE_ALIGN_RIGHT: HOEDOWN_BUFPUTSL(ob, " style=\"text-align: right\">"); break; default: HOEDOWN_BUFPUTSL(ob, ">"); } if (content) hoedown_buffer_put(ob, content->data, content->size); if (flags & HOEDOWN_TABLE_HEADER) { HOEDOWN_BUFPUTSL(ob, "</th>\n"); } else { HOEDOWN_BUFPUTSL(ob, "</td>\n"); } } static int rndr_superscript(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (!content || !content->size) return 0; HOEDOWN_BUFPUTSL(ob, "<sup>"); hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "</sup>"); return 1; } static void rndr_normal_text(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { if (content) escape_html(ob, content->data, content->size); } static void rndr_footnotes(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (ob->size) hoedown_buffer_putc(ob, '\n'); HOEDOWN_BUFPUTSL(ob, "<div class=\"footnotes\">\n"); hoedown_buffer_puts(ob, USE_XHTML(state) ? "<hr/>\n" : "<hr>\n"); HOEDOWN_BUFPUTSL(ob, "<ol>\n"); if (content) hoedown_buffer_put(ob, content->data, content->size); HOEDOWN_BUFPUTSL(ob, "\n</ol>\n</div>\n"); } static void rndr_footnote_def(hoedown_buffer *ob, const hoedown_buffer *content, unsigned int num, const hoedown_renderer_data *data) { size_t i = 0; int pfound = 0; /* insert anchor at the end of first paragraph block */ if (content) { while ((i+3) < content->size) { if (content->data[i++] != '<') continue; if (content->data[i++] != '/') continue; if (content->data[i++] != 'p' && content->data[i] != 'P') continue; if (content->data[i] != '>') continue; i -= 3; pfound = 1; break; } } hoedown_buffer_printf(ob, "\n<li id=\"fn%d\">\n", num); if (pfound) { hoedown_buffer_put(ob, content->data, i); hoedown_buffer_printf(ob, "&nbsp;<a href=\"#fnref%d\" rev=\"footnote\">&#8617;</a>", num); hoedown_buffer_put(ob, content->data + i, content->size - i); } else if (content) { hoedown_buffer_put(ob, content->data, content->size); } HOEDOWN_BUFPUTSL(ob, "</li>\n"); } static int rndr_footnote_ref(hoedown_buffer *ob, unsigned int num, const hoedown_renderer_data *data) { hoedown_buffer_printf(ob, "<sup id=\"fnref%d\"><a href=\"#fn%d\" rel=\"footnote\">%d</a></sup>", num, num, num); return 1; } static int rndr_math(hoedown_buffer *ob, const hoedown_buffer *text, int displaymode, const hoedown_renderer_data *data) { hoedown_buffer_put(ob, (const uint8_t *)(displaymode ? "\\[" : "\\("), 2); escape_html(ob, text->data, text->size); hoedown_buffer_put(ob, (const uint8_t *)(displaymode ? "\\]" : "\\)"), 2); return 1; } static void toc_header(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *attr, int level, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (level <= state->toc_data.nesting_level) { if (level < state->toc_data.level_offset) { state->toc_data.current_level++; return; } if (level > state->toc_data.current_level) { while (level > state->toc_data.current_level) { HOEDOWN_BUFPUTSL(ob, "<ul>\n<li>\n"); state->toc_data.current_level++; } } else if (level < state->toc_data.current_level) { HOEDOWN_BUFPUTSL(ob, "</li>\n"); while (level < state->toc_data.current_level) { HOEDOWN_BUFPUTSL(ob, "</ul>\n</li>\n"); state->toc_data.current_level--; } HOEDOWN_BUFPUTSL(ob,"<li>\n"); } else { HOEDOWN_BUFPUTSL(ob,"</li>\n<li>\n"); } if (attr && attr->size) { size_t n, i = 0; do { i++; } while (i < attr->size && attr->data[i-1] != '#'); if (i < attr->size) { n = i; while (n < attr->size && attr->data[n] != '#' && attr->data[n] != '.' && attr->data[n] != ' ') { n++; } HOEDOWN_BUFPUTSL(ob, "<a href=\"#"); escape_html(ob, attr->data + i, n - i); HOEDOWN_BUFPUTSL(ob, "\">"); } } else { hoedown_buffer_puts(ob, "<a href=\"#"); rndr_header_id(ob, content->data, content->size, 1, data); hoedown_buffer_puts(ob, "\">"); } if (content) { hoedown_buffer_put(ob, content->data, content->size); } HOEDOWN_BUFPUTSL(ob, "</a>\n"); } } static int toc_link(hoedown_buffer *ob, const hoedown_buffer *content, const hoedown_buffer *link, const hoedown_buffer *title, const hoedown_buffer *attr, const hoedown_renderer_data *data) { if (content && content->size) hoedown_buffer_put(ob, content->data, content->size); return 1; } static void toc_initialize(hoedown_buffer *ob, int inline_render, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state = data->opaque; if (state->toc_data.header) { hoedown_buffer_printf(ob, "%s\n", state->toc_data.header); } } static void toc_finalize(hoedown_buffer *ob, int inline_render, const hoedown_renderer_data *data) { hoedown_html_renderer_state *state; if (inline_render) return; state = data->opaque; while (state->toc_data.current_level > 0) { HOEDOWN_BUFPUTSL(ob, "</li>\n</ul>\n"); state->toc_data.current_level--; if (state->toc_data.current_level < state->toc_data.level_offset) { break; } } if (state->toc_data.footer) { hoedown_buffer_printf(ob, "%s\n", state->toc_data.footer); } state->toc_data.header_count = 0; } hoedown_renderer * hoedown_html_toc_renderer_new(int nesting_level) { static const hoedown_renderer cb_default = { NULL, NULL, NULL, toc_header, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, rndr_codespan, rndr_double_emphasis, rndr_emphasis, rndr_underline, rndr_highlight, rndr_quote, NULL, NULL, toc_link, rndr_triple_emphasis, rndr_strikethrough, rndr_superscript, NULL, NULL, NULL, NULL, rndr_normal_text, toc_initialize, toc_finalize, NULL, NULL, NULL, }; hoedown_html_renderer_state *state; hoedown_renderer *renderer; /* Prepare the state pointer */ state = hoedown_malloc(sizeof(hoedown_html_renderer_state)); memset(state, 0x0, sizeof(hoedown_html_renderer_state)); state->toc_data.nesting_level = nesting_level; /* Prepare the renderer */ renderer = hoedown_malloc(sizeof(hoedown_renderer)); memcpy(renderer, &cb_default, sizeof(hoedown_renderer)); state->hash.header_id = hoedown_hash_new(0); renderer->opaque = state; return renderer; } hoedown_renderer * hoedown_html_renderer_new(hoedown_html_flags render_flags, int nesting_level) { static const hoedown_renderer cb_default = { NULL, rndr_blockcode, rndr_blockquote, rndr_header, rndr_hrule, rndr_list, rndr_listitem, rndr_paragraph, rndr_table, rndr_table_header, rndr_table_body, rndr_tablerow, rndr_tablecell, rndr_footnotes, rndr_footnote_def, rndr_raw_block, rndr_autolink, rndr_codespan, rndr_double_emphasis, rndr_emphasis, rndr_underline, rndr_highlight, rndr_quote, rndr_image, rndr_linebreak, rndr_link, rndr_triple_emphasis, rndr_strikethrough, rndr_superscript, rndr_footnote_ref, rndr_math, rndr_raw_html, NULL, rndr_normal_text, NULL, NULL, NULL, NULL, NULL, }; hoedown_html_renderer_state *state; hoedown_renderer *renderer; /* Prepare the state pointer */ state = hoedown_malloc(sizeof(hoedown_html_renderer_state)); memset(state, 0x0, sizeof(hoedown_html_renderer_state)); state->flags = render_flags; state->toc_data.nesting_level = nesting_level; /* Prepare the renderer */ renderer = hoedown_malloc(sizeof(hoedown_renderer)); memcpy(renderer, &cb_default, sizeof(hoedown_renderer)); if (render_flags & HOEDOWN_HTML_SKIP_HTML || render_flags & HOEDOWN_HTML_ESCAPE) renderer->blockhtml = NULL; state->hash.header_id = hoedown_hash_new(0); renderer->opaque = state; return renderer; } void hoedown_html_renderer_free(hoedown_renderer *renderer) { if (renderer->opaque) { hoedown_html_renderer_state *state = renderer->opaque; if (state->hash.header_id) { hoedown_hash_free(state->hash.header_id); } } free(renderer->opaque); free(renderer); } ```
/content/code_sandbox/External/Hoextdown/html.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
9,673
```c #include "html.h" #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #ifdef _MSC_VER #define snprintf _snprintf #endif struct smartypants_data { int in_squote; int in_dquote; }; static size_t smartypants_cb__ltag(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__dquote(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__amp(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__period(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__number(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__dash(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__parens(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__squote(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__backtick(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t smartypants_cb__escape(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size); static size_t (*smartypants_cb_ptrs[]) (hoedown_buffer *, struct smartypants_data *, uint8_t, const uint8_t *, size_t) = { NULL, /* 0 */ smartypants_cb__dash, /* 1 */ smartypants_cb__parens, /* 2 */ smartypants_cb__squote, /* 3 */ smartypants_cb__dquote, /* 4 */ smartypants_cb__amp, /* 5 */ smartypants_cb__period, /* 6 */ smartypants_cb__number, /* 7 */ smartypants_cb__ltag, /* 8 */ smartypants_cb__backtick, /* 9 */ smartypants_cb__escape, /* 10 */ }; static const uint8_t smartypants_cb_chars[UINT8_MAX+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 5, 3, 2, 0, 0, 0, 0, 1, 6, 0, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; static int word_boundary(uint8_t c) { return c == 0 || isspace(c) || ispunct(c); } /* If 'text' begins with any kind of single quote (e.g. "'" or "&apos;" etc.), returns the length of the sequence of characters that makes up the single- quote. Otherwise, returns zero. */ static size_t squote_len(const uint8_t *text, size_t size) { static char* single_quote_list[] = { "'", "&#39;", "&#x27;", "&apos;", NULL }; char** p; for (p = single_quote_list; *p; ++p) { size_t len = strlen(*p); if (size >= len && memcmp(text, *p, len) == 0) { return len; } } return 0; } /* Converts " or ' at very beginning or end of a word to left or right quote */ static int smartypants_quotes(hoedown_buffer *ob, uint8_t previous_char, uint8_t next_char, uint8_t quote, int *is_open) { char ent[8]; if (*is_open && !word_boundary(next_char)) return 0; if (!(*is_open) && !word_boundary(previous_char)) return 0; snprintf(ent, sizeof(ent), "&%c%cquo;", (*is_open) ? 'r' : 'l', quote); *is_open = !(*is_open); hoedown_buffer_puts(ob, ent); return 1; } /* Converts ' to left or right single quote; but the initial ' might be in different forms, e.g. &apos; or &#39; or &#x27;. 'squote_text' points to the original single quote, and 'squote_size' is its length. 'text' points at the last character of the single-quote, e.g. ' or ; */ static size_t smartypants_squote(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size, const uint8_t *squote_text, size_t squote_size) { if (size >= 2) { uint8_t t1 = tolower(text[1]); size_t next_squote_len = squote_len(text+1, size-1); /* convert '' to &ldquo; or &rdquo; */ if (next_squote_len > 0) { uint8_t next_char = (size > 1+next_squote_len) ? text[1+next_squote_len] : 0; if (smartypants_quotes(ob, previous_char, next_char, 'd', &smrt->in_dquote)) return next_squote_len; } /* Tom's, isn't, I'm, I'd */ if ((t1 == 's' || t1 == 't' || t1 == 'm' || t1 == 'd') && (size == 3 || word_boundary(text[2]))) { HOEDOWN_BUFPUTSL(ob, "&rsquo;"); return 0; } /* you're, you'll, you've */ if (size >= 3) { uint8_t t2 = tolower(text[2]); if (((t1 == 'r' && t2 == 'e') || (t1 == 'l' && t2 == 'l') || (t1 == 'v' && t2 == 'e')) && (size == 4 || word_boundary(text[3]))) { HOEDOWN_BUFPUTSL(ob, "&rsquo;"); return 0; } } } if (smartypants_quotes(ob, previous_char, size > 0 ? text[1] : 0, 's', &smrt->in_squote)) return 0; hoedown_buffer_put(ob, squote_text, squote_size); return 0; } /* Converts ' to left or right single quote. */ static size_t smartypants_cb__squote(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { return smartypants_squote(ob, smrt, previous_char, text, size, text, 1); } /* Converts (c), (r), (tm) */ static size_t smartypants_cb__parens(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (size >= 3) { uint8_t t1 = tolower(text[1]); uint8_t t2 = tolower(text[2]); if (t1 == 'c' && t2 == ')') { HOEDOWN_BUFPUTSL(ob, "&copy;"); return 2; } if (t1 == 'r' && t2 == ')') { HOEDOWN_BUFPUTSL(ob, "&reg;"); return 2; } if (size >= 4 && t1 == 't' && t2 == 'm' && text[3] == ')') { HOEDOWN_BUFPUTSL(ob, "&trade;"); return 3; } } hoedown_buffer_putc(ob, text[0]); return 0; } /* Converts "--" to em-dash, etc. */ static size_t smartypants_cb__dash(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (size >= 3 && text[1] == '-' && text[2] == '-') { HOEDOWN_BUFPUTSL(ob, "&mdash;"); return 2; } if (size >= 2 && text[1] == '-') { HOEDOWN_BUFPUTSL(ob, "&ndash;"); return 1; } hoedown_buffer_putc(ob, text[0]); return 0; } /* Converts &quot; etc. */ static size_t smartypants_cb__amp(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { size_t len; if (size >= 6 && memcmp(text, "&quot;", 6) == 0) { if (smartypants_quotes(ob, previous_char, size >= 7 ? text[6] : 0, 'd', &smrt->in_dquote)) return 5; } len = squote_len(text, size); if (len > 0) { return (len-1) + smartypants_squote(ob, smrt, previous_char, text+(len-1), size-(len-1), text, len); } if (size >= 4 && memcmp(text, "&#0;", 4) == 0) return 3; hoedown_buffer_putc(ob, '&'); return 0; } /* Converts "..." to ellipsis */ static size_t smartypants_cb__period(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (size >= 3 && text[1] == '.' && text[2] == '.') { HOEDOWN_BUFPUTSL(ob, "&hellip;"); return 2; } if (size >= 5 && text[1] == ' ' && text[2] == '.' && text[3] == ' ' && text[4] == '.') { HOEDOWN_BUFPUTSL(ob, "&hellip;"); return 4; } hoedown_buffer_putc(ob, text[0]); return 0; } /* Converts `` to opening double quote */ static size_t smartypants_cb__backtick(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (size >= 2 && text[1] == '`') { if (smartypants_quotes(ob, previous_char, size >= 3 ? text[2] : 0, 'd', &smrt->in_dquote)) return 1; } hoedown_buffer_putc(ob, text[0]); return 0; } /* Converts 1/2, 1/4, 3/4 */ static size_t smartypants_cb__number(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (word_boundary(previous_char) && size >= 3) { if (text[0] == '1' && text[1] == '/' && text[2] == '2') { if (size == 3 || word_boundary(text[3])) { HOEDOWN_BUFPUTSL(ob, "&frac12;"); return 2; } } if (text[0] == '1' && text[1] == '/' && text[2] == '4') { if (size == 3 || word_boundary(text[3]) || (size >= 5 && tolower(text[3]) == 't' && tolower(text[4]) == 'h')) { HOEDOWN_BUFPUTSL(ob, "&frac14;"); return 2; } } if (text[0] == '3' && text[1] == '/' && text[2] == '4') { if (size == 3 || word_boundary(text[3]) || (size >= 6 && tolower(text[3]) == 't' && tolower(text[4]) == 'h' && tolower(text[5]) == 's')) { HOEDOWN_BUFPUTSL(ob, "&frac34;"); return 2; } } } hoedown_buffer_putc(ob, text[0]); return 0; } /* Converts " to left or right double quote */ static size_t smartypants_cb__dquote(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (!smartypants_quotes(ob, previous_char, size > 0 ? text[1] : 0, 'd', &smrt->in_dquote)) HOEDOWN_BUFPUTSL(ob, "&quot;"); return 0; } static size_t smartypants_cb__ltag(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { static const char *skip_tags[] = { "pre", "code", "var", "samp", "kbd", "math", "script", "style" }; static const size_t skip_tags_count = 8; size_t tag, i = 0; /* This is a comment. Copy everything verbatim until --> or EOF is seen. */ if (i + 4 < size && memcmp(text + i, "<!--", 4) == 0) { i += 4; while (i + 3 < size && memcmp(text + i, "-->", 3) != 0) i++; i += 3; hoedown_buffer_put(ob, text, i + 1); return i; } while (i < size && text[i] != '>') i++; for (tag = 0; tag < skip_tags_count; ++tag) { if (hoedown_html_is_tag(text, size, skip_tags[tag]) == HOEDOWN_HTML_TAG_OPEN) break; } if (tag < skip_tags_count) { for (;;) { while (i < size && text[i] != '<') i++; if (i == size) break; if (hoedown_html_is_tag(text + i, size - i, skip_tags[tag]) == HOEDOWN_HTML_TAG_CLOSE) break; i++; } while (i < size && text[i] != '>') i++; } hoedown_buffer_put(ob, text, i + 1); return i; } static size_t smartypants_cb__escape(hoedown_buffer *ob, struct smartypants_data *smrt, uint8_t previous_char, const uint8_t *text, size_t size) { if (size < 2) return 0; switch (text[1]) { case '\\': case '"': case '\'': case '.': case '-': case '`': hoedown_buffer_putc(ob, text[1]); return 1; default: hoedown_buffer_putc(ob, '\\'); return 0; } } #if 0 static struct { uint8_t c0; const uint8_t *pattern; const uint8_t *entity; int skip; } smartypants_subs[] = { { '\'', "'s>", "&rsquo;", 0 }, { '\'', "'t>", "&rsquo;", 0 }, { '\'', "'re>", "&rsquo;", 0 }, { '\'', "'ll>", "&rsquo;", 0 }, { '\'', "'ve>", "&rsquo;", 0 }, { '\'', "'m>", "&rsquo;", 0 }, { '\'', "'d>", "&rsquo;", 0 }, { '-', "--", "&mdash;", 1 }, { '-', "<->", "&ndash;", 0 }, { '.', "...", "&hellip;", 2 }, { '.', ". . .", "&hellip;", 4 }, { '(', "(c)", "&copy;", 2 }, { '(', "(r)", "&reg;", 2 }, { '(', "(tm)", "&trade;", 3 }, { '3', "<3/4>", "&frac34;", 2 }, { '3', "<3/4ths>", "&frac34;", 2 }, { '1', "<1/2>", "&frac12;", 2 }, { '1', "<1/4>", "&frac14;", 2 }, { '1', "<1/4th>", "&frac14;", 2 }, { '&', "&#0;", 0, 3 }, }; #endif void hoedown_html_smartypants(hoedown_buffer *ob, const uint8_t *text, size_t size) { size_t i; struct smartypants_data smrt = {0, 0}; if (!text) return; hoedown_buffer_grow(ob, size); for (i = 0; i < size; ++i) { size_t org; uint8_t action = 0; org = i; while (i < size && (action = smartypants_cb_chars[text[i]]) == 0) i++; if (i > org) hoedown_buffer_put(ob, text + org, i - org); if (i < size) { i += smartypants_cb_ptrs[(int)action] (ob, &smrt, i ? text[i - 1] : 0, text + i, size - i); } } } ```
/content/code_sandbox/External/Hoextdown/html_smartypants.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
4,881
```objective-c /* escape.h - escape utilities */ #ifndef HOEDOWN_ESCAPE_H #define HOEDOWN_ESCAPE_H #include "buffer.h" #ifdef __cplusplus extern "C" { #endif /************* * FUNCTIONS * *************/ /* hoedown_escape_href: escape (part of) a URL inside HTML */ void hoedown_escape_href(hoedown_buffer *ob, const uint8_t *data, size_t size); /* hoedown_escape_html: escape HTML */ void hoedown_escape_html(hoedown_buffer *ob, const uint8_t *data, size_t size, int secure); #ifdef __cplusplus } #endif #endif /** HOEDOWN_ESCAPE_H **/ ```
/content/code_sandbox/External/Hoextdown/escape.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
141
```c /* ANSI-C code produced by gperf version 3.0.3 */ /* Command-line: gperf -L ANSI-C -N hoedown_find_block_tag -c -C -E -S 1 --ignore-case -m100 html_block_names.gperf */ /* Computed positions: -k'1-2' */ #if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) /* The character set is not based on ISO-646. */ #error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>." #endif /* maximum key range = 24, duplicates = 0 */ #ifndef GPERF_DOWNCASE #define GPERF_DOWNCASE 1 static unsigned char gperf_downcase[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; #endif #ifndef GPERF_CASE_STRNCMP #define GPERF_CASE_STRNCMP 1 static int gperf_case_strncmp (register const char *s1, register const char *s2, register unsigned int n) { for (; n > 0;) { unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; if (c1 != 0 && c1 == c2) { n--; continue; } return (int)c1 - (int)c2; } return 0; } #endif #ifdef __GNUC__ __inline #else #ifdef __cplusplus inline #endif #endif static unsigned int hash (register const char *str, register unsigned int len) { static const unsigned char asso_values[] = { 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 22, 21, 19, 18, 16, 0, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 1, 25, 0, 25, 1, 0, 0, 13, 0, 25, 25, 11, 2, 1, 0, 25, 25, 5, 0, 2, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 1, 25, 0, 25, 1, 0, 0, 13, 0, 25, 25, 11, 2, 1, 0, 25, 25, 5, 0, 2, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25 }; register int hval = (int)len; switch (hval) { default: hval += asso_values[(unsigned char)str[1]+1]; /*FALLTHROUGH*/ case 1: hval += asso_values[(unsigned char)str[0]]; break; } return hval; } #ifdef __GNUC__ __inline #ifdef __GNUC_STDC_INLINE__ __attribute__ ((__gnu_inline__)) #endif #endif const char * hoedown_find_block_tag (register const char *str, register unsigned int len) { enum { TOTAL_KEYWORDS = 24, MIN_WORD_LENGTH = 1, MAX_WORD_LENGTH = 10, MIN_HASH_VALUE = 1, MAX_HASH_VALUE = 24 }; if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { register int key = hash (str, len); if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE) { register const char *resword; switch (key - 1) { case 0: resword = "p"; goto compare; case 1: resword = "h6"; goto compare; case 2: resword = "div"; goto compare; case 3: resword = "del"; goto compare; case 4: resword = "form"; goto compare; case 5: resword = "table"; goto compare; case 6: resword = "figure"; goto compare; case 7: resword = "pre"; goto compare; case 8: resword = "fieldset"; goto compare; case 9: resword = "noscript"; goto compare; case 10: resword = "script"; goto compare; case 11: resword = "style"; goto compare; case 12: resword = "dl"; goto compare; case 13: resword = "ol"; goto compare; case 14: resword = "ul"; goto compare; case 15: resword = "math"; goto compare; case 16: resword = "ins"; goto compare; case 17: resword = "h5"; goto compare; case 18: resword = "iframe"; goto compare; case 19: resword = "h4"; goto compare; case 20: resword = "h3"; goto compare; case 21: resword = "blockquote"; goto compare; case 22: resword = "h2"; goto compare; case 23: resword = "h1"; goto compare; } return 0; compare: if ((((unsigned char)*str ^ (unsigned char)*resword) & ~32) == 0 && !gperf_case_strncmp (str, resword, len) && resword[len] == '\0') return resword; } } return 0; } ```
/content/code_sandbox/External/Hoextdown/html_blocks.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
3,485
```c #include "version.h" void hoedown_version(int *major, int *minor, int *revision, int *extras) { *major = HOEDOWN_VERSION_MAJOR; *minor = HOEDOWN_VERSION_MINOR; *revision = HOEDOWN_VERSION_REVISION; *extras = HOEDOWN_VERSION_EXTRAS; } ```
/content/code_sandbox/External/Hoextdown/version.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
73
```c /* ANSI-C code produced by gperf version 3.0.4 */ /* Command-line: gperf -L ANSI-C -N hoedown_find_html5_block_tag -c -C -E -S 1 --ignore-case -m100 html5_block_names.gperf */ /* Computed positions: -k'1-2' */ #if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) /* The character set is not based on ISO-646. */ #error "gperf generated tables don't work with this execution character set. Please report a bug to <bug-gnu-gperf@gnu.org>." #endif /* maximum key range = 37, duplicates = 0 */ #ifndef GPERF_DOWNCASE #define GPERF_DOWNCASE 1 static unsigned char gperf_downcase[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; #endif #ifndef GPERF_CASE_STRNCMP #define GPERF_CASE_STRNCMP 1 static int gperf_case_strncmp (register const char *s1, register const char *s2, register unsigned int n) { for (; n > 0;) { unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; if (c1 != 0 && c1 == c2) { n--; continue; } return (int)c1 - (int)c2; } return 0; } #endif #ifdef __GNUC__ __inline #else #ifdef __cplusplus inline #endif #endif static unsigned int hash (register const char *str, register unsigned int len) { static const unsigned char asso_values[] = { 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 26, 25, 24, 23, 22, 21, 38, 38, 38, 38, 38, 38, 38, 38, 38, 17, 14, 9, 10, 38, 2, 16, 8, 6, 1, 38, 38, 0, 13, 18, 0, 38, 38, 1, 4, 1, 13, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 17, 14, 9, 10, 38, 2, 16, 8, 6, 1, 38, 38, 0, 13, 18, 0, 38, 38, 1, 4, 1, 13, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38 }; register int hval = len; switch (hval) { default: hval += asso_values[(unsigned char)str[1]+1]; /*FALLTHROUGH*/ case 1: hval += asso_values[(unsigned char)str[0]]; break; } return hval; } #ifdef __GNUC__ __inline #if defined __GNUC_STDC_INLINE__ || defined __GNUC_GNU_INLINE__ __attribute__ ((__gnu_inline__)) #endif #endif const char * hoedown_find_html5_block_tag (register const char *str, register unsigned int len) { enum { TOTAL_KEYWORDS = 35, MIN_WORD_LENGTH = 1, MAX_WORD_LENGTH = 10, MIN_HASH_VALUE = 1, MAX_HASH_VALUE = 37 }; if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) { register int key = hash (str, len); if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE) { register const char *resword; switch (key - 1) { case 0: resword = "p"; goto compare; case 2: resword = "ul"; goto compare; case 3: resword = "pre"; goto compare; case 5: resword = "form"; goto compare; case 6: resword = "style"; goto compare; case 7: resword = "footer"; goto compare; case 8: resword = "figure"; goto compare; case 9: resword = "section"; goto compare; case 10: resword = "fieldset"; goto compare; case 11: resword = "dl"; goto compare; case 12: resword = "figcaption"; goto compare; case 13: resword = "div"; goto compare; case 14: resword = "del"; goto compare; case 15: resword = "header"; goto compare; case 16: resword = "script"; goto compare; case 17: resword = "math"; goto compare; case 18: resword = "video"; goto compare; case 19: resword = "ol"; goto compare; case 20: resword = "noscript"; goto compare; case 21: resword = "hgroup"; goto compare; case 22: resword = "table"; goto compare; case 23: resword = "blockquote"; goto compare; case 24: resword = "article"; goto compare; case 25: resword = "aside"; goto compare; case 26: resword = "ins"; goto compare; case 27: resword = "iframe"; goto compare; case 28: resword = "canvas"; goto compare; case 29: resword = "nav"; goto compare; case 30: resword = "h6"; goto compare; case 31: resword = "h5"; goto compare; case 32: resword = "h4"; goto compare; case 33: resword = "h3"; goto compare; case 34: resword = "h2"; goto compare; case 35: resword = "h1"; goto compare; case 36: resword = "output"; goto compare; } return 0; compare: if ((((unsigned char)*str ^ (unsigned char)*resword) & ~32) == 0 && !gperf_case_strncmp (str, resword, len) && resword[len] == '\0') return resword; } } return 0; } ```
/content/code_sandbox/External/Hoextdown/html5_blocks.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
3,670
```objective-c /* version.h - holds Hoedown's version */ #ifndef HOEDOWN_VERSION_H #define HOEDOWN_VERSION_H #ifdef __cplusplus extern "C" { #endif /************* * CONSTANTS * *************/ #define HOEDOWN_VERSION "3.0.7.15" #define HOEDOWN_VERSION_MAJOR 3 #define HOEDOWN_VERSION_MINOR 0 #define HOEDOWN_VERSION_REVISION 7 #define HOEDOWN_VERSION_EXTRAS 15 /************* * FUNCTIONS * *************/ /* hoedown_version: retrieve Hoedown's version numbers */ void hoedown_version(int *major, int *minor, int *revision, int *extras); #ifdef __cplusplus } #endif #endif /** HOEDOWN_VERSION_H **/ ```
/content/code_sandbox/External/Hoextdown/version.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
156
```swift import ScreenObject import XCTest public class PasscodeScreen: ScreenObject { public init(app: XCUIApplication = XCUIApplication()) throws { try super.init( expectedElementGetters: [ { $0.staticTexts["1"].firstMatch }, { $0.staticTexts["4"].firstMatch }, { $0.staticTexts["7"].firstMatch }, { $0.staticTexts["0"].firstMatch } ], app: app ) } public func type(passcode: Int) { // This converts an Int into an [Int] of its digits let digits = "\(passcode.magnitude)".compactMap(\.wholeNumberValue) digits.forEach { digit in let input = app.staticTexts["\(digit)"] XCTAssertTrue(input.waitForExistence(timeout: 3)) // Both the custom UIButton and its UILabel match the "\(digit)" query. We need to pick // one for the tap to work. input.firstMatch.tap() } } public static func isLoaded(in app: XCUIApplication = XCUIApplication()) -> Bool { do { let screen = try PasscodeScreen(app: app) return screen.isLoaded } catch { return false } } } ```
/content/code_sandbox/UITestsFoundation/PasscodeScreen.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
266
```swift import XCTest extension XCUIApplication { public func assertLabelExists( withText text: String, timetout: TimeInterval = 5.0, file: StaticString = #file, line: UInt = #line ) { XCTAssertTrue( staticTexts[text].waitForExistence(timeout: timetout), #"Label with text "\#(text)" NOT found"#, file: file, line: line ) } } ```
/content/code_sandbox/UITestsFoundation/XCUIApplication+Assertions.swift
swift
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
101
```objective-c #import <Foundation/Foundation.h> FOUNDATION_EXPORT double UITestsFoundationVersionNumber; FOUNDATION_EXPORT const unsigned char UITestsFoundationVersionString[]; ```
/content/code_sandbox/UITestsFoundation/UITestsFoundation.h
objective-c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
27
```c #include "document.h" #include <assert.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include "stack.h" #ifndef _MSC_VER #include <strings.h> #else #define strncasecmp _strnicmp #endif #define REF_TABLE_SIZE 8 #define BUFFER_BLOCK 0 #define BUFFER_SPAN 1 #define BUFFER_ATTRIBUTE 2 const char *hoedown_find_block_tag(const char *str, unsigned int len); const char *hoedown_find_html5_block_tag(const char *str, unsigned int len); /*************** * LOCAL TYPES * ***************/ /* link_ref: reference to a link */ struct link_ref { unsigned int id; hoedown_buffer *link; hoedown_buffer *title; hoedown_buffer *attr; struct link_ref *next; }; /* footnote_ref: reference to a footnote */ struct footnote_ref { unsigned int id; int is_used; unsigned int num; hoedown_buffer *contents; /* the original string id of the footnote, before conversion to an int */ hoedown_buffer *name; }; /* footnote_item: an item in a footnote_list */ struct footnote_item { struct footnote_ref *ref; struct footnote_item *next; }; /* footnote_list: linked list of footnote_item */ struct footnote_list { unsigned int count; struct footnote_item *head; struct footnote_item *tail; }; /* char_trigger: function pointer to render active chars */ /* returns the number of chars taken care of */ /* data is the pointer of the beginning of the span */ /* offset is the number of valid chars before data */ typedef size_t (*char_trigger)(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_emphasis(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_quote(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_linebreak(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_codespan(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_escape(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_entity(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_langle_tag(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_autolink_url(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_autolink_email(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_autolink_www(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_link(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_image(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_superscript(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); static size_t char_math(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size); enum markdown_char_t { MD_CHAR_NONE = 0, MD_CHAR_EMPHASIS, MD_CHAR_CODESPAN, MD_CHAR_LINEBREAK, MD_CHAR_LINK, MD_CHAR_IMAGE, MD_CHAR_LANGLE, MD_CHAR_ESCAPE, MD_CHAR_ENTITY, MD_CHAR_AUTOLINK_URL, MD_CHAR_AUTOLINK_EMAIL, MD_CHAR_AUTOLINK_WWW, MD_CHAR_SUPERSCRIPT, MD_CHAR_QUOTE, MD_CHAR_MATH }; static char_trigger markdown_char_ptrs[] = { NULL, &char_emphasis, &char_codespan, &char_linebreak, &char_link, &char_image, &char_langle_tag, &char_escape, &char_entity, &char_autolink_url, &char_autolink_email, &char_autolink_www, &char_superscript, &char_quote, &char_math }; struct hoedown_document { hoedown_renderer md; hoedown_renderer_data data; uint8_t attr_activation; struct link_ref *refs[REF_TABLE_SIZE]; struct footnote_list footnotes_found; struct footnote_list footnotes_used; uint8_t active_char[256]; hoedown_stack work_bufs[3]; hoedown_extensions ext_flags; size_t max_nesting; int in_link_body; /* extra information provided to callbacks */ const hoedown_buffer *link_id; const hoedown_buffer *link_inline_attr; const hoedown_buffer *link_ref_attr; int is_escape_char; hoedown_header_type header_type; hoedown_link_type link_type; const hoedown_buffer *footnote_id; int list_depth; int blockquote_depth; uint8_t ul_item_char; uint8_t hrule_char; uint8_t fencedcode_char; const hoedown_buffer *ol_numeral; hoedown_user_block user_block; hoedown_buffer *meta; }; /*************************** * HELPER FUNCTIONS * ***************************/ static hoedown_buffer * newbuf(hoedown_document *doc, int type) { static const size_t buf_size[3] = {256, 64, 64}; hoedown_buffer *work = NULL; hoedown_stack *pool = &doc->work_bufs[type]; if (pool->size < pool->asize && pool->item[pool->size] != NULL) { work = pool->item[pool->size++]; work->size = 0; } else { work = hoedown_buffer_new(buf_size[type]); hoedown_stack_push(pool, work); } return work; } static void popbuf(hoedown_document *doc, int type) { doc->work_bufs[type].size--; } static void unscape_text(hoedown_buffer *ob, hoedown_buffer *src) { size_t i = 0, org; while (i < src->size) { org = i; while (i < src->size && src->data[i] != '\\') i++; if (i > org) hoedown_buffer_put(ob, src->data + org, i - org); if (i + 1 >= src->size) break; hoedown_buffer_putc(ob, src->data[i + 1]); i += 2; } } static unsigned int hash_link_ref(const uint8_t *link_ref, size_t length) { size_t i; unsigned int hash = 0; for (i = 0; i < length; ++i) hash = tolower(link_ref[i]) + (hash << 6) + (hash << 16) - hash; return hash; } static struct link_ref * add_link_ref( struct link_ref **references, const uint8_t *name, size_t name_size) { struct link_ref *ref = hoedown_calloc(1, sizeof(struct link_ref)); ref->id = hash_link_ref(name, name_size); ref->next = references[ref->id % REF_TABLE_SIZE]; references[ref->id % REF_TABLE_SIZE] = ref; return ref; } static struct link_ref * find_link_ref(struct link_ref **references, uint8_t *name, size_t length) { unsigned int hash = hash_link_ref(name, length); struct link_ref *ref = NULL; ref = references[hash % REF_TABLE_SIZE]; while (ref != NULL) { if (ref->id == hash) return ref; ref = ref->next; } return NULL; } static void free_link_refs(struct link_ref **references) { size_t i; for (i = 0; i < REF_TABLE_SIZE; ++i) { struct link_ref *r = references[i]; struct link_ref *next; while (r) { next = r->next; hoedown_buffer_free(r->link); hoedown_buffer_free(r->title); hoedown_buffer_free(r->attr); free(r); r = next; } } } static struct footnote_ref * create_footnote_ref(struct footnote_list *list, const uint8_t *name, size_t name_size) { struct footnote_ref *ref = hoedown_calloc(1, sizeof(struct footnote_ref)); ref->id = hash_link_ref(name, name_size); return ref; } static int add_footnote_ref(struct footnote_list *list, struct footnote_ref *ref) { struct footnote_item *item = hoedown_calloc(1, sizeof(struct footnote_item)); if (!item) return 0; item->ref = ref; if (list->head == NULL) { list->head = list->tail = item; } else { list->tail->next = item; list->tail = item; } list->count++; return 1; } static struct footnote_ref * find_footnote_ref(struct footnote_list *list, uint8_t *name, size_t length) { unsigned int hash = hash_link_ref(name, length); struct footnote_item *item = NULL; item = list->head; while (item != NULL) { if (item->ref->id == hash) return item->ref; item = item->next; } return NULL; } static void free_footnote_ref(struct footnote_ref *ref) { hoedown_buffer_free(ref->contents); hoedown_buffer_free(ref->name); free(ref); } static void free_footnote_list(struct footnote_list *list, int free_refs) { struct footnote_item *item = list->head; struct footnote_item *next; while (item) { next = item->next; if (free_refs) free_footnote_ref(item->ref); free(item); item = next; } } /* * Check whether a char is a Markdown spacing char. * Right now we only consider spaces the actual * space and a newline: tabs and carriage returns * are filtered out during the preprocessing phase. * * If we wanted to actually be UTF-8 compliant, we * should instead extract an Unicode codepoint from * this character and check for space properties. */ static int _isspace(int c) { return c == ' ' || c == '\n'; } /* is_empty_all: verify that all the data is spacing */ static int is_empty_all(const uint8_t *data, size_t size) { size_t i = 0; while (i < size && _isspace(data[i])) i++; return i == size; } /* * Replace all spacing characters in data with spaces. As a special * case, this collapses a newline with the previous space, if possible. */ static void replace_spacing(hoedown_buffer *ob, const uint8_t *data, size_t size) { size_t i = 0, mark; hoedown_buffer_grow(ob, size); while (1) { mark = i; while (i < size && data[i] != '\n') i++; hoedown_buffer_put(ob, data + mark, i - mark); if (i >= size) break; if (!(i > 0 && data[i-1] == ' ')) hoedown_buffer_putc(ob, ' '); i++; } } /**************************** * INLINE PARSING FUNCTIONS * ****************************/ /* is_mail_autolink looks for the address part of a mail autolink and '>' */ /* this is less strict than the original markdown e-mail address matching */ static size_t is_mail_autolink(uint8_t *data, size_t size) { size_t i = 0, nb = 0; /* address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@' */ for (i = 0; i < size; ++i) { if (isalnum(data[i])) continue; switch (data[i]) { case '@': nb++; case '-': case '.': case '_': break; case '>': return (nb == 1) ? i + 1 : 0; default: return 0; } } return 0; } static size_t script_tag_length(uint8_t *data, size_t size) { size_t i = 2; char comment = 0; if (size < 3 || data[0] != '<' || data[1] != '?') { return 0; } i = 2; while (i < size) { if (data[i - 1] == '?' && data[i] == '>' && comment == 0) { break; } if (data[i] == '\'' || data[i] == '"') { if (comment != 0) { if (data[i] == comment && data[i - 1] != '\\') { comment = 0; } } else { comment = data[i]; } } ++i; } if (i >= size) return i; return i + 1; } /* tag_length returns the length of the given tag, or 0 is it's not valid */ static size_t tag_length(uint8_t *data, size_t size, hoedown_autolink_type *autolink, int script_tag) { size_t i, j; /* a valid tag can't be shorter than 3 chars */ if (size < 3) return 0; if (data[0] != '<') return 0; /* HTML comment, laxist form */ if (size > 5 && data[1] == '!' && data[2] == '-' && data[3] == '-') { i = 5; while (i < size && !(data[i - 2] == '-' && data[i - 1] == '-' && data[i] == '>')) i++; i++; if (i <= size) return i; } /* begins with a '<' optionally followed by '/', followed by letter or number */ i = (data[1] == '/') ? 2 : 1; if (!isalnum(data[i])) { if (script_tag) { return script_tag_length(data, size); } return 0; } /* scheme test */ *autolink = HOEDOWN_AUTOLINK_NONE; /* try to find the beginning of an URI */ while (i < size && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-')) i++; if (i > 1 && i < size && data[i] == '@') { if ((j = is_mail_autolink(data + i, size - i)) != 0) { *autolink = HOEDOWN_AUTOLINK_EMAIL; return i + j; } } if (i > 2 && i < size && data[i] == ':') { *autolink = HOEDOWN_AUTOLINK_NORMAL; i++; } /* completing autolink test: no spacing or ' or " */ if (i >= size) *autolink = HOEDOWN_AUTOLINK_NONE; else if (*autolink) { j = i; while (i < size) { if (data[i] == '\\') i += 2; else if (data[i] == '>' || data[i] == '\'' || data[i] == '"' || data[i] == ' ' || data[i] == '\n') break; else i++; } if (i >= size) return 0; if (i > j && data[i] == '>') return i + 1; /* one of the forbidden chars has been found */ *autolink = HOEDOWN_AUTOLINK_NONE; } /* looking for something looking like a tag end */ while (i < size && data[i] != '>') i++; if (i >= size) return 0; return i + 1; } /* parse_inline parses inline markdown elements */ static void parse_inline(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { size_t i = 0, end = 0, consumed = 0; hoedown_buffer work = { 0, 0, 0, 0, NULL, NULL, NULL }; uint8_t *active_char = doc->active_char; if (doc->work_bufs[BUFFER_SPAN].size + doc->work_bufs[BUFFER_BLOCK].size > doc->max_nesting) return; while (i < size) { size_t user_block = 0; while (end < size) { if (doc->user_block) { user_block = doc->user_block(data+end, size - end, &doc->data); if (user_block) { break; } } /* copying inactive chars into the output */ if (active_char[data[end]] != 0) { break; } end++; } if (doc->md.normal_text) { work.data = data + i; work.size = end - i; doc->md.normal_text(ob, &work, &doc->data); } else hoedown_buffer_put(ob, data + i, end - i); if (end >= size) { break; } i = end; if (user_block) { work.data = data + i; work.size = user_block; end = user_block; if (doc->md.user_block) { doc->md.user_block(ob, &work, &doc->data); } else { hoedown_buffer_put(ob, data + i, size - i); } if (!end) { end = i + 1; } else { i += end; end = i; consumed = i; } } else { end = markdown_char_ptrs[ (int)active_char[data[end]] ](ob, doc, data + i, i - consumed, size - i); if (!end) /* no action from the callback */ end = i + 1; else { i += end; end = i; consumed = i; } } } } /* parse_inline_attributes parses inline attributes, returning the end position of the * attributes. attributes must be in the start. differs from parse_attributes in * that parses_attributes assumes attributes are at the end of data.*/ static size_t parse_inline_attributes(uint8_t *data, size_t size, struct hoedown_buffer *attr, uint8_t attr_activation) { size_t attr_start, i = 0; if (size < 1) return 0; if (data[i] == '{' && (!attr_activation || (i + 1 < size && data[i + 1] == attr_activation))) { attr_start = i + 1; /* skip an extra character to skip over the activation character if any */ if (attr_activation) attr_start++; } else { return 0; } while (i < size) { /* ignore escaped characters */ if (data[i] == '\\') { i += 2; } else if (data[i] == '}') { if (attr != NULL) { hoedown_buffer_put(attr, data + attr_start, i - attr_start); } return i + 1; } else { i++; } } return 0; } /* parse_attributes parses special attributes at the end of the data */ static size_t parse_attributes(uint8_t *data, size_t size, struct hoedown_buffer *attr, struct hoedown_buffer *block_attr, const uint8_t *block_id, size_t block_id_size, int is_header, uint8_t attr_activation) { size_t i, len, begin = 0, end = 0; if (size < 1) return 0; i = size; while (i && data[i-1] == '\n') { i--; } len = i; if (i && data[i-1] == '}') { do { i--; } while (i && data[i] != '{'); begin = i + 1; end = len - 1; while (i && data[i-1] == ' ') { i--; } } if (is_header && i && data[i-1] == '#') { while (i && data[i-1] == '#') { i--; } while (i && data[i-1] == ' ') { i--; } } if (begin && end && data[begin-1] == '{' && data[end] == '}') { if (begin >=2 && data[begin-2] == '\\' && data[end-1] == '\\') { return len; } if (block_attr && data[begin] == '@') { /* skip the @ by incrementing past it */ begin++; size_t j = 0; while (begin < end && data[begin] != ' ') { /* if a block_id was fed in, check to make sure the string until the * space is identical */ if (block_id_size != 0 && (j >= block_id_size || block_id[j] != data[begin])) { return len; } begin++; j++; } /* it might have matched only the first portion of block_id; make sure * there's no more to it here */ if (j != block_id_size) { return len; } if (block_attr) { if (block_attr->size) { hoedown_buffer_reset(block_attr); } hoedown_buffer_put(block_attr, data + begin, end - begin); } len = i; if (attr) { len = parse_attributes(data, len, attr, NULL, "", 0, is_header, attr_activation); } } else if (attr && (!attr_activation || attr_activation == data[begin])) { if (attr->size) { hoedown_buffer_reset(attr); } if (attr_activation) { begin++; } hoedown_buffer_put(attr, data + begin, end - begin); len = i; } } return len; } /* is_escaped returns whether special char at data[loc] is escaped by '\\' */ static int is_escaped(uint8_t *data, size_t loc) { size_t i = loc; while (i >= 1 && data[i - 1] == '\\') i--; /* odd numbers of backslashes escapes data[loc] */ return (loc - i) % 2; } /* is_backslashed returns whether special char at data[loc] is preceded by '\\', a stricter interpretation of escaping than is_escaped. */ static int is_backslashed(uint8_t *data, size_t loc) { return loc >= 1 && data[loc - 1] == '\\'; } /* find_emph_char looks for the next emph uint8_t, skipping other constructs */ static size_t find_emph_char(uint8_t *data, size_t size, uint8_t c) { size_t i = 0; while (i < size) { while (i < size && data[i] != c && data[i] != '[' && data[i] != '`') i++; if (i == size) return 0; /* not counting escaped chars */ if (is_escaped(data, i)) { i++; continue; } if (data[i] == c) return i; /* skipping a codespan */ if (data[i] == '`') { size_t span_nb = 0, bt; size_t tmp_i = 0; /* counting the number of opening backticks */ while (i < size && data[i] == '`') { i++; span_nb++; } if (i >= size) return 0; /* finding the matching closing sequence */ bt = 0; while (i < size && bt < span_nb) { if (!tmp_i && data[i] == c) tmp_i = i; if (data[i] == '`') bt++; else bt = 0; i++; } /* not a well-formed codespan; use found matching emph char */ if (bt < span_nb && i >= size) return tmp_i; } /* skipping a link */ else if (data[i] == '[') { size_t tmp_i = 0; uint8_t cc; i++; while (i < size && data[i] != ']') { if (!tmp_i && data[i] == c) tmp_i = i; i++; } i++; while (i < size && _isspace(data[i])) i++; if (i >= size) return tmp_i; switch (data[i]) { case '[': cc = ']'; break; case '(': cc = ')'; break; default: if (tmp_i) return tmp_i; else continue; } i++; while (i < size && data[i] != cc) { if (!tmp_i && data[i] == c) tmp_i = i; i++; } if (i >= size) return tmp_i; i++; } } return 0; } /* find_separator_char looks for the next unbackslashed separator character c */ static size_t find_separator_char(uint8_t *data, size_t size, uint8_t c) { size_t i = 0; while (i < size) { while (i < size && data[i] != c) i++; if (i == size) return 0; /* not counting backslashed separators */ if (is_backslashed(data, i)) { i++; continue; } if (data[i] == c) return i; } return 0; } /* parse_emph1 parsing single emphase */ /* closed by a symbol not preceded by spacing and not followed by symbol */ static size_t parse_emph1(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, uint8_t c) { size_t i = 0, len; hoedown_buffer *work = 0; int r; /* skipping one symbol if coming from emph3 */ if (size > 1 && data[0] == c && data[1] == c) i = 1; while (i < size) { len = find_emph_char(data + i, size - i, c); if (!len) return 0; i += len; if (i >= size) return 0; if (data[i] == c && !_isspace(data[i - 1])) { if (doc->ext_flags & HOEDOWN_EXT_NO_INTRA_EMPHASIS || (doc->ext_flags & HOEDOWN_EXT_NO_INTRA_UNDERLINE_EMPHASIS && c == '_')) { if (i + 1 < size && isalnum(data[i + 1])) continue; } work = newbuf(doc, BUFFER_SPAN); parse_inline(work, doc, data, i); if (doc->ext_flags & HOEDOWN_EXT_UNDERLINE && c == '_') r = doc->md.underline(ob, work, &doc->data); else r = doc->md.emphasis(ob, work, &doc->data); popbuf(doc, BUFFER_SPAN); return r ? i + 1 : 0; } } return 0; } /* parse_emph2 parsing single emphase */ static size_t parse_emph2(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, uint8_t c) { size_t i = 0, len; hoedown_buffer *work = 0; int r; while (i < size) { len = find_emph_char(data + i, size - i, c); if (!len) return 0; i += len; if (i + 1 < size && data[i] == c && data[i + 1] == c && i && !_isspace(data[i - 1])) { work = newbuf(doc, BUFFER_SPAN); parse_inline(work, doc, data, i); if (c == '~') r = doc->md.strikethrough(ob, work, &doc->data); else if (c == '=') r = doc->md.highlight(ob, work, &doc->data); else r = doc->md.double_emphasis(ob, work, &doc->data); popbuf(doc, BUFFER_SPAN); return r ? i + 2 : 0; } i++; } return 0; } /* parse_emph3 parsing single emphase */ /* finds the first closing tag, and delegates to the other emph */ static size_t parse_emph3(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, uint8_t c) { size_t i = 0, len; int r; while (i < size) { len = find_emph_char(data + i, size - i, c); if (!len) return 0; i += len; /* skip spacing preceded symbols */ if (data[i] != c || _isspace(data[i - 1])) continue; if (i + 2 < size && data[i + 1] == c && data[i + 2] == c && doc->md.triple_emphasis) { /* triple symbol found */ hoedown_buffer *work = newbuf(doc, BUFFER_SPAN); parse_inline(work, doc, data, i); r = doc->md.triple_emphasis(ob, work, &doc->data); popbuf(doc, BUFFER_SPAN); return r ? i + 3 : 0; } else if (i + 1 < size && data[i + 1] == c) { /* double symbol found, handing over to emph1 */ len = parse_emph1(ob, doc, data - 2, size + 2, c); if (!len) return 0; else return len - 2; } else { /* single symbol found, handing over to emph2 */ len = parse_emph2(ob, doc, data - 1, size + 1, c); if (!len) return 0; else return len - 1; } } return 0; } /* parse_math parses a math span until the given ending delimiter */ static size_t parse_math(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size, const char *end, size_t delimsz, int displaymode) { hoedown_buffer text = { NULL, 0, 0, 0, NULL, NULL, NULL }; size_t i = delimsz; if (!doc->md.math) return 0; /* find ending delimiter */ while (1) { while (i < size && data[i] != (uint8_t)end[0]) i++; if (i >= size) return 0; if (!is_escaped(data, i) && !(i + delimsz > size) && memcmp(data + i, end, delimsz) == 0) break; i++; } /* prepare buffers */ text.data = data + delimsz; text.size = i - delimsz; /* if this is a $$ and MATH_EXPLICIT is not active, * guess whether displaymode should be enabled from the context */ i += delimsz; if (delimsz == 2 && !(doc->ext_flags & HOEDOWN_EXT_MATH_EXPLICIT)) displaymode = is_empty_all(data - offset, offset) && is_empty_all(data + i, size - i); /* call callback */ if (doc->md.math(ob, &text, displaymode, &doc->data)) return i; return 0; } /* char_emphasis single and double emphasis parsing */ static size_t char_emphasis(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { uint8_t c = data[0]; size_t ret; if (doc->ext_flags & HOEDOWN_EXT_NO_INTRA_EMPHASIS) { if (offset > 0 && !_isspace(data[-1]) && data[-1] != '>' && data[-1] != '(') return 0; } if (size > 2 && data[1] != c) { /* spacing cannot follow an opening emphasis; * strikethrough and highlight only takes two characters '~~' */ if (c == '~' || c == '=' || _isspace(data[1]) || (ret = parse_emph1(ob, doc, data + 1, size - 1, c)) == 0) return 0; return ret + 1; } if (size > 3 && data[1] == c && data[2] != c) { if (_isspace(data[2]) || (ret = parse_emph2(ob, doc, data + 2, size - 2, c)) == 0) return 0; return ret + 2; } if (size > 4 && data[1] == c && data[2] == c && data[3] != c) { if (c == '~' || c == '=' || _isspace(data[3]) || (ret = parse_emph3(ob, doc, data + 3, size - 3, c)) == 0) return 0; return ret + 3; } return 0; } /* char_linebreak '\n' preceded by two spaces (assuming linebreak != 0) */ static size_t char_linebreak(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { if (offset < 2 || data[-1] != ' ' || data[-2] != ' ') return 0; /* removing the last space from ob and rendering */ while (ob->size && ob->data[ob->size - 1] == ' ') ob->size--; return doc->md.linebreak(ob, &doc->data) ? 1 : 0; } /* char_codespan '`' parsing a code span (assuming codespan != 0) */ static size_t char_codespan(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { hoedown_buffer work = { NULL, 0, 0, 0, NULL, NULL, NULL }; size_t end, nb = 0, i, f_begin, f_end; /* counting the number of backticks in the delimiter */ while (nb < size && data[nb] == '`') nb++; /* finding the next delimiter */ i = 0; for (end = nb; end < size && i < nb; end++) { if (data[end] == '`') { if (end + 1 == size || !is_escaped(data, end)) { i++; } else { i = 0; } } else i = 0; } if (i < nb && end >= size) return 0; /* no matching delimiter */ /* trimming outside whitespace */ f_begin = nb; while (f_begin < end && (data[f_begin] == ' ' || data[f_begin] == '\n')) f_begin++; f_end = end - nb; while (f_end > nb && (data[f_end-1] == ' ' || data[f_end-1] == '\n')) f_end--; /* real code span */ if (f_begin < f_end) { /* needed for parse_attribute functions as buffer functions do not work with * buffers made on the stack */ hoedown_buffer *attr = newbuf(doc, BUFFER_ATTRIBUTE); work.data = data + f_begin; work.size = f_end - f_begin; if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { end += parse_inline_attributes(data + end, size - end, attr, doc->attr_activation); } if (!doc->md.codespan(ob, &work, attr, &doc->data)) end = 0; popbuf(doc, BUFFER_ATTRIBUTE); } else { if (!doc->md.codespan(ob, 0, 0, &doc->data)) end = 0; } return end; } /* char_quote '"' parsing a quote */ static size_t char_quote(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { size_t end, nq = 0, i, f_begin, f_end; /* counting the number of quotes in the delimiter */ while (nq < size && data[nq] == '"') nq++; /* finding the next delimiter */ end = nq; while (1) { i = end; end += find_emph_char(data + end, size - end, '"'); if (end == i) return 0; /* no matching delimiter */ i = end; while (end < size && data[end] == '"' && end - i < nq) end++; if (end - i >= nq) break; } /* trimming outside spaces */ f_begin = nq; while (f_begin < end && data[f_begin] == ' ') f_begin++; f_end = end - nq; while (f_end > nq && data[f_end-1] == ' ') f_end--; /* real quote */ if (f_begin < f_end) { hoedown_buffer *work = newbuf(doc, BUFFER_SPAN); parse_inline(work, doc, data + f_begin, f_end - f_begin); if (!doc->md.quote(ob, work, &doc->data)) end = 0; popbuf(doc, BUFFER_SPAN); } else { if (!doc->md.quote(ob, 0, &doc->data)) end = 0; } return end; } /* char_escape '\\' backslash escape */ static size_t char_escape(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { static const char *escape_chars = "\\`*_{}[]()#+-.!:|&<>^~=\"$"; hoedown_buffer work = { 0, 0, 0, 0, NULL, NULL, NULL }; size_t w; if (size > 1) { if (data[1] == '\\' && (doc->ext_flags & HOEDOWN_EXT_MATH) && size > 2 && (data[2] == '(' || data[2] == '[')) { const char *end = (data[2] == '[') ? "\\\\]" : "\\\\)"; w = parse_math(ob, doc, data, offset, size, end, 3, data[2] == '['); if (w) return w; } if (strchr(escape_chars, data[1]) == NULL) return 0; if (doc->md.normal_text) { work.data = data + 1; work.size = 1; doc->is_escape_char = 1; doc->md.normal_text(ob, &work, &doc->data); doc->is_escape_char = 0; } else hoedown_buffer_putc(ob, data[1]); } else if (size == 1) { if (doc->md.normal_text) { work.data = data; work.size = 1; doc->md.normal_text(ob, &work, &doc->data); } else hoedown_buffer_putc(ob, data[0]); } return 2; } /* char_entity '&' escaped when it doesn't belong to an entity */ /* valid entities are assumed to be anything matching &#?[A-Za-z0-9]+; */ static size_t char_entity(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { size_t end = 1; hoedown_buffer work = { 0, 0, 0, 0, NULL, NULL, NULL }; if (end < size && data[end] == '#') end++; while (end < size && isalnum(data[end])) end++; if (end < size && data[end] == ';') end++; /* real entity */ else return 0; /* lone '&' */ if (doc->md.entity) { work.data = data; work.size = end; doc->md.entity(ob, &work, &doc->data); } else hoedown_buffer_put(ob, data, end); return end; } /* char_langle_tag '<' when tags or autolinks are allowed */ static size_t char_langle_tag(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { hoedown_buffer work = { NULL, 0, 0, 0, NULL, NULL, NULL }; hoedown_autolink_type altype = HOEDOWN_AUTOLINK_NONE; size_t end = tag_length(data, size, &altype, doc->ext_flags & HOEDOWN_EXT_SCRIPT_TAGS); int ret = 0; work.data = data; work.size = end; if (end > 2) { if (doc->md.autolink && altype != HOEDOWN_AUTOLINK_NONE) { hoedown_buffer *u_link = newbuf(doc, BUFFER_SPAN); work.data = data + 1; work.size = end - 2; unscape_text(u_link, &work); ret = doc->md.autolink(ob, u_link, altype, &doc->data); popbuf(doc, BUFFER_SPAN); } else if (doc->md.raw_html) ret = doc->md.raw_html(ob, &work, &doc->data); } if (!ret) return 0; else return end; } static size_t char_autolink_www(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { hoedown_buffer *link, *link_url, *link_text; size_t link_len, rewind; if (!doc->md.link || doc->in_link_body) return 0; link = newbuf(doc, BUFFER_SPAN); if ((link_len = hoedown_autolink__www(&rewind, link, data, offset, size, HOEDOWN_AUTOLINK_SHORT_DOMAINS)) > 0) { link_url = newbuf(doc, BUFFER_SPAN); HOEDOWN_BUFPUTSL(link_url, "http://"); hoedown_buffer_put(link_url, link->data, link->size); if (ob->size > rewind) ob->size -= rewind; else ob->size = 0; if (doc->md.normal_text) { link_text = newbuf(doc, BUFFER_SPAN); doc->md.normal_text(link_text, link, &doc->data); doc->md.link(ob, link_text, link_url, NULL, NULL, &doc->data); popbuf(doc, BUFFER_SPAN); } else { doc->md.link(ob, link, link_url, NULL, NULL, &doc->data); } popbuf(doc, BUFFER_SPAN); } popbuf(doc, BUFFER_SPAN); return link_len; } static size_t char_autolink_email(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { hoedown_buffer *link; size_t link_len, rewind; if (!doc->md.autolink || doc->in_link_body) return 0; link = newbuf(doc, BUFFER_SPAN); if ((link_len = hoedown_autolink__email(&rewind, link, data, offset, size, 0)) > 0) { if (ob->size > rewind) ob->size -= rewind; else ob->size = 0; doc->md.autolink(ob, link, HOEDOWN_AUTOLINK_EMAIL, &doc->data); } popbuf(doc, BUFFER_SPAN); return link_len; } static size_t char_autolink_url(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { hoedown_buffer *link; size_t link_len, rewind; if (!doc->md.autolink || doc->in_link_body) return 0; link = newbuf(doc, BUFFER_SPAN); if ((link_len = hoedown_autolink__url(&rewind, link, data, offset, size, 0)) > 0) { if (ob->size > rewind) ob->size -= rewind; else ob->size = 0; doc->md.autolink(ob, link, HOEDOWN_AUTOLINK_NORMAL, &doc->data); } popbuf(doc, BUFFER_SPAN); return link_len; } static size_t char_image(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { size_t ret; if (size < 2 || data[1] != '[') return 0; ret = char_link(ob, doc, data + 1, offset + 1, size - 1); if (!ret) return 0; return ret + 1; } /* char_link '[': parsing a link, a footnote or an image */ static size_t char_link(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { int is_img = (offset && data[-1] == '!' && !is_escaped(data - offset, offset - 1)); int is_footnote = (doc->ext_flags & HOEDOWN_EXT_FOOTNOTES && size > 1 && data[1] == '^'); size_t i = 1, txt_e, link_b = 0, link_e = 0, title_b = 0, title_e = 0; hoedown_buffer *content = NULL; hoedown_buffer *link = NULL; hoedown_buffer *title = NULL; hoedown_buffer *u_link = NULL; hoedown_buffer *inline_attr = NULL; hoedown_buffer *ref_attr = NULL; hoedown_buffer *attr = NULL; hoedown_buffer *id = NULL; size_t org_work_size = doc->work_bufs[BUFFER_SPAN].size; int ret = 0, in_title = 0, qtype = 0; hoedown_link_type link_type = HOEDOWN_LINK_NONE; int ref_attr_exists = 0, inline_attr_exists = 0; /* checking whether the correct renderer exists */ if ((is_footnote && !doc->md.footnote_ref) || (is_img && !doc->md.image) || (!is_img && !is_footnote && !doc->md.link)) goto cleanup; /* looking for the matching closing bracket */ i += find_emph_char(data + i, size - i, ']'); txt_e = i; if (i < size && data[i] == ']') i++; else goto cleanup; /* footnote link */ if (is_footnote) { hoedown_buffer id = { NULL, 0, 0, 0, NULL, NULL, NULL }; struct footnote_ref *fr; if (txt_e < 3) goto cleanup; id.data = data + 2; id.size = txt_e - 2; fr = find_footnote_ref(&doc->footnotes_found, id.data, id.size); /* mark footnote used */ if (fr && !fr->is_used) { if(!add_footnote_ref(&doc->footnotes_used, fr)) goto cleanup; fr->is_used = 1; fr->num = doc->footnotes_used.count; /* render */ if (doc->md.footnote_ref) { doc->link_id = &id; ret = doc->md.footnote_ref(ob, fr->num, &doc->data); doc->link_id = NULL; } } goto cleanup; } /* skip any amount of spacing */ /* (this is much more laxist than original markdown syntax) */ while (i < size && _isspace(data[i])) i++; /* inline style link */ if (i < size && data[i] == '(') { size_t nb_p; link_type = HOEDOWN_LINK_INLINE; /* skipping initial spacing */ i++; while (i < size && _isspace(data[i])) i++; link_b = i; /* looking for link end: ' " ) */ /* Count the number of open parenthesis */ nb_p = 0; while (i < size) { if (data[i] == '\\') i += 2; else if (data[i] == '(' && i != 0) { nb_p++; i++; } else if (data[i] == ')') { if (nb_p == 0) break; else nb_p--; i++; } else if (i >= 1 && _isspace(data[i-1]) && (data[i] == '\'' || data[i] == '"')) break; else i++; } if (i >= size) goto cleanup; link_e = i; /* looking for title end if present */ if (data[i] == '\'' || data[i] == '"') { qtype = data[i]; in_title = 1; i++; title_b = i; while (i < size) { if (data[i] == '\\') i += 2; else if (data[i] == qtype) {in_title = 0; i++;} else if ((data[i] == ')') && !in_title) break; else i++; } if (i >= size) goto cleanup; /* skipping spacing after title */ title_e = i - 1; while (title_e > title_b && _isspace(data[title_e])) title_e--; /* checking for closing quote presence */ if (data[title_e] != '\'' && data[title_e] != '"') { title_b = title_e = 0; link_e = i; } } /* remove spacing at the end of the link */ while (link_e > link_b && _isspace(data[link_e - 1])) link_e--; /* remove optional angle brackets around the link */ if (data[link_b] == '<' && data[link_e - 1] == '>') { link_b++; link_e--; } /* building escaped link and title */ if (link_e > link_b) { link = newbuf(doc, BUFFER_SPAN); hoedown_buffer_put(link, data + link_b, link_e - link_b); } if (title_e > title_b) { title = newbuf(doc, BUFFER_SPAN); hoedown_buffer_put(title, data + title_b, title_e - title_b); } i++; } /* reference style link */ else if (i < size && data[i] == '[') { struct link_ref *lr; id = newbuf(doc, BUFFER_SPAN); /* looking for the id */ i++; link_b = i; while (i < size && data[i] != ']') i++; if (i >= size) goto cleanup; link_e = i; /* finding the link_ref */ if (link_b == link_e) { link_type = HOEDOWN_LINK_EMPTY_REFERENCE; replace_spacing(id, data + 1, txt_e - 1); } else { link_type = HOEDOWN_LINK_REFERENCE; hoedown_buffer_put(id, data + link_b, link_e - link_b); } lr = find_link_ref(doc->refs, id->data, id->size); if (!lr) goto cleanup; /* keeping link and title from link_ref */ link = lr->link; title = lr->title; ref_attr = lr->attr; i++; } /* shortcut reference style link */ else { struct link_ref *lr; id = newbuf(doc, BUFFER_SPAN); link_type = HOEDOWN_LINK_SHORTCUT; /* crafting the id */ replace_spacing(id, data + 1, txt_e - 1); /* finding the link_ref */ lr = find_link_ref(doc->refs, id->data, id->size); if (!lr) goto cleanup; /* keeping link and title from link_ref */ link = lr->link; title = lr->title; ref_attr = lr->attr; /* rewinding the spacing */ i = txt_e + 1; } /* building content: img alt is kept, only link content is parsed */ if (txt_e > 1) { content = newbuf(doc, BUFFER_SPAN); if (is_img) { hoedown_buffer_put(content, data + 1, txt_e - 1); } else { /* disable autolinking when parsing inline the * content of a link */ doc->in_link_body = 1; parse_inline(content, doc, data + 1, txt_e - 1); doc->in_link_body = 0; } } if (link) { u_link = newbuf(doc, BUFFER_SPAN); unscape_text(u_link, link); } /* if special attributes are enabled, attempt to parse an inline one from * the link */ if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { /* attr is a span because cleanup code depends on it being span */ inline_attr = newbuf(doc, BUFFER_SPAN); i += parse_inline_attributes(data + i, size - i, inline_attr, doc->attr_activation); } /* remove optional < and > around inline and ref special attributes */ if (ref_attr && ref_attr->size > 0) { if (ref_attr->size > 1) { if (ref_attr->data[0] == '<') { hoedown_buffer_slurp(ref_attr, 1); } if (ref_attr->data[ref_attr->size - 1] == '>') { ref_attr->size--; } } } if (inline_attr && inline_attr->size > 0) { if (inline_attr->size > 1) { if (inline_attr->data[0] == '<') { hoedown_buffer_slurp(inline_attr, 1); } if (inline_attr->data[inline_attr->size - 1] == '>') { inline_attr->size--; } } } /* construct the final attr that is actually applied to the link */ ref_attr_exists = ref_attr && ref_attr->size > 0; inline_attr_exists = inline_attr && inline_attr->size > 0; if (ref_attr_exists || inline_attr_exists) { attr = newbuf(doc, BUFFER_SPAN); if (ref_attr_exists) { hoedown_buffer_put(attr, ref_attr->data, ref_attr->size); } /* if both inline and ref attrs exist, join them with a space to prevent * conflicts */ if (ref_attr_exists && inline_attr_exists) { hoedown_buffer_putc(attr, ' '); } if (inline_attr_exists) { hoedown_buffer_put(attr, inline_attr->data, inline_attr->size); } } /* calling the relevant rendering function */ doc->link_id = id; doc->link_type = link_type; doc->link_ref_attr = ref_attr; doc->link_inline_attr = inline_attr; if (is_img) { ret = doc->md.image(ob, u_link, title, content, attr, &doc->data); } else { ret = doc->md.link(ob, content, u_link, title, attr, &doc->data); } doc->link_inline_attr = NULL; doc->link_ref_attr = NULL; doc->link_type = HOEDOWN_LINK_NONE; doc->link_id = NULL; /* cleanup */ cleanup: doc->work_bufs[BUFFER_SPAN].size = (int)org_work_size; return ret ? i : 0; } static size_t char_superscript(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { size_t sup_start, sup_len; hoedown_buffer *sup; if (!doc->md.superscript) return 0; if (size < 2) return 0; if (data[1] == '(') { sup_start = 2; sup_len = find_emph_char(data + 2, size - 2, ')') + 2; if (sup_len == size) return 0; } else { sup_start = sup_len = 1; while (sup_len < size && !_isspace(data[sup_len])) sup_len++; } if (sup_len - sup_start == 0) return (sup_start == 2) ? 3 : 0; sup = newbuf(doc, BUFFER_SPAN); parse_inline(sup, doc, data + sup_start, sup_len - sup_start); doc->md.superscript(ob, sup, &doc->data); popbuf(doc, BUFFER_SPAN); return (sup_start == 2) ? sup_len + 1 : sup_len; } static size_t char_math(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t offset, size_t size) { /* double dollar */ if (size > 1 && data[1] == '$') return parse_math(ob, doc, data, offset, size, "$$", 2, 1); /* single dollar allowed only with MATH_EXPLICIT flag */ if (doc->ext_flags & HOEDOWN_EXT_MATH_EXPLICIT) return parse_math(ob, doc, data, offset, size, "$", 1, 0); return 0; } /********************************* * BLOCK-LEVEL PARSING FUNCTIONS * *********************************/ /* is_empty returns the line length when it is empty, 0 otherwise */ static size_t is_empty(const uint8_t *data, size_t size) { size_t i; for (i = 0; i < size && data[i] != '\n'; i++) if (data[i] != ' ') return 0; return i + 1; } /* is_hrule returns whether a line is a horizontal rule */ static int is_hrule(uint8_t *data, size_t size) { size_t i = 0, n = 0; uint8_t c; /* skipping initial spaces */ if (size < 3) return 0; if (data[0] == ' ') { i++; if (data[1] == ' ') { i++; if (data[2] == ' ') { i++; } } } /* looking at the hrule uint8_t */ if (i + 2 >= size || (data[i] != '*' && data[i] != '-' && data[i] != '_')) return 0; c = data[i]; /* the whole line must be the char or space */ while (i < size && data[i] != '\n') { if (data[i] == c) n++; else if (data[i] != ' ') return 0; i++; } return n >= 3; } /* check if a line is a code fence; return the * end of the code fence. if passed, width of * the fence rule and character will be returned */ static size_t is_codefence(uint8_t *data, size_t size, size_t *width, uint8_t *chr) { size_t i = 0, n = 1; uint8_t c; /* skipping initial spaces */ if (size < 3) return 0; if (data[0] == ' ') { i++; if (data[1] == ' ') { i++; if (data[2] == ' ') { i++; } } } /* looking at the hrule uint8_t */ c = data[i]; if (i + 2 >= size || !(c=='~' || c=='`')) return 0; /* the fence must be that same character */ while (++i < size && data[i] == c) ++n; if (n < 3) return 0; if (width) *width = n; if (chr) *chr = c; return i; } /* expects single line, checks if it's a codefence and extracts language */ static int parse_codefence(hoedown_document *doc, uint8_t *data, size_t size, hoedown_buffer *lang, size_t *width, uint8_t *chr, unsigned int flags, hoedown_buffer *attr) { size_t i, w, lang_start, attr_start = 0; i = w = is_codefence(data, size, width, chr); if (i == 0) return 0; while (i < size && _isspace(data[i])) i++; lang_start = i; if (flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { attr_start = i + parse_attributes(data + i, size - i, attr, NULL, "", 0, 0, doc->attr_activation); while (i < attr_start) { if (_isspace(data[i])) { break; } i++; } } else { while (i < size && !_isspace(data[i])) i++; } lang->data = data + lang_start; lang->size = i - lang_start; /* Avoid parsing a codespan as a fence */ i = lang_start + 2; while (i < size && !(data[i] == *chr && data[i-1] == *chr && data[i-2] == *chr)) i++; if (i < size) return 0; return w; } /* is_atxheader returns whether the line is a hash-prefixed header */ static int is_atxheader(hoedown_document *doc, uint8_t *data, size_t size) { size_t level = 0, begin = 0, len; uint8_t *p; if (data[0] != '#') return 0; while (level < size && level < 6 && data[level] == '#') level++; if (level >= size || data[level] == '\n') { return 0; } len = size - level; p = memchr(data + level, '\n', len); if (p) { len = p - (data + level) + 1; } /* if the header is only whitespace, it is not a header */ if (len && is_empty_all(data + level, len)) { return 0; } if ((doc->ext_flags & HOEDOWN_EXT_SPACE_HEADERS) && level < size && data[level] != ' ') { return 0; } /* if the header is only special attribute, it is not a header */ if (len && (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE)) { p = memchr(data + level, '{', len); if (p) { /* get number of characters from # to { */ begin = p - (data + level); if (begin > 0 && !is_empty_all(data + level, begin)) { return 1; } /* check for special attributes after the # */ return !parse_inline_attributes(data + level + begin, len - begin, NULL, doc->attr_activation); } } return 1; } /* is_headerline returns whether the line is a setext-style hdr underline */ static int is_headerline(uint8_t *data, size_t size) { size_t i = 0; /* test of level 1 header */ if (data[i] == '=') { for (i = 1; i < size && data[i] == '='; i++); while (i < size && data[i] == ' ') i++; return (i >= size || data[i] == '\n') ? 1 : 0; } /* test of level 2 header */ if (data[i] == '-') { for (i = 1; i < size && data[i] == '-'; i++); while (i < size && data[i] == ' ') i++; return (i >= size || data[i] == '\n') ? 2 : 0; } return 0; } static int is_next_headerline(uint8_t *data, size_t size) { size_t i = 0; while (i < size && data[i] != '\n') i++; if (++i >= size) return 0; return is_headerline(data + i, size - i); } /* prefix_quote returns blockquote prefix length */ static size_t prefix_quote(uint8_t *data, size_t size) { size_t i = 0; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == '>') { if (i + 1 < size && data[i + 1] == ' ') return i + 2; return i + 1; } return 0; } /* prefix_code returns prefix length for block code*/ static size_t prefix_code(uint8_t *data, size_t size) { if (size > 3 && data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ') return 4; return 0; } /* prefix_oli returns ordered list item prefix */ static size_t prefix_oli(uint8_t *data, size_t size) { size_t i = 0; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i >= size || data[i] < '0' || data[i] > '9') return 0; while (i < size && data[i] >= '0' && data[i] <= '9') i++; if (i + 1 >= size || data[i] != '.' || data[i + 1] != ' ') return 0; if (is_next_headerline(data + i, size - i)) return 0; return i + 2; } /* prefix_uli returns unordered list item prefix */ static size_t prefix_uli(uint8_t *data, size_t size) { size_t i = 0; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i + 1 >= size || (data[i] != '*' && data[i] != '+' && data[i] != '-') || data[i + 1] != ' ') return 0; if (is_next_headerline(data + i, size - i)) return 0; return i + 2; } /* prefix_dt returns dictionary definition prefix * this is in the form of /\s{0,3}:/ (e.g. " :", where spacing is optional) */ static size_t prefix_dt(uint8_t *data, size_t size) { size_t i = 0; /* skip up to 3 whitespaces (since it's an indented codeblock at 4) */ if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; if (i < size && data[i] == ' ') i++; /* if the first character after whitespaces isn't :, it isn't a dt */ if (i + 1 >= size || data[i] != ':' || data[i + 1] != ' ') return 0; if (is_next_headerline(data + i, size - i)) return 0; return i + 2; } /* is_paragraph returns if the next block is a paragraph (doesn't follow any * other special rules for other types of blocks) */ static int is_paragraph(hoedown_document *doc, uint8_t *txt_data, size_t end); /* prefix_dli returns dictionary definition prefix * a dli looks like a block of text, followed by optional whitespace, followed * by another block with : as the first non-whitespace character */ static size_t prefix_dli(hoedown_document *doc, uint8_t *data, size_t size) { /* end is to keep track of the final return value */ size_t i = 0, j = 0, end = 0; int empty = 0; /* if the first line has a : in front of it, it can't be a definition list * that starts at this point */ if (prefix_dt(data, size)) { return 0; } /* temporarily toggle definition lists off to prevent infinite loops */ doc->ext_flags &= ~HOEDOWN_EXT_DEFINITION_LISTS; /* check if it is a block of text with no double newlines inside, followed by * another block of text starting with : */ while (i < size) { /* if the line we are on is empty, flip the empty flag to indicate that * the next block of text we see has to start with : to be considered * a definition list; then skip to the next line */ j = is_empty(data + i, size - i); if(j != 0) { empty = 1; i += j; continue; } /* if anything special is found while parsing the definition term part, * then return so that the main loop can deal with it */ if (!is_paragraph(doc, data + i, size - i)) { break; } /* check if the current line starts with :, returning the position of the * beginning of the line if it does */ j = prefix_dt(data + i, size - i); if (j > 0) { end = i; break; } else if(empty) { /* if an empty newline has been found, then since : was not the first * character after whitespaces, it can't be a definition list */ break; } /* scan characters until the next newline */ for (i = i + 1; i < size && data[i - 1] != '\n'; i++); } doc->ext_flags |= HOEDOWN_EXT_DEFINITION_LISTS; return end; } /* parse_block parsing of one block, returning next uint8_t to parse */ static void parse_block(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size); /* parse_blockquote handles parsing of a blockquote fragment */ static size_t parse_blockquote(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { size_t beg, end = 0, pre, work_size = 0; uint8_t *work_data = 0; hoedown_buffer *out = 0; doc->blockquote_depth++; out = newbuf(doc, BUFFER_BLOCK); beg = 0; while (beg < size) { for (end = beg + 1; end < size && data[end - 1] != '\n'; end++); pre = prefix_quote(data + beg, end - beg); if (pre) beg += pre; /* skipping prefix */ /* empty line finished */ else if ((doc->ext_flags & HOEDOWN_EXT_BLOCKQUOTE_EMPTY_LINE) && (is_empty(data + beg, end - beg))) break; /* empty line followed by non-quote line */ else if (is_empty(data + beg, end - beg) && (end >= size || (prefix_quote(data + end, size - end) == 0 && !is_empty(data + end, size - end)))) break; if (beg < end) { /* copy into the in-place working buffer */ /* hoedown_buffer_put(work, data + beg, end - beg); */ if (!work_data) work_data = data + beg; else if (data + beg != work_data + work_size) memmove(work_data + work_size, data + beg, end - beg); work_size += end - beg; } beg = end; } parse_block(out, doc, work_data, work_size); if (doc->md.blockquote) doc->md.blockquote(ob, out, &doc->data); popbuf(doc, BUFFER_BLOCK); doc->blockquote_depth--; return end; } static size_t parse_htmlblock(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, int do_render); /* parse_paragraph handles parsing of a regular paragraph */ static size_t parse_paragraph(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { hoedown_buffer work = { NULL, 0, 0, 0, NULL, NULL, NULL }; size_t i = 0, end = 0; int level = 0; work.data = data; while (i < size) { for (end = i + 1; end < size && data[end - 1] != '\n'; end++) /* empty */; if (is_empty(data + i, size - i)) break; if ((level = is_headerline(data + i, size - i)) != 0) { if (i == 0) { level = 0; i = end; } break; } if (is_atxheader(doc, data + i, size - i) || is_hrule(data + i, size - i) || prefix_quote(data + i, size - i)) { end = i; break; } i = end; } work.size = i; while (work.size && data[work.size - 1] == '\n') work.size--; if (!level) { hoedown_buffer *attr = newbuf(doc, BUFFER_ATTRIBUTE); if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { parse_attributes(work.data, work.size, NULL, attr, "paragraph", 9, 1, doc->attr_activation); if (attr->size > 0) { /* remove the length of the attribute from the work size - the 12 comes * from the leading space (1), the paragraph (9), the @ symbol (1), and * the {} (2) (any extra spaces in the attribute are included inside * the attribute) */ work.size -= attr->size + 12; } } hoedown_buffer *tmp = newbuf(doc, BUFFER_BLOCK); parse_inline(tmp, doc, work.data, work.size); if (doc->md.paragraph) doc->md.paragraph(ob, tmp, attr, &doc->data); popbuf(doc, BUFFER_BLOCK); popbuf(doc, BUFFER_ATTRIBUTE); } else { hoedown_buffer *header_work; hoedown_buffer *attr_work; size_t len; if (work.size) { size_t beg; i = work.size; work.size -= 1; while (work.size && data[work.size] != '\n') work.size -= 1; beg = work.size + 1; while (work.size && data[work.size - 1] == '\n') work.size -= 1; if (work.size > 0) { hoedown_buffer *tmp = newbuf(doc, BUFFER_BLOCK); parse_inline(tmp, doc, work.data, work.size); if (doc->md.paragraph) doc->md.paragraph(ob, tmp, NULL, &doc->data); popbuf(doc, BUFFER_BLOCK); work.data += beg; work.size = i - beg; } else work.size = i; } header_work = newbuf(doc, BUFFER_SPAN); attr_work = newbuf(doc, BUFFER_ATTRIBUTE); len = work.size; if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { len = parse_attributes(work.data, work.size, attr_work, NULL, "", 0, 1, doc->attr_activation); } parse_inline(header_work, doc, work.data, len); if (doc->md.header) { doc->header_type = HOEDOWN_HEADER_SETEXT; doc->md.header(ob, header_work, attr_work, (int)level, &doc->data); doc->header_type = HOEDOWN_HEADER_NONE; } popbuf(doc, BUFFER_SPAN); popbuf(doc, BUFFER_ATTRIBUTE); } return end; } /* parse_fencedcode handles parsing of a block-level code fragment */ static size_t parse_fencedcode(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, unsigned int flags) { hoedown_buffer text = { 0, 0, 0, 0, NULL, NULL, NULL }; hoedown_buffer lang = { 0, 0, 0, 0, NULL, NULL, NULL }; size_t i = 0, text_start, line_start; size_t w, w2; size_t width, width2; uint8_t chr, chr2; /* needed for parse_attribute functions as buffer functions do not work with * buffers on the stack */ hoedown_buffer *attr = newbuf(doc, BUFFER_ATTRIBUTE); /* parse codefence line */ while (i < size && data[i] != '\n') i++; w = parse_codefence(doc, data, i, &lang, &width, &chr, flags, attr); if (!w) { popbuf(doc, BUFFER_ATTRIBUTE); return 0; } /* search for end */ i++; text_start = i; while ((line_start = i) < size) { while (i < size && data[i] != '\n') i++; w2 = is_codefence(data + line_start, i - line_start, &width2, &chr2); if (w == w2 && width == width2 && chr == chr2 && is_empty(data + (line_start+w), i - (line_start+w))) break; if (i < size) i++; } text.data = data + text_start; text.size = line_start - text_start; if (doc->md.blockcode) { doc->fencedcode_char = chr; doc->md.blockcode(ob, text.size ? &text : NULL, lang.size ? &lang : NULL, attr->size ? attr : NULL, &doc->data); doc->fencedcode_char = 0; } popbuf(doc, BUFFER_ATTRIBUTE); return i; } static size_t parse_blockcode(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { size_t beg, end, pre; hoedown_buffer *work = 0; hoedown_buffer *attr = 0; work = newbuf(doc, BUFFER_BLOCK); attr = newbuf(doc, BUFFER_ATTRIBUTE); beg = 0; while (beg < size) { for (end = beg + 1; end < size && data[end - 1] != '\n'; end++) {}; pre = prefix_code(data + beg, end - beg); if (pre) beg += pre; /* skipping prefix */ else if (!is_empty(data + beg, end - beg)) /* non-empty non-prefixed line breaks the pre */ break; if (beg < end) { /* verbatim copy to the working buffer, escaping entities */ if (is_empty(data + beg, end - beg)) hoedown_buffer_putc(work, '\n'); else hoedown_buffer_put(work, data + beg, end - beg); } beg = end; } while (work->size && work->data[work->size - 1] == '\n') work->size -= 1; if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { work->size = parse_attributes(work->data, work->size, NULL, attr, "", 0, 0, doc->attr_activation); } hoedown_buffer_putc(work, '\n'); if (doc->md.blockcode) doc->md.blockcode(ob, work, NULL, attr, &doc->data); popbuf(doc, BUFFER_BLOCK); popbuf(doc, BUFFER_ATTRIBUTE); return beg; } /* parse_listitem parsing of a single list item */ /* assuming initial prefix is already removed */ static size_t parse_listitem(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, hoedown_list_flags *flags, hoedown_buffer *attribute) { hoedown_buffer *work = 0, *inter = 0; hoedown_buffer *attr = 0; size_t beg = 0, end, pre, sublist = 0, orgpre = 0, i, len, fence_pre = 0; int in_empty = 0, has_inside_empty = 0, in_fence = 0; uint8_t ul_item_char = '*'; hoedown_buffer *ol_numeral = NULL; /* keeping track of the first indentation prefix */ while (orgpre < 3 && orgpre < size && data[orgpre] == ' ') orgpre++; beg = prefix_uli(data, size); if (beg) ul_item_char = data[beg - 2]; if (!beg) { beg = prefix_oli(data, size); if (beg) { ol_numeral = hoedown_buffer_new(1024); /* -2 to eliminate the trailing ". " */ hoedown_buffer_put(ol_numeral, data, beg - 2); } if (*flags & HOEDOWN_LIST_DEFINITION) { beg = prefix_dt(data, size); if (beg) ul_item_char = data[beg - 2]; } } if (!beg) { if (ol_numeral) hoedown_buffer_free(ol_numeral); return 0; } /* skipping to the beginning of the following line */ end = beg; while (end < size && data[end - 1] != '\n') end++; /* getting working buffers */ work = newbuf(doc, BUFFER_SPAN); inter = newbuf(doc, BUFFER_SPAN); /* calculating the indentation */ i = 0; while (i < 4 && beg + i < end && data[beg + i] == ' ') i++; beg += i; /* putting the first line into the working buffer */ hoedown_buffer_put(work, data + beg, end - beg); beg = end; attr = newbuf(doc, BUFFER_ATTRIBUTE); /* process the following lines */ while (beg < size) { size_t has_next_uli = 0, has_next_oli = 0, has_next_dli = 0; end++; while (end < size && data[end - 1] != '\n') end++; /* process an empty line */ if (is_empty(data + beg, end - beg)) { in_empty = 1; beg = end; continue; } /* calculating the indentation */ i = 0; while (i < 4 && beg + i < end && data[beg + i] == ' ') i++; if (in_fence && i > fence_pre) { i = fence_pre; } pre = i; if (doc->ext_flags & HOEDOWN_EXT_FENCED_CODE) { if (is_codefence(data + beg + i, end - beg - i, NULL, NULL)) in_fence = !in_fence; if (in_fence && fence_pre == 0) { fence_pre = pre; } } /* Only check for new list items if we are **not** inside * a fenced code block */ if (!in_fence) { has_next_uli = prefix_uli(data + beg + i, end - beg - i); has_next_oli = prefix_oli(data + beg + i, end - beg - i); /* only check for the next definition if it is same indentation or less * since embedded definition lists need terms, so finding just a * colon by itself does not mean anything */ if (pre <= orgpre) has_next_dli = prefix_dt(data + beg + i, end - beg - i); } /* checking for a new item */ if ((has_next_uli && !is_hrule(data + beg + i, end - beg - i)) || has_next_oli || (*flags & HOEDOWN_LI_DD && has_next_dli)) { if (in_empty) has_inside_empty = 1; /* the following item must have the same (or less) indentation */ if (pre <= orgpre) { /* if the following item has different list type, we end this list */ if (in_empty && ( ((*flags & HOEDOWN_LIST_ORDERED) && has_next_uli) || (!(*flags & HOEDOWN_LIST_ORDERED) && has_next_oli))) { *flags |= HOEDOWN_LI_END; has_inside_empty = 0; } break; } if (!sublist) sublist = work->size; } /* joining only indented stuff after empty lines; * note that now we only require 1 space of indentation * to continue a list */ else if (in_empty && pre == 0) { *flags |= HOEDOWN_LI_END; break; } if (in_empty) { hoedown_buffer_putc(work, '\n'); has_inside_empty = 1; in_empty = 0; } /* adding the line without prefix into the working buffer */ hoedown_buffer_put(work, data + beg + i, end - beg - i); beg = end; } /* render of li contents */ if (has_inside_empty) *flags |= HOEDOWN_LI_BLOCK; if (*flags & HOEDOWN_LI_BLOCK) { /* intermediate render of block li */ pre = 0; if (sublist && sublist < work->size) { end = sublist; } else { end = work->size; } do { if (!(doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE)) { break; } i = 0; while (i < end && work->data[i] != '\n') { i++; } len = parse_attributes(work->data, i, attr, attribute, "list", 4, 0, doc->attr_activation); if (i == len) { break; } pre = i; parse_block(inter, doc, work->data, len); } while (0); parse_block(inter, doc, work->data + pre, end - pre); if (end == sublist) { parse_block(inter, doc, work->data + sublist, work->size - sublist); } } else { /* intermediate render of inline li */ if (sublist && sublist < work->size) { if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { len = parse_attributes(work->data, sublist, attr, attribute, "list", 4, 0, doc->attr_activation); } else { len = sublist; } parse_inline(inter, doc, work->data, len); parse_block(inter, doc, work->data + sublist, work->size - sublist); } else { if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { len = parse_attributes(work->data, work->size, attr, attribute, "list", 4, 0, doc->attr_activation); } else { len = work->size; } parse_inline(inter, doc, work->data, len); } } /* render of li itself */ if (doc->md.listitem) { doc->ul_item_char = ul_item_char; doc->ol_numeral = ol_numeral; doc->md.listitem(ob, inter, attr, flags, &doc->data); doc->ol_numeral = NULL; doc->ul_item_char = 0; } if (ol_numeral) hoedown_buffer_free(ol_numeral); popbuf(doc, BUFFER_SPAN); popbuf(doc, BUFFER_SPAN); popbuf(doc, BUFFER_ATTRIBUTE); return beg; } /* parse_definition parsing of a term/definition pair, assuming starting * at start of line */ static size_t parse_definition(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, hoedown_list_flags *flags, hoedown_buffer *attribute) { /* end represents the position of the first line where definitions start */ size_t j = 0, k = 0, len = 0, end = prefix_dli(doc, data, size); if (end <= 0) { return 0; } hoedown_buffer *work = 0, *attr_work; /* scan all the definition terms, rendering them to the output buffer * the +1 is to account for the trailing newline on each term * j is a counter keeping track of the beginning of each new term */ *flags |= HOEDOWN_LI_DT; while (j + 1 < end) { /* find the end of the term (where the newline is) */ for(k = j + 1; k - 1 < end && data[k - 1] != '\n'; k++); len = k - j; if (is_empty(data + j, len)) { j = k; continue; } work = newbuf(doc, BUFFER_BLOCK); attr_work = newbuf(doc, BUFFER_ATTRIBUTE); if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { len = parse_attributes(data + j, len, attr_work, NULL, "", 0, 1, doc->attr_activation); } parse_inline(work, doc, data + j, len); if (doc->md.listitem) { doc->md.listitem(ob, work, attr_work, flags, &doc->data); } j = k; popbuf(doc, BUFFER_BLOCK); popbuf(doc, BUFFER_ATTRIBUTE); } *flags &= ~HOEDOWN_LI_DT; /* scan all the definitions, rendering it to the output buffer */ *flags |= HOEDOWN_LI_DD; while (end < size) { j = parse_listitem(ob, doc, data + end, size - end, flags, attribute); if (j <= 0) { break; } end += j; } *flags &= ~HOEDOWN_LI_DD; *flags &= ~HOEDOWN_LI_END; return end; } /* parse_list parsing ordered or unordered list block */ static size_t parse_list(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, hoedown_list_flags flags) { hoedown_buffer *work = 0; hoedown_buffer *attr = 0; size_t i = 0, j; doc->list_depth++; work = newbuf(doc, BUFFER_BLOCK); attr = newbuf(doc, BUFFER_ATTRIBUTE); while (i < size) { if (flags & HOEDOWN_LIST_DEFINITION) { j = parse_definition(work, doc, data + i, size - i, &flags, attr); } else { j = parse_listitem(work, doc, data + i, size - i, &flags, attr); } i += j; if (!j || (flags & HOEDOWN_LI_END)) break; } if (doc->md.list) doc->md.list(ob, work, attr, flags, &doc->data); popbuf(doc, BUFFER_BLOCK); popbuf(doc, BUFFER_ATTRIBUTE); doc->list_depth--; return i; } /* parse_atxheader parsing of atx-style headers */ static size_t parse_atxheader(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { size_t level = 0; size_t i, end, skip; while (level < size && level < 6 && data[level] == '#') level++; for (i = level; i < size && data[i] == ' '; i++); for (end = i; end < size && data[end] != '\n'; end++); skip = end; while (end && data[end - 1] == '#') end--; while (end && data[end - 1] == ' ') end--; if (end > i) { hoedown_buffer *work = newbuf(doc, BUFFER_SPAN); hoedown_buffer *attr = newbuf(doc, BUFFER_ATTRIBUTE); size_t len; len = end - i; if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { len = parse_attributes(data + i, end - i, attr, NULL, "", 0, 1, doc->attr_activation); } parse_inline(work, doc, data + i, len); if (doc->md.header) { doc->header_type = HOEDOWN_HEADER_ATX; doc->md.header(ob, work, attr, (int)level, &doc->data); doc->header_type = HOEDOWN_HEADER_NONE; } popbuf(doc, BUFFER_SPAN); popbuf(doc, BUFFER_ATTRIBUTE); } else { doc->md.header(ob, NULL, NULL, (int)level, &doc->data); } return skip; } /* parse_footnote_def parse a single footnote definition */ static void parse_footnote_def(hoedown_buffer *ob, hoedown_document *doc, unsigned int num, const hoedown_buffer *name, uint8_t *data, size_t size) { hoedown_buffer *work = 0; work = newbuf(doc, BUFFER_SPAN); doc->footnote_id = name; parse_block(work, doc, data, size); if (doc->md.footnote_def) doc->md.footnote_def(ob, work, num, &doc->data); doc->footnote_id = NULL; popbuf(doc, BUFFER_SPAN); } /* parse_footnote_list render the contents of the footnotes */ static void parse_footnote_list(hoedown_buffer *ob, hoedown_document *doc, struct footnote_list *footnotes) { hoedown_buffer *work = 0; struct footnote_item *item; struct footnote_ref *ref; if (footnotes->count == 0) return; work = newbuf(doc, BUFFER_BLOCK); item = footnotes->head; while (item) { ref = item->ref; parse_footnote_def(work, doc, ref->num, ref->name, ref->contents->data, ref->contents->size); item = item->next; } if (doc->md.footnotes) doc->md.footnotes(ob, work, &doc->data); popbuf(doc, BUFFER_BLOCK); } /* htmlblock_is_end check for end of HTML block : </tag>( *)\n */ /* returns tag length on match, 0 otherwise */ /* assumes data starts with "<" */ static size_t htmlblock_is_end( const char *tag, size_t tag_len, hoedown_document *doc, uint8_t *data, size_t size) { size_t i = tag_len + 3, w; /* try to match the end tag */ /* note: we're not considering tags like "</tag >" which are still valid */ if (i > size || data[1] != '/' || strncasecmp((char *)data + 2, tag, tag_len) != 0 || data[tag_len + 2] != '>') return 0; /* rest of the line must be empty */ if ((w = is_empty(data + i, size - i)) == 0 && i < size) return 0; return i + w; } /* htmlblock_find_end try to find HTML block ending tag */ /* returns the length on match, 0 otherwise */ static size_t htmlblock_find_end( const char *tag, size_t tag_len, hoedown_document *doc, uint8_t *data, size_t size) { size_t i = 0, w; while (1) { while (i < size && data[i] != '<') i++; if (i >= size) return 0; w = htmlblock_is_end(tag, tag_len, doc, data + i, size - i); if (w) return i + w; i++; } } /* htmlblock_find_end_strict try to find end of HTML block in strict mode */ /* (it must have a blank line or a new HTML tag afterwards) */ /* returns the length on match, 0 otherwise */ static size_t htmlblock_find_end_strict( const char *tag, size_t tag_len, hoedown_document *doc, uint8_t *data, size_t size) { size_t i = 0, mark; while (1) { mark = i; while (i < size && data[i] != '\n') i++; if (i < size) i++; if (i == mark) return 0; mark += htmlblock_find_end(tag, tag_len, doc, data + mark, i - mark); if (mark == i && (is_empty(data + i, size - i) || (i + 1 < size && data[i] == '<' && data[i + 1] != '/') || i >= size)) break; } return i; } /* parse_htmlblock parsing of inline HTML block */ static size_t parse_htmlblock(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, int do_render) { hoedown_buffer work = { NULL, 0, 0, 0, NULL, NULL, NULL }; size_t i, j = 0, tag_len, tag_end; const char *curtag = NULL; int meta = 0; work.data = data; /* identification of the opening tag */ if (size < 2 || data[0] != '<') return 0; i = 1; while (i < size && data[i] != '>' && data[i] != ' ') i++; if (i < size) { if (doc->ext_flags & HOEDOWN_EXT_HTML5_BLOCKS) curtag = hoedown_find_html5_block_tag((char *)data + 1, (int)i - 1); else curtag = hoedown_find_block_tag((char *)data + 1, (int)i - 1); } /* handling of special cases */ if (!curtag) { /* HTML comment, laxist form */ if (size > 5 && data[1] == '!' && data[2] == '-' && data[3] == '-') { i = 5; if (data[4] == '*') { meta++; } while (i < size && !(data[i - 2] == '-' && data[i - 1] == '-' && data[i] == '>')) i++; if (data[i - 3] == '*') { meta++; } i++; if (i < size) j = is_empty(data + i, size - i); if (j) { work.size = i + j; if (do_render && doc->ext_flags & HOEDOWN_EXT_META_BLOCK && meta == 2 && doc->meta) { size_t org, sz; sz = work.size - 5; while (sz > 0 && work.data[sz - 1] == '\n') { sz--; } org = 5; while (org < sz && work.data[org] == '\n') { org++; } if (org < sz) { hoedown_buffer_put(doc->meta, work.data + org, sz - org); hoedown_buffer_putc(doc->meta, '\n'); } } else if (do_render && doc->md.blockhtml) { doc->md.blockhtml(ob, &work, &doc->data); } return work.size; } } /* HR, which is the only self-closing block tag considered */ if (size > 4 && (data[1] == 'h' || data[1] == 'H') && (data[2] == 'r' || data[2] == 'R')) { i = 3; while (i < size && data[i] != '>') i++; if (i + 1 < size) { i++; j = is_empty(data + i, size - i); if (j) { work.size = i + j; if (do_render && doc->md.blockhtml) doc->md.blockhtml(ob, &work, &doc->data); return work.size; } } } /* Extension script tags */ if (doc->ext_flags & HOEDOWN_EXT_SCRIPT_TAGS) { i = script_tag_length(data, size); if (i) { if (i < size) { j = is_empty(data + i, size - i); } if (j) { work.size = i + j; if (do_render && doc->md.blockhtml) { doc->md.blockhtml(ob, &work, &doc->data); } return work.size; } } } /* no special case recognised */ return 0; } /* looking for a matching closing tag in strict mode */ tag_len = strlen(curtag); tag_end = htmlblock_find_end_strict(curtag, tag_len, doc, data, size); /* if not found, trying a second pass looking for indented match */ /* but not if tag is "ins" or "del" (following original Markdown.pl) */ if (!tag_end && strcmp(curtag, "ins") != 0 && strcmp(curtag, "del") != 0) tag_end = htmlblock_find_end(curtag, tag_len, doc, data, size); if (!tag_end) return 0; /* the end of the block has been found */ work.size = tag_end; if (do_render && doc->md.blockhtml) doc->md.blockhtml(ob, &work, &doc->data); return tag_end; } /* Common function to parse table main rows and continued rows. */ static size_t parse_table_cell_line( hoedown_buffer *ob, uint8_t *data, size_t size, size_t offset, char separator, int is_continuation) { size_t pos, line_end, cell_start, cell_end, len, copy_start, copy_end; pos = offset; while (pos < size && _isspace(data[pos])) pos++; cell_start = pos; line_end = pos; while (line_end < size && data[line_end] != '\n') line_end++; len = find_separator_char(data + pos, line_end - pos, separator); /* Two possibilities for len == 0: 1) No more separator char found in the current line. 2) The next separator is right after the current one, i.e. empty cell. For case 1, we skip to the end of line; for case 2 we just continue. */ if (len == 0 && pos < size && data[pos] != separator) { while (pos + len < size && data[pos + len] != '\n') len++; } pos += len; cell_end = pos - 1; while (cell_end > cell_start && _isspace(data[cell_end])) cell_end--; /* If this isn't the first line of the cell, add a new line before the extra cell contents, to separate them (and make backslash linebreaks work). */ if (is_continuation) hoedown_buffer_putc(ob, '\n'); /* Remove escaping from pipes */ copy_start = copy_end = cell_start; while (copy_end < cell_end + 1) { if (data[copy_end] == separator && copy_end > copy_start && data[copy_end - 1] == '\\') { hoedown_buffer_put(ob, data + copy_start, copy_end - copy_start - 1); copy_start = copy_end; } copy_end++; } hoedown_buffer_put(ob, data + copy_start, copy_end - copy_start); return pos - offset; } static void parse_table_row( hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size, size_t columns, size_t rows, hoedown_table_flags *col_data, hoedown_table_flags header_flag) { size_t i = 0, col; hoedown_buffer *row_work = 0; if (!doc->md.table_cell || !doc->md.table_row) return; row_work = newbuf(doc, BUFFER_SPAN); /* skip optional first pipe */ if (i < size && data[i] == '|') i++; for (col = 0; col < columns && i < size; ++col) { size_t pos, extra_rows_in_cell; hoedown_buffer *cell_content; hoedown_buffer *cell_work; /* cell_content is the text that is inline parsed into cell_work. It consists of the values of this cell from each row, concatenated and separated by new lines. */ cell_content = newbuf(doc, BUFFER_SPAN); cell_work = newbuf(doc, BUFFER_SPAN); i += parse_table_cell_line(cell_content, data, size, i, '|', 0 /* is_contination */); /* Add extra rows of the cell. This only occurs if rows is greater than 0, which only happens when multiline tables are enabled. Each extra row is a colon, followed by cell contents for the continued row, separated by colons. */ extra_rows_in_cell = rows - 1; pos = i; while (extra_rows_in_cell > 0 && pos < size) { size_t c; /* seek to the end of the current row */ while (pos < size && data[pos] != '\n') { pos++; } /* skip new line and leading colon */ if (pos < size) pos++; if (pos < size) pos++; /* Seek to the beginning of the correct column on the continuation line. * The continuation line should have the expected number of columns, and * so we never expect pos >= size or data[pos] == '\n'. These checks serve * as defense in depth against wrong preconditions. */ for (c = 0; c < col; c++) { while (pos < size && data[pos] != '\n' && (is_backslashed(data, pos) || data[pos] != ':')) pos++; if (pos < size && data[pos] == ':') pos++; /* skip colon */ } parse_table_cell_line(cell_content, data, size, pos, ':', 1 /* is_contination */); extra_rows_in_cell--; } parse_inline(cell_work, doc, cell_content->data, cell_content->size); doc->md.table_cell(row_work, cell_work, col_data[col] | header_flag, &doc->data); popbuf(doc, BUFFER_SPAN); popbuf(doc, BUFFER_SPAN); i++; } for (; col < columns; ++col) { hoedown_buffer empty_cell = { 0, 0, 0, 0, NULL, NULL, NULL }; doc->md.table_cell(row_work, &empty_cell, col_data[col] | header_flag, &doc->data); } doc->md.table_row(ob, row_work, &doc->data); popbuf(doc, BUFFER_SPAN); } static size_t parse_table_header( hoedown_buffer *ob, hoedown_buffer *attr, hoedown_document *doc, uint8_t *data, size_t size, size_t *columns, hoedown_table_flags **column_data) { int pipes, rows; size_t i = 0, col, header_end, under_end; hoedown_buffer *header_contents = 0; pipes = 0; while (i < size && data[i] != '\n') { if (!is_backslashed(data, i) && data[i] == '|') { pipes++; } i++; } if (i == size || pipes == 0) return 0; header_end = i; while (header_end > 0 && _isspace(data[header_end - 1])) header_end--; if (data[0] == '|') pipes--; if (header_end && data[header_end - 1] == '|' && !is_backslashed(data, header_end - 1)) pipes--; if (doc->ext_flags & HOEDOWN_EXT_SPECIAL_ATTRIBUTE) { size_t n = parse_attributes(data, header_end, attr, NULL, "", 0, 1, doc->attr_activation); /* n == header_end when no attribute is found */ if (n != header_end) { while (n > 0 && _isspace(data[n - 1])) n--; if (attr->size && n && data[n - 1] == '|' && !is_backslashed(data, n - 1)) pipes--; header_end = n + 1; } } if (pipes < 0) return 0; /* header_contents will have the lines of the header copied into it, and then is passed to parse_table_row. We need a separate buffer to avoid passing the attribute to parse_table_row. */ header_contents = newbuf(doc, BUFFER_SPAN); hoedown_buffer_put(header_contents, data, header_end); *columns = pipes + 1; *column_data = hoedown_calloc(*columns, sizeof(hoedown_table_flags)); /* If the multiline table extension is enabled, check the next lines for continuation markers, to find the number of text rows that make up this logical row, and copy the contents of each row to header_contents, separated by new lines. */ rows = 1; if ((doc->ext_flags & HOEDOWN_EXT_MULTILINE_TABLES) != 0) { while (i < size) { size_t j = i + 1; int colons = 0; /* Require that the continuation line starts with a colon */ if (j >= size || data[j] != ':') break; /* Skip the leading colon to match the pipe counting behavior above */ j++; /* Require that the continuation line start with ": ", to distinguish from ":-" which could start a left-aligned header bar. */ if (j >= size || data[j] != ' ') break; while (j < size && data[j] != '\n') { j++; if (j < size && !is_backslashed(data, j) && data[j] == ':') colons++; } /* Allow a trailing colon to match the pipe counting behavior above */ if (!is_backslashed(data, j - 1) && data[j - 1] == ':') colons--; if (colons != pipes) break; hoedown_buffer_putc(header_contents, '\n'); /* data[i] is the previous new line, and data[j] is the next new line. This copies all the text between the new lines. */ hoedown_buffer_put(header_contents, data + i + 1, j - i - 1); rows++; i = j; header_end = j; } } /* Parse the header underline */ i++; if (i < size && data[i] == '|') i++; under_end = i; while (under_end < size && data[under_end] != '\n') under_end++; for (col = 0; col < *columns && i < under_end; ++col) { size_t dashes = 0; while (i < under_end && data[i] == ' ') i++; if (i < under_end && data[i] == ':') { i++; (*column_data)[col] |= HOEDOWN_TABLE_ALIGN_LEFT; dashes++; } while (i < under_end && data[i] == '-') { i++; dashes++; } if (i < under_end && data[i] == ':') { i++; (*column_data)[col] |= HOEDOWN_TABLE_ALIGN_RIGHT; dashes++; } while (i < under_end && data[i] == ' ') i++; if (i < under_end && data[i] != '|' && data[i] != '+') break; if (dashes < 3) break; i++; } if (col < *columns) { /* clean up header_contents */ popbuf(doc, BUFFER_SPAN); return 0; } parse_table_row( ob, doc, header_contents->data, header_contents->size, *columns, rows, *column_data, HOEDOWN_TABLE_HEADER ); /* clean up header_contents */ popbuf(doc, BUFFER_SPAN); return under_end + 1; } static size_t parse_table( hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { size_t i; hoedown_buffer *work = 0; hoedown_buffer *header_work = 0; hoedown_buffer *body_work = 0; hoedown_buffer *attr_work = 0; size_t columns; hoedown_table_flags *col_data = NULL; work = newbuf(doc, BUFFER_BLOCK); header_work = newbuf(doc, BUFFER_SPAN); body_work = newbuf(doc, BUFFER_BLOCK); attr_work = newbuf(doc, BUFFER_ATTRIBUTE); i = parse_table_header(header_work, attr_work, doc, data, size, &columns, &col_data); if (i > 0) { while (i < size) { size_t row_start; int pipes = 0; size_t rows = 1; row_start = i; while (i < size && data[i] != '\n') { if (data[i] == '|' && !is_backslashed(data, i)) pipes++; i++; } if (pipes == 0 || i == size) { i = row_start; break; } /* Don't count a leading pipe. */ if (data[row_start] == '|') pipes--; /* Don't count a trailing pipe. */ if (data[i - 1] == '|' && !is_backslashed(data, i - 1)) pipes--; /* If the multiline table extension is enabled, check the next lines for continuation markers, to find the number of text rows that make up this logical row. */ if ((doc->ext_flags & HOEDOWN_EXT_MULTILINE_TABLES) != 0) { while (i < size) { size_t j = i + 1; int colons = 0; /* Require that a continued row starts with a colon. */ if (j >= size || data[j] != ':') break; /* Don't count leading colon for comparison to pipes. */ j++; while (j < size && data[j] != '\n') { if (!is_backslashed(data, j) && data[j] == ':') colons++; j++; } /* Don't count a trailing colon for comparison to pipes. */ if (!is_backslashed(data, j - 1) && data[j - 1] == ':') colons--; /* Hoedown allows table rows where the number of cells is different * from `columns`. In this case, `parse_table_row` will add empty * cells. However, the code does not work in the multi-line case, so * we require the right number of columns. */ if (colons != pipes || colons != columns - 1) break; rows++; i = j; } } parse_table_row( body_work, doc, data + row_start, i - row_start, columns, rows, col_data, 0 ); i++; /* Skip an optional row separator, if it's there. */ if ((doc->ext_flags & HOEDOWN_EXT_MULTILINE_TABLES) != 0) { /* Use j instead of i, and set i to j only if this is actually a row separator. */ size_t j = i, next_line_end = i, col; /* Seek next_line_end to the position of the terminating new line. */ while (next_line_end < size && data[next_line_end] != '\n') next_line_end++; /* Skip leading pipe, if any. */ if (j < next_line_end && data[j] == '|') j++; /* Ensure that there are at least columns pipe/plus separated runs of dashes, each at least 3 long. The pipes may be padded with spaces, and the line may end in a pipe. */ for (col = 0; col < columns && j < next_line_end; col++) { size_t dashes = 0; while (j < next_line_end && data[j] == ' ') j++; while (j < next_line_end && data[j] == '-') { j++; dashes++; } while (j < next_line_end && data[j] == ' ') j++; if (j < next_line_end && data[j] != '|' && data[j] != '+') break; if (dashes < 3) break; j++; } /* Skip i past the row separator, if it was valid. */ if (col == columns) i = next_line_end + 1; } } if (doc->md.table_header) doc->md.table_header(work, header_work, &doc->data); if (doc->md.table_body) doc->md.table_body(work, body_work, &doc->data); if (doc->md.table) doc->md.table(ob, work, attr_work, &doc->data); } free(col_data); popbuf(doc, BUFFER_SPAN); popbuf(doc, BUFFER_BLOCK); popbuf(doc, BUFFER_BLOCK); popbuf(doc, BUFFER_ATTRIBUTE); return i; } /* parse_userblock parsing of user block */ static size_t parse_userblock(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { hoedown_buffer work = { 0, 0, 0, 0, NULL, NULL, NULL }; size_t len = doc->user_block(data, size, &doc->data); if (!len) { return 0; } work.data = data; work.size = len; if (doc->md.user_block) { doc->md.user_block(ob, &work, &doc->data); } else { hoedown_buffer_put(ob, work.data, work.size); } return len; } /* is_paragraph returns if the next block is a paragraph (doesn't follow any * other special rules for other types of blocks) */ static int is_paragraph(hoedown_document *doc, uint8_t *txt_data, size_t end) { /* temporary buffer for results of checking special blocks */ hoedown_buffer *tmp = newbuf(doc, BUFFER_BLOCK); /* temporary renderer that has no rendering function */ hoedown_renderer temp_renderer; /* ensure all callbacks are NULL */ memset(&temp_renderer, 0, sizeof(hoedown_renderer)); /* store the old renderer */ hoedown_renderer old_renderer; memcpy(&old_renderer, &doc->md, sizeof(hoedown_renderer)); /* copy the new renderer over to the document */ memcpy(&doc->md, &temp_renderer, sizeof(hoedown_renderer)); /* these are all the if branches inside parse_block, wrapped into one bool, * with minimal parsing, and completely idempotent */ int result = !(is_atxheader(doc, txt_data, end) || (doc->user_block && parse_userblock(tmp, doc, txt_data, end)) || (txt_data[0] == '<' && parse_htmlblock(tmp, doc, txt_data, end, 0)) || is_hrule(txt_data, end) || ((doc->ext_flags & HOEDOWN_EXT_FENCED_CODE) && parse_fencedcode(tmp, doc, txt_data, end, doc->ext_flags)) || ((doc->ext_flags & HOEDOWN_EXT_TABLES) && parse_table(tmp, doc, txt_data, end)) || prefix_quote(txt_data, end) || (!(doc->ext_flags & HOEDOWN_EXT_DISABLE_INDENTED_CODE) && prefix_code(txt_data, end)) || prefix_uli(txt_data, end) || prefix_oli(txt_data, end) || ((doc->ext_flags & HOEDOWN_EXT_DEFINITION_LISTS) && prefix_dli(doc, txt_data, end))); popbuf(doc, BUFFER_BLOCK); memcpy(&doc->md, &old_renderer, sizeof(hoedown_renderer)); return result; } /* parse_block parsing of one block, returning next uint8_t to parse */ static void parse_block(hoedown_buffer *ob, hoedown_document *doc, uint8_t *data, size_t size) { size_t beg, end, i; uint8_t *txt_data; beg = 0; if (doc->work_bufs[BUFFER_SPAN].size + doc->work_bufs[BUFFER_BLOCK].size > doc->max_nesting) return; while (beg < size) { txt_data = data + beg; end = size - beg; if (is_atxheader(doc, txt_data, end)) beg += parse_atxheader(ob, doc, txt_data, end); else if (doc->user_block && (i = parse_userblock(ob, doc, txt_data, end)) != 0) beg += i; else if (data[beg] == '<' && doc->md.blockhtml && (i = parse_htmlblock(ob, doc, txt_data, end, 1)) != 0) beg += i; else if ((i = is_empty(txt_data, end)) != 0) beg += i; else if (is_hrule(txt_data, end)) { while (beg < size && data[beg] != '\n') beg++; if (doc->md.hrule) { doc->hrule_char = data[beg - 1]; doc->md.hrule(ob, &doc->data); doc->hrule_char = 0; } beg++; } else if ((doc->ext_flags & HOEDOWN_EXT_FENCED_CODE) != 0 && (i = parse_fencedcode(ob, doc, txt_data, end, doc->ext_flags)) != 0) beg += i; else if ((doc->ext_flags & HOEDOWN_EXT_TABLES) != 0 && (i = parse_table(ob, doc, txt_data, end)) != 0) beg += i; else if (prefix_quote(txt_data, end)) beg += parse_blockquote(ob, doc, txt_data, end); else if (!(doc->ext_flags & HOEDOWN_EXT_DISABLE_INDENTED_CODE) && prefix_code(txt_data, end)) beg += parse_blockcode(ob, doc, txt_data, end); else if (prefix_uli(txt_data, end)) beg += parse_list(ob, doc, txt_data, end, 0); else if (prefix_oli(txt_data, end)) beg += parse_list(ob, doc, txt_data, end, HOEDOWN_LIST_ORDERED); else if ((doc->ext_flags & HOEDOWN_EXT_DEFINITION_LISTS) && prefix_dli(doc, txt_data, end)) beg += parse_list(ob, doc, txt_data, end, HOEDOWN_LIST_DEFINITION); else beg += parse_paragraph(ob, doc, txt_data, end); } } /********************* * REFERENCE PARSING * *********************/ /* is_footnote returns whether a line is a footnote definition or not */ static int is_footnote(const uint8_t *data, size_t beg, size_t end, size_t *last, struct footnote_list *list) { size_t i = 0; hoedown_buffer *contents = NULL; hoedown_buffer *name = NULL; size_t ind = 0; int in_empty = 0; size_t start = 0; size_t id_offset, id_end; size_t id_indent = 0, content_line = 0, content_indent = 0; /* up to 3 optional leading spaces */ if (beg + 3 >= end) return 0; if (data[beg] == ' ') { i = 1; if (data[beg + 1] == ' ') { i = 2; if (data[beg + 2] == ' ') { i = 3; if (data[beg + 3] == ' ') return 0; } } } i += beg; /* id part: caret followed by anything between brackets */ if (data[i] != '[') return 0; i++; if (i >= end || data[i] != '^') return 0; i++; id_offset = i; while (i < end && data[i] != '\n' && data[i] != '\r' && data[i] != ']') i++; if (i >= end || data[i] != ']') return 0; id_end = i; /* spacer: colon (space | tab)* newline? (space | tab)* */ i++; if (i >= end || data[i] != ':') return 0; i++; if (i >= end) return 0; /* getting content and name buffers */ contents = hoedown_buffer_new(64); name = hoedown_buffer_new(64); start = i; /* getting item indent size */ while (id_indent != start && data[start - id_indent] != '\n' && data[start - id_indent] != '\r') { id_indent++; } /* process lines similar to a list item */ while (i < end) { while (i < end && data[i] != '\n' && data[i] != '\r') i++; /* process an empty line */ if (is_empty(data + start, i - start)) { in_empty = 1; if (i < end && (data[i] == '\n' || data[i] == '\r')) { i++; if (i < end && data[i] == '\n' && data[i - 1] == '\r') i++; } start = i; continue; } /* calculating the indentation */ ind = 0; while (ind < 4 && start + ind < end && data[start + ind] == ' ') ind++; content_line++; /* joining only indented stuff after empty lines; * note that now we only require 1 space of indentation * to continue, just like lists */ if (ind == 0) { if (start == id_end + 2 && data[start] == '\t') {} else break; } else if (in_empty) { hoedown_buffer_putc(contents, '\n'); } in_empty = 0; /* re-calculating the indentation */ if (content_line == 2 && data[start + ind] == ' ') { while (ind < id_indent && data[start + ind] == ' ') { ind++; } content_indent = ind; } if (content_indent > ind) { while (ind < content_indent && data[start + ind] == ' ') { ind++; } } /* adding the line into the content buffer */ hoedown_buffer_put(contents, data + start + ind, i - start - ind); /* add carriage return */ if (i < end) { hoedown_buffer_putc(contents, '\n'); if (i < end && (data[i] == '\n' || data[i] == '\r')) { i++; if (i < end && data[i] == '\n' && data[i - 1] == '\r') i++; } } start = i; } if (last) *last = start; if (list) { struct footnote_ref *ref; ref = create_footnote_ref(list, data + id_offset, id_end - id_offset); if (!ref) return 0; if (!add_footnote_ref(list, ref)) { free_footnote_ref(ref); return 0; } ref->contents = contents; hoedown_buffer_put(name, data + id_offset, id_end - id_offset); ref->name = name; } return 1; } /* is_html_comment returns whether a html comment or not */ static int is_html_comment(const uint8_t *data, size_t beg, size_t end, size_t *last) { size_t i = 0; if (beg + 5 >= end) return 0; if (!(data[beg] == '<' && data[beg + 1] == '!' && data[beg + 2] == '-' && data[beg + 3] == '-')) return 0; i = 5; while (beg + i < end && !(data[beg + i - 2] == '-' && data[beg + i - 1] == '-' && data[beg + i] == '>')) i++; /* i can only ever be beyond the end if the ending --> is not found */ if (beg + i >= end) return 0; i++; if (beg + i < end && (data[beg + i] == '\n' || data[beg + i] == '\r')) { i++; if (beg + i < end && data[beg + i] == '\r' && data[beg + i - 1] == '\n') i++; } if (last) *last = beg + i; return 1; } /* is_ref returns whether a line is a reference or not */ static int is_ref(const uint8_t *data, size_t beg, size_t end, size_t *last, struct link_ref **refs) { /* int n; */ size_t i = 0; size_t id_offset, id_end; size_t link_offset, link_end; size_t title_offset, title_end; size_t line_end; size_t attr_offset = 0, attr_end = 0; /* up to 3 optional leading spaces */ if (beg + 3 >= end) return 0; if (data[beg] == ' ') { i = 1; if (data[beg + 1] == ' ') { i = 2; if (data[beg + 2] == ' ') { i = 3; if (data[beg + 3] == ' ') return 0; } } } i += beg; /* id part: anything but a newline between brackets */ if (data[i] != '[') return 0; i++; id_offset = i; while (i < end && data[i] != '\n' && data[i] != '\r' && data[i] != ']') i++; if (i >= end || data[i] != ']') return 0; id_end = i; /* spacer: colon (space | tab)* newline? (space | tab)* */ i++; if (i >= end || data[i] != ':') return 0; i++; while (i < end && data[i] == ' ') i++; if (i < end && (data[i] == '\n' || data[i] == '\r')) { i++; if (i < end && data[i] == '\r' && data[i - 1] == '\n') i++; } while (i < end && data[i] == ' ') i++; if (i >= end) return 0; /* link: spacing-free sequence, optionally between angle brackets */ if (data[i] == '<') i++; link_offset = i; while (i < end && data[i] != ' ' && data[i] != '\n' && data[i] != '\r') i++; if (data[i - 1] == '>') link_end = i - 1; else link_end = i; /* optional spacer: (space | tab)* (newline | '\'' | '"' | '(' ) */ while (i < end && data[i] == ' ') i++; if (i < end && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(') return 0; line_end = 0; /* computing end-of-line */ if (i >= end || data[i] == '\r' || data[i] == '\n') line_end = i; if (i + 1 < end && data[i] == '\n' && data[i + 1] == '\r') line_end = i + 1; /* optional (space|tab)* spacer after a newline */ if (line_end) { i = line_end + 1; while (i < end && data[i] == ' ') i++; } /* optional title: any non-newline sequence enclosed in '"() alone on its line */ title_offset = title_end = 0; if (i + 1 < end && (data[i] == '\'' || data[i] == '"' || data[i] == '(')) { char d = data[i++]; title_offset = i; /* looking for end of tile */ while (i < end && data[i] != d && data[i] != '\n' && data[i] != '\r') { ++i; } if (i + 1 < end && data[i] == d) { title_end = i++; attr_offset = i; /* looking for EOL */ while (i < end && data[i] != '\n' && data[i] != '\r') { i++; } /* looking for attribute */ if (data[i-1] == '}' && memchr(&data[attr_offset], '{', i - attr_offset)) { while (attr_offset < i && data[attr_offset] != '{') { ++attr_offset; } ++attr_offset; attr_end = i - 1; } else { if (data[i-1] == d) { title_end = i - 1; } else { title_end = i; } attr_offset = 0; attr_end = 0; } if (i + 1 < end && data[i] == '\r' && data[i + 1] == '\n') { ++i; } line_end = i; } else { /* looking for EOL */ while (i < end && data[i] != '\n' && data[i] != '\r') { i++; } if (i + 1 < end && data[i] == '\n' && data[i + 1] == '\r') { title_end = i + 1; } else { title_end = i; } /* stepping back */ i -= 1; while (i > title_offset && data[i] == ' ') { i -= 1; } if (i > title_offset && (data[i] == '\'' || data[i] == '"' || data[i] == ')')) { line_end = title_end; title_end = i; } } } if (!line_end || link_end == link_offset) return 0; /* garbage after the link empty link */ /* a valid ref has been found, filling-in return structures */ if (last) *last = line_end; if (refs) { struct link_ref *ref; ref = add_link_ref(refs, data + id_offset, id_end - id_offset); if (!ref) return 0; ref->link = hoedown_buffer_new(link_end - link_offset); hoedown_buffer_put(ref->link, data + link_offset, link_end - link_offset); if (title_end > title_offset) { ref->title = hoedown_buffer_new(title_end - title_offset); hoedown_buffer_put(ref->title, data + title_offset, title_end - title_offset); } if (attr_end > attr_offset) { ref->attr = hoedown_buffer_new(attr_end - attr_offset); hoedown_buffer_put(ref->attr, data + attr_offset, attr_end - attr_offset); } } return 1; } static void expand_tabs(hoedown_buffer *ob, const uint8_t *line, size_t size) { /* This code makes two assumptions: * - Input is valid UTF-8. (Any byte with top two bits 10 is skipped, * whether or not it is a valid UTF-8 continuation byte.) * - Input contains no combining characters. (Combining characters * should be skipped but are not.) */ size_t i = 0, tab = 0; while (i < size) { size_t org = i; while (i < size && line[i] != '\t') { /* ignore UTF-8 continuation bytes */ if ((line[i] & 0xc0) != 0x80) tab++; i++; } if (i > org) hoedown_buffer_put(ob, line + org, i - org); if (i >= size) break; do { hoedown_buffer_putc(ob, ' '); tab++; } while (tab % 4); i++; } } /********************** * EXPORTED FUNCTIONS * **********************/ hoedown_document * hoedown_document_new( const hoedown_renderer *renderer, hoedown_extensions extensions, size_t max_nesting, uint8_t attr_activation, hoedown_user_block user_block, hoedown_buffer *meta) { hoedown_document *doc = NULL; assert(max_nesting > 0 && renderer); doc = hoedown_malloc(sizeof(hoedown_document)); memcpy(&doc->md, renderer, sizeof(hoedown_renderer)); doc->data.opaque = renderer->opaque; hoedown_stack_init(&doc->work_bufs[BUFFER_BLOCK], 4); hoedown_stack_init(&doc->work_bufs[BUFFER_SPAN], 8); hoedown_stack_init(&doc->work_bufs[BUFFER_ATTRIBUTE], 8); memset(doc->active_char, 0x0, 256); if (extensions & HOEDOWN_EXT_UNDERLINE && doc->md.underline) { doc->active_char['_'] = MD_CHAR_EMPHASIS; } if (doc->md.emphasis || doc->md.double_emphasis || doc->md.triple_emphasis) { doc->active_char['*'] = MD_CHAR_EMPHASIS; doc->active_char['_'] = MD_CHAR_EMPHASIS; if (extensions & HOEDOWN_EXT_STRIKETHROUGH) doc->active_char['~'] = MD_CHAR_EMPHASIS; if (extensions & HOEDOWN_EXT_HIGHLIGHT) doc->active_char['='] = MD_CHAR_EMPHASIS; } if (doc->md.codespan) doc->active_char['`'] = MD_CHAR_CODESPAN; if (doc->md.linebreak) doc->active_char['\n'] = MD_CHAR_LINEBREAK; if (doc->md.image || doc->md.link || doc->md.footnotes || doc->md.footnote_ref) { doc->active_char['['] = MD_CHAR_LINK; doc->active_char['!'] = MD_CHAR_IMAGE; } doc->active_char['<'] = MD_CHAR_LANGLE; doc->active_char['\\'] = MD_CHAR_ESCAPE; doc->active_char['&'] = MD_CHAR_ENTITY; if (extensions & HOEDOWN_EXT_AUTOLINK) { doc->active_char[':'] = MD_CHAR_AUTOLINK_URL; doc->active_char['@'] = MD_CHAR_AUTOLINK_EMAIL; doc->active_char['w'] = MD_CHAR_AUTOLINK_WWW; } if (extensions & HOEDOWN_EXT_SUPERSCRIPT) doc->active_char['^'] = MD_CHAR_SUPERSCRIPT; if (extensions & HOEDOWN_EXT_QUOTE) doc->active_char['"'] = MD_CHAR_QUOTE; if (extensions & HOEDOWN_EXT_MATH) doc->active_char['$'] = MD_CHAR_MATH; /* Extension data */ doc->ext_flags = extensions; doc->max_nesting = max_nesting; doc->attr_activation = attr_activation; doc->in_link_body = 0; doc->link_id = NULL; doc->link_ref_attr = NULL; doc->link_inline_attr = NULL; doc->is_escape_char = 0; doc->header_type = HOEDOWN_HEADER_NONE; doc->link_type = HOEDOWN_LINK_NONE; doc->footnote_id = NULL; doc->list_depth = 0; doc->blockquote_depth = 0; doc->ul_item_char = 0; doc->hrule_char = 0; doc->fencedcode_char = 0; doc->ol_numeral = NULL; doc->user_block = user_block; doc->meta = meta; return doc; } void hoedown_document_render(hoedown_document *doc, hoedown_buffer *ob, const uint8_t *data, size_t size) { static const uint8_t UTF8_BOM[] = {0xEF, 0xBB, 0xBF}; hoedown_buffer *text; size_t beg, end; int footnotes_enabled; text = hoedown_buffer_new(64); /* Preallocate enough space for our buffer to avoid expanding while copying */ hoedown_buffer_grow(text, size); /* reset the references table */ memset(&doc->refs, 0x0, REF_TABLE_SIZE * sizeof(void *)); footnotes_enabled = doc->ext_flags & HOEDOWN_EXT_FOOTNOTES; /* reset the footnotes lists */ if (footnotes_enabled) { memset(&doc->footnotes_found, 0x0, sizeof(doc->footnotes_found)); memset(&doc->footnotes_used, 0x0, sizeof(doc->footnotes_used)); } /* first pass: looking for references, copying everything else */ beg = 0; /* Skip a possible UTF-8 BOM, even though the Unicode standard * discourages having these in UTF-8 documents */ if (size >= 3 && memcmp(data, UTF8_BOM, 3) == 0) beg += 3; while (beg < size) /* iterating over lines */ if (footnotes_enabled && is_footnote(data, beg, size, &end, &doc->footnotes_found)) { if (doc->md.footnote_ref_def) { hoedown_buffer original = { NULL, 0, 0, 0, NULL, NULL, NULL }; original.data = (uint8_t*) (data + beg); original.size = end - beg; doc->md.footnote_ref_def(&original, &doc->data); } beg = end; } else if (is_html_comment(data, beg, size, &end)) { size_t i = 0; while (i < (end - beg) && beg + i < size) { if (data[beg + i] == '\t' && (data[beg + i] & 0xc0) != 0x80) { hoedown_buffer_put(text, (uint8_t*)" ", 4); } else { hoedown_buffer_putc(text, data[beg + i]); } i++; } beg = end; } else if (is_ref(data, beg, size, &end, doc->refs)) { if (doc->md.ref) { hoedown_buffer original = { NULL, 0, 0, 0, NULL, NULL, NULL }; original.data = (uint8_t*) (data + beg); original.size = end - beg; doc->md.ref(&original, &doc->data); } beg = end; } else { /* skipping to the next line */ end = beg; while (end < size && data[end] != '\n' && data[end] != '\r') end++; /* adding the line body if present */ if (end > beg) expand_tabs(text, data + beg, end - beg); while (end < size && (data[end] == '\n' || data[end] == '\r')) { /* add one \n per newline */ if (data[end] == '\n' || (end + 1 < size && data[end + 1] != '\n')) hoedown_buffer_putc(text, '\n'); end++; } beg = end; } /* pre-grow the output buffer to minimize allocations */ hoedown_buffer_grow(ob, text->size + (text->size >> 1)); /* second pass: actual rendering */ if (doc->md.doc_header) doc->md.doc_header(ob, 0, &doc->data); if (text->size) { /* adding a final newline if not already present */ if (text->data[text->size - 1] != '\n') hoedown_buffer_putc(text, '\n'); parse_block(ob, doc, text->data, text->size); } /* footnotes */ if (footnotes_enabled) parse_footnote_list(ob, doc, &doc->footnotes_used); if (doc->md.doc_footer) doc->md.doc_footer(ob, 0, &doc->data); /* clean-up */ hoedown_buffer_free(text); free_link_refs(doc->refs); if (footnotes_enabled) { free_footnote_list(&doc->footnotes_found, 1); free_footnote_list(&doc->footnotes_used, 0); } assert(doc->work_bufs[BUFFER_SPAN].size == 0); assert(doc->work_bufs[BUFFER_BLOCK].size == 0); assert(doc->work_bufs[BUFFER_ATTRIBUTE].size == 0); } void hoedown_document_render_inline(hoedown_document *doc, hoedown_buffer *ob, const uint8_t *data, size_t size) { size_t i = 0, mark; hoedown_buffer *text = hoedown_buffer_new(64); /* reset the references table */ memset(&doc->refs, 0x0, REF_TABLE_SIZE * sizeof(void *)); /* first pass: expand tabs and process newlines */ hoedown_buffer_grow(text, size); while (1) { mark = i; while (i < size && data[i] != '\n' && data[i] != '\r') i++; expand_tabs(text, data + mark, i - mark); if (i >= size) break; while (i < size && (data[i] == '\n' || data[i] == '\r')) { /* add one \n per newline */ if (data[i] == '\n' || (i + 1 < size && data[i + 1] != '\n')) hoedown_buffer_putc(text, '\n'); i++; } } /* second pass: actual rendering */ hoedown_buffer_grow(ob, text->size + (text->size >> 1)); if (doc->md.doc_header) doc->md.doc_header(ob, 1, &doc->data); parse_inline(ob, doc, text->data, text->size); if (doc->md.doc_footer) doc->md.doc_footer(ob, 1, &doc->data); /* clean-up */ hoedown_buffer_free(text); assert(doc->work_bufs[BUFFER_SPAN].size == 0); assert(doc->work_bufs[BUFFER_BLOCK].size == 0); } void hoedown_document_free(hoedown_document *doc) { size_t i; for (i = 0; i < (size_t)doc->work_bufs[BUFFER_SPAN].asize; ++i) hoedown_buffer_free(doc->work_bufs[BUFFER_SPAN].item[i]); for (i = 0; i < (size_t)doc->work_bufs[BUFFER_BLOCK].asize; ++i) hoedown_buffer_free(doc->work_bufs[BUFFER_BLOCK].item[i]); for (i = 0; i < (size_t)doc->work_bufs[BUFFER_ATTRIBUTE].asize; ++i) hoedown_buffer_free(doc->work_bufs[BUFFER_ATTRIBUTE].item[i]); hoedown_stack_uninit(&doc->work_bufs[BUFFER_SPAN]); hoedown_stack_uninit(&doc->work_bufs[BUFFER_BLOCK]); hoedown_stack_uninit(&doc->work_bufs[BUFFER_ATTRIBUTE]); free(doc); } const hoedown_buffer* hoedown_document_link_id(hoedown_document* document) { return document->link_id; } const hoedown_buffer* hoedown_document_link_ref_attr(hoedown_document* document) { return document->link_ref_attr; } const hoedown_buffer* hoedown_document_link_inline_attr(hoedown_document* document) { return document->link_inline_attr; } int hoedown_document_is_escaped(hoedown_document* document) { return document->is_escape_char; } hoedown_header_type hoedown_document_header_type(hoedown_document* document) { return document->header_type; } hoedown_link_type hoedown_document_link_type(hoedown_document* document) { return document->link_type; } const hoedown_buffer* hoedown_document_footnote_id(hoedown_document* document) { return document->footnote_id; } int hoedown_document_list_depth(hoedown_document* document) { return document->list_depth; } int hoedown_document_blockquote_depth(hoedown_document* document) { return document->blockquote_depth; } uint8_t hoedown_document_ul_item_char(hoedown_document* document) { return document->ul_item_char; } uint8_t hoedown_document_hrule_char(hoedown_document* document) { return document->hrule_char; } uint8_t hoedown_document_fencedcode_char(hoedown_document* document) { return document->fencedcode_char; } const hoedown_buffer* hoedown_document_ol_numeral(hoedown_document* document) { return document->ol_numeral; } ```
/content/code_sandbox/External/Hoextdown/document.c
c
2016-08-11T15:55:22
2024-08-14T02:42:22
simplenote-ios
Automattic/simplenote-ios
2,038
34,150
```qmake # Add project specific ProGuard rules here. # By default, the flags in this file are appended to flags specified # in C:\Users\Mikhail\Documents\tools\android_sdk/tools/proguard/proguard-android.txt # You can edit the include path and order by changing the proguardFiles # directive in build.gradle. # # For more details, see # path_to_url # Add any project specific keep options here: # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/proguard-rules.pro
qmake
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
144
```gradle apply plugin: 'maven-publish' apply plugin: 'signing' apply plugin: 'org.jetbrains.dokka' task androidSourcesJar(type: Jar) { archiveClassifier.set('sources') if (project.plugins.findPlugin("com.android.library")) { from android.sourceSets.main.java.srcDirs } else { from sourceSets.main.java.srcDirs } } //tasks.withType(dokkaHtmlPartial.getClass()).configureEach { // pluginsMapConfiguration.set( // ["org.jetbrains.dokka.base.DokkaBase": """{ "separateInheritedMembers": true}"""] // ) //} task javadocJar(type: Jar) { archiveClassifier.set('javadoc') } artifacts { archives androidSourcesJar archives javadocJar } group = PUBLISH_GROUP_ID version = PUBLISH_VERSION afterEvaluate { publishing { publications { release(MavenPublication) { groupId PUBLISH_GROUP_ID artifactId PUBLISH_ARTIFACT_ID version PUBLISH_VERSION if (project.plugins.findPlugin("com.android.library")) { artifact bundleReleaseAar } else { artifact("$buildDir/libs/${project.getName()}-${version}.jar") } artifact androidSourcesJar artifact javadocJar pom { name = PUBLISH_ARTIFACT_ID description = 'Carousel Layout Manager for RecyclerView' url = 'path_to_url licenses { license { url = 'path_to_url } } developers { developer { id = 'mig35' name = 'Mikhail Gurevich' email = 'mig35@mig35.com' } } scm { connection = 'scm:git:github.com/Azoft/CarouselLayoutManager.git' developerConnection = 'scm:git:ssh://github.com/Azoft/CarouselLayoutManager.git' url = 'path_to_url } } } } } } signing { sign publishing.publications } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/publish-module.gradle
gradle
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
438
```gradle ext["signing.keyId"] = '' ext["signing.password"] = '' ext["signing.secretKeyRingFile"] = '' ext["ossrhUsername"] = '' ext["ossrhPassword"] = '' ext["sonatypeStagingProfileId"] = '' File secretPropsFile = project.rootProject.file('local.properties') if (secretPropsFile.exists()) { // Read local.properties file first if it exists Properties p = new Properties() new FileInputStream(secretPropsFile).withCloseable { is -> p.load(is) } p.each { name, value -> ext[name] = value } } else { // Use system environment variables ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME') ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD') ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID') ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID') ext["signing.password"] = System.getenv('SIGNING_PASSWORD') ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE') } // Set up Sonatype repository nexusPublishing { repositories { sonatype { stagingProfileId = sonatypeStagingProfileId username = ossrhUsername password = ossrhPassword /* Existing params here... */ nexusUrl.set(uri("path_to_url")) snapshotRepositoryUrl.set(uri("path_to_url")) } } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/publish-root.gradle
gradle
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
322
```java package com.mig35.carousellayoutmanager; import androidx.annotation.NonNull; import android.view.View; /** * Implementation of {@link CarouselLayoutManager.PostLayoutListener} that makes interesting scaling of items. <br /> * We are trying to make items scaling quicker for closer items for center and slower for when they are far away.<br /> * Tis implementation uses atan function for this purpose. */ public class CarouselZoomPostLayoutListener extends CarouselLayoutManager.PostLayoutListener { private final float mScaleMultiplier; public CarouselZoomPostLayoutListener() { this(0.17f); } public CarouselZoomPostLayoutListener(final float scaleMultiplier) { mScaleMultiplier = scaleMultiplier; } @Override public ItemTransformation transformChild(@NonNull final View child, final float itemPositionToCenterDiff, final int orientation) { final float scale = 1.0f - mScaleMultiplier * Math.abs(itemPositionToCenterDiff); // because scaling will make view smaller in its center, then we should move this item to the top or bottom to make it visible final float translateY; final float translateX; if (CarouselLayoutManager.VERTICAL == orientation) { final float translateYGeneral = child.getMeasuredHeight() * (1 - scale) / 2f; translateY = Math.signum(itemPositionToCenterDiff) * translateYGeneral; translateX = 0; } else { final float translateXGeneral = child.getMeasuredWidth() * (1 - scale) / 2f; translateX = Math.signum(itemPositionToCenterDiff) * translateXGeneral; translateY = 0; } return new ItemTransformation(scale, scale, translateX, translateY); } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/CarouselZoomPostLayoutListener.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
361
```java package com.mig35.carousellayoutmanager; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.View; public class DefaultChildSelectionListener extends CarouselChildSelectionListener { @NonNull private final OnCenterItemClickListener mOnCenterItemClickListener; protected DefaultChildSelectionListener(@NonNull final OnCenterItemClickListener onCenterItemClickListener, @NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager) { super(recyclerView, carouselLayoutManager); mOnCenterItemClickListener = onCenterItemClickListener; } @Override protected void onCenterItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v) { mOnCenterItemClickListener.onCenterItemClicked(recyclerView, carouselLayoutManager, v); } @Override protected void onBackItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v) { recyclerView.smoothScrollToPosition(carouselLayoutManager.getPosition(v)); } public static DefaultChildSelectionListener initCenterItemListener(@NonNull final OnCenterItemClickListener onCenterItemClickListener, @NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager) { return new DefaultChildSelectionListener(onCenterItemClickListener, recyclerView, carouselLayoutManager); } public interface OnCenterItemClickListener { void onCenterItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v); } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/DefaultChildSelectionListener.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
294
```java package com.mig35.carousellayoutmanager; import android.graphics.PointF; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.View; /** * Custom implementation of {@link RecyclerView.SmoothScroller} that can work only with {@link CarouselLayoutManager}. * * @see CarouselLayoutManager */ public class CarouselSmoothScroller { public CarouselSmoothScroller(@NonNull final RecyclerView.State state, final int position) { if (0 > position) { throw new IllegalArgumentException("position can't be less then 0. position is : " + position); } if (position >= state.getItemCount()) { throw new IllegalArgumentException("position can't be great then adapter items count. position is : " + position); } } @SuppressWarnings("unused") public PointF computeScrollVectorForPosition(final int targetPosition, @NonNull final CarouselLayoutManager carouselLayoutManager) { return carouselLayoutManager.computeScrollVectorForPosition(targetPosition); } @SuppressWarnings("unused") public int calculateDyToMakeVisible(final View view, @NonNull final CarouselLayoutManager carouselLayoutManager) { if (!carouselLayoutManager.canScrollVertically()) { return 0; } return carouselLayoutManager.getOffsetForCurrentView(view); } @SuppressWarnings("unused") public int calculateDxToMakeVisible(final View view, @NonNull final CarouselLayoutManager carouselLayoutManager) { if (!carouselLayoutManager.canScrollHorizontally()) { return 0; } return carouselLayoutManager.getOffsetForCurrentView(view); } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/CarouselSmoothScroller.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
318
```java package com.mig35.carousellayoutmanager; public class ItemTransformation { final float mScaleX; final float mScaleY; final float mTranslationX; final float mTranslationY; public ItemTransformation(final float scaleX, final float scaleY, final float translationX, final float translationY) { mScaleX = scaleX; mScaleY = scaleY; mTranslationX = translationX; mTranslationY = translationY; } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/ItemTransformation.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
101
```java package com.mig35.carousellayoutmanager; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import android.view.View; public abstract class CarouselChildSelectionListener { @NonNull private final RecyclerView mRecyclerView; @NonNull private final CarouselLayoutManager mCarouselLayoutManager; private final View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(final View v) { final RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v); final int position = holder.getAdapterPosition(); if (position == mCarouselLayoutManager.getCenterItemPosition()) { onCenterItemClicked(mRecyclerView, mCarouselLayoutManager, v); } else { onBackItemClicked(mRecyclerView, mCarouselLayoutManager, v); } } }; protected CarouselChildSelectionListener(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager) { mRecyclerView = recyclerView; mCarouselLayoutManager = carouselLayoutManager; mRecyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(@NonNull final View view) { view.setOnClickListener(mOnClickListener); } @Override public void onChildViewDetachedFromWindow(@NonNull final View view) { view.setOnClickListener(null); } }); } protected abstract void onCenterItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v); protected abstract void onBackItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v); } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/CarouselChildSelectionListener.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
326
```java package com.mig35.carousellayoutmanager; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; /** * Class for centering items after scroll event.<br /> * This class will listen to current scroll state and if item is not centered after scroll it will automatically scroll it to center. */ public class CenterScrollListener extends RecyclerView.OnScrollListener { private boolean mAutoSet = true; @Override public void onScrollStateChanged(@NonNull final RecyclerView recyclerView, final int newState) { super.onScrollStateChanged(recyclerView, newState); final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (!(layoutManager instanceof CarouselLayoutManager)) { mAutoSet = true; return; } final CarouselLayoutManager lm = (CarouselLayoutManager) layoutManager; if (!mAutoSet) { if (RecyclerView.SCROLL_STATE_IDLE == newState) { final int scrollNeeded = lm.getOffsetCenterView(); if (CarouselLayoutManager.HORIZONTAL == lm.getOrientation()) { recyclerView.smoothScrollBy(scrollNeeded, 0); } else { recyclerView.smoothScrollBy(0, scrollNeeded); } mAutoSet = true; } } if (RecyclerView.SCROLL_STATE_DRAGGING == newState || RecyclerView.SCROLL_STATE_SETTLING == newState) { mAutoSet = false; } } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/CenterScrollListener.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
279
```java package com.mig35.carousellayoutmanager.sample; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.mig35.carousellayoutmanager.CarouselLayoutManager; import com.mig35.carousellayoutmanager.CarouselZoomPostLayoutListener; import com.mig35.carousellayoutmanager.CenterScrollListener; import com.mig35.carousellayoutmanager.DefaultChildSelectionListener; import com.mig35.carousellayoutmanager.sample.databinding.ActivityCarouselPreviewBinding; import com.mig35.carousellayoutmanager.sample.databinding.ItemViewBinding; import java.util.Locale; import java.util.Random; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; public class CarouselPreviewActivity extends AppCompatActivity { @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); final ActivityCarouselPreviewBinding binding = ActivityCarouselPreviewBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); setSupportActionBar(binding.toolbar); final TestAdapter adapter = new TestAdapter(); // create layout manager with needed params: vertical, cycle initRecyclerView(binding.listHorizontal, new CarouselLayoutManager(CarouselLayoutManager.HORIZONTAL, false), adapter); initRecyclerView(binding.listVertical, new CarouselLayoutManager(CarouselLayoutManager.VERTICAL, true), adapter); // fab button will add element to the end of the list binding.fabScroll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { /* final int itemToRemove = adapter.mItemsCount; if (10 != itemToRemove) { adapter.mItemsCount++; adapter.notifyItemInserted(itemToRemove); } */ binding.listHorizontal.smoothScrollToPosition(adapter.getItemCount() - 2); binding.listVertical.smoothScrollToPosition(adapter.getItemCount() - 2); } }); // fab button will remove element from the end of the list binding.fabChangeData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { /* final int itemToRemove = adapter.mItemsCount - 1; if (0 <= itemToRemove) { adapter.mItemsCount--; adapter.notifyItemRemoved(itemToRemove); } */ binding.listHorizontal.smoothScrollToPosition(1); binding.listVertical.smoothScrollToPosition(1); } }); } private void initRecyclerView(final RecyclerView recyclerView, final CarouselLayoutManager layoutManager, final TestAdapter adapter) { // enable zoom effect. this line can be customized layoutManager.setPostLayoutListener(new CarouselZoomPostLayoutListener()); layoutManager.setMaxVisibleItems(3); recyclerView.setLayoutManager(layoutManager); // we expect only fixed sized item for now recyclerView.setHasFixedSize(true); // sample adapter with random data recyclerView.setAdapter(adapter); // enable center post scrolling recyclerView.addOnScrollListener(new CenterScrollListener()); // enable center post touching on item and item click listener DefaultChildSelectionListener.initCenterItemListener(new DefaultChildSelectionListener.OnCenterItemClickListener() { @Override public void onCenterItemClicked(@NonNull final RecyclerView recyclerView, @NonNull final CarouselLayoutManager carouselLayoutManager, @NonNull final View v) { final int position = recyclerView.getChildLayoutPosition(v); final String msg = String.format(Locale.US, "Item %1$d was clicked", position); Toast.makeText(CarouselPreviewActivity.this, msg, Toast.LENGTH_SHORT).show(); } }, recyclerView, layoutManager); layoutManager.addOnItemSelectionListener(new CarouselLayoutManager.OnCenterItemSelectionListener() { @Override public void onCenterItemChanged(final int adapterPosition) { if (CarouselLayoutManager.INVALID_POSITION != adapterPosition) { final int value = adapter.mPosition[adapterPosition]; /* adapter.mPosition[adapterPosition] = (value % 10) + (value / 10 + 1) * 10; adapter.notifyItemChanged(adapterPosition); */ } } }); } private static final class TestAdapter extends RecyclerView.Adapter<TestViewHolder> { private final int[] mColors; private final int[] mPosition; private final int mItemsCount = 100; TestAdapter() { mColors = new int[mItemsCount]; mPosition = new int[mItemsCount]; for (int i = 0; mItemsCount > i; ++i) { //noinspection MagicNumber final Random random = new Random(); mColors[i] = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256)); mPosition[i] = i; } } @Override public TestViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) { Log.e("!!!!!!!!!", "onCreateViewHolder"); return new TestViewHolder(ItemViewBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false)); } @Override public void onBindViewHolder(final TestViewHolder holder, final int position) { Log.e("!!!!!!!!!", "onBindViewHolder: " + position); holder.mItemViewBinding.cItem1.setText(String.valueOf(mPosition[position])); holder.mItemViewBinding.cItem2.setText(String.valueOf(mPosition[position])); holder.itemView.setBackgroundColor(mColors[position]); } @Override public int getItemCount() { return mItemsCount; } @Override public long getItemId(final int position) { return position; } } private static class TestViewHolder extends RecyclerView.ViewHolder { private final ItemViewBinding mItemViewBinding; TestViewHolder(final ItemViewBinding itemViewBinding) { super(itemViewBinding.getRoot()); mItemViewBinding = itemViewBinding; } } } ```
/content/code_sandbox/CarouselLayoutManager/sample/src/main/java/com/mig35/carousellayoutmanager/sample/CarouselPreviewActivity.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
1,199
```java package com.mig35.carousellayoutmanager; import android.graphics.PointF; import android.os.Handler; import android.os.Looper; import android.os.Parcel; import android.os.Parcelable; import android.view.View; import android.view.ViewGroup; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import androidx.annotation.CallSuper; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.view.ViewCompat; import androidx.recyclerview.widget.LinearSmoothScroller; import androidx.recyclerview.widget.OrientationHelper; import androidx.recyclerview.widget.RecyclerView; /** * An implementation of {@link RecyclerView.LayoutManager} that layout items like carousel. * Generally there is one center item and bellow this item there are maximum {@link CarouselLayoutManager#getMaxVisibleItems()} items on each side of the center * item. By default {@link CarouselLayoutManager#getMaxVisibleItems()} is {@link CarouselLayoutManager#MAX_VISIBLE_ITEMS}.<br /> * <br /> * This LayoutManager supports only fixedSized adapter items.<br /> * <br /> * This LayoutManager supports {@link CarouselLayoutManager#HORIZONTAL} and {@link CarouselLayoutManager#VERTICAL} orientations. <br /> * <br /> * This LayoutManager supports circle layout. By default it if disabled. We don't recommend to use circle layout with adapter items count less then 3. <br /> * <br /> * Please be sure that layout_width of adapter item is a constant value and not {@link ViewGroup.LayoutParams#MATCH_PARENT} * for {@link #HORIZONTAL} orientation. * So like layout_height is not {@link ViewGroup.LayoutParams#MATCH_PARENT} for {@link CarouselLayoutManager#VERTICAL}<br /> * <br /> */ public class CarouselLayoutManager extends RecyclerView.LayoutManager implements RecyclerView.SmoothScroller.ScrollVectorProvider { public static final int HORIZONTAL = OrientationHelper.HORIZONTAL; public static final int VERTICAL = OrientationHelper.VERTICAL; public static final int INVALID_POSITION = -1; public static final int MAX_VISIBLE_ITEMS = 3; private static final boolean CIRCLE_LAYOUT = false; private boolean mDecoratedChildSizeInvalid; private Integer mDecoratedChildWidth; private Integer mDecoratedChildHeight; private final int mOrientation; private boolean mCircleLayout; private int mPendingScrollPosition; private final LayoutHelper mLayoutHelper = new LayoutHelper(MAX_VISIBLE_ITEMS); private PostLayoutListener mViewPostLayout; private final List<OnCenterItemSelectionListener> mOnCenterItemSelectionListeners = new ArrayList<>(); private int mCenterItemPosition = INVALID_POSITION; private int mItemsCount; @Nullable private CarouselSavedState mPendingCarouselSavedState; /** * @param orientation should be {@link #VERTICAL} or {@link #HORIZONTAL} */ @SuppressWarnings("unused") public CarouselLayoutManager(final int orientation) { this(orientation, CIRCLE_LAYOUT); } /** * If circleLayout is true then all items will be in cycle. Scroll will be infinite on both sides. * * @param orientation should be {@link #VERTICAL} or {@link #HORIZONTAL} * @param circleLayout true for enabling circleLayout */ @SuppressWarnings("unused") public CarouselLayoutManager(final int orientation, final boolean circleLayout) { if (HORIZONTAL != orientation && VERTICAL != orientation) { throw new IllegalArgumentException("orientation should be HORIZONTAL or VERTICAL"); } mOrientation = orientation; mCircleLayout = circleLayout; mPendingScrollPosition = INVALID_POSITION; } /** * Change circle layout type */ @SuppressWarnings("unused") public void setCircleLayout(final boolean circleLayout) { if (mCircleLayout != circleLayout) { mCircleLayout = circleLayout; requestLayout(); } } /** * Setup {@link CarouselLayoutManager.PostLayoutListener} for this LayoutManager. * Its methods will be called for each visible view item after general LayoutManager layout finishes. <br /> * <br /> * Generally this method should be used for scaling and translating view item for better (different) view presentation of layouting. * * @param postLayoutListener listener for item layout changes. Can be null. */ @SuppressWarnings("unused") public void setPostLayoutListener(@Nullable final PostLayoutListener postLayoutListener) { mViewPostLayout = postLayoutListener; requestLayout(); } /** * Setup maximum visible (layout) items on each side of the center item. * Basically during scrolling there can be more visible items (+1 item on each side), but in idle state this is the only reached maximum. * * @param maxVisibleItems should be great then 0, if bot an {@link IllegalAccessException} will be thrown */ @CallSuper @SuppressWarnings("unused") public void setMaxVisibleItems(final int maxVisibleItems) { if (0 > maxVisibleItems) { throw new IllegalArgumentException("maxVisibleItems can't be less then 0"); } mLayoutHelper.mMaxVisibleItems = maxVisibleItems; requestLayout(); } /** * @return current setup for maximum visible items. * @see #setMaxVisibleItems(int) */ @SuppressWarnings("unused") public int getMaxVisibleItems() { return mLayoutHelper.mMaxVisibleItems; } @Override public RecyclerView.LayoutParams generateDefaultLayoutParams() { return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); } /** * @return current layout orientation * @see #VERTICAL * @see #HORIZONTAL */ public int getOrientation() { return mOrientation; } @Override public boolean canScrollHorizontally() { return 0 != getChildCount() && HORIZONTAL == mOrientation; } @Override public boolean canScrollVertically() { return 0 != getChildCount() && VERTICAL == mOrientation; } /** * @return current layout center item */ public int getCenterItemPosition() { return mCenterItemPosition; } /** * @param onCenterItemSelectionListener listener that will trigger when ItemSelectionChanges. can't be null */ public void addOnItemSelectionListener(@NonNull final OnCenterItemSelectionListener onCenterItemSelectionListener) { mOnCenterItemSelectionListeners.add(onCenterItemSelectionListener); } /** * @param onCenterItemSelectionListener listener that was previously added by {@link #addOnItemSelectionListener(OnCenterItemSelectionListener)} */ public void removeOnItemSelectionListener(@NonNull final OnCenterItemSelectionListener onCenterItemSelectionListener) { mOnCenterItemSelectionListeners.remove(onCenterItemSelectionListener); } @SuppressWarnings("RefusedBequest") @Override public void scrollToPosition(final int position) { if (0 > position) { throw new IllegalArgumentException("position can't be less then 0. position is : " + position); } mPendingScrollPosition = position; requestLayout(); } @SuppressWarnings("RefusedBequest") @Override public void smoothScrollToPosition(@NonNull final RecyclerView recyclerView, @NonNull final RecyclerView.State state, final int position) { final LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) { @Override public int calculateDyToMakeVisible(final View view, final int snapPreference) { if (!canScrollVertically()) { return 0; } return getOffsetForCurrentView(view); } @Override public int calculateDxToMakeVisible(final View view, final int snapPreference) { if (!canScrollHorizontally()) { return 0; } return getOffsetForCurrentView(view); } }; linearSmoothScroller.setTargetPosition(position); startSmoothScroll(linearSmoothScroller); } @Override @Nullable public PointF computeScrollVectorForPosition(final int targetPosition) { if (0 == getChildCount()) { return null; } final float directionDistance = getScrollDirection(targetPosition); //noinspection NumericCastThatLosesPrecision final int direction = (int) -Math.signum(directionDistance); if (HORIZONTAL == mOrientation) { return new PointF(direction, 0); } else { return new PointF(0, direction); } } private float getScrollDirection(final int targetPosition) { final float currentScrollPosition = makeScrollPositionInRange0ToCount(getCurrentScrollPosition(), mItemsCount); if (mCircleLayout) { final float t1 = currentScrollPosition - targetPosition; final float t2 = Math.abs(t1) - mItemsCount; if (Math.abs(t1) > Math.abs(t2)) { return Math.signum(t1) * t2; } else { return t1; } } else { return currentScrollPosition - targetPosition; } } @Override public int scrollVerticallyBy(final int dy, @NonNull final RecyclerView.Recycler recycler, @NonNull final RecyclerView.State state) { if (HORIZONTAL == mOrientation) { return 0; } return scrollBy(dy, recycler, state); } @Override public int scrollHorizontallyBy(final int dx, final RecyclerView.Recycler recycler, final RecyclerView.State state) { if (VERTICAL == mOrientation) { return 0; } return scrollBy(dx, recycler, state); } /** * This method is called from {@link #scrollHorizontallyBy(int, RecyclerView.Recycler, RecyclerView.State)} and * {@link #scrollVerticallyBy(int, RecyclerView.Recycler, RecyclerView.State)} to calculate needed scroll that is allowed. <br /> * <br /> * This method may do relayout work. * * @param diff distance that we want to scroll by * @param recycler Recycler to use for fetching potentially cached views for a position * @param state Transient state of RecyclerView * @return distance that we actually scrolled by */ @CallSuper protected int scrollBy(final int diff, @NonNull final RecyclerView.Recycler recycler, @NonNull final RecyclerView.State state) { if (null == mDecoratedChildWidth || null == mDecoratedChildHeight) { return 0; } if (0 == getChildCount() || 0 == diff) { return 0; } final int resultScroll; if (mCircleLayout) { resultScroll = diff; mLayoutHelper.mScrollOffset += resultScroll; final int maxOffset = getScrollItemSize() * mItemsCount; while (0 > mLayoutHelper.mScrollOffset) { mLayoutHelper.mScrollOffset += maxOffset; } while (mLayoutHelper.mScrollOffset > maxOffset) { mLayoutHelper.mScrollOffset -= maxOffset; } mLayoutHelper.mScrollOffset -= resultScroll; } else { final int maxOffset = getMaxScrollOffset(); if (0 > mLayoutHelper.mScrollOffset + diff) { resultScroll = -mLayoutHelper.mScrollOffset; //to make it 0 } else if (mLayoutHelper.mScrollOffset + diff > maxOffset) { resultScroll = maxOffset - mLayoutHelper.mScrollOffset; //to make it maxOffset } else { resultScroll = diff; } } if (0 != resultScroll) { mLayoutHelper.mScrollOffset += resultScroll; fillData(recycler, state); } return resultScroll; } @Override public void onMeasure(@NonNull final RecyclerView.Recycler recycler, @NonNull final RecyclerView.State state, final int widthSpec, final int heightSpec) { mDecoratedChildSizeInvalid = true; super.onMeasure(recycler, state, widthSpec, heightSpec); } @SuppressWarnings("rawtypes") @Override public void onAdapterChanged(final RecyclerView.Adapter oldAdapter, final RecyclerView.Adapter newAdapter) { super.onAdapterChanged(oldAdapter, newAdapter); removeAllViews(); } @SuppressWarnings("RefusedBequest") @Override @CallSuper public void onLayoutChildren(@NonNull final RecyclerView.Recycler recycler, @NonNull final RecyclerView.State state) { if (0 == state.getItemCount()) { removeAndRecycleAllViews(recycler); selectItemCenterPosition(INVALID_POSITION); return; } detachAndScrapAttachedViews(recycler); if (null == mDecoratedChildWidth || mDecoratedChildSizeInvalid) { final List<RecyclerView.ViewHolder> scrapList = recycler.getScrapList(); final boolean shouldRecycle; final View view; if (scrapList.isEmpty()) { shouldRecycle = true; final int itemsCount = state.getItemCount(); view = recycler.getViewForPosition( mPendingScrollPosition == INVALID_POSITION ? 0 : Math.max(0, Math.min(itemsCount - 1, mPendingScrollPosition)) ); addView(view); } else { shouldRecycle = false; view = scrapList.get(0).itemView; } measureChildWithMargins(view, 0, 0); final int decoratedChildWidth = getDecoratedMeasuredWidth(view); final int decoratedChildHeight = getDecoratedMeasuredHeight(view); if (shouldRecycle) { detachAndScrapView(view, recycler); } if (null != mDecoratedChildWidth && (mDecoratedChildWidth != decoratedChildWidth || mDecoratedChildHeight != decoratedChildHeight)) { if (INVALID_POSITION == mPendingScrollPosition && null == mPendingCarouselSavedState) { mPendingScrollPosition = mCenterItemPosition; } } mDecoratedChildWidth = decoratedChildWidth; mDecoratedChildHeight = decoratedChildHeight; mDecoratedChildSizeInvalid = false; } if (INVALID_POSITION != mPendingScrollPosition) { final int itemsCount = state.getItemCount(); mPendingScrollPosition = 0 == itemsCount ? INVALID_POSITION : Math.max(0, Math.min(itemsCount - 1, mPendingScrollPosition)); } if (INVALID_POSITION != mPendingScrollPosition) { mLayoutHelper.mScrollOffset = calculateScrollForSelectingPosition(mPendingScrollPosition, state); mPendingScrollPosition = INVALID_POSITION; mPendingCarouselSavedState = null; } else if (null != mPendingCarouselSavedState) { mLayoutHelper.mScrollOffset = calculateScrollForSelectingPosition(mPendingCarouselSavedState.mCenterItemPosition, state); mPendingCarouselSavedState = null; } else if (state.didStructureChange() && INVALID_POSITION != mCenterItemPosition) { mLayoutHelper.mScrollOffset = calculateScrollForSelectingPosition(mCenterItemPosition, state); } fillData(recycler, state); } private int calculateScrollForSelectingPosition(final int itemPosition, final RecyclerView.State state) { if (itemPosition == INVALID_POSITION) { return 0; } final int fixedItemPosition = itemPosition < state.getItemCount() ? itemPosition : state.getItemCount() - 1; return fixedItemPosition * (VERTICAL == mOrientation ? mDecoratedChildHeight : mDecoratedChildWidth); } private void fillData(@NonNull final RecyclerView.Recycler recycler, @NonNull final RecyclerView.State state) { final float currentScrollPosition = getCurrentScrollPosition(); generateLayoutOrder(currentScrollPosition, state); detachAndScrapAttachedViews(recycler); recyclerOldViews(recycler); final int width = getWidthNoPadding(); final int height = getHeightNoPadding(); if (VERTICAL == mOrientation) { fillDataVertical(recycler, width, height); } else { fillDataHorizontal(recycler, width, height); } recycler.clear(); detectOnItemSelectionChanged(currentScrollPosition, state); } private void detectOnItemSelectionChanged(final float currentScrollPosition, final RecyclerView.State state) { final float absCurrentScrollPosition = makeScrollPositionInRange0ToCount(currentScrollPosition, state.getItemCount()); final int centerItem = Math.round(absCurrentScrollPosition); if (mCenterItemPosition != centerItem) { mCenterItemPosition = centerItem; new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { selectItemCenterPosition(centerItem); } }); } } private void selectItemCenterPosition(final int centerItem) { for (final OnCenterItemSelectionListener onCenterItemSelectionListener : mOnCenterItemSelectionListeners) { onCenterItemSelectionListener.onCenterItemChanged(centerItem); } } private void fillDataVertical(final RecyclerView.Recycler recycler, final int width, final int height) { final int start = (width - mDecoratedChildWidth) / 2; final int end = start + mDecoratedChildWidth; final int centerViewTop = (height - mDecoratedChildHeight) / 2; for (int i = 0, count = mLayoutHelper.mLayoutOrder.length; i < count; ++i) { final LayoutOrder layoutOrder = mLayoutHelper.mLayoutOrder[i]; final int offset = getCardOffsetByPositionDiff(layoutOrder.mItemPositionDiff); final int top = centerViewTop + offset; final int bottom = top + mDecoratedChildHeight; fillChildItem(start, top, end, bottom, layoutOrder, recycler, i); } } private void fillDataHorizontal(final RecyclerView.Recycler recycler, final int width, final int height) { final int top = (height - mDecoratedChildHeight) / 2; final int bottom = top + mDecoratedChildHeight; final int centerViewStart = (width - mDecoratedChildWidth) / 2; for (int i = 0, count = mLayoutHelper.mLayoutOrder.length; i < count; ++i) { final LayoutOrder layoutOrder = mLayoutHelper.mLayoutOrder[i]; final int offset = getCardOffsetByPositionDiff(layoutOrder.mItemPositionDiff); final int start = centerViewStart + offset; final int end = start + mDecoratedChildWidth; fillChildItem(start, top, end, bottom, layoutOrder, recycler, i); } } @SuppressWarnings("MethodWithTooManyParameters") private void fillChildItem(final int start, final int top, final int end, final int bottom, @NonNull final LayoutOrder layoutOrder, @NonNull final RecyclerView.Recycler recycler, final int i) { final View view = bindChild(layoutOrder.mItemAdapterPosition, recycler); ViewCompat.setElevation(view, i); ItemTransformation transformation = null; if (null != mViewPostLayout) { transformation = mViewPostLayout.transformChild(view, layoutOrder.mItemPositionDiff, mOrientation, layoutOrder.mItemAdapterPosition); } if (null == transformation) { view.layout(start, top, end, bottom); } else { view.layout(Math.round(start + transformation.mTranslationX), Math.round(top + transformation.mTranslationY), Math.round(end + transformation.mTranslationX), Math.round(bottom + transformation.mTranslationY)); view.setScaleX(transformation.mScaleX); view.setScaleY(transformation.mScaleY); } } /** * @return current scroll position of center item. this value can be in any range if it is cycle layout. * if this is not, that then it is in [0, {@link #mItemsCount - 1}] */ private float getCurrentScrollPosition() { final int fullScrollSize = getMaxScrollOffset(); if (0 == fullScrollSize) { return 0; } return 1.0f * mLayoutHelper.mScrollOffset / getScrollItemSize(); } /** * @return maximum scroll value to fill up all items in layout. Generally this is only needed for non cycle layouts. */ private int getMaxScrollOffset() { return getScrollItemSize() * (mItemsCount - 1); } /** * Because we can support old Android versions, we should layout our children in specific order to make our center view in the top of layout * (this item should layout last). So this method will calculate layout order and fill up {@link #mLayoutHelper} object. * This object will be filled by only needed to layout items. Non visible items will not be there. * * @param currentScrollPosition current scroll position this is a value that indicates position of center item * (if this value is int, then center item is really in the center of the layout, else it is near state). * Be aware that this value can be in any range is it is cycle layout * @param state Transient state of RecyclerView * @see #getCurrentScrollPosition() */ private void generateLayoutOrder(final float currentScrollPosition, @NonNull final RecyclerView.State state) { mItemsCount = state.getItemCount(); final float absCurrentScrollPosition = makeScrollPositionInRange0ToCount(currentScrollPosition, mItemsCount); final int centerItem = Math.round(absCurrentScrollPosition); if (mCircleLayout && 1 < mItemsCount) { final int layoutCount = Math.min(mLayoutHelper.mMaxVisibleItems * 2 + 1, mItemsCount); mLayoutHelper.initLayoutOrder(layoutCount); final int countLayoutHalf = layoutCount / 2; // before center item for (int i = 1; i <= countLayoutHalf; ++i) { final int position = Math.round(absCurrentScrollPosition - i + mItemsCount) % mItemsCount; mLayoutHelper.setLayoutOrder(countLayoutHalf - i, position, centerItem - absCurrentScrollPosition - i); } // after center item for (int i = layoutCount - 1; i >= countLayoutHalf + 1; --i) { final int position = Math.round(absCurrentScrollPosition - i + layoutCount) % mItemsCount; mLayoutHelper.setLayoutOrder(i - 1, position, centerItem - absCurrentScrollPosition + layoutCount - i); } mLayoutHelper.setLayoutOrder(layoutCount - 1, centerItem, centerItem - absCurrentScrollPosition); } else { final int firstVisible = Math.max(centerItem - mLayoutHelper.mMaxVisibleItems, 0); final int lastVisible = Math.min(centerItem + mLayoutHelper.mMaxVisibleItems, mItemsCount - 1); final int layoutCount = lastVisible - firstVisible + 1; mLayoutHelper.initLayoutOrder(layoutCount); for (int i = firstVisible; i <= lastVisible; ++i) { if (i == centerItem) { mLayoutHelper.setLayoutOrder(layoutCount - 1, i, i - absCurrentScrollPosition); } else if (i < centerItem) { mLayoutHelper.setLayoutOrder(i - firstVisible, i, i - absCurrentScrollPosition); } else { mLayoutHelper.setLayoutOrder(layoutCount - (i - centerItem) - 1, i, i - absCurrentScrollPosition); } } } } public int getWidthNoPadding() { return getWidth() - getPaddingStart() - getPaddingEnd(); } public int getHeightNoPadding() { return getHeight() - getPaddingEnd() - getPaddingStart(); } private View bindChild(final int position, @NonNull final RecyclerView.Recycler recycler) { final View view = recycler.getViewForPosition(position); addView(view); measureChildWithMargins(view, 0, 0); return view; } private void recyclerOldViews(final RecyclerView.Recycler recycler) { for (RecyclerView.ViewHolder viewHolder : new ArrayList<>(recycler.getScrapList())) { int adapterPosition = viewHolder.getAdapterPosition(); boolean found = false; for (LayoutOrder layoutOrder : mLayoutHelper.mLayoutOrder) { if (layoutOrder.mItemAdapterPosition == adapterPosition) { found = true; break; } } if (!found) { recycler.recycleView(viewHolder.itemView); } } } /** * Called during {@link #fillData(RecyclerView.Recycler, RecyclerView.State)} to calculate item offset from layout center line. <br /> * <br /> * Returns {@link #convertItemPositionDiffToSmoothPositionDiff(float)} * (size off area above center item when it is on the center). <br /> * Sign is: plus if this item is bellow center line, minus if not<br /> * <br /> * ----- - area above it<br /> * ||||| - center item<br /> * ----- - area bellow it (it has the same size as are above center item)<br /> * * @param itemPositionDiff current item difference with layout center line. if this is 0, then this item center is in layout center line. * if this is 1 then this item is bellow the layout center line in the full item size distance. * @return offset in scroll px coordinates. */ protected int getCardOffsetByPositionDiff(final float itemPositionDiff) { final double smoothPosition = convertItemPositionDiffToSmoothPositionDiff(itemPositionDiff); final int dimenDiff; if (VERTICAL == mOrientation) { dimenDiff = (getHeightNoPadding() - mDecoratedChildHeight) / 2; } else { dimenDiff = (getWidthNoPadding() - mDecoratedChildWidth) / 2; } //noinspection NumericCastThatLosesPrecision return (int) Math.round(Math.signum(itemPositionDiff) * dimenDiff * smoothPosition); } /** * Called during {@link #getCardOffsetByPositionDiff(float)} for better item movement. <br/> * Current implementation speed up items that are far from layout center line and slow down items that are close to this line. * This code is full of maths. If you want to make items move in a different way, probably you should override this method.<br /> * Please see code comments for better explanations. * * @param itemPositionDiff current item difference with layout center line. if this is 0, then this item center is in layout center line. * if this is 1 then this item is bellow the layout center line in the full item size distance. * @return smooth position offset. needed for scroll calculation and better user experience. * @see #getCardOffsetByPositionDiff(float) */ @SuppressWarnings({"MagicNumber", "InstanceMethodNamingConvention"}) protected double convertItemPositionDiffToSmoothPositionDiff(final float itemPositionDiff) { // generally item moves the same way above center and bellow it. So we don't care about diff sign. final float absIemPositionDiff = Math.abs(itemPositionDiff); // we detect if this item is close for center or not. We use (1 / maxVisibleItem) ^ (1/3) as close definer. if (absIemPositionDiff > StrictMath.pow(1.0f / mLayoutHelper.mMaxVisibleItems, 1.0f / 3)) { // this item is far from center line, so we should make it move like square root function return StrictMath.pow(absIemPositionDiff / mLayoutHelper.mMaxVisibleItems, 1 / 2.0f); } else { // this item is close from center line. we should slow it down and don't make it speed up very quick. // so square function in range of [0, (1/maxVisible)^(1/3)] is quite good in it; return StrictMath.pow(absIemPositionDiff, 2.0f); } } /** * @return full item size */ protected int getScrollItemSize() { if (VERTICAL == mOrientation) { return mDecoratedChildHeight; } else { return mDecoratedChildWidth; } } @Override public Parcelable onSaveInstanceState() { if (null != mPendingCarouselSavedState) { return new CarouselSavedState(mPendingCarouselSavedState); } final CarouselSavedState savedState = new CarouselSavedState(super.onSaveInstanceState()); savedState.mCenterItemPosition = mCenterItemPosition; return savedState; } @Override public void onRestoreInstanceState(final Parcelable state) { if (state instanceof CarouselSavedState) { mPendingCarouselSavedState = (CarouselSavedState) state; super.onRestoreInstanceState(mPendingCarouselSavedState.mSuperState); } else { super.onRestoreInstanceState(state); } } /** * @return Scroll offset from nearest item from center */ protected int getOffsetCenterView() { return Math.round(getCurrentScrollPosition()) * getScrollItemSize() - mLayoutHelper.mScrollOffset; } protected int getOffsetForCurrentView(@NonNull final View view) { final int targetPosition = getPosition(view); final float directionDistance = getScrollDirection(targetPosition); return Math.round(directionDistance * getScrollItemSize()); } /** * Helper method that make scroll in range of [0, count). Generally this method is needed only for cycle layout. * * @param currentScrollPosition any scroll position range. * @param count adapter items count * @return good scroll position in range of [0, count) */ private static float makeScrollPositionInRange0ToCount(final float currentScrollPosition, final int count) { float absCurrentScrollPosition = currentScrollPosition; while (0 > absCurrentScrollPosition) { absCurrentScrollPosition += count; } while (Math.round(absCurrentScrollPosition) >= count) { absCurrentScrollPosition -= count; } return absCurrentScrollPosition; } /** * This interface methods will be called for each visible view item after general LayoutManager layout finishes. <br /> * <br /> * Generally this method should be used for scaling and translating view item for better (different) view presentation of layouting. */ @SuppressWarnings("InterfaceNeverImplemented") public abstract static class PostLayoutListener { /** * Called after child layout finished. Generally you can do any translation and scaling work here. * * @param child view that was layout * @param itemPositionToCenterDiff view center line difference to layout center. if > 0 then this item is bellow layout center line, else if not * @param orientation layoutManager orientation {@link #getLayoutDirection()} * @param itemPositionInAdapter item position inside adapter for this layout pass */ public ItemTransformation transformChild( @NonNull final View child, final float itemPositionToCenterDiff, final int orientation, final int itemPositionInAdapter ) { return transformChild(child, itemPositionToCenterDiff, orientation); } /** * Called after child layout finished. Generally you can do any translation and scaling work here. * * @param child view that was layout * @param itemPositionToCenterDiff view center line difference to layout center. if > 0 then this item is bellow layout center line, else if not * @param orientation layoutManager orientation {@link #getLayoutDirection()} */ public ItemTransformation transformChild( @NonNull final View child, final float itemPositionToCenterDiff, final int orientation ) { throw new IllegalStateException("at least one transformChild should be implemented"); } } public interface OnCenterItemSelectionListener { /** * Listener that will be called on every change of center item. * This listener will be triggered on <b>every</b> layout operation if item was changed. * Do not do any expensive operations in this method since this will effect scroll experience. * * @param adapterPosition current layout center item */ void onCenterItemChanged(final int adapterPosition); } /** * Helper class that holds currently visible items. * Generally this class fills this list. <br /> * <br /> * This class holds all scroll and maxVisible items state. * * @see #getMaxVisibleItems() */ private static class LayoutHelper { private int mMaxVisibleItems; private int mScrollOffset; private LayoutOrder[] mLayoutOrder; private final List<WeakReference<LayoutOrder>> mReusedItems = new ArrayList<>(); LayoutHelper(final int maxVisibleItems) { mMaxVisibleItems = maxVisibleItems; } /** * Called before any fill calls. Needed to recycle old items and init new array list. Generally this list is an array an it is reused. * * @param layoutCount items count that will be layout */ void initLayoutOrder(final int layoutCount) { if (null == mLayoutOrder || mLayoutOrder.length != layoutCount) { if (null != mLayoutOrder) { recycleItems(mLayoutOrder); } mLayoutOrder = new LayoutOrder[layoutCount]; fillLayoutOrder(); } } /** * Called during layout generation process of filling this list. Should be called only after {@link #initLayoutOrder(int)} method call. * * @param arrayPosition position in layout order * @param itemAdapterPosition adapter position of item for future data filling logic * @param itemPositionDiff difference of current item scroll position and center item position. * if this is a center item and it is in real center of layout, then this will be 0. * if current layout is not in the center, then this value will never be int. * if this item center is bellow layout center line then this value is greater then 0, * else less then 0. */ void setLayoutOrder(final int arrayPosition, final int itemAdapterPosition, final float itemPositionDiff) { final LayoutOrder item = mLayoutOrder[arrayPosition]; item.mItemAdapterPosition = itemAdapterPosition; item.mItemPositionDiff = itemPositionDiff; } /** * Checks is this screen Layout has this adapterPosition view in layout * * @param adapterPosition adapter position of item for future data filling logic * @return true is adapterItem is in layout */ boolean hasAdapterPosition(final int adapterPosition) { if (null != mLayoutOrder) { for (final LayoutOrder layoutOrder : mLayoutOrder) { if (layoutOrder.mItemAdapterPosition == adapterPosition) { return true; } } } return false; } @SuppressWarnings("VariableArgumentMethod") private void recycleItems(@NonNull final LayoutOrder... layoutOrders) { for (final LayoutOrder layoutOrder : layoutOrders) { //noinspection ObjectAllocationInLoop mReusedItems.add(new WeakReference<>(layoutOrder)); } } private void fillLayoutOrder() { for (int i = 0, length = mLayoutOrder.length; i < length; ++i) { if (null == mLayoutOrder[i]) { mLayoutOrder[i] = createLayoutOrder(); } } } private LayoutOrder createLayoutOrder() { final Iterator<WeakReference<LayoutOrder>> iterator = mReusedItems.iterator(); while (iterator.hasNext()) { final WeakReference<LayoutOrder> layoutOrderWeakReference = iterator.next(); final LayoutOrder layoutOrder = layoutOrderWeakReference.get(); iterator.remove(); if (null != layoutOrder) { return layoutOrder; } } return new LayoutOrder(); } } /** * Class that holds item data. * This class is filled during {@link #generateLayoutOrder(float, RecyclerView.State)} and used during {@link #fillData(RecyclerView.Recycler, RecyclerView.State)} */ private static class LayoutOrder { /** * Item adapter position */ private int mItemAdapterPosition; /** * Item center difference to layout center. If center of item is bellow layout center, then this value is greater then 0, else it is less. */ private float mItemPositionDiff; } protected static class CarouselSavedState implements Parcelable { private final Parcelable mSuperState; private int mCenterItemPosition; protected CarouselSavedState(@Nullable final Parcelable superState) { mSuperState = superState; } private CarouselSavedState(@NonNull final Parcel in) { mSuperState = in.readParcelable(Parcelable.class.getClassLoader()); mCenterItemPosition = in.readInt(); } protected CarouselSavedState(@NonNull final CarouselSavedState other) { mSuperState = other.mSuperState; mCenterItemPosition = other.mCenterItemPosition; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(final Parcel parcel, final int i) { parcel.writeParcelable(mSuperState, i); parcel.writeInt(mCenterItemPosition); } public static final Parcelable.Creator<CarouselSavedState> CREATOR = new Parcelable.Creator<CarouselSavedState>() { @Override public CarouselSavedState createFromParcel(final Parcel parcel) { return new CarouselSavedState(parcel); } @Override public CarouselSavedState[] newArray(final int i) { return new CarouselSavedState[i]; } }; } } ```
/content/code_sandbox/CarouselLayoutManager/carousellayoutmanager/src/main/java/com/mig35/carousellayoutmanager/CarouselLayoutManager.java
java
2016-03-30T09:57:49
2024-08-16T03:15:37
CarouselLayoutManager
Azoft/CarouselLayoutManager
2,549
8,113
```php <?php declare(strict_types=1); namespace Functional; use App\Radio\Enums\FrontendAdapters; use FunctionalTester; class Api_Admin_StationsCest extends CestAbstract { /** * @before setupComplete * @before login */ public function manageStations(FunctionalTester $I): void { $I->wantTo('Manage stations via API.'); $this->testCrudApi( $I, '/api/admin/stations', [ 'name' => 'Test Station', 'short_name' => 'test_station', ], [ 'name' => 'Modified Station', 'frontend_type' => FrontendAdapters::Shoutcast->value, ] ); } } ```
/content/code_sandbox/tests/Functional/Api_Admin_StationsCest.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
164
```php <?php declare(strict_types=1); /* Placeholder */ ```
/content/code_sandbox/tests/Functional/_bootstrap.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
13
```php <?php declare(strict_types=1); namespace Unit; use App\Entity\Enums\PlaylistTypes; use App\Entity\Station; use App\Entity\StationPlaylist; use App\Entity\StationSchedule; use App\Radio\AutoDJ\Scheduler; use App\Tests\Module; use Carbon\CarbonImmutable; use Codeception\Test\Unit; use DateTimeZone; use Mockery; use UnitTester; class StationPlaylistTest extends Unit { protected UnitTester $tester; protected Scheduler $scheduler; protected function _inject(Module $testsModule): void { $di = $testsModule->container; $this->scheduler = $di->get(Scheduler::class); } public function testScheduledPlaylist(): void { /** @var Station $station */ $station = Mockery::mock(Station::class); $playlist = new StationPlaylist($station); $playlist->setName('Test Playlist'); // Sample playlist that plays from 10PM to 4AM the next day. $scheduleEntry = new StationSchedule($playlist); $scheduleEntry->setStartTime(2200); $scheduleEntry->setEndTime(400); $scheduleEntry->setDays([1, 2, 3]); // Monday, Tuesday, Wednesday $playlist->getScheduleItems()->add($scheduleEntry); $utc = new DateTimeZone('UTC'); $testMonday = CarbonImmutable::create(2018, 1, 15, 0, 0, 0, $utc); $testThursday = CarbonImmutable::create(2018, 1, 18, 0, 0, 0, $utc); // Sanity check: Jan 15, 2018 is a Monday, and Jan 18, 2018 is a Thursday. self::assertTrue($testMonday->isMonday()); self::assertTrue($testThursday->isThursday()); // Playlist SHOULD play Monday evening at 10:30PM. $testTime = $testMonday->setTime(22, 30); self::assertTrue($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); // Playlist SHOULD play Thursday morning at 3:00AM. $testTime = $testThursday->setTime(3, 0); self::assertTrue($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); // Playlist SHOULD NOT play Monday morning at 3:00AM. $testTime = $testMonday->setTime(3, 0); self::assertFalse($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); // Playlist SHOULD NOT play Thursday evening at 10:30PM. $testTime = $testThursday->setTime(22, 30); self::assertFalse($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); } public function testOncePerXMinutesPlaylist() { /** @var Station $station */ $station = Mockery::mock(Station::class); $playlist = new StationPlaylist($station); $playlist->setName('Test Playlist'); $playlist->setType(PlaylistTypes::OncePerXMinutes); $playlist->setPlayPerMinutes(30); $utc = new DateTimeZone('UTC'); $testDay = CarbonImmutable::create(2018, 1, 15, 0, 0, 0, $utc); // Last played 20 minutes ago, SHOULD NOT play again. $lastPlayed = $testDay->addMinutes(0 - 20); $playlist->setPlayedAt($lastPlayed->getTimestamp()); self::assertFalse($this->scheduler->shouldPlaylistPlayNow($playlist, $testDay)); // Last played 40 minutes ago, SHOULD play again. $lastPlayed = $testDay->addMinutes(0 - 40); $playlist->setPlayedAt($lastPlayed->getTimestamp()); self::assertTrue($this->scheduler->shouldPlaylistPlayNow($playlist, $testDay)); } public function testOncePerHourPlaylist() { /** @var Station $station */ $station = Mockery::mock(Station::class); $playlist = new StationPlaylist($station); $playlist->setName('Test Playlist'); $playlist->setType(PlaylistTypes::OncePerHour); $playlist->setPlayPerHourMinute(50); $utc = new DateTimeZone('UTC'); $testDay = CarbonImmutable::create(2018, 1, 15, 0, 0, 0, $utc); // Playlist SHOULD try to play at 11:59 PM. $testTime = $testDay->setTime(23, 59); self::assertTrue($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); // Playlist SHOULD try to play at 12:04 PM. $testTime = $testDay->setTime(12, 4); self::assertTrue($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); // Playlist SHOULD NOT try to play at 11:49 PM. $testTime = $testDay->setTime(23, 49); self::assertFalse($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); // Playlist SHOULD NOT try to play at 12:06 PM. $testTime = $testDay->setTime(12, 6); self::assertFalse($this->scheduler->shouldPlaylistPlayNow($playlist, $testTime)); } } ```
/content/code_sandbox/tests/Unit/StationPlaylistTest.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
1,184
```php <?php declare(strict_types=1); namespace Functional; use App\Radio\Enums\RemoteAdapters; use FunctionalTester; class Api_Stations_RemotesCest extends CestAbstract { /** * @before setupComplete * @before login */ public function manageRemotes(FunctionalTester $I): void { $I->wantTo('Manage station remote relays via API.'); $station = $this->getTestStation(); $this->testCrudApi( $I, '/api/station/' . $station->getId() . '/remotes', [ 'type' => RemoteAdapters::Icecast->value, 'display_name' => 'Test Remote Relay', ], [ 'display_name' => 'Modified Remote Relay', ] ); } } ```
/content/code_sandbox/tests/Functional/Api_Stations_RemotesCest.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
179
```php <?php declare(strict_types=1); namespace Functional; use FunctionalTester; class Api_Admin_AuditLogCest extends CestAbstract { /** * @before setupComplete * @before login */ public function viewAuditLog(FunctionalTester $I): void { $I->wantTo('View audit log via API.'); $I->sendGet('/api/admin/auditlog'); $I->seeResponseCodeIs(200); } } ```
/content/code_sandbox/tests/Functional/Api_Admin_AuditLogCest.php
php
2016-04-30T21:41:23
2024-08-16T18:27:26
AzuraCast
AzuraCast/AzuraCast
2,978
104