Skip to content
Snippets Groups Projects
Commit d846479f authored by broman's avatar broman
Browse files

Further work on drag and drop, format overhaul to swift 5

parent 7c61053e
No related branches found
No related tags found
1 merge request!1Add settings menu, add drag and drop functionality
...@@ -11,7 +11,6 @@ import SKQueue ...@@ -11,7 +11,6 @@ import SKQueue
@NSApplicationMain @NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate { class AppDelegate: NSObject, NSApplicationDelegate {
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
let popover = NSPopover() let popover = NSPopover()
let viewController = PopoverMenu(nibName: "PopoverMenu", let viewController = PopoverMenu(nibName: "PopoverMenu",
...@@ -19,81 +18,81 @@ class AppDelegate: NSObject, NSApplicationDelegate { ...@@ -19,81 +18,81 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let statusIcon = NSImage(named: "status_icon") let statusIcon = NSImage(named: "status_icon")
var spinnerView = NSView() var spinnerView = NSView()
let spinner = NSProgressIndicator() let spinner = NSProgressIndicator()
func applicationDidFinishLaunching(_ aNotification: Notification) { func applicationDidFinishLaunching(_: Notification) {
statusItem.button!.image = statusIcon statusItem.button!.image = statusIcon
statusItem.button!.action = #selector(togglePopover) statusItem.button!.action = #selector(togglePopover)
popover.contentViewController = viewController popover.contentViewController = viewController
//popover.behavior = .transient // popover.behavior = .transient
// Set up file watching // Set up file watching
let queue = SKQueue(delegate: UploadReceiver()) let queue = SKQueue(delegate: UploadReceiver())
queue?.addPath(NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true)[0], notifyingAbout: .Write) queue?.addPath(NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true)[0], notifyingAbout: .Write)
// Create spinner view for progress purposes // Create spinner view for progress purposes
spinnerView = NSView(frame: statusItem.button!.frame) spinnerView = NSView(frame: statusItem.button!.frame)
spinner.isIndeterminate = false spinner.isIndeterminate = false
spinner.style = .spinning spinner.style = .spinning
spinner.frame = statusItem.button!.frame spinner.frame = statusItem.button!.frame
spinnerView.addSubview(spinner) spinnerView.addSubview(spinner)
// Reciever for progress // Reciever for progress
NotificationCenter.default.addObserver(self, selector: #selector(self.setProgressWithNotifiedValue(notification:)), name: Notification.Name("UpdateIconWithProgressValue"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(setProgressWithNotifiedValue(notification:)), name: Notification.Name("UpdateIconWithProgressValue"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.resetIndicator), name: Notification.Name("UpdateIconWithCompletion"), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(resetIndicator), name: Notification.Name("UpdateIconWithCompletion"), object: nil)
} }
// MARK: Notification callbacks for icons // MARK: Notification callbacks for icons
@objc func setProgressWithNotifiedValue(notification: Notification) -> Void {
// Get progress from notification @objc func setProgressWithNotifiedValue(notification: Notification) {
guard let progress : Double = notification.userInfo!["progress"] as? Double else { // Get progress from notification
guard let progress: Double = notification.userInfo!["progress"] as? Double else {
return return
} }
spinner.doubleValue = progress * 100 spinner.doubleValue = progress * 100
print("Currently at \(Double(progress))") print("Currently at \(Double(progress))")
// Take a faux image in order to set as a status bar item. // Take a faux image in order to set as a status bar item.
// https://stackoverflow.com/a/30147199/3874884 // https://stackoverflow.com/a/30147199/3874884
let dataOfView = spinnerView.dataWithPDF(inside: spinnerView.bounds) let dataOfView = spinnerView.dataWithPDF(inside: spinnerView.bounds)
let imageOfView = resizeWithTemplate(image: NSImage(data: dataOfView)!) let imageOfView = resizeWithTemplate(image: NSImage(data: dataOfView)!)
// This allows us to ignore dark/light mode and have the system convert. // This allows us to ignore dark/light mode and have the system convert.
// The PDF view does not appear to account for the current system // The PDF view does not appear to account for the current system
// appearance. // appearance.
imageOfView.isTemplate = true imageOfView.isTemplate = true
statusItem.button!.image = imageOfView statusItem.button!.image = imageOfView
} }
@objc func resetIndicator() { @objc func resetIndicator() {
statusItem.image = statusIcon statusItem.image = statusIcon
} }
@objc func resizeWithTemplate(image: NSImage) -> (NSImage) { @objc func resizeWithTemplate(image: NSImage) -> (NSImage) {
// We want 80% of the current status item's size. Additionally // We want 80% of the current status item's size. Additionally
let oldImageSize = image.size let oldImageSize = image.size
let newSize:NSSize = NSSize(width: Int(oldImageSize.width * 0.8), height: Int(oldImageSize.height * 0.8)) let newSize: NSSize = NSSize(width: Int(oldImageSize.width * 0.8), height: Int(oldImageSize.height * 0.8))
// Cast the NSImage to a CGImage // Cast the NSImage to a CGImage
var imageRect:CGRect = CGRect(x: 0, y: 0, width: oldImageSize.width, height: oldImageSize.height) var imageRect: CGRect = CGRect(x: 0, y: 0, width: oldImageSize.width, height: oldImageSize.height)
let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil) let imageRef = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
// Create NSImage from the CGImage using the new size // Create NSImage from the CGImage using the new size
let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize) let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize)
return imageWithNewSize return imageWithNewSize
} }
@objc func quitApplication() { @objc func quitApplication() {
NSApplication.shared.terminate(self) NSApplication.shared.terminate(self)
} }
func applicationWillTerminate(_ aNotification: Notification) { func applicationWillTerminate(_: Notification) {
// Insert code here to tear down your application // Insert code here to tear down your application
} }
// MARK: Popovers // MARK: Popovers
@objc func togglePopover(sender: AnyObject?) { @objc func togglePopover(sender: AnyObject?) {
if popover.isShown { if popover.isShown {
closePopover(sender: sender) closePopover(sender: sender)
...@@ -101,20 +100,20 @@ class AppDelegate: NSObject, NSApplicationDelegate { ...@@ -101,20 +100,20 @@ class AppDelegate: NSObject, NSApplicationDelegate {
showPopover(sender: sender) showPopover(sender: sender)
} }
} }
func showPopover(sender: AnyObject?) { func showPopover(sender _: AnyObject?) {
if let button = statusItem.button { if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY) popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
} }
} }
func closePopover(sender: AnyObject?) { func closePopover(sender: AnyObject?) {
popover.performClose(sender) popover.performClose(sender)
} }
} }
class UploadReceiver: SKQueueDelegate { class UploadReceiver: SKQueueDelegate {
func receivedNotification(_ notification: SKQueueNotification, path: String, queue: SKQueue) { func receivedNotification(_: SKQueueNotification, path: String, queue _: SKQueue) {
UploadManager().uploadFile(path: path, fromQueue: true) UploadManager().uploadFile(path: path, fromQueue: true)
} }
} }
...@@ -9,42 +9,49 @@ ...@@ -9,42 +9,49 @@
import Cocoa import Cocoa
class DropView: NSImageView { class DropView: NSImageView {
@IBOutlet var uploadImage: DropView! @IBOutlet var uploadImage: DropView!
@IBOutlet weak var textLabel: NSTextField! @IBOutlet var textLabel: NSTextField!
var filePath: String? var filePath: String?
required init?(coder: NSCoder) { required init?(coder: NSCoder) {
super.init(coder: coder) super.init(coder: coder)
self.isEditable = false isEditable = false
self.wantsLayer = true wantsLayer = true
registerForDraggedTypes([NSPasteboard.PasteboardType.URL, NSPasteboard.PasteboardType.fileURL]) registerForDraggedTypes([NSPasteboard.PasteboardType.URL, NSPasteboard.PasteboardType.fileURL])
} }
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { override func draggingEntered(_: NSDraggingInfo) -> NSDragOperation {
textLabel.stringValue = "*notices your file* owo what's this?" textLabel.stringValue = "*notices your file* owo what's this?"
return .copy return .copy
} }
override func draggingEnded(_ sender: NSDraggingInfo) { override func draggingEnded(_: NSDraggingInfo) {
textLabel.stringValue = "Drag and Drop to Upload" textLabel.stringValue = "Drag and Drop to Upload"
} image = NSImage(named: "upload")
/*
override func draggingExited(_ sender: NSDraggingInfo?) { * For anybody in the future: The reason we change the image is because, for some reason, the
textLabel.stringValue = "Drag and Drop to Upload" * image view in PopoverMenu will not connect to the outlet, meaning I cannot mark it as un-editable.
} * No matter how hard I try it is an editable image view.
* If you, future person, find a solution, please email me. My email will be on https://github.com/broman
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { * But I am currently reachable at ryan@broman.dev
guard let pasteboard = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray, */
let path = pasteboard[0] as? String }
else {
return false override func draggingExited(_: NSDraggingInfo?) {
} textLabel.stringValue = "Drag and Drop to Upload"
}
self.filePath = path
//UploadManager().uploadFrom(path: path, shouldDelete: false) override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
print("File pseudo-uploaded") guard let pasteboard = sender.draggingPasteboard.propertyList(forType: NSPasteboard.PasteboardType(rawValue: "NSFilenamesPboardType")) as? NSArray,
let path = pasteboard[0] as? String
return true else {
} return false
}
filePath = path
UploadManager().uploadFrom(path: path, shouldDelete: false)
return true
}
} }
...@@ -7,28 +7,28 @@ ...@@ -7,28 +7,28 @@
// Copyright © 2017 JOS Computing. All rights reserved. // Copyright © 2017 JOS Computing. All rights reserved.
// //
import Foundation
import Alamofire import Alamofire
import Foundation
class PomfManager { class PomfManager {
func uploadFile(pathToFile: String, completionHandler: @escaping (_ : Error?, _ : String) -> Void) { func uploadFile(pathToFile: String, completionHandler: @escaping (_: Error?, _: String) -> Void) {
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
let uploadPath = defaults.string(forKey: "pomfUploadPath") let uploadPath = defaults.string(forKey: "pomfUploadPath")
if uploadPath == nil { if uploadPath == nil {
// Alert the user they're not configured. // Alert the user they're not configured.
let userInfo: [AnyHashable : Any] = [ let userInfo: [AnyHashable: Any] = [
NSLocalizedDescriptionKey : NSLocalizedString("Unsuccessful", value: "Go to Settings and enter a Pomf upload url.", comment: "") , NSLocalizedDescriptionKey: NSLocalizedString("Unsuccessful", value: "Go to Settings and enter a Pomf upload url.", comment: ""),
] ]
completionHandler(NSError(domain: "PomfErrorDomain", code: 1, userInfo: userInfo as? [String : Any]), "https://google.com") completionHandler(NSError(domain: "PomfErrorDomain", code: 1, userInfo: userInfo as? [String: Any]), "https://google.com")
return return
} }
// Create a POST request // Create a POST request
let fileToUpload = URL(fileURLWithPath: pathToFile) let fileToUpload = URL(fileURLWithPath: pathToFile)
Alamofire.upload( Alamofire.upload(
multipartFormData: { multipartFormData in multipartFormData: { multipartFormData in
multipartFormData.append(fileToUpload, withName: "files[]") multipartFormData.append(fileToUpload, withName: "files[]")
}, },
to: uploadPath!, to: uploadPath!,
encodingCompletion: { encodingResult in encodingCompletion: { encodingResult in
switch encodingResult { switch encodingResult {
...@@ -37,39 +37,38 @@ class PomfManager { ...@@ -37,39 +37,38 @@ class PomfManager {
// Broadcast current progress // Broadcast current progress
NotificationCenter.default.post(name: Notification.Name("UpdateIconWithProgressValue"), object: nil, userInfo: ["progress": progress.fractionCompleted]) NotificationCenter.default.post(name: Notification.Name("UpdateIconWithProgressValue"), object: nil, userInfo: ["progress": progress.fractionCompleted])
} }
upload.responseJSON { response in upload.responseJSON { response in
// Parse JSON from the server. // Parse JSON from the server.
// However, before parsing, set the original image // However, before parsing, set the original image
NotificationCenter.default.post(name: Notification.Name("UpdateIconWithCompletion"), object: nil) NotificationCenter.default.post(name: Notification.Name("UpdateIconWithCompletion"), object: nil)
if let parsedData : NSDictionary = response.result.value as? NSDictionary { if let parsedData: NSDictionary = response.result.value as? NSDictionary {
let status : Bool = parsedData["success"] as! Bool let status: Bool = parsedData["success"] as! Bool
if (status == false) { if status == false {
let description : String = parsedData["description"] as! String let description: String = parsedData["description"] as! String
let userInfo: [AnyHashable : Any] = [ let userInfo: [AnyHashable: Any] = [
NSLocalizedDescriptionKey : NSLocalizedString("Unsuccessful", value: description, comment: "") , NSLocalizedDescriptionKey: NSLocalizedString("Unsuccessful", value: description, comment: ""),
NSLocalizedFailureReasonErrorKey : NSLocalizedString("Unsuccessful", value: description, comment: "") NSLocalizedFailureReasonErrorKey: NSLocalizedString("Unsuccessful", value: description, comment: ""),
] ]
let errorCode : Int = parsedData["errorcode"] as! Int let errorCode: Int = parsedData["errorcode"] as! Int
completionHandler(NSError(domain: "PomfErrorDomain", code: errorCode, userInfo: userInfo as? [String : Any]), "https://google.com") completionHandler(NSError(domain: "PomfErrorDomain", code: errorCode, userInfo: userInfo as? [String: Any]), "https://google.com")
return return
} }
// Attempt to get information returned over the uploaded file. // Attempt to get information returned over the uploaded file.
let test : [NSDictionary] = parsedData["files"] as! [NSDictionary] let test: [NSDictionary] = parsedData["files"] as! [NSDictionary]
let furtherTest : NSDictionary = test[0] let furtherTest: NSDictionary = test[0]
// https://discord.coffee/c58cec.png // https://discord.coffee/c58cec.png
let fileName = furtherTest.object(forKey: "url") as! String? ?? "c58cec.png" let fileName = furtherTest.object(forKey: "url") as! String? ?? "c58cec.png"
completionHandler(nil, "\(defaults.string(forKey: "pomfBaseDomain")!)/\(fileName)" ) completionHandler(nil, "\(defaults.string(forKey: "pomfBaseDomain")!)/\(fileName)")
} }
} }
case .failure(let encodingError): case let .failure(encodingError):
print(encodingError) print(encodingError)
completionHandler(encodingError, "https://google.com/") completionHandler(encodingError, "https://google.com/")
} }
} }
) )
} }
} }
...@@ -9,23 +9,21 @@ ...@@ -9,23 +9,21 @@
import Cocoa import Cocoa
class PopoverMenu: NSViewController { class PopoverMenu: NSViewController {
let settingsMenu = NSMenu() let settingsMenu = NSMenu()
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
// Do view setup here. // Do view setup here.
let settingsItem = NSMenuItem() let settingsItem = NSMenuItem()
settingsItem.action = #selector(presentSettingsDialog) settingsItem.action = #selector(presentSettingsDialog)
settingsItem.title = "Settings" settingsItem.title = "Settings"
settingsMenu.addItem(settingsItem) settingsMenu.addItem(settingsItem)
let uploadItem = NSMenuItem() let uploadItem = NSMenuItem()
uploadItem.action = #selector(openDialog) uploadItem.action = #selector(openDialog)
uploadItem.title = "Upload File" uploadItem.title = "Upload File"
settingsMenu.addItem(uploadItem) settingsMenu.addItem(uploadItem)
// Seperator + quit // Seperator + quit
settingsMenu.addItem(NSMenuItem.separator()) settingsMenu.addItem(NSMenuItem.separator())
let quitItem = NSMenuItem() let quitItem = NSMenuItem()
...@@ -33,26 +31,26 @@ class PopoverMenu: NSViewController { ...@@ -33,26 +31,26 @@ class PopoverMenu: NSViewController {
quitItem.title = "Quit" quitItem.title = "Quit"
settingsMenu.addItem(quitItem) settingsMenu.addItem(quitItem)
} }
@objc func presentSettingsDialog(sender: Any) { @objc func presentSettingsDialog(sender _: Any) {
Bundle.main.loadNibNamed("SettingsView", owner: self, topLevelObjects: nil) Bundle.main.loadNibNamed("SettingsView", owner: self, topLevelObjects: nil)
AppDelegate().closePopover(sender: self) AppDelegate().closePopover(sender: self)
} }
@objc func openDialog(sender: Any) { @objc func openDialog(sender _: Any) {
let dialog = NSOpenPanel(); let dialog = NSOpenPanel()
dialog.title = "Choose a file to upload."; dialog.title = "Choose a file to upload."
dialog.showsResizeIndicator = true; dialog.showsResizeIndicator = true
dialog.showsHiddenFiles = false; dialog.showsHiddenFiles = false
dialog.canChooseDirectories = false; dialog.canChooseDirectories = false
dialog.canCreateDirectories = false; dialog.canCreateDirectories = false
dialog.allowsMultipleSelection = false; dialog.allowsMultipleSelection = false
if (dialog.runModal() == .OK) { if dialog.runModal() == .OK {
let result = dialog.url // Pathname of the file let result = dialog.url // Pathname of the file
if (result != nil) { if result != nil {
let path = result!.path let path = result!.path
UploadManager().uploadFile(path: path, fromQueue: false) UploadManager().uploadFile(path: path, fromQueue: false)
} }
...@@ -60,13 +58,14 @@ class PopoverMenu: NSViewController { ...@@ -60,13 +58,14 @@ class PopoverMenu: NSViewController {
// User clicked on "Cancel" // User clicked on "Cancel"
return return
} }
} }
@IBAction func toggleGearMenu(_ sender: Any) { @IBAction func toggleGearMenu(_ sender: Any) {
if let event = NSApplication.shared.currentEvent { if let event = NSApplication.shared.currentEvent {
NSMenu.popUpContextMenu(settingsMenu, with: event, for: sender as! NSView) NSMenu.popUpContextMenu(settingsMenu, with: event, for: sender as! NSView)
} }
} }
@IBAction func uploadFileClicked(_ sender: Any) { @IBAction func uploadFileClicked(_ sender: Any) {
openDialog(sender: sender as Any) openDialog(sender: sender as Any)
} }
......
...@@ -13,8 +13,7 @@ ...@@ -13,8 +13,7 @@
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="DropView"> <customObject id="-3" userLabel="Application" customClass="DropView">
<connections> <connections>
<outlet property="textLabel" destination="r6E-aY-KOH" id="CS5-MT-f3v"/> <outlet property="uploadImage" destination="687-0U-0uf" id="lti-id-9I9"/>
<outlet property="uploadImage" destination="687-0U-0uf" id="Fxy-xp-WkC"/>
</connections> </connections>
</customObject> </customObject>
<customView id="Hz6-mo-xeY"> <customView id="Hz6-mo-xeY">
...@@ -47,6 +46,9 @@ ...@@ -47,6 +46,9 @@
<rect key="frame" x="20" y="49" width="225" height="215"/> <rect key="frame" x="20" y="49" width="225" height="215"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/> <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="upload" id="DPA-2I-1fC"/> <imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="upload" id="DPA-2I-1fC"/>
<connections>
<outlet property="textLabel" destination="r6E-aY-KOH" id="nQx-7n-fKo"/>
</connections>
</imageView> </imageView>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="r6E-aY-KOH"> <textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="r6E-aY-KOH">
<rect key="frame" x="5" y="95" width="254" height="23"/> <rect key="frame" x="5" y="95" width="254" height="23"/>
......
...@@ -9,38 +9,39 @@ ...@@ -9,38 +9,39 @@
import Cocoa import Cocoa
class SettingsView: NSView { class SettingsView: NSView {
@IBOutlet weak var apiURL: NSTextField! @IBOutlet var apiURL: NSTextField!
@IBOutlet weak var apiEndDomain: NSTextField! @IBOutlet var apiEndDomain: NSTextField!
@IBOutlet weak var owoToken: NSTextField! @IBOutlet var owoToken: NSTextField!
@IBOutlet weak var owoTokenDescription: NSTextField! @IBOutlet var owoTokenDescription: NSTextField!
@IBOutlet weak var serviceSelection: NSPopUpButton! @IBOutlet var serviceSelection: NSPopUpButton!
let owoBetaAPIURL = "https://api.awau.moe/upload/pomf?key=" let owoBetaAPIURL = "https://api.awau.moe/upload/pomf?key="
let standard = UserDefaults.standard let standard = UserDefaults.standard
// Load defaults // Load defaults
func viewWillMove(_ currentWindow: NSWindow?) { func viewWillMove(_ currentWindow: NSWindow?) {
currentWindow!.makeKeyAndOrderFront(self) currentWindow!.makeKeyAndOrderFront(self)
owoToken.stringValue = standard.string(forKey: "owoToken") ?? "" owoToken.stringValue = standard.string(forKey: "owoToken") ?? ""
apiURL.stringValue = standard.string(forKey: "pomfUploadPath") ?? "" apiURL.stringValue = standard.string(forKey: "pomfUploadPath") ?? ""
apiEndDomain.stringValue = standard.string(forKey: "pomfBaseDomain") ?? "" apiEndDomain.stringValue = standard.string(forKey: "pomfBaseDomain") ?? ""
serviceSelection.selectItem(at: standard.integer(forKey: "selectedService")) serviceSelection.selectItem(at: standard.integer(forKey: "selectedService"))
} }
@IBAction func saveData(_ sender: Any) { @IBAction func saveData(_: Any) {
if serviceSelection.selectedItem?.title == "OwO Beta" || owoToken.stringValue != "" { if serviceSelection.selectedItem?.title == "OwO Beta" || owoToken.stringValue != "" {
let url = "\(owoBetaAPIURL)\(owoToken.stringValue)" let url = "\(owoBetaAPIURL)\(owoToken.stringValue)"
standard.set(url, forKey: "pomfUploadPath") standard.set(url, forKey: "pomfUploadPath")
} else { } else {
standard.set("pomfUploadPath", forKey: apiURL.stringValue) standard.set("pomfUploadPath", forKey: apiURL.stringValue)
} }
standard.set(apiEndDomain.stringValue, forKey: "pomfBaseDomain") standard.set(apiEndDomain.stringValue, forKey: "pomfBaseDomain")
standard.set(owoToken.stringValue, forKey: "owoToken") standard.set(owoToken.stringValue, forKey: "owoToken")
standard.set(serviceSelection.indexOfSelectedItem, forKey: "selectedService") standard.set(serviceSelection.indexOfSelectedItem, forKey: "selectedService")
} }
@IBAction func serviceTypeUpdated(_ sender: Any) {
@IBAction func serviceTypeUpdated(_: Any) {
if serviceSelection.selectedItem?.title != "OwO Beta" { if serviceSelection.selectedItem?.title != "OwO Beta" {
owoToken.isHidden = true owoToken.isHidden = true
owoTokenDescription.isHidden = true owoTokenDescription.isHidden = true
...@@ -49,8 +50,8 @@ class SettingsView: NSView { ...@@ -49,8 +50,8 @@ class SettingsView: NSView {
owoTokenDescription.isHidden = false owoTokenDescription.isHidden = false
} }
} }
@IBAction func owoTokenUpdated(_ sender: Any) { @IBAction func owoTokenUpdated(_: Any) {
apiURL.stringValue = "\(owoBetaAPIURL)\(owoToken.stringValue)" apiURL.stringValue = "\(owoBetaAPIURL)\(owoToken.stringValue)"
} }
} }
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14313.13.2" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct"> <document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies> <dependencies>
<deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14313.13.2"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies> </dependencies>
<objects> <objects>
<customObject id="-2" userLabel="File's Owner"/> <customObject id="-2" userLabel="File's Owner"/>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/>
<window title="Preferences" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g"> <window title="Settings" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/>
<rect key="contentRect" x="196" y="240" width="410" height="478"/> <rect key="contentRect" x="196" y="240" width="410" height="478"/>
<rect key="screenRect" x="0.0" y="0.0" width="1920" height="1177"/> <rect key="screenRect" x="0.0" y="0.0" width="1440" height="877"/>
<view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ" customClass="SettingsView" customModule="Screenshottr" customModuleProvider="target"> <view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ" customClass="SettingsView" customModule="Screenshottr" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="410" height="478"/> <rect key="frame" x="0.0" y="0.0" width="410" height="478"/>
<autoresizingMask key="autoresizingMask"/> <autoresizingMask key="autoresizingMask"/>
...@@ -127,6 +126,15 @@ ...@@ -127,6 +126,15 @@
<action selector="performClose:" target="QvC-M9-y7g" id="e3t-a4-0VU"/> <action selector="performClose:" target="QvC-M9-y7g" id="e3t-a4-0VU"/>
</connections> </connections>
</button> </button>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Rre-0n-8Pa">
<rect key="frame" x="18" y="135" width="374" height="17"/>
<autoresizingMask key="autoresizingMask"/>
<textFieldCell key="cell" lineBreakMode="clipping" title="Upload icon provided by 8Icons" id="QIA-eh-0x8">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews> </subviews>
<connections> <connections>
<outlet property="apiEndDomain" destination="uKy-PG-R3s" id="53E-RA-Rwb"/> <outlet property="apiEndDomain" destination="uKy-PG-R3s" id="53E-RA-Rwb"/>
......
...@@ -6,41 +6,41 @@ ...@@ -6,41 +6,41 @@
// Copyright © 2017 JOS Computing. All rights reserved. // Copyright © 2017 JOS Computing. All rights reserved.
// //
import Foundation
import AppKit import AppKit
import Foundation
class UploadManager : NSObject { class UploadManager: NSObject {
let uploadingKey = "isUploadingAlready" let uploadingKey = "isUploadingAlready"
func uploadFile(path: String, fromQueue: Bool) { func uploadFile(path: String, fromQueue: Bool) {
if (fromQueue) { if fromQueue {
let defaults = UserDefaults.standard let defaults = UserDefaults.standard
if (defaults.bool(forKey: uploadingKey)) { if defaults.bool(forKey: uploadingKey) {
// We're already uploading, don't need to again. // We're already uploading, don't need to again.
#if DEBUG #if DEBUG
print("Goodbye.") print("Goodbye.")
#endif #endif
} else { } else {
defaults.set(true, forKey: uploadingKey) defaults.set(true, forKey: uploadingKey)
// This could probably be done better // This could probably be done better
// oh well lol // oh well lol
sleep(2) // sleep(2)
let fileManager = FileManager.default let fileManager = FileManager.default
do { do {
// Grab contents by predicate, convert to array, loop through array with paths // Grab contents by predicate, convert to array, loop through array with paths
let allFiles = try fileManager.contentsOfDirectory(atPath: path) let allFiles = try fileManager.contentsOfDirectory(atPath: path)
let toSeach: [String] = (allFiles as NSArray).compactMap({ $0 as? String }) let toSeach: [String] = (allFiles as NSArray).compactMap { $0 as? String }
var toUpload: [URL] = [] var toUpload: [URL] = []
for fileName in toSeach { for fileName in toSeach {
let filePath = URL(fileURLWithPath:path).appendingPathComponent(fileName) let filePath = URL(fileURLWithPath: path).appendingPathComponent(fileName)
let metadata : NSMetadataItem? = NSMetadataItem.init(url: filePath) let metadata: NSMetadataItem? = NSMetadataItem(url: filePath)
if (metadata == nil) { if metadata == nil {
print("That probably shouldn't have happened. File: \(filePath)") print("That probably shouldn't have happened. File: \(filePath)")
} else { } else {
// Check if tagged as screen capture or screen recording // Check if tagged as screen capture or screen recording
let attributes = metadata!.attributes let attributes = metadata!.attributes
if (attributes.contains("kMDItemIsScreenCapture") || attributes.contains("kMDItemIsScreenRecording")) { if attributes.contains("kMDItemIsScreenCapture") || attributes.contains("kMDItemIsScreenRecording") {
toUpload.append(filePath) toUpload.append(filePath)
print(toUpload) print(toUpload)
} }
...@@ -51,7 +51,7 @@ class UploadManager : NSObject { ...@@ -51,7 +51,7 @@ class UploadManager : NSObject {
uploadFrom(path: screenshot.path, shouldDelete: true) uploadFrom(path: screenshot.path, shouldDelete: true)
} }
defaults.set(false, forKey: uploadingKey) defaults.set(false, forKey: uploadingKey)
} catch let error { } catch {
showFailureNotification(errorText: error.localizedDescription) showFailureNotification(errorText: error.localizedDescription)
defaults.set(false, forKey: uploadingKey) defaults.set(false, forKey: uploadingKey)
} }
...@@ -60,23 +60,23 @@ class UploadManager : NSObject { ...@@ -60,23 +60,23 @@ class UploadManager : NSObject {
uploadFrom(path: path, shouldDelete: false) uploadFrom(path: path, shouldDelete: false)
} }
} }
func uploadFrom(path: String, shouldDelete: Bool) { func uploadFrom(path: String, shouldDelete: Bool) {
PomfManager().uploadFile(pathToFile: path) { (error, url) in PomfManager().uploadFile(pathToFile: path) { error, url in
self.finalizeUpload(path: path, error: error, url: url, shouldDelete: shouldDelete) {} self.finalizeUpload(path: path, error: error, url: url, shouldDelete: shouldDelete) {}
} }
} }
func finalizeUpload(path: String, error: Error?, url: String, shouldDelete: Bool, handler: () -> Void) { func finalizeUpload(path: String, error: Error?, url: String, shouldDelete: Bool, handler: () -> Void) {
if (error != nil) { if error != nil {
self.showFailureNotification(errorText: error!.localizedDescription) showFailureNotification(errorText: error!.localizedDescription)
handler() handler()
} else { } else {
NSPasteboard.general.clearContents() NSPasteboard.general.clearContents()
NSPasteboard.general.setString(url, forType: .string) NSPasteboard.general.setString(url, forType: .string)
print("File available at \(url)") print("File available at \(url)")
if (shouldDelete) { if shouldDelete {
// Trash file // Trash file
do { do {
_ = try FileManager.default.trashItem(at: URL(fileURLWithPath: path), resultingItemURL: nil) _ = try FileManager.default.trashItem(at: URL(fileURLWithPath: path), resultingItemURL: nil)
...@@ -84,26 +84,25 @@ class UploadManager : NSObject { ...@@ -84,26 +84,25 @@ class UploadManager : NSObject {
// whoops I did nothing // whoops I did nothing
} }
} }
let notification = NSUserNotification() let notification = NSUserNotification()
notification.title = "Success!" notification.title = "Success!"
notification.informativeText = "The link has been copied to your clipboard." notification.informativeText = "The link has been copied to your clipboard."
notification.soundName = NSUserNotificationDefaultSoundName notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.default.deliver(notification) NSUserNotificationCenter.default.deliver(notification)
handler() handler()
} }
} }
// We leave this as its own function for usage in failures in other areas. // We leave this as its own function for usage in failures in other areas.
func showFailureNotification(errorText: String) { func showFailureNotification(errorText: String) {
print(errorText) print(errorText)
let notification = NSUserNotification() let notification = NSUserNotification()
notification.title = "Screenshot machine 🅱roke." notification.title = "Screenshot machine 🅱roke."
notification.informativeText = errorText notification.informativeText = errorText
NSUserNotificationCenter.default.deliver(notification) NSUserNotificationCenter.default.deliver(notification)
} }
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment