Skip to content

Commit

Permalink
Change direction of console window, add clean console button, run swi…
Browse files Browse the repository at this point in the history
…ftformat
  • Loading branch information
John Sterling committed Apr 26, 2020
1 parent d2e42b7 commit 721dfc4
Show file tree
Hide file tree
Showing 13 changed files with 200 additions and 182 deletions.
6 changes: 3 additions & 3 deletions Finicky/Finicky/API.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ import JavaScriptCore

@objc open class FinickyAPI: NSObject, FinickyAPIExports {
fileprivate static var context: JSContext!
fileprivate static var logToConsole: ((_ message: String) -> Void)?
fileprivate static var logToConsole: ((_ message: String, _ clearConsole: Bool) -> Void)?

static func log(_ message: String?) {
if message != nil {
NSLog(message!)
logToConsole?(message!)
logToConsole?(message!, false)
}
}

Expand All @@ -31,7 +31,7 @@ import JavaScriptCore
self.context = context
}

@objc class func setLog(_ logToConsole: @escaping (_ message: String) -> Void) {
@objc class func setLog(_ logToConsole: @escaping (_ message: String, _ clearConsole: Bool) -> Void) {
self.logToConsole = logToConsole
}
}
24 changes: 13 additions & 11 deletions Finicky/Finicky/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,18 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
@IBOutlet var yourTextField: NSTextField!
@IBOutlet var textView: NSTextView!

@IBAction func ClearConsole(_: Any? = nil) {
textView.string = ""
}

@objc var statusItem: NSStatusItem!
var configLoader: FinickyConfig!
var shortUrlResolver: FNShortUrlResolver = FNShortUrlResolver()
@objc var isActive: Bool = true

func applicationWillFinishLaunching(_: Notification) {
yourTextField.delegate = self
ClearConsole()
let bundleId = "net.kassett.Finicky"
LSSetDefaultHandlerForURLScheme("http" as CFString, bundleId as CFString)
LSSetDefaultHandlerForURLScheme("https" as CFString, bundleId as CFString)
Expand Down Expand Up @@ -93,12 +98,13 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele
testConfigWindow.orderFront(sender)
}

func logToConsole(_ message: String) {
func logToConsole(_ message: String, clearConsole _: Bool = false) {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: date)
textView.string = dateString + " - " + message + "\n\n" + textView.string.prefix(20000).trimmingCharacters(in: .whitespacesAndNewlines)
textView.string = textView.string + dateString + " - " + message + "\n"
textView.scrollToEndOfDocument(self)
}

@IBAction func testUrl(_ sender: NSTextField) {
Expand All @@ -121,26 +127,22 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDele

func performTest(url: URL) {
if let appDescriptor = configLoader.determineOpeningApp(url: url, sourceBundleIdentifier: "net.kassett.finicky") {
var description = """
Would open url: \(appDescriptor.url)
"""
var description = ""

if appDescriptor.browsers.count == 1 {
if let browser = appDescriptor.browsers.first {
description += "Browser:\n"
description += " \(browser.name) \(browser.openInBackground ? "(opens in background)" : "")\n"
description += "Opens browser: \(browser.name)\(browser.openInBackground ? " (opens in background)" : "")"
}
} else if appDescriptor.browsers.count == 0 {
description += "Won't open any browser"
} else {
description += "First active browser of:\n"
description += "Opens first active browser of: "
for (index, browser) in appDescriptor.browsers.enumerated() {
description += " [\(index)]: \(browser.name) \(browser.openInBackground ? "(opens in background)" : "")\n"
description += "[\(index)]: \(browser.name) \(browser.openInBackground ? "(opens in background)" : "")"
}
}

description += ", url: \(appDescriptor.url)"
logToConsole(description)
}
}
Expand Down
16 changes: 8 additions & 8 deletions Finicky/Finicky/AppDescriptor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ enum BrowserError: Error {
case cantFindBrowser(msg: String)
}

public struct BrowserOpts : CustomStringConvertible {
public struct BrowserOpts: CustomStringConvertible {
public var name: String
public var openInBackground: Bool
public var bundleId: String?
public var appPath: String?

public var description: String {
if let bundleId = self.bundleId {
return bundleId
} else if let appPath = self.appPath {
return appPath
} else {
return self.name
return name
}
}

Expand All @@ -33,21 +33,21 @@ public struct BrowserOpts : CustomStringConvertible {
self.openInBackground = openInBackground ?? false

if appType == AppDescriptorType.bundleId {
self.bundleId = name
bundleId = name
} else if appType == AppDescriptorType.appPath {
self.appPath = name
appPath = name
} else if let path = NSWorkspace.shared.fullPath(forApplication: name) {
if let bundle = Bundle(path: path) {
self.bundleId = bundle.bundleIdentifier!
self.appPath = path
bundleId = bundle.bundleIdentifier!
appPath = path
} else {
throw BrowserError.cantFindBrowser(msg: "Couldn't find application \"\(name)\"")
}
} else {
throw BrowserError.cantFindBrowser(msg: "Couldn't find application \"\(name)\"")
}
}

public static func isAppDirectory(_ path: String) -> Bool {
var isDirectory = ObjCBool(true)
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
Expand Down
27 changes: 19 additions & 8 deletions Finicky/Finicky/Base.lproj/MainMenu.xib
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14868" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14868"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
Expand Down Expand Up @@ -715,7 +715,7 @@
<windowStyleMask key="styleMask" titled="YES" closable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="163" y="199" width="591" height="500"/>
<rect key="screenRect" x="0.0" y="0.0" width="1680" height="1027"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1057"/>
<view key="contentView" id="7j0-3Z-aDh">
<rect key="frame" x="0.0" y="0.0" width="591" height="500"/>
<autoresizingMask key="autoresizingMask"/>
Expand All @@ -742,18 +742,18 @@
</textFieldCell>
</textField>
<scrollView fixedFrame="YES" borderType="none" autohidesScrollers="YES" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" horizontalScrollElasticity="none" translatesAutoresizingMaskIntoConstraints="NO" id="NNs-Xk-fv6">
<rect key="frame" x="9" y="8" width="572" height="436"/>
<rect key="frame" x="9" y="33" width="572" height="411"/>
<autoresizingMask key="autoresizingMask"/>
<clipView key="contentView" ambiguous="YES" drawsBackground="NO" copiesOnScroll="NO" id="k0G-uq-6Cu">
<rect key="frame" x="0.0" y="0.0" width="572" height="436"/>
<rect key="frame" x="0.0" y="0.0" width="572" height="411"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textView ambiguous="YES" editable="NO" importsGraphics="NO" richText="NO" verticallyResizable="YES" allowsCharacterPickerTouchBarItem="NO" textCompletion="NO" id="qaM-sW-3L0">
<rect key="frame" x="0.0" y="0.0" width="572" height="436"/>
<rect key="frame" x="0.0" y="0.0" width="572" height="411"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
<size key="minSize" width="572" height="436"/>
<size key="minSize" width="572" height="411"/>
<size key="maxSize" width="572" height="10000000"/>
<color key="insertionPointColor" name="textColor" catalog="System" colorSpace="catalog"/>
</textView>
Expand All @@ -768,6 +768,17 @@
<autoresizingMask key="autoresizingMask"/>
</scroller>
</scrollView>
<button verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="e9u-jv-iSO">
<rect key="frame" x="-2" y="-1" width="123" height="32"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<buttonCell key="cell" type="push" title="Clear console" bezelStyle="rounded" alignment="center" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="XVX-Nz-543">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
<connections>
<action selector="ClearConsole:" target="Voe-Tx-rLC" id="2bk-u0-Z8a"/>
</connections>
</button>
</subviews>
</view>
<point key="canvasLocation" x="71.5" y="-176"/>
Expand All @@ -776,7 +787,7 @@
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="163" y="199" width="480" height="307"/>
<rect key="screenRect" x="0.0" y="0.0" width="1680" height="1027"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1057"/>
<view key="contentView" id="sle-Xy-ZMj">
<rect key="frame" x="0.0" y="0.0" width="480" height="307"/>
<autoresizingMask key="autoresizingMask"/>
Expand Down
9 changes: 9 additions & 0 deletions Finicky/Finicky/Battery.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//
// Battery.swift
// Finicky
//
// Created by John Sterling on 2020-04-26.
// Copyright © 2020 John sterling. All rights reserved.
//

import Foundation
6 changes: 2 additions & 4 deletions Finicky/Finicky/Browsers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@ enum Browser: String {

public func getBrowserCommand(_ browserOpts: BrowserOpts, url: URL) -> [String] {
var command = ["open", url.absoluteString]

// appPath takes priority over bundleId as it is always unique.
if let appPath = browserOpts.appPath {
command.append(contentsOf: ["-a", appPath])
} else if let bundleId = browserOpts.bundleId {
command.append(contentsOf: ["-b", bundleId])
} else {

}
} else {}

if browserOpts.openInBackground {
command.append("-g")
Expand Down
17 changes: 9 additions & 8 deletions Finicky/Finicky/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import JavaScriptCore
var FNConfigPath: String = "~/.finicky.js"

public typealias Callback<T> = (T) -> Void
public typealias Callback2<T, U> = (T, U) -> Void

open class FinickyConfig {
var ctx: JSContext!
Expand All @@ -17,15 +18,15 @@ open class FinickyConfig {
var fileDescriptor: Int32 = -1
var lastModificationDate: Date?
var toggleIconCallback: Callback<Bool>?
var logToConsole: Callback<String>?
var logToConsole: Callback2<String, Bool>?
var setShortUrlProviders: Callback<[String]?>?
var updateStatus: Callback<Bool>?

public init() {
configAPIString = loadJS("finickyConfigAPI.js")
}

public convenience init(toggleIconCallback: @escaping Callback<Bool>, logToConsoleCallback: @escaping Callback<String>, setShortUrlProviders: @escaping Callback<[String]?>, updateStatus: @escaping Callback<Bool>) {
public convenience init(toggleIconCallback: @escaping Callback<Bool>, logToConsoleCallback: @escaping Callback2<String, Bool>, setShortUrlProviders: @escaping Callback<[String]?>, updateStatus: @escaping Callback<Bool>) {
self.init()
self.toggleIconCallback = toggleIconCallback
logToConsole = logToConsoleCallback
Expand Down Expand Up @@ -112,7 +113,7 @@ open class FinickyConfig {
let shortMessage = "Configuration: \(String(describing: exception!))"
print(message)
showNotification(title: "Configuration", informativeText: String(describing: exception!), error: true)
self.logToConsole?(shortMessage)
self.logToConsole?(shortMessage, false)
}

ctx.evaluateScript("const module = {}")
Expand Down Expand Up @@ -144,7 +145,7 @@ open class FinickyConfig {
print(message)
showNotification(title: message, error: true)

logToConsole?(message)
logToConsole?(message, false)

return false
} else {
Expand Down Expand Up @@ -189,7 +190,7 @@ open class FinickyConfig {
]
};
// For more examples, see the Finicky github page https://github.com/johnste/finicky
""")
""", false)

return
}
Expand All @@ -209,7 +210,7 @@ open class FinickyConfig {
if showSuccess {
showNotification(title: "Reloaded config successfully")

logToConsole?("Reloaded config successfully")
logToConsole?("Reloaded config successfully", false)
}
}
}
Expand Down Expand Up @@ -252,7 +253,7 @@ open class FinickyConfig {
return browser
} catch _ as BrowserError {
showNotification(title: "Couldn't find browser \"\(browserName)\"")
logToConsole?("Couldn't find browser \"\(browserName)\"")
logToConsole?("Couldn't find browser \"\(browserName)\"", false)
return nil
} catch let msg {
print("Unknown error resolving browser: \(msg)")
Expand All @@ -267,7 +268,7 @@ open class FinickyConfig {
if let rewrittenUrl = URL(string: newUrl) {
finalUrl = rewrittenUrl
} else {
logToConsole?("Couldn't generate url from handler \(newUrl), falling back to original url")
logToConsole?("Couldn't generate url from handler \(newUrl), falling back to original url", false)
}
}

Expand Down
2 changes: 1 addition & 1 deletion Finicky/Finicky/ShortUrlResolver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ final class FNShortUrlResolver {

func isShortUrl(_ url: URL) -> Bool {
guard let host = url.host,
shortUrlProviders.contains(host) else {return false}
shortUrlProviders.contains(host) else { return false }

// Can't load insecure cleartext HTTP
// https://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http
Expand Down
38 changes: 19 additions & 19 deletions Finicky/Finicky/UpdateCheck.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import Foundation

public struct Version: Decodable, Hashable {
public let title: String
public let version: String
public let prerelease: Bool

enum CodingKeys: String, CodingKey {
case title = "name"
case version = "tag_name"
case prerelease
}
public struct Version: Decodable, Hashable {
public let title: String
public let version: String
public let prerelease: Bool

enum CodingKeys: String, CodingKey {
case title = "name"
case version = "tag_name"
case prerelease
}
}

struct defaultsKeys {
Expand All @@ -18,7 +18,7 @@ struct defaultsKeys {

func checkForUpdate(_ newVersionCallback: @escaping Callback<Version?>) {
guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
let url = URL(string: "https://api.github.com/repos/johnste/finicky/releases") else {return}
let url = URL(string: "https://api.github.com/repos/johnste/finicky/releases") else { return }
var request = URLRequest(url: url)
request.setValue("finicky/\(version)", forHTTPHeaderField: "User-Agent")

Expand All @@ -35,14 +35,14 @@ func checkForUpdate(_ newVersionCallback: @escaping Callback<Version?>) {
try compareVersions(versionA.version, versionB.version) == .orderedDescending
})

guard let latestVersion = sortedVersions.first else { newVersionCallback(nil); return }
let laterThanCurrent = try compareVersions(version, latestVersion.version)
guard laterThanCurrent == ComparisonResult.orderedAscending else { newVersionCallback(nil); return }
guard let latestSeenBefore = defaults.string(forKey: defaultsKeys.keyLatestVersionSeen) else { return }
guard let latestVersion = sortedVersions.first else { newVersionCallback(nil); return }
let laterThanCurrent = try compareVersions(version, latestVersion.version)
guard laterThanCurrent == ComparisonResult.orderedAscending else { newVersionCallback(nil); return }
guard let latestSeenBefore = defaults.string(forKey: defaultsKeys.keyLatestVersionSeen) else { return }
print("latestSeenBefore \(latestSeenBefore)")
if latestSeenBefore != latestVersion.version {
defaults.set(latestVersion.version, forKey: defaultsKeys.keyLatestVersionSeen)
newVersionCallback(latestVersion)
defaults.set(latestVersion.version, forKey: defaultsKeys.keyLatestVersionSeen)
newVersionCallback(latestVersion)
}
} catch {
print("error")
Expand Down Expand Up @@ -90,6 +90,6 @@ public func compareVersions(_ versionA: String, _ versionB: String) throws -> Co
}

func getVersions(data: Data) throws -> Set<Version> {
let versions = try JSONDecoder().decode(Set<Version>.self, from: data)
return versions.filter{!$0.prerelease}
let versions = try JSONDecoder().decode(Set<Version>.self, from: data)
return versions.filter { !$0.prerelease }
}
Loading

0 comments on commit 721dfc4

Please sign in to comment.