diff --git a/Keyboard/CatboardBanner.swift b/Keyboard/CatboardBanner.swift index c4a2bc56..164a8482 100644 --- a/Keyboard/CatboardBanner.swift +++ b/Keyboard/CatboardBanner.swift @@ -52,7 +52,9 @@ class CatboardBanner: ExtraView { self.updateAppearance() } - func updateAppearance() { + override func updateAppearance() { + super.updateAppearance() + if self.catSwitch.on { self.catLabel.text = "😺" self.catLabel.alpha = 1 diff --git a/Keyboard/DefaultKeyboard.swift b/Keyboard/DefaultKeyboard.swift index 9733e33f..cb2f9f92 100644 --- a/Keyboard/DefaultKeyboard.swift +++ b/Keyboard/DefaultKeyboard.swift @@ -7,81 +7,81 @@ // func defaultKeyboard() -> Keyboard { - var defaultKeyboard = Keyboard() + let defaultKeyboard = Keyboard() for key in ["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"] { - var keyModel = Key(.Character) + let keyModel = Key(.Character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 0) } for key in ["A", "S", "D", "F", "G", "H", "J", "K", "L"] { - var keyModel = Key(.Character) + let keyModel = Key(.Character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 1, page: 0) } - var keyModel = Key(.Shift) + let keyModel = Key(.Shift) defaultKeyboard.addKey(keyModel, row: 2, page: 0) for key in ["Z", "X", "C", "V", "B", "N", "M"] { - var keyModel = Key(.Character) + let keyModel = Key(.Character) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 2, page: 0) } - var backspace = Key(.Backspace) + let backspace = Key(.Backspace) defaultKeyboard.addKey(backspace, row: 2, page: 0) - var keyModeChangeNumbers = Key(.ModeChange) + let keyModeChangeNumbers = Key(.ModeChange) keyModeChangeNumbers.uppercaseKeyCap = "123" keyModeChangeNumbers.toMode = 1 defaultKeyboard.addKey(keyModeChangeNumbers, row: 3, page: 0) - var keyboardChange = Key(.KeyboardChange) + let keyboardChange = Key(.KeyboardChange) defaultKeyboard.addKey(keyboardChange, row: 3, page: 0) - var settings = Key(.Settings) + let settings = Key(.Settings) defaultKeyboard.addKey(settings, row: 3, page: 0) - var space = Key(.Space) + let space = Key(.Space) space.uppercaseKeyCap = "space" space.uppercaseOutput = " " space.lowercaseOutput = " " defaultKeyboard.addKey(space, row: 3, page: 0) - var returnKey = Key(.Return) + let returnKey = Key(.Return) returnKey.uppercaseKeyCap = "return" returnKey.uppercaseOutput = "\n" returnKey.lowercaseOutput = "\n" defaultKeyboard.addKey(returnKey, row: 3, page: 0) for key in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] { - var keyModel = Key(.SpecialCharacter) + let keyModel = Key(.SpecialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 1) } for key in ["-", "/", ":", ";", "(", ")", "$", "&", "@", "\""] { - var keyModel = Key(.SpecialCharacter) + let keyModel = Key(.SpecialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 1, page: 1) } - var keyModeChangeSpecialCharacters = Key(.ModeChange) + let keyModeChangeSpecialCharacters = Key(.ModeChange) keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+=" keyModeChangeSpecialCharacters.toMode = 2 defaultKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1) for key in [".", ",", "?", "!", "'"] { - var keyModel = Key(.SpecialCharacter) + let keyModel = Key(.SpecialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 2, page: 1) } defaultKeyboard.addKey(Key(backspace), row: 2, page: 1) - var keyModeChangeLetters = Key(.ModeChange) + let keyModeChangeLetters = Key(.ModeChange) keyModeChangeLetters.uppercaseKeyCap = "ABC" keyModeChangeLetters.toMode = 0 defaultKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1) @@ -95,13 +95,13 @@ func defaultKeyboard() -> Keyboard { defaultKeyboard.addKey(Key(returnKey), row: 3, page: 1) for key in ["[", "]", "{", "}", "#", "%", "^", "*", "+", "="] { - var keyModel = Key(.SpecialCharacter) + let keyModel = Key(.SpecialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 0, page: 2) } for key in ["_", "\\", "|", "~", "<", ">", "€", "£", "¥", "•"] { - var keyModel = Key(.SpecialCharacter) + let keyModel = Key(.SpecialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 1, page: 2) } @@ -109,7 +109,7 @@ func defaultKeyboard() -> Keyboard { defaultKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2) for key in [".", ",", "?", "!", "'"] { - var keyModel = Key(.SpecialCharacter) + let keyModel = Key(.SpecialCharacter) keyModel.setLetter(key) defaultKeyboard.addKey(keyModel, row: 2, page: 2) } diff --git a/Keyboard/DefaultSettings.swift b/Keyboard/DefaultSettings.swift index cd33e347..3e4a5f13 100644 --- a/Keyboard/DefaultSettings.swift +++ b/Keyboard/DefaultSettings.swift @@ -16,12 +16,6 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { @IBOutlet var settingsLabel: UILabel? @IBOutlet var pixelLine: UIView? - override var darkMode: Bool { - didSet { - self.updateAppearance(darkMode) - } - } - let cellBackgroundColorDark = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(0.25)) let cellBackgroundColorLight = UIColor.whiteColor().colorWithAlphaComponent(CGFloat(1)) let cellLabelColorDark = UIColor.whiteColor() @@ -62,7 +56,7 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { self.loadNib() } - required init(coder aDecoder: NSCoder) { + required init?(coder aDecoder: NSCoder) { fatalError("loading from nib not supported") } @@ -70,8 +64,8 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { let assets = NSBundle(forClass: self.dynamicType).loadNibNamed("DefaultSettings", owner: self, options: nil) if assets.count > 0 { - if var rootView = assets.first as? UIView { - rootView.setTranslatesAutoresizingMaskIntoConstraints(false) + if let rootView = assets.first as? UIView { + rootView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(rootView) let left = NSLayoutConstraint(item: rootView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) @@ -93,7 +87,7 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { // XXX: this is here b/c a totally transparent background does not support scrolling in blank areas self.tableView?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.01) - self.updateAppearance(self.darkMode) + self.updateAppearance() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { @@ -122,7 +116,7 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - if var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? DefaultSettingsTableViewCell { + if let cell = tableView.dequeueReusableCellWithIdentifier("cell") as? DefaultSettingsTableViewCell { let key = self.settingsList[indexPath.section].1[indexPath.row] if cell.sw.allTargets().count == 0 { @@ -147,23 +141,23 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { } } - func updateAppearance(dark: Bool) { - if dark { + override func updateAppearance() { + super.updateAppearance() + + if darkMode { self.effectsView?.effect let blueColor = UIColor(red: 135/CGFloat(255), green: 206/CGFloat(255), blue: 250/CGFloat(255), alpha: 1) self.pixelLine?.backgroundColor = blueColor.colorWithAlphaComponent(CGFloat(0.5)) self.backButton?.setTitleColor(blueColor, forState: UIControlState.Normal) self.settingsLabel?.textColor = UIColor.whiteColor() - if let visibleCells = self.tableView?.visibleCells() { + if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { - if var cell = cell as? UITableViewCell { - cell.backgroundColor = cellBackgroundColorDark - var label = cell.viewWithTag(2) as? UILabel - label?.textColor = cellLabelColorDark - var longLabel = cell.viewWithTag(3) as? UITextView - longLabel?.textColor = cellLongLabelColorDark - } + cell.backgroundColor = cellBackgroundColorDark + let label = cell.viewWithTag(2) as? UILabel + label?.textColor = cellLabelColorDark + let longLabel = cell.viewWithTag(3) as? UITextView + longLabel?.textColor = cellLongLabelColorDark } } } @@ -173,15 +167,13 @@ class DefaultSettings: ExtraView, UITableViewDataSource, UITableViewDelegate { self.backButton?.setTitleColor(blueColor, forState: UIControlState.Normal) self.settingsLabel?.textColor = UIColor.grayColor() - if let visibleCells = self.tableView?.visibleCells() { + if let visibleCells = self.tableView?.visibleCells { for cell in visibleCells { - if var cell = cell as? UITableViewCell { - cell.backgroundColor = cellBackgroundColorLight - var label = cell.viewWithTag(2) as? UILabel - label?.textColor = cellLabelColorLight - var longLabel = cell.viewWithTag(3) as? UITextView - longLabel?.textColor = cellLongLabelColorLight - } + cell.backgroundColor = cellBackgroundColorLight + let label = cell.viewWithTag(2) as? UILabel + label?.textColor = cellLabelColorLight + let longLabel = cell.viewWithTag(3) as? UITextView + longLabel?.textColor = cellLongLabelColorLight } } } @@ -215,9 +207,9 @@ class DefaultSettingsTableViewCell: UITableViewCell { super.init(style: style, reuseIdentifier: reuseIdentifier) - self.sw.setTranslatesAutoresizingMaskIntoConstraints(false) - self.label.setTranslatesAutoresizingMaskIntoConstraints(false) - self.longLabel.setTranslatesAutoresizingMaskIntoConstraints(false) + self.sw.translatesAutoresizingMaskIntoConstraints = false + self.label.translatesAutoresizingMaskIntoConstraints = false + self.longLabel.translatesAutoresizingMaskIntoConstraints = false self.longLabel.text = nil self.longLabel.scrollEnabled = false @@ -232,14 +224,14 @@ class DefaultSettingsTableViewCell: UITableViewCell { self.addSubview(self.label) self.addSubview(self.longLabel) - self.addConstraints() + self.setupConstraints() } - required init(coder aDecoder: NSCoder) { + required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } - func addConstraints() { + func setupConstraints() { let margin: CGFloat = 8 let sideMargin = margin * 2 @@ -294,7 +286,7 @@ class DefaultSettingsTableViewCell: UITableViewCell { if hasLongText != self.constraintsSetForLongLabel { self.removeConstraints(self.cellConstraints) self.cellConstraints.removeAll() - self.addConstraints() + self.setupConstraints() } } } diff --git a/Keyboard/DirectionEnum.swift b/Keyboard/DirectionEnum.swift index c950622b..3c0fbdaf 100644 --- a/Keyboard/DirectionEnum.swift +++ b/Keyboard/DirectionEnum.swift @@ -6,7 +6,7 @@ // Copyright (c) 2014 Apple. All rights reserved. // -enum Direction: Int, Printable { +enum Direction: Int, CustomStringConvertible { case Left = 0 case Down = 3 case Right = 2 diff --git a/Keyboard/ExtraView.swift b/Keyboard/ExtraView.swift index 4979e58d..6a6c12f2 100644 --- a/Keyboard/ExtraView.swift +++ b/Keyboard/ExtraView.swift @@ -11,7 +11,14 @@ import UIKit class ExtraView: UIView { var globalColors: GlobalColors.Type? - var darkMode: Bool + var darkMode: Bool { + didSet { + if oldValue != darkMode { + updateAppearance() + } + } + } + var solidColorMode: Bool required init(globalColors: GlobalColors.Type?, darkMode: Bool, solidColorMode: Bool) { @@ -22,11 +29,15 @@ class ExtraView: UIView { super.init(frame: CGRectZero) } - required init(coder aDecoder: NSCoder) { + required init?(coder aDecoder: NSCoder) { self.globalColors = nil self.darkMode = false self.solidColorMode = false super.init(coder: aDecoder) } + + func updateAppearance() { + + } } diff --git a/Keyboard/ForwardingView.swift b/Keyboard/ForwardingView.swift index 3054a4cd..3b90e2c7 100644 --- a/Keyboard/ForwardingView.swift +++ b/Keyboard/ForwardingView.swift @@ -23,7 +23,7 @@ class ForwardingView: UIView { self.opaque = false } - required init(coder: NSCoder) { + required init?(coder: NSCoder) { fatalError("NSCoding not supported") } @@ -46,12 +46,10 @@ class ForwardingView: UIView { if let control = view as? UIControl { let targets = control.allTargets() for target in targets { - if var actions = control.actionsForTarget(target, forControlEvent: controlEvent) { + if let actions = control.actionsForTarget(target, forControlEvent: controlEvent) { for action in actions { - if let selectorString = action as? String { - let selector = Selector(selectorString) - control.sendAction(selector, to: target, forEvent: nil) - } + let selector = Selector(action) + control.sendAction(selector, to: target, forEvent: nil) } } } @@ -67,24 +65,22 @@ class ForwardingView: UIView { var closest: (UIView, CGFloat)? = nil for anyView in self.subviews { - if let view = anyView as? UIView { - if view.hidden { - continue - } - - view.alpha = 1 - - let distance = distanceBetween(view.frame, point: position) - - if closest != nil { - if distance < closest!.1 { - closest = (view, distance) - } - } - else { - closest = (view, distance) + if anyView.hidden { + continue + } + + anyView.alpha = 1 + + let distance = distanceBetween(anyView.frame, point: position) + + if closest != nil { + if distance < closest!.1 { + closest = (anyView, distance) } } + else { + closest = (anyView, distance) + } } if closest != nil { @@ -151,81 +147,73 @@ class ForwardingView: UIView { return foundView } - override func touchesBegan(touches: Set, withEvent event: UIEvent) { - for obj in touches { - if let touch = obj as? UITouch { - let position = touch.locationInView(self) - var view = findNearestView(position) - - var viewChangedOwnership = self.ownView(touch, viewToOwn: view) + override func touchesBegan(touches: Set, withEvent event: UIEvent?) { + for touch in touches { + let position = touch.locationInView(self) + let view = findNearestView(position) + + let viewChangedOwnership = self.ownView(touch, viewToOwn: view) + + if !viewChangedOwnership { + self.handleControl(view, controlEvent: .TouchDown) - if !viewChangedOwnership { - self.handleControl(view, controlEvent: .TouchDown) - - if touch.tapCount > 1 { - // two events, I think this is the correct behavior but I have not tested with an actual UIControl - self.handleControl(view, controlEvent: .TouchDownRepeat) - } + if touch.tapCount > 1 { + // two events, I think this is the correct behavior but I have not tested with an actual UIControl + self.handleControl(view, controlEvent: .TouchDownRepeat) } } } } - override func touchesMoved(touches: Set, withEvent event: UIEvent) { - for obj in touches { - if let touch = obj as? UITouch { - let position = touch.locationInView(self) + override func touchesMoved(touches: Set, withEvent event: UIEvent?) { + for touch in touches { + let position = touch.locationInView(self) + + let oldView = self.touchToView[touch] + let newView = findNearestView(position) + + if oldView != newView { + self.handleControl(oldView, controlEvent: .TouchDragExit) - var oldView = self.touchToView[touch] - var newView = findNearestView(position) + let viewChangedOwnership = self.ownView(touch, viewToOwn: newView) - if oldView != newView { - self.handleControl(oldView, controlEvent: .TouchDragExit) - - var viewChangedOwnership = self.ownView(touch, viewToOwn: newView) - - if !viewChangedOwnership { - self.handleControl(newView, controlEvent: .TouchDragEnter) - } - else { - self.handleControl(newView, controlEvent: .TouchDragInside) - } + if !viewChangedOwnership { + self.handleControl(newView, controlEvent: .TouchDragEnter) } else { - self.handleControl(oldView, controlEvent: .TouchDragInside) + self.handleControl(newView, controlEvent: .TouchDragInside) } } + else { + self.handleControl(oldView, controlEvent: .TouchDragInside) + } } } - override func touchesEnded(touches: Set, withEvent event: UIEvent) { - for obj in touches { - if let touch = obj as? UITouch { - var view = self.touchToView[touch] - - let touchPosition = touch.locationInView(self) - - if self.bounds.contains(touchPosition) { - self.handleControl(view, controlEvent: .TouchUpInside) - } - else { - self.handleControl(view, controlEvent: .TouchCancel) - } - - self.touchToView[touch] = nil + override func touchesEnded(touches: Set, withEvent event: UIEvent?) { + for touch in touches { + let view = self.touchToView[touch] + + let touchPosition = touch.locationInView(self) + + if self.bounds.contains(touchPosition) { + self.handleControl(view, controlEvent: .TouchUpInside) } + else { + self.handleControl(view, controlEvent: .TouchCancel) + } + + self.touchToView[touch] = nil } } - override func touchesCancelled(touches: Set, withEvent event: UIEvent!) { - for obj in touches { - if let touch = obj as? UITouch { - var view = self.touchToView[touch] - - self.handleControl(view, controlEvent: .TouchCancel) - - self.touchToView[touch] = nil - } + override func touchesCancelled(touches: Set?, withEvent event: UIEvent?) { + for touch in touches ?? [] { + let view = self.touchToView[touch] + + self.handleControl(view, controlEvent: .TouchCancel) + + self.touchToView[touch] = nil } } } diff --git a/Keyboard/ImageKey.swift b/Keyboard/ImageKey.swift index 9d6612f3..ae0ae90e 100644 --- a/Keyboard/ImageKey.swift +++ b/Keyboard/ImageKey.swift @@ -12,11 +12,11 @@ class ImageKey: KeyboardKey { var image: UIImageView? { willSet { - var anImage = image + let anImage = image anImage?.removeFromSuperview() } didSet { - if var imageView = image { + if let imageView = image { self.addSubview(imageView) imageView.contentMode = UIViewContentMode.ScaleAspectFit self.redrawImage() diff --git a/Keyboard/KeyboardConnector.swift b/Keyboard/KeyboardConnector.swift index 0b3a3a3f..69c9d2a6 100644 --- a/Keyboard/KeyboardConnector.swift +++ b/Keyboard/KeyboardConnector.swift @@ -44,7 +44,7 @@ class KeyboardConnector: KeyboardKeyBackground { super.init(cornerRadius: cornerRadius, underOffset: underOffset) } - required init(coder: NSCoder) { + required init?(coder: NSCoder) { fatalError("NSCoding not supported") } @@ -117,7 +117,7 @@ class KeyboardConnector: KeyboardKeyBackground { myConvertedStartPoints.1 = tempPoint } - var path = CGPathCreateMutable(); + let path = CGPathCreateMutable(); CGPathMoveToPoint(path, nil, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y) CGPathAddLineToPoint(path, nil, myConvertedEndPoints.1.x, myConvertedEndPoints.1.y) @@ -137,7 +137,7 @@ class KeyboardConnector: KeyboardKeyBackground { midpoint = myConvertedStartPoints.0.x + (myConvertedEndPoints.1.x - myConvertedStartPoints.0.x) / 2 } - var bezierPath = UIBezierPath() + let bezierPath = UIBezierPath() var currentEdgePath = UIBezierPath() var edgePaths = [UIBezierPath]() diff --git a/Keyboard/KeyboardInputTraits.swift b/Keyboard/KeyboardInputTraits.swift index f2d5266c..266f9348 100644 --- a/Keyboard/KeyboardInputTraits.swift +++ b/Keyboard/KeyboardInputTraits.swift @@ -29,12 +29,10 @@ extension KeyboardViewController { } func pollTraits() { - if let proxy = (self.textDocumentProxy as? UITextInputTraits) { - if let layout = self.layout { - let appearanceIsDark = (proxy.keyboardAppearance == UIKeyboardAppearance.Dark) - if appearanceIsDark != layout.darkMode { - self.updateAppearances(appearanceIsDark) - } + if let layout = self.layout { + let appearanceIsDark = (textDocumentProxy.keyboardAppearance == UIKeyboardAppearance.Dark) + if appearanceIsDark != layout.darkMode { + self.updateAppearances(appearanceIsDark) } } } diff --git a/Keyboard/KeyboardKey.swift b/Keyboard/KeyboardKey.swift index c49ec2d0..1a3f2c39 100644 --- a/Keyboard/KeyboardKey.swift +++ b/Keyboard/KeyboardKey.swift @@ -156,29 +156,31 @@ class KeyboardKey: UIControl { self.addSubview(self.background) self.background.addSubview(self.label) - let setupViews: Void = { - self.displayView.opaque = false - self.underView?.opaque = false - self.borderView?.opaque = false - - self.shadowLayer.shadowOpacity = Float(0.2) - self.shadowLayer.shadowRadius = 4 - self.shadowLayer.shadowOffset = CGSizeMake(0, 3) - - self.borderView?.lineWidth = CGFloat(0.5) - self.borderView?.fillColor = UIColor.clearColor() - - self.label.textAlignment = NSTextAlignment.Center - self.label.baselineAdjustment = UIBaselineAdjustment.AlignCenters - self.label.font = self.label.font.fontWithSize(22) - self.label.adjustsFontSizeToFitWidth = true - self.label.minimumScaleFactor = CGFloat(0.1) - self.label.userInteractionEnabled = false - self.label.numberOfLines = 1 - }() + setupViews() } - required init(coder: NSCoder) { + private func setupViews() { + self.displayView.opaque = false + self.underView?.opaque = false + self.borderView?.opaque = false + + self.shadowLayer.shadowOpacity = Float(0.2) + self.shadowLayer.shadowRadius = 4 + self.shadowLayer.shadowOffset = CGSizeMake(0, 3) + + self.borderView?.lineWidth = CGFloat(0.5) + self.borderView?.fillColor = UIColor.clearColor() + + self.label.textAlignment = NSTextAlignment.Center + self.label.baselineAdjustment = UIBaselineAdjustment.AlignCenters + self.label.font = self.label.font.fontWithSize(22) + self.label.adjustsFontSizeToFitWidth = true + self.label.minimumScaleFactor = CGFloat(0.1) + self.label.userInteractionEnabled = false + self.label.numberOfLines = 1 + } + + required init?(coder: NSCoder) { fatalError("NSCoding not supported") } @@ -190,7 +192,7 @@ class KeyboardKey: UIControl { override func layoutSubviews() { self.layoutPopupIfNeeded() - var boundingBox = (self.popup != nil ? CGRectUnion(self.bounds, self.popup!.frame) : self.bounds) + let boundingBox = (self.popup != nil ? CGRectUnion(self.bounds, self.popup!.frame) : self.bounds) if self.bounds.width == 0 || self.bounds.height == 0 { return @@ -233,22 +235,22 @@ class KeyboardKey: UIControl { self.popup?.layoutIfNeeded() self.connector?.layoutIfNeeded() - var testPath = UIBezierPath() - var edgePath = UIBezierPath() + let testPath = UIBezierPath() + let edgePath = UIBezierPath() let unitSquare = CGRectMake(0, 0, 1, 1) // TODO: withUnder let addCurves = { (fromShape: KeyboardKeyBackground?, toPath: UIBezierPath, toEdgePaths: UIBezierPath) -> Void in if let shape = fromShape { - var path = shape.fillPath - var translatedUnitSquare = self.displayView.convertRect(unitSquare, fromView: shape) + let path = shape.fillPath + let translatedUnitSquare = self.displayView.convertRect(unitSquare, fromView: shape) let transformFromShapeToView = CGAffineTransformMakeTranslation(translatedUnitSquare.origin.x, translatedUnitSquare.origin.y) path?.applyTransform(transformFromShapeToView) if path != nil { toPath.appendPath(path!) } if let edgePaths = shape.edgePaths { - for (e, anEdgePath) in enumerate(edgePaths) { - var editablePath = anEdgePath + for (_, anEdgePath) in edgePaths.enumerate() { + let editablePath = anEdgePath editablePath.applyTransform(transformFromShapeToView) toEdgePaths.appendPath(editablePath) } @@ -259,19 +261,19 @@ class KeyboardKey: UIControl { addCurves(self.popup, testPath, edgePath) addCurves(self.connector, testPath, edgePath) - var shadowPath = UIBezierPath(CGPath: testPath.CGPath) + let shadowPath = UIBezierPath(CGPath: testPath.CGPath) addCurves(self.background, testPath, edgePath) - var underPath = self.background.underPath - var translatedUnitSquare = self.displayView.convertRect(unitSquare, fromView: self.background) + let underPath = self.background.underPath + let translatedUnitSquare = self.displayView.convertRect(unitSquare, fromView: self.background) let transformFromShapeToView = CGAffineTransformMakeTranslation(translatedUnitSquare.origin.x, translatedUnitSquare.origin.y) underPath?.applyTransform(transformFromShapeToView) CATransaction.begin() CATransaction.setDisableActions(true) - if let popup = self.popup { + if self.popup != nil { self.shadowLayer.shadowPath = shadowPath.CGPath } @@ -429,11 +431,11 @@ class KeyboardKey: UIControl { if self.popup == nil { self.layer.zPosition = 1000 - var popup = KeyboardKeyBackground(cornerRadius: 9.0, underOffset: self.underOffset) + let popup = KeyboardKeyBackground(cornerRadius: 9.0, underOffset: self.underOffset) self.popup = popup self.addSubview(popup) - var popupLabel = UILabel() + let popupLabel = UILabel() popupLabel.textAlignment = self.label.textAlignment popupLabel.baselineAdjustment = self.label.baselineAdjustment popupLabel.font = self.label.font.fontWithSize(22 * 2) @@ -551,7 +553,7 @@ class ShapeView: UIView { //self.layer.rasterizationScale = UIScreen.mainScreen().scale } - required init(coder aDecoder: NSCoder) { + required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } diff --git a/Keyboard/KeyboardKeyBackground.swift b/Keyboard/KeyboardKeyBackground.swift index a067f02c..23b3adb5 100644 --- a/Keyboard/KeyboardKeyBackground.swift +++ b/Keyboard/KeyboardKeyBackground.swift @@ -55,7 +55,7 @@ class KeyboardKeyBackground: UIView, Connectable { arcCenters.reserveCapacity(4) arcStartingAngles.reserveCapacity(4) - for i in 0..<4 { + for _ in 0..<4 { startingPoints.append(CGPointZero) segmentPoints.append((CGPointZero, CGPointZero)) arcCenters.append(CGPointZero) @@ -70,7 +70,7 @@ class KeyboardKeyBackground: UIView, Connectable { self.userInteractionEnabled = false } - required init(coder: NSCoder) { + required init?(coder: NSCoder) { fatalError("NSCoding not supported") } @@ -141,16 +141,16 @@ class KeyboardKeyBackground: UIView, Connectable { floatYCorner = cornerRadius } - var p0 = CGPointMake( + let p0 = CGPointMake( currentPoint.x + (floatXCorner), currentPoint.y + underOffset + (floatYCorner)) - var p1 = CGPointMake( + let p1 = CGPointMake( nextPoint.x - (floatXCorner), nextPoint.y + underOffset - (floatYCorner)) self.segmentPoints[i] = (p0, p1) - var c = CGPointMake( + let c = CGPointMake( p0.x - (floatYCorner), p0.y + (floatXCorner)) @@ -164,7 +164,7 @@ class KeyboardKeyBackground: UIView, Connectable { // by simply using CGPathAddPath, since it closes all the subpaths, so we have to // duplicate the code a little bit. - var fillPath = UIBezierPath() + let fillPath = UIBezierPath() var edgePaths: [UIBezierPath] = [] var prevPoint: CGPoint? @@ -230,8 +230,8 @@ class KeyboardKeyBackground: UIView, Connectable { fillPath.closePath() fillPath.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset)) - var underPath = { () -> UIBezierPath in - var underPath = UIBezierPath() + let underPath = { () -> UIBezierPath in + let underPath = UIBezierPath() underPath.moveToPoint(self.segmentPoints[2].1) @@ -268,7 +268,7 @@ class KeyboardKeyBackground: UIView, Connectable { } func attachmentPoints(direction: Direction) -> (CGPoint, CGPoint) { - var returnValue = ( + let returnValue = ( self.segmentPoints[direction.clockwise().rawValue].0, self.segmentPoints[direction.counterclockwise().rawValue].1) diff --git a/Keyboard/KeyboardLayout.swift b/Keyboard/KeyboardLayout.swift index 529a3474..d15afad7 100644 --- a/Keyboard/KeyboardLayout.swift +++ b/Keyboard/KeyboardLayout.swift @@ -147,7 +147,7 @@ class LayoutConstants: NSObject { return elements[self.findThreshholdIndex(threshholds, measurement: measurement)] } class func findThreshholdIndex(threshholds: [CGFloat], measurement: CGFloat) -> Int { - for (i, threshhold) in enumerate(reverse(threshholds)) { + for (i, threshhold) in Array(threshholds.reverse()).enumerate() { if measurement >= threshhold { let actualIndex = threshholds.count - i return actualIndex @@ -162,7 +162,7 @@ class GlobalColors: NSObject { class var darkModeRegularKey: UIColor { get { return UIColor.whiteColor().colorWithAlphaComponent(CGFloat(0.3)) }} class var darkModeSolidColorRegularKey: UIColor { get { return UIColor(red: CGFloat(83)/CGFloat(255), green: CGFloat(83)/CGFloat(255), blue: CGFloat(83)/CGFloat(255), alpha: 1) }} class var lightModeSpecialKey: UIColor { get { return GlobalColors.lightModeSolidColorSpecialKey }} - class var lightModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(177)/CGFloat(255), green: CGFloat(177)/CGFloat(255), blue: CGFloat(177)/CGFloat(255), alpha: 1) }} + class var lightModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(167)/CGFloat(255), green: CGFloat(176)/CGFloat(255), blue: CGFloat(187)/CGFloat(255), alpha: 1) }} class var darkModeSpecialKey: UIColor { get { return UIColor.grayColor().colorWithAlphaComponent(CGFloat(0.3)) }} class var darkModeSolidColorSpecialKey: UIColor { get { return UIColor(red: CGFloat(45)/CGFloat(255), green: CGFloat(45)/CGFloat(255), blue: CGFloat(45)/CGFloat(255), alpha: 1) }} class var darkModeShiftKeyDown: UIColor { get { return UIColor(red: CGFloat(214)/CGFloat(255), green: CGFloat(220)/CGFloat(255), blue: CGFloat(208)/CGFloat(255), alpha: 1) }} @@ -315,9 +315,9 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { self.positionKeys(pageNum) // reset state - for (p, page) in enumerate(self.model.pages) { - for (_, row) in enumerate(page.rows) { - for (_, key) in enumerate(row) { + for (p, page) in self.model.pages.enumerate() { + for (_, row) in page.rows.enumerate() { + for (_, key) in row.enumerate() { if let keyView = self.modelToView[key] { keyView.hidePopup() keyView.highlighted = false @@ -356,25 +356,25 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { // pass 1: reuse any keys that match the required size for (key, frame) in keyMap { - if var keyView = self.pooledKey(key: key, model: self.model, frame: frame) { + if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) { foundCachedKeys.append(key) setupKey(keyView, key, frame) } } - foundCachedKeys.map { - keyMap.removeValueForKey($0) + for key in foundCachedKeys { + keyMap.removeValueForKey(key) } // pass 2: fill in the blanks for (key, frame) in keyMap { - var keyView = self.generateKey() + let keyView = self.generateKey() setupKey(keyView, key, frame) } } else { for (key, frame) in keyMap { - if var keyView = self.pooledKey(key: key, model: self.model, frame: frame) { + if let keyView = self.pooledKey(key: key, model: self.model, frame: frame) { setupKey(keyView, key, frame) } } @@ -466,8 +466,8 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { if model.type == Key.KeyType.Settings { if let imageKey = key as? ImageKey { if imageKey.image == nil { - var gearImage = UIImage(named: "gear") - var settingsImageView = UIImageView(image: gearImage) + let gearImage = UIImage(named: "gear") + let settingsImageView = UIImageView(image: gearImage) imageKey.image = settingsImageView } } @@ -588,9 +588,9 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { // TODO: O(N^2) in terms of total # of keys since pooledKey is called for each key, but probably doesn't matter var foundKey: Bool = false - for (pp, page) in enumerate(model.pages) { - for (rr, row) in enumerate(page.rows) { - for (kk, key) in enumerate(row) { + for (pp, page) in model.pages.enumerate() { + for (rr, row) in page.rows.enumerate() { + for (kk, key) in row.enumerate() { if key == aKey { p = pp r = rr @@ -650,7 +650,7 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { // if pool is disabled, always generates a new key func generateKey() -> KeyboardKey { let createAndSetupNewKey = { () -> KeyboardKey in - var keyView = self.createNewKey() + let keyView = self.createNewKey() keyView.enabled = true keyView.delegate = self @@ -720,13 +720,13 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { return shape } else { - var shape = shapeClass(frame: CGRectZero) + let shape = shapeClass.init(frame: CGRectZero) self.shapePool[className] = shape return shape } } else { - return shapeClass(frame: CGRectZero) + return shapeClass.init(frame: CGRectZero) } } @@ -763,14 +763,11 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { let rowGap: CGFloat = (isLandscape ? self.layoutConstants.rowGapLandscape : self.layoutConstants.rowGapPortrait(bounds.width)) let lastRowGap: CGFloat = (isLandscape ? rowGap : self.layoutConstants.rowGapPortraitLastRow(bounds.width)) - let flexibleEndRowM = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthMPortrait) - let flexibleEndRowC = (isLandscape ? self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCLandscape : self.layoutConstants.flexibleEndRowTotalWidthToKeyWidthCPortrait) - let lastRowLeftSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeFirstTwoButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitFirstTwoButtonAreaWidthToKeyboardAreaWidth) let lastRowRightSideRatio = (isLandscape ? self.layoutConstants.lastRowLandscapeLastButtonAreaWidthToKeyboardAreaWidth : self.layoutConstants.lastRowPortraitLastButtonAreaWidthToKeyboardAreaWidth) let lastRowKeyGap = (isLandscape ? self.layoutConstants.lastRowKeyGapLandscape(bounds.width) : self.layoutConstants.lastRowKeyGapPortrait) - for (p, page) in enumerate(model.pages) { + for (p, page) in model.pages.enumerate() { if p != pageToLayout { continue } @@ -779,7 +776,7 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { let mostKeysInRow: Int = { var currentMax: Int = 0 - for (i, row) in enumerate(page.rows) { + for (_, row) in page.rows.enumerate() { currentMax = max(currentMax, row.count) } return currentMax @@ -791,24 +788,24 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { let keyHeight: CGFloat = { let totalGaps = bottomEdge + topEdge + rowGapTotal - var returnHeight = (bounds.height - totalGaps) / CGFloat(numRows) + let returnHeight = (bounds.height - totalGaps) / CGFloat(numRows) return self.rounded(returnHeight) }() let letterKeyWidth: CGFloat = { let totalGaps = (sideEdges * CGFloat(2)) + (keyGap * CGFloat(mostKeysInRow - 1)) - var returnWidth = (bounds.width - totalGaps) / CGFloat(mostKeysInRow) + let returnWidth = (bounds.width - totalGaps) / CGFloat(mostKeysInRow) return self.rounded(returnWidth) }() let processRow = { (row: [Key], frames: [CGRect], inout map: [Key:CGRect]) -> Void in assert(row.count == frames.count, "row and frames don't match") - for (k, key) in enumerate(row) { + for (k, key) in row.enumerate() { map[key] = frames[k] } } - for (r, row) in enumerate(page.rows) { + for (r, row) in page.rows.enumerate() { let rowGapCurrentTotal = (r == page.rows.count - 1 ? rowGapTotal : CGFloat(r) * rowGap) let frame = CGRectMake(rounded(sideEdges), rounded(topEdge + (CGFloat(r) * keyHeight) + rowGapCurrentTotal), rounded(bounds.width - CGFloat(2) * sideEdges), rounded(keyHeight)) @@ -860,7 +857,7 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { var currentOrigin = frame.origin.x + sideSpace - for (k, key) in enumerate(row) { + for (_, _) in row.enumerate() { let roundedOrigin = rounded(currentOrigin) // avoiding rounding errors @@ -907,7 +904,7 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { let specialCharacterGap = sideSpace - specialCharacterWidth var currentOrigin = frame.origin.x - for (k, key) in enumerate(row) { + for (k, _) in row.enumerate() { if k == 0 { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, specialCharacterWidth, frame.height)) currentOrigin += (specialCharacterWidth + specialCharacterGap) @@ -937,7 +934,7 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { var keysBeforeSpace = 0 var keysAfterSpace = 0 var reachedSpace = false - for (k, key) in enumerate(row) { + for (_, key) in row.enumerate() { if key.type == Key.KeyType.Space { reachedSpace = true } @@ -975,7 +972,7 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { var currentOrigin = frame.origin.x var beforeSpace: Bool = true - for (k, key) in enumerate(row) { + for (k, key) in row.enumerate() { if key.type == Key.KeyType.Space { frames.append(CGRectMake(rounded(currentOrigin), frame.origin.y, spaceWidth, frame.height)) currentOrigin += (spaceWidth + gapWidth) @@ -1010,7 +1007,6 @@ class KeyboardLayout: NSObject, KeyboardKeyProtocol { let popupWidth = key.bounds.width + self.layoutConstants.popupWidthIncrement let popupHeight = totalHeight - self.layoutConstants.popupGap - key.bounds.height - let popupCenterY = 0 return CGRectMake((key.bounds.width - popupWidth) / CGFloat(2), -popupHeight - self.layoutConstants.popupGap, popupWidth, popupHeight) } diff --git a/Keyboard/KeyboardModel.swift b/Keyboard/KeyboardModel.swift index 5d901158..79f41a3a 100644 --- a/Keyboard/KeyboardModel.swift +++ b/Keyboard/KeyboardModel.swift @@ -36,7 +36,7 @@ class Keyboard { func addKey(key: Key, row: Int, page: Int) { if self.pages.count <= page { - for i in self.pages.count...page { + for _ in self.pages.count...page { self.pages.append(Page()) } } @@ -54,7 +54,7 @@ class Page { func addKey(key: Key, row: Int) { if self.rows.count <= row { - for i in self.rows.count...row { + for _ in self.rows.count...row { self.rows.append([]) } } diff --git a/Keyboard/KeyboardViewController.swift b/Keyboard/KeyboardViewController.swift index 4d7659b6..15117d8c 100644 --- a/Keyboard/KeyboardViewController.swift +++ b/Keyboard/KeyboardViewController.swift @@ -114,7 +114,7 @@ class KeyboardViewController: UIInputViewController { NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("defaultsChanged:"), name: NSUserDefaultsDidChangeNotification, object: nil) } - required init(coder: NSCoder) { + required init?(coder: NSCoder) { fatalError("NSCoding not supported") } @@ -126,7 +126,6 @@ class KeyboardViewController: UIInputViewController { } func defaultsChanged(notification: NSNotification) { - let defaults = notification.object as? NSUserDefaults self.updateKeyCaps(self.shiftState.uppercase()) } @@ -134,9 +133,9 @@ class KeyboardViewController: UIInputViewController { var kludge: UIView? func setupKludge() { if self.kludge == nil { - var kludge = UIView() + let kludge = UIView() self.view.addSubview(kludge) - kludge.setTranslatesAutoresizingMaskIntoConstraints(false) + kludge.translatesAutoresizingMaskIntoConstraints = false kludge.hidden = true let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0) @@ -171,7 +170,7 @@ class KeyboardViewController: UIInputViewController { var constraintsAdded: Bool = false func setupLayout() { if !constraintsAdded { - self.layout = self.dynamicType.layoutClass(model: self.keyboard, superview: self.forwardingView, layoutConstants: self.dynamicType.layoutConstants, globalColors: self.dynamicType.globalColors, darkMode: self.darkMode(), solidColorMode: self.solidColorMode()) + self.layout = self.dynamicType.layoutClass.init(model: self.keyboard, superview: self.forwardingView, layoutConstants: self.dynamicType.layoutConstants, globalColors: self.dynamicType.globalColors, darkMode: self.darkMode(), solidColorMode: self.solidColorMode()) self.layout?.initialize() self.setMode(0) @@ -179,7 +178,7 @@ class KeyboardViewController: UIInputViewController { self.setupKludge() self.updateKeyCaps(self.shiftState.uppercase()) - var capsWasSet = self.setCapsIfNeeded() + self.setCapsIfNeeded() self.updateAppearances(self.darkMode()) self.addInputTraitsObservers() @@ -190,13 +189,8 @@ class KeyboardViewController: UIInputViewController { // only available after frame becomes non-zero func darkMode() -> Bool { - var darkMode = { () -> Bool in - if let proxy = self.textDocumentProxy as? UITextDocumentProxy { - return proxy.keyboardAppearance == UIKeyboardAppearance.Dark - } - else { - return false - } + let darkMode = { () -> Bool in + return textDocumentProxy.keyboardAppearance == UIKeyboardAppearance.Dark }() return darkMode @@ -238,7 +232,7 @@ class KeyboardViewController: UIInputViewController { override func loadView() { super.loadView() - if var aBanner = self.createBanner() { + if let aBanner = self.createBanner() { aBanner.hidden = true self.view.insertSubview(aBanner, belowSubview: self.forwardingView) self.bannerView = aBanner @@ -311,7 +305,7 @@ class KeyboardViewController: UIInputViewController { case Key.KeyType.KeyboardChange: keyView.addTarget(self, action: "advanceTapped:", forControlEvents: .TouchUpInside) case Key.KeyType.Backspace: - let cancelEvents: UIControlEvents = UIControlEvents.TouchUpInside|UIControlEvents.TouchUpInside|UIControlEvents.TouchDragExit|UIControlEvents.TouchUpOutside|UIControlEvents.TouchCancel|UIControlEvents.TouchDragOutside + let cancelEvents: UIControlEvents = [UIControlEvents.TouchUpInside, UIControlEvents.TouchUpInside, UIControlEvents.TouchDragExit, UIControlEvents.TouchUpOutside, UIControlEvents.TouchCancel, UIControlEvents.TouchDragOutside] keyView.addTarget(self, action: "backspaceDown:", forControlEvents: .TouchDown) keyView.addTarget(self, action: "backspaceUp:", forControlEvents: cancelEvents) @@ -329,9 +323,9 @@ class KeyboardViewController: UIInputViewController { if key.isCharacter { if UIDevice.currentDevice().userInterfaceIdiom != UIUserInterfaceIdiom.Pad { - keyView.addTarget(self, action: Selector("showPopup:"), forControlEvents: .TouchDown | .TouchDragInside | .TouchDragEnter) - keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: .TouchDragExit | .TouchCancel) - keyView.addTarget(self, action: Selector("hidePopupDelay:"), forControlEvents: .TouchUpInside | .TouchUpOutside | .TouchDragOutside) + keyView.addTarget(self, action: Selector("showPopup:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter]) + keyView.addTarget(keyView, action: Selector("hidePopup"), forControlEvents: [.TouchDragExit, .TouchCancel]) + keyView.addTarget(self, action: Selector("hidePopupDelay:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside]) } } @@ -340,8 +334,8 @@ class KeyboardViewController: UIInputViewController { } if key.type != Key.KeyType.Shift && key.type != Key.KeyType.ModeChange { - keyView.addTarget(self, action: Selector("highlightKey:"), forControlEvents: .TouchDown | .TouchDragInside | .TouchDragEnter) - keyView.addTarget(self, action: Selector("unHighlightKey:"), forControlEvents: .TouchUpInside | .TouchUpOutside | .TouchDragOutside | .TouchDragExit | .TouchCancel) + keyView.addTarget(self, action: Selector("highlightKey:"), forControlEvents: [.TouchDown, .TouchDragInside, .TouchDragEnter]) + keyView.addTarget(self, action: Selector("unHighlightKey:"), forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchDragOutside, .TouchDragExit, .TouchCancel]) } keyView.addTarget(self, action: Selector("playKeySound"), forControlEvents: .TouchDown) @@ -394,7 +388,7 @@ class KeyboardViewController: UIInputViewController { } // TODO: this is currently not working as intended; only called when selection changed -- iOS bug - override func textDidChange(textInput: UITextInput) { + override func textDidChange(textInput: UITextInput?) { self.contextChanged() } @@ -413,7 +407,7 @@ class KeyboardViewController: UIInputViewController { attribute:NSLayoutAttribute.NotAnAttribute, multiplier:0, constant:height) - self.heightConstraint!.priority = 1000 + self.heightConstraint!.priority = 999 self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added? } @@ -457,8 +451,8 @@ class KeyboardViewController: UIInputViewController { // auto period on double space // TODO: timeout - var lastCharCountInBeforeContext: Int = 0 - var readyForDoubleSpacePeriod: Bool = true +// var lastCharCountInBeforeContext: Int = 0 +// var readyForDoubleSpacePeriod: Bool = true self.handleAutoPeriod(model) // TODO: reset context @@ -479,9 +473,9 @@ class KeyboardViewController: UIInputViewController { } let charactersAreInCorrectState = { () -> Bool in - let previousContext = (self.textDocumentProxy as? UITextDocumentProxy)?.documentContextBeforeInput + let previousContext = self.textDocumentProxy.documentContextBeforeInput - if previousContext == nil || count(previousContext!) < 3 { + if previousContext == nil || (previousContext!).characters.count < 3 { return false } @@ -507,10 +501,10 @@ class KeyboardViewController: UIInputViewController { }() if charactersAreInCorrectState { - (self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward() - (self.textDocumentProxy as? UITextDocumentProxy)?.deleteBackward() - (self.textDocumentProxy as? UITextDocumentProxy)?.insertText(".") - (self.textDocumentProxy as? UITextDocumentProxy)?.insertText(" ") + self.textDocumentProxy.deleteBackward() + self.textDocumentProxy.deleteBackward() + self.textDocumentProxy.insertText(".") + self.textDocumentProxy.insertText(" ") } self.autoPeriodState = .NoSpace @@ -530,15 +524,14 @@ class KeyboardViewController: UIInputViewController { } func backspaceDown(sender: KeyboardKey) { - self.cancelBackspaceTimers() + cancelBackspaceTimers() - if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { - textDocumentProxy.deleteBackward() - } - self.setCapsIfNeeded() + textDocumentProxy.deleteBackward() + setCapsIfNeeded() // trigger for subsequent deletes - self.backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false) + backspaceDelayTimer = NSTimer.scheduledTimerWithTimeInterval(backspaceDelay - backspaceRepeat, + target: self, selector: Selector("backspaceDelayCallback"), userInfo: nil, repeats: false) } func backspaceUp(sender: KeyboardKey) { @@ -551,12 +544,10 @@ class KeyboardViewController: UIInputViewController { } func backspaceRepeatCallback() { - self.playKeySound() + playKeySound() - if let textDocumentProxy = self.textDocumentProxy as? UIKeyInput { - textDocumentProxy.deleteBackward() - } - self.setCapsIfNeeded() + textDocumentProxy.deleteBackward() + setCapsIfNeeded() } func shiftDown(sender: KeyboardKey) { @@ -657,14 +648,14 @@ class KeyboardViewController: UIInputViewController { @IBAction func toggleSettings() { // lazy load settings if self.settingsView == nil { - if var aSettings = self.createSettings() { + if let aSettings = self.createSettings() { aSettings.darkMode = self.darkMode() aSettings.hidden = true self.view.addSubview(aSettings) self.settingsView = aSettings - aSettings.setTranslatesAutoresizingMaskIntoConstraints(false) + aSettings.translatesAutoresizingMaskIntoConstraints = false let widthConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0) let heightConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0) @@ -729,7 +720,7 @@ class KeyboardViewController: UIInputViewController { func stringIsWhitespace(string: String?) -> Bool { if string != nil { - for char in string! { + for char in (string!).characters { if !characterIsWhitespace(char) { return false } @@ -743,61 +734,54 @@ class KeyboardViewController: UIInputViewController { return false } - if let traits = self.textDocumentProxy as? UITextInputTraits { - if let autocapitalization = traits.autocapitalizationType { - var documentProxy = self.textDocumentProxy as? UITextDocumentProxy - var beforeContext = documentProxy?.documentContextBeforeInput - - switch autocapitalization { - case .None: - return false - case .Words: - if let beforeContext = documentProxy?.documentContextBeforeInput { - let previousCharacter = beforeContext[beforeContext.endIndex.predecessor()] - return self.characterIsWhitespace(previousCharacter) - } - else { - return true - } + if let autocapitalization = textDocumentProxy.autocapitalizationType { + + switch autocapitalization { + case .None: + return false + case .Words: + if let beforeContext = textDocumentProxy.documentContextBeforeInput { + let previousCharacter = beforeContext[beforeContext.endIndex.predecessor()] + return self.characterIsWhitespace(previousCharacter) + } + else { + return true + } - case .Sentences: - if let beforeContext = documentProxy?.documentContextBeforeInput { - let offset = min(3, count(beforeContext)) - var index = beforeContext.endIndex + case .Sentences: + if let beforeContext = textDocumentProxy.documentContextBeforeInput { + let offset = min(3, beforeContext.characters.count) + var index = beforeContext.endIndex + + for (var i = 0; i < offset; i += 1) { + index = index.predecessor() + let char = beforeContext[index] - for (var i = 0; i < offset; i += 1) { - index = index.predecessor() - let char = beforeContext[index] - - if characterIsPunctuation(char) { - if i == 0 { - return false //not enough spaces after punctuation - } - else { - return true //punctuation with at least one space after it - } + if characterIsPunctuation(char) { + if i == 0 { + return false //not enough spaces after punctuation } else { - if !characterIsWhitespace(char) { - return false //hit a foreign character before getting to 3 spaces - } - else if characterIsNewline(char) { - return true //hit start of line - } + return true //punctuation with at least one space after it + } + } + else { + if !characterIsWhitespace(char) { + return false //hit a foreign character before getting to 3 spaces + } + else if characterIsNewline(char) { + return true //hit start of line } } - - return true //either got 3 spaces or hit start of line - } - else { - return true } - case .AllCharacters: + + return true //either got 3 spaces or hit start of line + } + else { return true } - } - else { - return false + case .AllCharacters: + return true } } else { @@ -825,9 +809,7 @@ class KeyboardViewController: UIInputViewController { class var globalColors: GlobalColors.Type { get { return GlobalColors.self }} func keyPressed(key: Key) { - if let proxy = (self.textDocumentProxy as? UIKeyInput) { - proxy.insertText(key.outputForCase(self.shiftState.uppercase())) - } + textDocumentProxy.insertText(key.outputForCase(self.shiftState.uppercase())) } // a banner that sits in the empty space on top of the keyboard @@ -840,7 +822,7 @@ class KeyboardViewController: UIInputViewController { // a settings view that replaces the keyboard when the settings button is pressed func createSettings() -> ExtraView? { // note that dark mode is not yet valid here, so we just put false for clarity - var settingsView = DefaultSettings(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode()) + let settingsView = DefaultSettings(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode()) settingsView.backButton?.addTarget(self, action: Selector("toggleSettings"), forControlEvents: UIControlEvents.TouchUpInside) return settingsView } diff --git a/Keyboard/Shapes.swift b/Keyboard/Shapes.swift index b42e1c61..118ba435 100644 --- a/Keyboard/Shapes.swift +++ b/Keyboard/Shapes.swift @@ -16,7 +16,7 @@ import UIKit class BackspaceShape: Shape { override func drawCall(color: UIColor) { - drawBackspace(self.bounds, color) + drawBackspace(self.bounds, color: color) } } @@ -28,20 +28,20 @@ class ShiftShape: Shape { } override func drawCall(color: UIColor) { - drawShift(self.bounds, color, self.withLock) + drawShift(self.bounds, color: color, withRect: self.withLock) } } class GlobeShape: Shape { override func drawCall(color: UIColor) { - drawGlobe(self.bounds, color) + drawGlobe(self.bounds, color: color) } } class Shape: UIView { var color: UIColor? { didSet { - if let color = self.color { + if self.color != nil { self.overflowCanvas.setNeedsDisplay() } } @@ -64,7 +64,7 @@ class Shape: UIView { self.addSubview(self.overflowCanvas) } - required init(coder aDecoder: NSCoder) { + required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -104,13 +104,12 @@ class Shape: UIView { self.opaque = false } - required init(coder aDecoder: NSCoder) { + required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() - let csp = CGColorSpaceCreateDeviceRGB() CGContextSaveGState(ctx) @@ -131,7 +130,7 @@ class Shape: UIView { func getFactors(fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) { - var xSize = { () -> CGFloat in + let xSize = { () -> CGFloat in let scaledSize = (fromSize.width / CGFloat(2)) if scaledSize > toRect.width { return (toRect.width / scaledSize) / CGFloat(2) @@ -141,7 +140,7 @@ func getFactors(fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, y } }() - var ySize = { () -> CGFloat in + let ySize = { () -> CGFloat in let scaledSize = (fromSize.height / CGFloat(2)) if scaledSize > toRect.height { return (toRect.height / scaledSize) / CGFloat(2) @@ -171,12 +170,12 @@ func endCenter() { } func drawBackspace(bounds: CGRect, color: UIColor) { - let factors = getFactors(CGSizeMake(44, 32), bounds) + let factors = getFactors(CGSizeMake(44, 32), toRect: bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor - centerShape(CGSizeMake(44 * xScalingFactor, 32 * yScalingFactor), bounds) + centerShape(CGSizeMake(44 * xScalingFactor, 32 * yScalingFactor), toRect: bounds) //// Color Declarations @@ -184,7 +183,8 @@ func drawBackspace(bounds: CGRect, color: UIColor) { let color2 = UIColor.grayColor() // TODO: //// Bezier Drawing - var bezierPath = UIBezierPath() + let + bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 26 * yScalingFactor), controlPoint1: CGPointMake(38 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 32 * yScalingFactor)) @@ -199,7 +199,7 @@ func drawBackspace(bounds: CGRect, color: UIColor) { //// Bezier 2 Drawing - var bezier2Path = UIBezierPath() + let bezier2Path = UIBezierPath() bezier2Path.moveToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 22 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor)) @@ -212,7 +212,7 @@ func drawBackspace(bounds: CGRect, color: UIColor) { //// Bezier 3 Drawing - var bezier3Path = UIBezierPath() + let bezier3Path = UIBezierPath() bezier3Path.moveToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor)) bezier3Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 10 * yScalingFactor)) bezier3Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor)) @@ -227,19 +227,18 @@ func drawBackspace(bounds: CGRect, color: UIColor) { } func drawShift(bounds: CGRect, color: UIColor, withRect: Bool) { - let factors = getFactors(CGSizeMake(38, (withRect ? 34 + 4 : 32)), bounds) + let factors = getFactors(CGSizeMake(38, (withRect ? 34 + 4 : 32)), toRect: bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor - let lineWidthScalingFactor = factors.lineWidthScalingFactor - centerShape(CGSizeMake(38 * xScalingFactor, (withRect ? 34 + 4 : 32) * yScalingFactor), bounds) + centerShape(CGSizeMake(38 * xScalingFactor, (withRect ? 34 + 4 : 32) * yScalingFactor), toRect: bounds) //// Color Declarations let color2 = color //// Bezier Drawing - var bezierPath = UIBezierPath() + let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor)) @@ -268,26 +267,26 @@ func drawShift(bounds: CGRect, color: UIColor, withRect: Bool) { } func drawGlobe(bounds: CGRect, color: UIColor) { - let factors = getFactors(CGSizeMake(41, 40), bounds) + let factors = getFactors(CGSizeMake(41, 40), toRect: bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor - centerShape(CGSizeMake(41 * xScalingFactor, 40 * yScalingFactor), bounds) + centerShape(CGSizeMake(41 * xScalingFactor, 40 * yScalingFactor), toRect: bounds) //// Color Declarations let color = color //// Oval Drawing - var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0 * xScalingFactor, 0 * yScalingFactor, 40 * xScalingFactor, 40 * yScalingFactor)) + let ovalPath = UIBezierPath(ovalInRect: CGRectMake(0 * xScalingFactor, 0 * yScalingFactor, 40 * xScalingFactor, 40 * yScalingFactor)) color.setStroke() ovalPath.lineWidth = 1 * lineWidthScalingFactor ovalPath.stroke() //// Bezier Drawing - var bezierPath = UIBezierPath() + let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, 40 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor)) @@ -298,7 +297,7 @@ func drawGlobe(bounds: CGRect, color: UIColor) { //// Bezier 2 Drawing - var bezier2Path = UIBezierPath() + let bezier2Path = UIBezierPath() bezier2Path.moveToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(39.5 * xScalingFactor, 19.5 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor)) @@ -309,10 +308,10 @@ func drawGlobe(bounds: CGRect, color: UIColor) { //// Bezier 3 Drawing - var bezier3Path = UIBezierPath() + let bezier3Path = UIBezierPath() bezier3Path.moveToPoint(CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor)) bezier3Path.addCurveToPoint(CGPointMake(21.63 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor), controlPoint2: CGPointMake(41 * xScalingFactor, 19 * yScalingFactor)) - bezier3Path.lineCapStyle = kCGLineCapRound; + bezier3Path.lineCapStyle = CGLineCap.Round; color.setStroke() bezier3Path.lineWidth = 1 * lineWidthScalingFactor @@ -320,10 +319,10 @@ func drawGlobe(bounds: CGRect, color: UIColor) { //// Bezier 4 Drawing - var bezier4Path = UIBezierPath() + let bezier4Path = UIBezierPath() bezier4Path.moveToPoint(CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor)) bezier4Path.addCurveToPoint(CGPointMake(18.72 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor), controlPoint2: CGPointMake(-2.5 * xScalingFactor, 19.04 * yScalingFactor)) - bezier4Path.lineCapStyle = kCGLineCapRound; + bezier4Path.lineCapStyle = CGLineCap.Round; color.setStroke() bezier4Path.lineWidth = 1 * lineWidthScalingFactor @@ -331,10 +330,10 @@ func drawGlobe(bounds: CGRect, color: UIColor) { //// Bezier 5 Drawing - var bezier5Path = UIBezierPath() + let bezier5Path = UIBezierPath() bezier5Path.moveToPoint(CGPointMake(6 * xScalingFactor, 7 * yScalingFactor)) bezier5Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 7 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 7 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 21 * yScalingFactor)) - bezier5Path.lineCapStyle = kCGLineCapRound; + bezier5Path.lineCapStyle = CGLineCap.Round; color.setStroke() bezier5Path.lineWidth = 1 * lineWidthScalingFactor @@ -342,10 +341,10 @@ func drawGlobe(bounds: CGRect, color: UIColor) { //// Bezier 6 Drawing - var bezier6Path = UIBezierPath() + let bezier6Path = UIBezierPath() bezier6Path.moveToPoint(CGPointMake(6 * xScalingFactor, 33 * yScalingFactor)) bezier6Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 33 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 33 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 22 * yScalingFactor)) - bezier6Path.lineCapStyle = kCGLineCapRound; + bezier6Path.lineCapStyle = CGLineCap.Round; color.setStroke() bezier6Path.lineWidth = 1 * lineWidthScalingFactor diff --git a/Keyboard/Utilities.swift b/Keyboard/Utilities.swift index 4898d4c8..de772380 100644 --- a/Keyboard/Utilities.swift +++ b/Keyboard/Utilities.swift @@ -40,7 +40,7 @@ func memoize(fn : T -> U) -> T -> U { var cache = [T:U]() return { (val : T) -> U in - var value = cache[val] + let value = cache[val] if value != nil { return value! } else {