Xcode // AppCode quality check (Swift).

This commit is contained in:
ShikiSuen 2022-04-11 16:01:53 +08:00
parent 9e072bc47e
commit 9e5ced8055
29 changed files with 101 additions and 97 deletions

View File

@ -78,7 +78,7 @@ class AppDelegate: NSWindowController, NSApplicationDelegate {
return return
} }
self.installingVersion = installingVersion self.installingVersion = installingVersion
self.archiveUtil = ArchiveUtil(appName: kTargetBin, targetAppBundleName: kTargetBundle) archiveUtil = ArchiveUtil(appName: kTargetBin, targetAppBundleName: kTargetBundle)
_ = archiveUtil?.validateIfNotarizedArchiveExists() _ = archiveUtil?.validateIfNotarizedArchiveExists()
cancelButton.nextKeyView = installButton cancelButton.nextKeyView = installButton
@ -153,7 +153,7 @@ class AppDelegate: NSWindowController, NSApplicationDelegate {
atPath: (kTargetPartialPath as NSString).expandingTildeInPath) atPath: (kTargetPartialPath as NSString).expandingTildeInPath)
== false == false
{ {
self.installInputMethod( installInputMethod(
previousExists: false, previousVersionNotFullyDeactivatedWarning: false) previousExists: false, previousVersionNotFullyDeactivatedWarning: false)
return return
} }
@ -208,7 +208,7 @@ class AppDelegate: NSWindowController, NSApplicationDelegate {
timeInterval: kTranslocationRemovalTickInterval, target: self, timeInterval: kTranslocationRemovalTickInterval, target: self,
selector: #selector(timerTick(_:)), userInfo: nil, repeats: true) selector: #selector(timerTick(_:)), userInfo: nil, repeats: true)
} else { } else {
self.installInputMethod( installInputMethod(
previousExists: false, previousVersionNotFullyDeactivatedWarning: false) previousExists: false, previousVersionNotFullyDeactivatedWarning: false)
} }
} }

View File

@ -83,7 +83,7 @@ struct ArchiveUtil {
} }
func unzipNotarizedArchive() -> String? { func unzipNotarizedArchive() -> String? {
if !self.validateIfNotarizedArchiveExists() { if !validateIfNotarizedArchiveExists() {
return nil return nil
} }
guard let notarizedArchive = notarizedArchive, guard let notarizedArchive = notarizedArchive,

View File

@ -18,13 +18,13 @@ class ConversionDictionary {
guard let dict = CCDictCreateMarisaWithPath(path) else { guard let dict = CCDictCreateMarisaWithPath(path) else {
throw ConversionError(ccErrorno) throw ConversionError(ccErrorno)
} }
self.group = [] group = []
self.dict = dict self.dict = dict
} }
init(group: [ConversionDictionary]) { init(group: [ConversionDictionary]) {
var rawGroup = group.map { $0.dict } var rawGroup = group.map { $0.dict }
self.group = group self.group = group
self.dict = CCDictCreateWithGroup(&rawGroup, rawGroup.count) dict = CCDictCreateWithGroup(&rawGroup, rawGroup.count)
} }
} }

View File

@ -30,7 +30,7 @@ extension ChineseConverter {
throw ConversionError.fileNotFound throw ConversionError.fileNotFound
} }
return try DictionaryLoader.dictCache.value(for: path) { return try DictionaryLoader.dictCache.value(for: path) {
return try ConversionDictionary(path: path) try ConversionDictionary(path: path)
} }
} }
} }
@ -44,15 +44,15 @@ extension ChineseConverter.DictionaryLoader {
} }
func conversionChain(options: ChineseConverter.Options) throws -> [ConversionDictionary] { func conversionChain(options: ChineseConverter.Options) throws -> [ConversionDictionary] {
return try options.conversionChain.compactMap { names in try options.conversionChain.compactMap { names in
switch names.count { switch names.count {
case 0: case 0:
return nil return nil
case 1: case 1:
return try dict(names.first!) return try dict(names.first!)
case _: case _:
let dicts = try names.map(dict) let dicts = try names.map(dict)
return ConversionDictionary(group: dicts) return ConversionDictionary(group: dicts)
} }
} }
} }

View File

@ -23,7 +23,7 @@ class WeakValueCache<Key: Hashable, Value: AnyObject> {
private var lock = NSLock() private var lock = NSLock()
func value(for key: Key) -> Value? { func value(for key: Key) -> Value? {
return storage[key]?.value storage[key]?.value
} }
func value(for key: Key, make: () throws -> Value) rethrows -> Value { func value(for key: Key, make: () throws -> Value) rethrows -> Value {

View File

@ -16,7 +16,7 @@ let testCases: [(String, ChineseConverter.Options)] = [
class OpenCCTests: XCTestCase { class OpenCCTests: XCTestCase {
func converter(option: ChineseConverter.Options) throws -> ChineseConverter { func converter(option: ChineseConverter.Options) throws -> ChineseConverter {
return try ChineseConverter(options: option) try ChineseConverter(options: option)
} }
func testConversion() throws { func testConversion() throws {

View File

@ -56,7 +56,7 @@ extension Preferences {
minimumLabelWidth: Double = 0, minimumLabelWidth: Double = 0,
@SectionBuilder builder: @escaping () -> [Section] @SectionBuilder builder: @escaping () -> [Section]
) { ) {
self.sectionBuilder = builder sectionBuilder = builder
self.contentWidth = contentWidth self.contentWidth = contentWidth
self.minimumLabelWidth = minimumLabelWidth self.minimumLabelWidth = minimumLabelWidth
} }

View File

@ -52,7 +52,7 @@ extension Preferences {
self.identifier = identifier self.identifier = identifier
self.title = title self.title = title
self.toolbarIcon = toolbarIcon self.toolbarIcon = toolbarIcon
self.content = contentView() content = contentView()
} }
public var body: some View { content } public var body: some View { content }
@ -76,9 +76,9 @@ extension Preferences {
toolbarIcon: NSImage, toolbarIcon: NSImage,
content: Content content: Content
) { ) {
self.preferencePaneIdentifier = identifier preferencePaneIdentifier = identifier
self.preferencePaneTitle = title preferencePaneTitle = title
self.toolbarItemIcon = toolbarIcon toolbarItemIcon = toolbarIcon
super.init(rootView: content) super.init(rootView: content)
} }

View File

@ -78,6 +78,7 @@ extension Preferences {
- Parameters: - Parameters:
- bottomDivider: Whether to place a `Divider` after the section content. Default is `false`. - bottomDivider: Whether to place a `Divider` after the section content. Default is `false`.
- verticalAlignement: The vertical alignment of the section content. - verticalAlignement: The vertical alignment of the section content.
- verticalAlignment:
- label: A view describing preference handled by this section. - label: A view describing preference handled by this section.
- content: A content view. - content: A content view.
*/ */
@ -103,6 +104,7 @@ extension Preferences {
- title: A string describing preference handled by this section. - title: A string describing preference handled by this section.
- bottomDivider: Whether to place a `Divider` after the section content. Default is `false`. - bottomDivider: Whether to place a `Divider` after the section content. Default is `false`.
- verticalAlignement: The vertical alignment of the section content. - verticalAlignement: The vertical alignment of the section content.
- verticalAlignment:
- content: A content view. - content: A content view.
*/ */
public init<Content: View>( public init<Content: View>(

View File

@ -18,7 +18,7 @@ struct ComboBox: NSViewRepresentable {
@Binding var text: String @Binding var text: String
func makeCoordinator() -> Coordinator { func makeCoordinator() -> Coordinator {
return Coordinator(self) Coordinator(self)
} }
func makeNSView(context: Context) -> NSComboBox { func makeNSView(context: Context) -> NSComboBox {

View File

@ -127,13 +127,13 @@ class AppDelegate: NSObject, NSApplicationDelegate, ctlNonModalAlertWindowDelega
checkTask = VersionUpdateApi.check(forced: forced) { [self] result in checkTask = VersionUpdateApi.check(forced: forced) { [self] result in
defer { defer {
self.checkTask = nil checkTask = nil
} }
switch result { switch result {
case .success(let apiResult): case .success(let apiResult):
switch apiResult { switch apiResult {
case .shouldUpdate(let report): case .shouldUpdate(let report):
self.updateNextStepURL = report.siteUrl updateNextStepURL = report.siteUrl
let content = String( let content = String(
format: NSLocalizedString( format: NSLocalizedString(
"You're currently using vChewing %@ (%@), a new version %@ (%@) is now available. Do you want to visit vChewing's website to download the version?%@", "You're currently using vChewing %@ (%@), a new version %@ (%@) is now available. Do you want to visit vChewing's website to download the version?%@",
@ -144,7 +144,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, ctlNonModalAlertWindowDelega
report.remoteVersion, report.remoteVersion,
report.versionDescription) report.versionDescription)
IME.prtDebugIntel("vChewingDebug: \(content)") IME.prtDebugIntel("vChewingDebug: \(content)")
self.currentAlertType = "Update" currentAlertType = "Update"
ctlNonModalAlertWindow.shared.show( ctlNonModalAlertWindow.shared.show(
title: NSLocalizedString( title: NSLocalizedString(
"New Version Available", comment: ""), "New Version Available", comment: ""),
@ -170,7 +170,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, ctlNonModalAlertWindowDelega
comment: ""), message) comment: ""), message)
let buttonTitle = NSLocalizedString("Dismiss", comment: "") let buttonTitle = NSLocalizedString("Dismiss", comment: "")
IME.prtDebugIntel("vChewingDebug: \(content)") IME.prtDebugIntel("vChewingDebug: \(content)")
self.currentAlertType = "Update" currentAlertType = "Update"
ctlNonModalAlertWindow.shared.show( ctlNonModalAlertWindow.shared.show(
title: title, content: content, title: title, content: content,
confirmButtonTitle: buttonTitle, confirmButtonTitle: buttonTitle,
@ -185,7 +185,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, ctlNonModalAlertWindowDelega
} }
func selfUninstall() { func selfUninstall() {
self.currentAlertType = "Uninstall" currentAlertType = "Uninstall"
let content = String( let content = String(
format: NSLocalizedString( format: NSLocalizedString(
"This will remove vChewing Input Method from this user account, requiring your confirmation.", "This will remove vChewing Input Method from this user account, requiring your confirmation.",
@ -199,25 +199,25 @@ class AppDelegate: NSObject, NSApplicationDelegate, ctlNonModalAlertWindowDelega
} }
func ctlNonModalAlertWindowDidConfirm(_ controller: ctlNonModalAlertWindow) { func ctlNonModalAlertWindowDidConfirm(_ controller: ctlNonModalAlertWindow) {
switch self.currentAlertType { switch currentAlertType {
case "Uninstall": case "Uninstall":
NSWorkspace.shared.openFile( NSWorkspace.shared.openFile(
mgrLangModel.dataFolderPath(isDefaultFolder: true), withApplication: "Finder") mgrLangModel.dataFolderPath(isDefaultFolder: true), withApplication: "Finder")
IME.uninstall(isSudo: false, selfKill: true) IME.uninstall(isSudo: false, selfKill: true)
case "Update": case "Update":
if let updateNextStepURL = self.updateNextStepURL { if let updateNextStepURL = updateNextStepURL {
NSWorkspace.shared.open(updateNextStepURL) NSWorkspace.shared.open(updateNextStepURL)
} }
self.updateNextStepURL = nil updateNextStepURL = nil
default: default:
break break
} }
} }
func ctlNonModalAlertWindowDidCancel(_ controller: ctlNonModalAlertWindow) { func ctlNonModalAlertWindowDidCancel(_ controller: ctlNonModalAlertWindow) {
switch self.currentAlertType { switch currentAlertType {
case "Update": case "Update":
self.updateNextStepURL = nil updateNextStepURL = nil
default: default:
break break
} }

View File

@ -24,7 +24,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Cocoa import Cocoa
@objc class AppleKeyboardConverter: NSObject { class AppleKeyboardConverter: NSObject {
static let arrDynamicBasicKeyLayout: [String] = [ static let arrDynamicBasicKeyLayout: [String] = [
"com.apple.keylayout.ZhuyinBopomofo", "com.apple.keylayout.ZhuyinBopomofo",
"com.apple.keylayout.ZhuyinEten", "com.apple.keylayout.ZhuyinEten",
@ -40,13 +40,13 @@ import Cocoa
"org.unknown.keylayout.vChewingMiTAC", "org.unknown.keylayout.vChewingMiTAC",
] ]
@objc class func isDynamicBasicKeyboardLayoutEnabled() -> Bool { @objc class func isDynamicBasicKeyboardLayoutEnabled() -> Bool {
return AppleKeyboardConverter.arrDynamicBasicKeyLayout.contains(mgrPrefs.basicKeyboardLayout) AppleKeyboardConverter.arrDynamicBasicKeyLayout.contains(mgrPrefs.basicKeyboardLayout)
} }
// Apple // Apple
@objc class func cnvApple2ABC(_ charCode: UniChar) -> UniChar { @objc class func cnvApple2ABC(_ charCode: UniChar) -> UniChar {
var charCode = charCode var charCode = charCode
// OVMandarin OVMandarin // OVMandarin OVMandarin
if self.isDynamicBasicKeyboardLayoutEnabled() { if isDynamicBasicKeyboardLayoutEnabled() {
// Apple // Apple
switch mgrPrefs.basicKeyboardLayout { switch mgrPrefs.basicKeyboardLayout {
case "com.apple.keylayout.ZhuyinBopomofo": case "com.apple.keylayout.ZhuyinBopomofo":
@ -186,7 +186,7 @@ import Cocoa
@objc class func cnvStringApple2ABC(_ strProcessed: String) -> String { @objc class func cnvStringApple2ABC(_ strProcessed: String) -> String {
var strProcessed = strProcessed var strProcessed = strProcessed
if self.isDynamicBasicKeyboardLayoutEnabled() { if isDynamicBasicKeyboardLayoutEnabled() {
// Apple // Apple
switch mgrPrefs.basicKeyboardLayout { switch mgrPrefs.basicKeyboardLayout {
case "com.apple.keylayout.ZhuyinBopomofo": case "com.apple.keylayout.ZhuyinBopomofo":

View File

@ -410,7 +410,7 @@ class InputState: NSObject {
} }
@objc class SymbolNode: NSObject { class SymbolNode: NSObject {
@objc var title: String @objc var title: String
@objc var children: [SymbolNode]? @objc var children: [SymbolNode]?
@ -422,7 +422,7 @@ class InputState: NSObject {
@objc init(_ title: String, symbols: String) { @objc init(_ title: String, symbols: String) {
self.title = title self.title = title
self.children = Array(symbols).map { SymbolNode(String($0), nil) } children = Array(symbols).map { SymbolNode(String($0), nil) }
super.init() super.init()
} }

View File

@ -116,7 +116,7 @@ class keyParser: NSObject {
self.inputText = inputText self.inputText = inputText
self.inputTextIgnoringModifiers = inputTextIgnoringModifiers self.inputTextIgnoringModifiers = inputTextIgnoringModifiers
self.flags = flags self.flags = flags
self.isFlagChanged = false isFlagChanged = false
useVerticalMode = isVerticalMode useVerticalMode = isVerticalMode
self.keyCode = keyCode self.keyCode = keyCode
self.charCode = AppleKeyboardConverter.cnvApple2ABC(charCode) self.charCode = AppleKeyboardConverter.cnvApple2ABC(charCode)
@ -295,7 +295,7 @@ class keyParser: NSObject {
@objc var isUpperCaseASCIILetterKey: Bool { @objc var isUpperCaseASCIILetterKey: Bool {
// flags == .shift Shift // flags == .shift Shift
self.charCode >= 65 && self.charCode <= 90 && flags == .shift charCode >= 65 && charCode <= 90 && flags == .shift
} }
@objc var isSymbolMenuPhysicalKey: Bool { @objc var isSymbolMenuPhysicalKey: Bool {

View File

@ -30,7 +30,7 @@ extension String {
} }
} }
@objc class vChewingKanjiConverter: NSObject { class vChewingKanjiConverter: NSObject {
@objc class func cnvTradToKangXi(_ strObj: String) -> String { @objc class func cnvTradToKangXi(_ strObj: String) -> String {
var strObj = strObj var strObj = strObj
strObj.selfReplace("", "") strObj.selfReplace("", "")

View File

@ -44,7 +44,7 @@ public class FSEventStreamHelper: NSObject {
@objc public init(path: String, queue: DispatchQueue) { @objc public init(path: String, queue: DispatchQueue) {
self.path = path self.path = path
self.dispatchQueue = queue dispatchQueue = queue
} }
private var stream: FSEventStreamRef? private var stream: FSEventStreamRef?

View File

@ -25,7 +25,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Carbon import Carbon
import Cocoa import Cocoa
@objc public class IME: NSObject { public class IME: NSObject {
static let arrSupportedLocales = ["en", "zh-Hant", "zh-Hans", "ja"] static let arrSupportedLocales = ["en", "zh-Hant", "zh-Hans", "ja"]
static let dlgOpenPath = NSOpenPanel() static let dlgOpenPath = NSOpenPanel()
@ -34,7 +34,7 @@ import Cocoa
// MARK: - ctlInputMethod // MARK: - ctlInputMethod
static func getInputMode() -> InputMode { static func getInputMode() -> InputMode {
return ctlInputMethod.currentKeyHandler.inputMode ctlInputMethod.currentKeyHandler.inputMode
} }
// MARK: - Print debug information to the console. // MARK: - Print debug information to the console.
@ -333,13 +333,15 @@ extension RangeReplaceableCollection where Element: Hashable {
// MARK: - Error Extension // MARK: - Error Extension
extension String: Error {} extension String: Error {}
extension String: LocalizedError { extension String: LocalizedError {
public var errorDescription: String? { return self } public var errorDescription: String? {
self
}
} }
// MARK: - Ensuring trailing slash of a string: // MARK: - Ensuring trailing slash of a string:
extension String { extension String {
mutating func ensureTrailingSlash() { mutating func ensureTrailingSlash() {
if !self.hasSuffix("/") { if !hasSuffix("/") {
self += "/" self += "/"
} }
} }

View File

@ -400,7 +400,7 @@ extension ctlInputMethod {
return true return true
} }
candidates.sort { candidates.sort {
return $0.count > $1.count $0.count > $1.count
} }
// If there is a candidate which is too long, we use the vertical // If there is a candidate which is too long, we use the vertical
// candidate list window automatically. // candidate list window automatically.

View File

@ -81,7 +81,7 @@ private let kDefaultKeys = "123456789"
@objc extension UserDefaults { @objc extension UserDefaults {
func setDefault(_ value: Any?, forKey defaultName: String) { func setDefault(_ value: Any?, forKey defaultName: String) {
if self.object(forKey: defaultName) == nil { if object(forKey: defaultName) == nil {
self.set(value, forKey: defaultName) self.set(value, forKey: defaultName)
} }
} }
@ -200,7 +200,7 @@ struct ComposingBufferSize {
} }
// MARK: - // MARK: -
@objc public class mgrPrefs: NSObject { public class mgrPrefs: NSObject {
static var allKeys: [String] { static var allKeys: [String] {
[ [
UserDef.kIsDebugModeEnabled, UserDef.kIsDebugModeEnabled,
@ -293,7 +293,7 @@ struct ComposingBufferSize {
@objc static var mandarinParser: Int @objc static var mandarinParser: Int
@objc static var mandarinParserName: String { @objc static var mandarinParserName: String {
(MandarinParser(rawValue: self.mandarinParser) ?? MandarinParser.ofStandard).name (MandarinParser(rawValue: mandarinParser) ?? MandarinParser.ofStandard).name
} }
@UserDefault( @UserDefault(
@ -372,7 +372,7 @@ struct ComposingBufferSize {
chineseConversionEnabled = !chineseConversionEnabled chineseConversionEnabled = !chineseConversionEnabled
// JIS // JIS
if chineseConversionEnabled && shiftJISShinjitaiOutputEnabled { if chineseConversionEnabled && shiftJISShinjitaiOutputEnabled {
self.toggleShiftJISShinjitaiOutputEnabled() toggleShiftJISShinjitaiOutputEnabled()
UserDefaults.standard.set( UserDefaults.standard.set(
shiftJISShinjitaiOutputEnabled, forKey: UserDef.kShiftJISShinjitaiOutputEnabled) shiftJISShinjitaiOutputEnabled, forKey: UserDef.kShiftJISShinjitaiOutputEnabled)
} }
@ -387,7 +387,7 @@ struct ComposingBufferSize {
shiftJISShinjitaiOutputEnabled = !shiftJISShinjitaiOutputEnabled shiftJISShinjitaiOutputEnabled = !shiftJISShinjitaiOutputEnabled
// JIS // JIS
if shiftJISShinjitaiOutputEnabled && chineseConversionEnabled { if shiftJISShinjitaiOutputEnabled && chineseConversionEnabled {
self.toggleChineseConversionEnabled() toggleChineseConversionEnabled()
} }
UserDefaults.standard.set( UserDefaults.standard.set(
shiftJISShinjitaiOutputEnabled, forKey: UserDef.kShiftJISShinjitaiOutputEnabled) shiftJISShinjitaiOutputEnabled, forKey: UserDef.kShiftJISShinjitaiOutputEnabled)

View File

@ -28,7 +28,7 @@ import Cocoa
// MARK: - // MARK: -
static func getBundleDataPath(_ filenameSansExt: String) -> String { static func getBundleDataPath(_ filenameSansExt: String) -> String {
return Bundle.main.path(forResource: filenameSansExt, ofType: "txt")! Bundle.main.path(forResource: filenameSansExt, ofType: "txt")!
} }
// MARK: - 使 // MARK: - 使
@ -36,27 +36,27 @@ import Cocoa
static func userPhrasesDataPath(_ mode: InputMode) -> String { static func userPhrasesDataPath(_ mode: InputMode) -> String {
let fileName = (mode == InputMode.imeModeCHT) ? "userdata-cht.txt" : "userdata-chs.txt" let fileName = (mode == InputMode.imeModeCHT) ? "userdata-cht.txt" : "userdata-chs.txt"
return URL(fileURLWithPath: self.dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path return URL(fileURLWithPath: dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path
} }
static func userSymbolDataPath(_ mode: InputMode) -> String { static func userSymbolDataPath(_ mode: InputMode) -> String {
let fileName = (mode == InputMode.imeModeCHT) ? "usersymbolphrases-cht.txt" : "usersymbolphrases-chs.txt" let fileName = (mode == InputMode.imeModeCHT) ? "usersymbolphrases-cht.txt" : "usersymbolphrases-chs.txt"
return URL(fileURLWithPath: self.dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path return URL(fileURLWithPath: dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path
} }
static func userAssociatedPhrasesDataPath(_ mode: InputMode) -> String { static func userAssociatedPhrasesDataPath(_ mode: InputMode) -> String {
let fileName = (mode == InputMode.imeModeCHT) ? "associatedPhrases-cht.txt" : "associatedPhrases-chs.txt" let fileName = (mode == InputMode.imeModeCHT) ? "associatedPhrases-cht.txt" : "associatedPhrases-chs.txt"
return URL(fileURLWithPath: self.dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path return URL(fileURLWithPath: dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path
} }
static func excludedPhrasesDataPath(_ mode: InputMode) -> String { static func excludedPhrasesDataPath(_ mode: InputMode) -> String {
let fileName = (mode == InputMode.imeModeCHT) ? "exclude-phrases-cht.txt" : "exclude-phrases-chs.txt" let fileName = (mode == InputMode.imeModeCHT) ? "exclude-phrases-cht.txt" : "exclude-phrases-chs.txt"
return URL(fileURLWithPath: self.dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path return URL(fileURLWithPath: dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path
} }
static func phraseReplacementDataPath(_ mode: InputMode) -> String { static func phraseReplacementDataPath(_ mode: InputMode) -> String {
let fileName = (mode == InputMode.imeModeCHT) ? "phrases-replacement-cht.txt" : "phrases-replacement-chs.txt" let fileName = (mode == InputMode.imeModeCHT) ? "phrases-replacement-cht.txt" : "phrases-replacement-chs.txt"
return URL(fileURLWithPath: self.dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path return URL(fileURLWithPath: dataFolderPath(isDefaultFolder: false)).appendingPathComponent(fileName).path
} }
// MARK: - 使 // MARK: - 使
@ -86,7 +86,7 @@ import Cocoa
} }
static func chkUserLMFilesExist(_ mode: InputMode) -> Bool { static func chkUserLMFilesExist(_ mode: InputMode) -> Bool {
if !self.checkIfUserDataFolderExists() { if !checkIfUserDataFolderExists() {
return false return false
} }
if !ensureFileExists(userPhrasesDataPath(mode)) if !ensureFileExists(userPhrasesDataPath(mode))
@ -136,8 +136,8 @@ import Cocoa
// //
if folderExist && !isFolder.boolValue { if folderExist && !isFolder.boolValue {
do { do {
if self.dataFolderPath(isDefaultFolder: false) if dataFolderPath(isDefaultFolder: false)
== self.dataFolderPath(isDefaultFolder: true) == dataFolderPath(isDefaultFolder: true)
{ {
let formatter = DateFormatter.init() let formatter = DateFormatter.init()
formatter.dateFormat = "YYYYMMDD-HHMM'Hrs'-ss's'" formatter.dateFormat = "YYYYMMDD-HHMM'Hrs'-ss's'"
@ -199,13 +199,13 @@ import Cocoa
_ userPhrase: String?, inputMode mode: InputMode, areWeDuplicating: Bool, areWeDeleting: Bool _ userPhrase: String?, inputMode mode: InputMode, areWeDuplicating: Bool, areWeDeleting: Bool
) -> Bool { ) -> Bool {
if var currentMarkedPhrase: String = userPhrase { if var currentMarkedPhrase: String = userPhrase {
if !self.chkUserLMFilesExist(InputMode.imeModeCHS) if !chkUserLMFilesExist(InputMode.imeModeCHS)
|| !self.chkUserLMFilesExist(InputMode.imeModeCHT) || !chkUserLMFilesExist(InputMode.imeModeCHT)
{ {
return false return false
} }
let path = areWeDeleting ? self.excludedPhrasesDataPath(mode) : self.userPhrasesDataPath(mode) let path = areWeDeleting ? excludedPhrasesDataPath(mode) : userPhrasesDataPath(mode)
if areWeDuplicating && !areWeDeleting { if areWeDuplicating && !areWeDeleting {
// Do not use ASCII characters to comment here. // Do not use ASCII characters to comment here.
@ -227,12 +227,12 @@ import Cocoa
// We enforce the format consolidation here, since the pragma header // We enforce the format consolidation here, since the pragma header
// will let the UserPhraseLM bypasses the consolidating process on load. // will let the UserPhraseLM bypasses the consolidating process on load.
self.consolidate(givenFile: path, shouldCheckPragma: false) consolidate(givenFile: path, shouldCheckPragma: false)
// We use FSEventStream to monitor possible changes of the user phrase folder, hence the // We use FSEventStream to monitor possible changes of the user phrase folder, hence the
// lack of the needs of manually load data here unless FSEventStream is disabled by user. // lack of the needs of manually load data here unless FSEventStream is disabled by user.
if !mgrPrefs.shouldAutoReloadUserDataFiles { if !mgrPrefs.shouldAutoReloadUserDataFiles {
self.loadUserPhrases() loadUserPhrases()
} }
return true return true
} }

View File

@ -26,7 +26,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Cocoa import Cocoa
@objc public class clsSFX: NSObject, NSSoundDelegate { public class clsSFX: NSObject, NSSoundDelegate {
private static let shared = clsSFX() private static let shared = clsSFX()
private override init() { private override init() {
super.init() super.init()

View File

@ -116,7 +116,7 @@ private class HorizontalCandidateView: NSView {
} }
override func draw(_ dirtyRect: NSRect) { override func draw(_ dirtyRect: NSRect) {
let bounds = self.bounds let bounds = bounds
NSColor.controlBackgroundColor.setFill() // Candidate list panel base background NSColor.controlBackgroundColor.setFill() // Candidate list panel base background
NSBezierPath.fill(bounds) NSBezierPath.fill(bounds)
@ -190,7 +190,7 @@ private class HorizontalCandidateView: NSView {
private func findHitIndex(event: NSEvent) -> UInt? { private func findHitIndex(event: NSEvent) -> UInt? {
let location = convert(event.locationInWindow, to: nil) let location = convert(event.locationInWindow, to: nil)
if !NSPointInRect(location, self.bounds) { if !bounds.contains(location) {
return nil return nil
} }
var accuWidth: CGFloat = 0.0 var accuWidth: CGFloat = 0.0
@ -212,7 +212,7 @@ private class HorizontalCandidateView: NSView {
return return
} }
highlightedIndex = newIndex highlightedIndex = newIndex
self.setNeedsDisplay(self.bounds) setNeedsDisplay(bounds)
} }
override func mouseDown(with event: NSEvent) { override func mouseDown(with event: NSEvent) {
@ -227,7 +227,7 @@ private class HorizontalCandidateView: NSView {
} }
trackingHighlightedIndex = 0 trackingHighlightedIndex = 0
self.setNeedsDisplay(self.bounds) setNeedsDisplay(bounds)
if triggerAction { if triggerAction {
if let target = target as? NSObject, let action = action { if let target = target as? NSObject, let action = action {
target.perform(action, with: self) target.perform(action, with: self)
@ -236,7 +236,7 @@ private class HorizontalCandidateView: NSView {
} }
} }
@objc public class ctlCandidateHorizontal: ctlCandidate { public class ctlCandidateHorizontal: ctlCandidate {
private var candidateView: HorizontalCandidateView private var candidateView: HorizontalCandidateView
private var prevPageButton: NSButton private var prevPageButton: NSButton
private var nextPageButton: NSButton private var nextPageButton: NSButton
@ -438,7 +438,7 @@ extension ctlCandidateHorizontal {
let topLeftPoint = NSPoint(x: frameRect.origin.x, y: frameRect.origin.y + frameRect.size.height) let topLeftPoint = NSPoint(x: frameRect.origin.x, y: frameRect.origin.y + frameRect.size.height)
frameRect.size = newSize frameRect.size = newSize
frameRect.origin = NSPoint(x: topLeftPoint.x, y: topLeftPoint.y - frameRect.size.height) frameRect.origin = NSPoint(x: topLeftPoint.x, y: topLeftPoint.y - frameRect.size.height)
self.window?.setFrame(frameRect, display: false) window?.setFrame(frameRect, display: false)
candidateView.setNeedsDisplay(candidateView.bounds) candidateView.setNeedsDisplay(candidateView.bounds)
} }

View File

@ -122,7 +122,7 @@ private class VerticalCandidateView: NSView {
} }
override func draw(_ dirtyRect: NSRect) { override func draw(_ dirtyRect: NSRect) {
let bounds = self.bounds let bounds = bounds
NSColor.controlBackgroundColor.setFill() // Candidate list panel base background NSColor.controlBackgroundColor.setFill() // Candidate list panel base background
NSBezierPath.fill(bounds) NSBezierPath.fill(bounds)
@ -195,7 +195,7 @@ private class VerticalCandidateView: NSView {
private func findHitIndex(event: NSEvent) -> UInt? { private func findHitIndex(event: NSEvent) -> UInt? {
let location = convert(event.locationInWindow, to: nil) let location = convert(event.locationInWindow, to: nil)
if !NSPointInRect(location, self.bounds) { if !bounds.contains(location) {
return nil return nil
} }
var accuHeight: CGFloat = 0.0 var accuHeight: CGFloat = 0.0
@ -217,7 +217,7 @@ private class VerticalCandidateView: NSView {
return return
} }
highlightedIndex = newIndex highlightedIndex = newIndex
self.setNeedsDisplay(self.bounds) setNeedsDisplay(bounds)
} }
override func mouseDown(with event: NSEvent) { override func mouseDown(with event: NSEvent) {
@ -232,7 +232,7 @@ private class VerticalCandidateView: NSView {
} }
trackingHighlightedIndex = 0 trackingHighlightedIndex = 0
self.setNeedsDisplay(self.bounds) setNeedsDisplay(bounds)
if triggerAction { if triggerAction {
if let target = target as? NSObject, let action = action { if let target = target as? NSObject, let action = action {
target.perform(action, with: self) target.perform(action, with: self)
@ -241,7 +241,7 @@ private class VerticalCandidateView: NSView {
} }
} }
@objc public class ctlCandidateVertical: ctlCandidate { public class ctlCandidateVertical: ctlCandidate {
private var candidateView: VerticalCandidateView private var candidateView: VerticalCandidateView
private var prevPageButton: NSButton private var prevPageButton: NSButton
private var nextPageButton: NSButton private var nextPageButton: NSButton
@ -443,7 +443,7 @@ extension ctlCandidateVertical {
let topLeftPoint = NSPoint(x: frameRect.origin.x, y: frameRect.origin.y + frameRect.size.height) let topLeftPoint = NSPoint(x: frameRect.origin.x, y: frameRect.origin.y + frameRect.size.height)
frameRect.size = newSize frameRect.size = newSize
frameRect.origin = NSPoint(x: topLeftPoint.x, y: topLeftPoint.y - frameRect.size.height) frameRect.origin = NSPoint(x: topLeftPoint.x, y: topLeftPoint.y - frameRect.size.height)
self.window?.setFrame(frameRect, display: false) window?.setFrame(frameRect, display: false)
candidateView.setNeedsDisplay(candidateView.bounds) candidateView.setNeedsDisplay(candidateView.bounds)
} }

View File

@ -69,12 +69,12 @@ public class NotifierController: NSWindowController, NotifierWindowDelegate {
private var shouldStay: Bool = false private var shouldStay: Bool = false
private var backgroundColor: NSColor = .textBackgroundColor { private var backgroundColor: NSColor = .textBackgroundColor {
didSet { didSet {
self.window?.backgroundColor = backgroundColor window?.backgroundColor = backgroundColor
} }
} }
private var foregroundColor: NSColor = .controlTextColor { private var foregroundColor: NSColor = .controlTextColor {
didSet { didSet {
self.messageTextField.textColor = foregroundColor messageTextField.textColor = foregroundColor
} }
} }
private var waitTimer: Timer? private var waitTimer: Timer?
@ -155,7 +155,7 @@ public class NotifierController: NSWindowController, NotifierWindowDelegate {
} }
let lastLocation = NotifierController.lastLocation let lastLocation = NotifierController.lastLocation
let screenRect = NSScreen.main?.visibleFrame ?? NSRect.zero let screenRect = NSScreen.main?.visibleFrame ?? NSRect.zero
var windowRect = self.window?.frame ?? NSRect.zero var windowRect = window?.frame ?? NSRect.zero
windowRect.origin.x = lastLocation.x windowRect.origin.x = lastLocation.x
windowRect.origin.y = lastLocation.y - 10 - windowRect.height windowRect.origin.y = lastLocation.y - 10 - windowRect.height
@ -163,11 +163,11 @@ public class NotifierController: NSWindowController, NotifierWindowDelegate {
return return
} }
self.window?.setFrame(windowRect, display: true) window?.setFrame(windowRect, display: true)
} }
func moveIn() { func moveIn() {
let afterRect = self.window?.frame ?? NSRect.zero let afterRect = window?.frame ?? NSRect.zero
NotifierController.lastLocation = afterRect.origin NotifierController.lastLocation = afterRect.origin
var beforeRect = afterRect var beforeRect = afterRect
beforeRect.origin.y += 10 beforeRect.origin.y += 10
@ -186,11 +186,11 @@ public class NotifierController: NSWindowController, NotifierWindowDelegate {
} }
@objc private func doFadeOut(_ timer: Timer) { @objc private func doFadeOut(_ timer: Timer) {
let opacity = self.window?.alphaValue ?? 0 let opacity = window?.alphaValue ?? 0
if opacity <= 0 { if opacity <= 0 {
self.close() close()
} else { } else {
self.window?.alphaValue = opacity - 0.2 window?.alphaValue = opacity - 0.2
} }
} }
@ -212,6 +212,6 @@ public class NotifierController: NSWindowController, NotifierWindowDelegate {
} }
fileprivate func windowDidBecomeClicked(_ window: NotifierWindow) { fileprivate func windowDidBecomeClicked(_ window: NotifierWindow) {
self.fadeOut() fadeOut()
} }
} }

View File

@ -264,8 +264,8 @@ import Cocoa
let bolPreviousFolderValidity = mgrLangModel.checkIfSpecifiedUserDataFolderValid( let bolPreviousFolderValidity = mgrLangModel.checkIfSpecifiedUserDataFolderValid(
NSString(string: mgrPrefs.userDataFolderSpecified).expandingTildeInPath) NSString(string: mgrPrefs.userDataFolderSpecified).expandingTildeInPath)
if self.window != nil { if window != nil {
IME.dlgOpenPath.beginSheetModal(for: self.window!) { result in IME.dlgOpenPath.beginSheetModal(for: window!) { result in
if result == NSApplication.ModalResponse.OK { if result == NSApplication.ModalResponse.OK {
if IME.dlgOpenPath.url != nil { if IME.dlgOpenPath.url != nil {
// CommonDialog // CommonDialog

View File

@ -38,7 +38,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
} }
func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
return .terminateNow .terminateNow
} }
// New About Window // New About Window
@objc func showAbout() { @objc func showAbout() {

View File

@ -41,7 +41,7 @@ extension Content {
} }
func data() -> Data? { func data() -> Data? {
return contentString.data(using: .utf8) contentString.data(using: .utf8)
} }
} }

View File

@ -38,19 +38,19 @@ class Document: NSDocument {
// This enables auto save. // This enables auto save.
override class var autosavesInPlace: Bool { override class var autosavesInPlace: Bool {
return true true
} }
// This enables asynchronous-writing. // This enables asynchronous-writing.
override func canAsynchronouslyWrite( override func canAsynchronouslyWrite(
to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType
) -> Bool { ) -> Bool {
return true true
} }
// This enables asynchronous reading. // This enables asynchronous reading.
override class func canConcurrentlyReadDocuments(ofType: String) -> Bool { override class func canConcurrentlyReadDocuments(ofType: String) -> Bool {
return ofType == "public.plain-text" ofType == "public.plain-text"
} }
// MARK: - User Interface // MARK: - User Interface

View File

@ -30,7 +30,7 @@ extension String {
do { do {
let regex = try NSRegularExpression( let regex = try NSRegularExpression(
pattern: pattern, options: [.caseInsensitive, .anchorsMatchLines]) pattern: pattern, options: [.caseInsensitive, .anchorsMatchLines])
let range = NSRange(self.startIndex..., in: self) let range = NSRange(startIndex..., in: self)
self = regex.stringByReplacingMatches( self = regex.stringByReplacingMatches(
in: self, options: [], range: range, withTemplate: replaceWith) in: self, options: [], range: range, withTemplate: replaceWith)
} catch { return } } catch { return }