Skip to content

Commit

Permalink
#96 add SwiftyJSON for data and refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewtavis committed Oct 14, 2022
1 parent 011b1b3 commit 7138b9f
Show file tree
Hide file tree
Showing 14 changed files with 209 additions and 77 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ Emojis for the following are chosen based on [gitmoji](https://gitmoji.dev/).

- The labels for conjugations and declinations have been made darker in dark mode to be more readable.

### ♻️ Code Refactoring

- Loading JSONs for language data is now handled by SwiftyJSON, with the code being refactored to implement it.
- This is a first step in refining the data loading process to better handle large amounts of data.

# Scribe-iOS 2.0.0

### ✨ New Features
Expand Down
76 changes: 36 additions & 40 deletions Keyboards/KeyboardsBase/KeyboardViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -291,41 +291,37 @@ class KeyboardViewController: UIInputViewController {
} else {
/// We have to consider these different cases as the key always has to match.
/// Else, even if the lowercased prefix is present in the dictionary, if the actual prefix isn't present we won't get an output.
if let autosuggestions = autosuggestions {
if autosuggestions.keys.contains(prefix.lowercased()) {
let suggestions = autosuggestions[prefix.lowercased()] as! [String]
completionWords = [String]()
var i = 0
while i < 3 {
if shiftButtonState == .shift {
completionWords.append(suggestions[i].capitalize())
} else if shiftButtonState == .caps {
completionWords.append(suggestions[i].uppercased())
} else {
if !(nouns?.keys.contains(suggestions[i]) ?? true) {
completionWords.append(suggestions[i].lowercased())
} else {
completionWords.append(suggestions[i])
}
}
i += 1
}
} else if autosuggestions.keys.contains(prefix.capitalize()) {
let suggestions = autosuggestions[prefix.capitalize()] as! [String]
completionWords = [String]()
var i = 0
while i < 3 {
if shiftButtonState == .shift {
completionWords.append(suggestions[i].capitalize())
} else if shiftButtonState == .caps {
completionWords.append(suggestions[i].uppercased())
if autosuggestions[prefix.lowercased()].exists() {
let suggestions: [String] = autosuggestions[prefix.lowercased()].rawValue as! [String]
completionWords = [String]()
var i = 0
while i < 3 {
if shiftButtonState == .shift {
completionWords.append(suggestions[i].capitalize())
} else if shiftButtonState == .caps {
completionWords.append(suggestions[i].uppercased())
} else {
if !nouns[suggestions[i]].exists() {
completionWords.append(suggestions[i].lowercased())
} else {
completionWords.append(suggestions[i])
}
i += 1
}
} else {
getDefaultAutosuggestions()
i += 1
}
} else if autosuggestions[prefix.capitalize()].exists() {
let suggestions: [String] = autosuggestions[prefix.capitalize()].rawValue as! [String]
completionWords = [String]()
var i = 0
while i < 3 {
if shiftButtonState == .shift {
completionWords.append(suggestions[i].capitalize())
} else if shiftButtonState == .caps {
completionWords.append(suggestions[i].uppercased())
} else {
completionWords.append(suggestions[i])
}
i += 1
}
} else {
getDefaultAutosuggestions()
Expand Down Expand Up @@ -969,11 +965,11 @@ class KeyboardViewController: UIInputViewController {

// Populate conjugation view buttons.
for index in 0..<allConjugations.count {
if verbs?[verbToConjugate]![allConjugations[index]] as? String == "" {
if verbs[verbToConjugate][allConjugations[index]].string == "" {
// Assign the invalid message if the conjugation isn't present in the directory.
styleBtn(btn: allConjugationBtns[index], title: invalidCommandMsg, radius: keyCornerRadius)
} else {
conjugationToDisplay = verbs?[verbToConjugate]![allConjugations[index]] as! String
conjugationToDisplay = verbs[verbToConjugate][allConjugations[index]].string!
if inputWordIsCapitalized && deConjugationState != .indicativePerfect {
conjugationToDisplay = conjugationToDisplay.capitalized
}
Expand Down Expand Up @@ -1075,15 +1071,15 @@ class KeyboardViewController: UIInputViewController {
allNonSpecialKeys = allKeys.filter { !specialKeys.contains($0) }

// Make sure that Scribe shows up in auto actions.
nouns?["Scribe"] = [
nouns["Scribe"] = [
"plural": "Scribes",
"form": ""
] as AnyObject
]

var uniqueAutosuggestKeys: [String] = [String]()
for elem in Array(autosuggestions!.keys) {
if elem.count > 2 && !nouns!.keys.contains(elem) {
if autosuggestions!.keys.contains(elem.lowercased())
for elem in autosuggestions.dictionaryValue.keys {
if elem.count > 2 && !nouns[elem].exists() {
if autosuggestions[elem.lowercased()].exists()
&& !uniqueAutosuggestKeys.contains(elem.lowercased()) {
uniqueAutosuggestKeys.append(elem.lowercased())
} else if
Expand All @@ -1095,7 +1091,7 @@ class KeyboardViewController: UIInputViewController {
}
}
}
autocompleteWords = Array(nouns!.keys) + uniqueAutosuggestKeys
autocompleteWords = Array(nouns.dictionaryValue.keys) + uniqueAutosuggestKeys
autocompleteWords = autocompleteWords.filter(
{ $0.rangeOfCharacter(from: CharacterSet(charactersIn: "1234567890-")) == nil }
).sorted{$0.caseInsensitiveCompare($1) == .orderedAscending}
Expand Down Expand Up @@ -1713,7 +1709,7 @@ class KeyboardViewController: UIInputViewController {
wordToCheck = lastWordTyped!
}
}
isPrep = prepositions?[wordToCheck.lowercased()] != nil
isPrep = prepositions[wordToCheck.lowercased()].exists()
if isPrep {
resetCaseDeclensionState()
commandState = .selectCaseDeclension
Expand Down
17 changes: 6 additions & 11 deletions Keyboards/KeyboardsBase/LoadData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,15 @@
//

import Foundation
import SwiftyJSON

/// Loads a JSON file that contains grammatical information into a dictionary.
///
/// - Parameters
/// - filename: the name of the JSON file to be loaded.
func loadJSONToDict(filename fileName: String) -> [String: AnyObject]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let jsonData = try JSONSerialization.jsonObject(with: data)
return jsonData as? [String: AnyObject]
} catch {
print("error:\(error)")
}
}
return nil
func loadJSON(filename fileName: String) -> JSON {
let url = Bundle.main.url(forResource: fileName, withExtension: "json")!
let data = NSData(contentsOf: url)
let jsonData = try! JSON(data: data! as Data)
return jsonData
}
16 changes: 8 additions & 8 deletions Keyboards/KeyboardsBase/ScribeFunctionality/Annotate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ func selectedWordAnnotation(_ KVC: KeyboardViewController) {
wordToCheck = wordToCheck.lowercased()
}

isNoun = nouns?[wordToCheck] != nil
isPrep = prepositions?[wordToCheck.lowercased()] != nil
isNoun = nouns[wordToCheck].exists()
isPrep = prepositions[wordToCheck.lowercased()].exists()

annotationsToAssign = [String]()
annotationBtns = [UIButton]()
Expand Down Expand Up @@ -73,7 +73,7 @@ func selectedWordAnnotation(_ KVC: KeyboardViewController) {
setBtn(btn: annotationBtn, color: commandKeyColor, name: "ScribeAnnotation", canCap: false, isSpecial: false)
} else {
if isNoun {
let nounAnnotationForm: String = nouns?[wordToCheck]?["form"] as! String
let nounAnnotationForm: String = nouns[wordToCheck]["form"].string ?? ""
if nounAnnotationForm != "" {
if !nounAnnotationForm.contains("/") {
annotationsToAssign.append(nounAnnotationForm)
Expand All @@ -87,7 +87,7 @@ func selectedWordAnnotation(_ KVC: KeyboardViewController) {

if isPrep {
activateAnnotationBtn = true
prepAnnotationForm = prepositions?[wordToCheck.lowercased()] as! String
prepAnnotationForm = prepositions[wordToCheck.lowercased()].string ?? ""
if prepAnnotationForm != "" {
if !prepAnnotationForm.contains("/") {
annotationsToAssign.append(prepAnnotationForm)
Expand Down Expand Up @@ -199,8 +199,8 @@ func typedWordAnnotation(_ KVC: KeyboardViewController) {
wordToCheck = lastWordTyped!
}

isNoun = nouns?[wordToCheck] != nil
isPrep = prepositions?[wordToCheck.lowercased()] != nil
isNoun = nouns[wordToCheck].exists()
isPrep = prepositions[wordToCheck.lowercased()].exists()

annotationsToAssign = [String]()
annotationBtns = [UIButton]()
Expand Down Expand Up @@ -238,7 +238,7 @@ func typedWordAnnotation(_ KVC: KeyboardViewController) {
setBtn(btn: annotationBtn, color: commandKeyColor, name: "ScribeAnnotation", canCap: false, isSpecial: false)
} else {
if isNoun {
let nounAnnotationForm: String = nouns?[wordToCheck]?["form"] as! String
let nounAnnotationForm: String = nouns[wordToCheck]["form"].string ?? ""
if nounAnnotationForm != "" {
if !nounAnnotationForm.contains("/") {
annotationsToAssign.append(nounAnnotationForm)
Expand All @@ -252,7 +252,7 @@ func typedWordAnnotation(_ KVC: KeyboardViewController) {

if isPrep {
activateAnnotationBtn = true
prepAnnotationForm = prepositions?[wordToCheck.lowercased()] as! String
prepAnnotationForm = prepositions[wordToCheck.lowercased()].string ?? ""
if prepAnnotationForm != "" {
if !prepAnnotationForm.contains("/") {
annotationsToAssign.append(prepAnnotationForm)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ var backspaceTimer: Timer?
var scribeKeyHeight = CGFloat(0)

// All data needed for Scribe commands for the given language keyboard.
var nouns = loadJSONToDict(filename: "nouns")
let verbs = loadJSONToDict(filename: "verbs")
let translations = loadJSONToDict(filename: "translations")
let prepositions = loadJSONToDict(filename: "prepositions")
let autosuggestions = loadJSONToDict(filename: "autosuggestions")
var nouns = loadJSON(filename: "nouns")
let verbs = loadJSON(filename: "verbs")
let translations = loadJSON(filename: "translations")
let prepositions = loadJSON(filename: "prepositions")
let autosuggestions = loadJSON(filename: "autosuggestions")

// Words that should not be included in autocomplete should be added to the string below.
var autocompleteWords = [String]()
Expand Down
8 changes: 4 additions & 4 deletions Keyboards/KeyboardsBase/ScribeFunctionality/Conjugate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func triggerVerbConjugation(commandBar: UILabel) -> Bool {
inputWordIsCapitalized = firstLetter.isUppercase
verbToConjugate = verbToConjugate.lowercased()

return verbs?[verbToConjugate] != nil
return verbs[verbToConjugate].exists()
}

/// Returns a conjugation once a user presses a key in the conjugateView or triggers a declension.
Expand All @@ -211,17 +211,17 @@ func returnConjugation(keyPressed: UIButton, requestedForm: String) {
proxy.insertText("")
} else if formsDisplayDimensions == .view3x2 {
if deConjugationState != .indicativePerfect {
wordToReturn = verbs?[verbToConjugate]![requestedForm] as! String
wordToReturn = verbs[verbToConjugate][requestedForm].string ?? ""
if inputWordIsCapitalized == true {
proxy.insertText(wordToReturn.capitalized + " ")
} else {
proxy.insertText(wordToReturn + " ")
}
} else {
proxy.insertText(verbs?[verbToConjugate]!["pastParticiple"] as! String + " ")
proxy.insertText(verbs[verbToConjugate]["pastParticiple"].string ?? "" + " ")
}
} else if formsDisplayDimensions == .view2x2 {
wordToReturn = verbs?[verbToConjugate]![requestedForm] as! String
wordToReturn = verbs[verbToConjugate][requestedForm].string ?? ""
if inputWordIsCapitalized == true {
proxy.insertText(wordToReturn.capitalized + " ")
} else {
Expand Down
6 changes: 3 additions & 3 deletions Keyboards/KeyboardsBase/ScribeFunctionality/Plural.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ func queryPlural(commandBar: UILabel) {
inputWordIsCapitalized = firstLetter.isUppercase
noun = noun.lowercased()
}
let nounInDirectory = nouns?[noun] != nil
let nounInDirectory = nouns[noun].exists()
if nounInDirectory {
if nouns?[noun]?["plural"] as? String != "isPlural" {
guard let plural = nouns?[noun]?["plural"] as? String else { return }
if nouns[noun]["plural"].string != "isPlural" {
guard let plural: String = nouns[noun]["plural"].string else { return }
if inputWordIsCapitalized == false {
proxy.insertText(plural + " ")
} else {
Expand Down
4 changes: 2 additions & 2 deletions Keyboards/KeyboardsBase/ScribeFunctionality/Translate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ func queryTranslation(commandBar: UILabel) {
inputWordIsCapitalized = firstLetter.isUppercase
wordToTranslate = wordToTranslate.lowercased()

let wordInDirectory = translations?[wordToTranslate] != nil
let wordInDirectory = translations[wordToTranslate].exists()
if wordInDirectory {
wordToReturn = translations?[wordToTranslate] as! String
wordToReturn = translations[wordToTranslate].string ?? ""
if inputWordIsCapitalized {
proxy.insertText(wordToReturn.capitalized + " ")
} else {
Expand Down
1 change: 1 addition & 0 deletions Keyboards/LanguageKeyboards/French/Data/prepositions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions Keyboards/LanguageKeyboards/Italian/Data/prepositions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions Keyboards/LanguageKeyboards/Spanish/Data/prepositions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions Keyboards/LanguageKeyboards/Swedish/Data/prepositions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
Loading

0 comments on commit 7138b9f

Please sign in to comment.