diff --git a/QuickDrop.xcodeproj/project.pbxproj b/QuickDrop.xcodeproj/project.pbxproj index 9f4bcc6..0507983 100644 --- a/QuickDrop.xcodeproj/project.pbxproj +++ b/QuickDrop.xcodeproj/project.pbxproj @@ -783,8 +783,8 @@ MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; - SHARED_BUILD = 17; - SHARED_VERSION = 1.4.2; + SHARED_BUILD = 19; + SHARED_VERSION = 1.4.4; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; @@ -842,8 +842,8 @@ MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; - SHARED_BUILD = 17; - SHARED_VERSION = 1.4.2; + SHARED_BUILD = 19; + SHARED_VERSION = 1.4.4; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; }; diff --git a/ShareExtension/ShareViewController.swift b/ShareExtension/ShareViewController.swift index c072d58..01e8a11 100644 --- a/ShareExtension/ShareViewController.swift +++ b/ShareExtension/ShareViewController.swift @@ -12,145 +12,139 @@ import NearbyShare class ShareViewController: NSViewController, ShareExtensionDelegate{ - private var urls:[URL]=[] - private var foundDevices:[RemoteDeviceInfo]=[] - private var chosenDevice:RemoteDeviceInfo? - private var lastError:Error? + private var urls:[URL]=[] + private var foundDevices:[RemoteDeviceInfo]=[] + private var chosenDevice:RemoteDeviceInfo? + private var lastError:Error? private var refreshTimer: Timer? = nil private var isDiscovering=false - - private var connectionEstablished = false - @IBOutlet var filesIcon:NSImageView? - @IBOutlet var filesLabel:NSTextField? - @IBOutlet var loadingOverlay:NSStackView? - @IBOutlet var largeProgress:NSProgressIndicator? - @IBOutlet var listView:NSCollectionView? - @IBOutlet var listViewWrapper:NSView? - @IBOutlet var contentWrap:NSView? - @IBOutlet var progressView:NSView? - @IBOutlet var progressDeviceIcon:NSImageView? - @IBOutlet var progressDeviceName:NSTextField? - @IBOutlet var progressProgressBar:NSProgressIndicator? - @IBOutlet var progressState:NSTextField? - @IBOutlet var progressDeviceIconWrap:NSView? - @IBOutlet var progressDeviceSecondaryIcon:NSImageView? + private var connectionEstablished = false + private var timeoutDispatchWorkItem: DispatchWorkItem? = nil + + @IBOutlet var filesIcon:NSImageView? + @IBOutlet var filesLabel:NSTextField? + @IBOutlet var loadingOverlay:NSStackView? + @IBOutlet var largeProgress:NSProgressIndicator? + @IBOutlet var listView:NSCollectionView? + @IBOutlet var listViewWrapper:NSView? + @IBOutlet var contentWrap:NSView? + @IBOutlet var progressView:NSView? + @IBOutlet var progressDeviceIcon:NSImageView? + @IBOutlet var progressDeviceName:NSTextField? + @IBOutlet var progressProgressBar:NSProgressIndicator? + @IBOutlet var progressState:NSTextField? + @IBOutlet var progressDeviceIconWrap:NSView? + @IBOutlet var progressDeviceSecondaryIcon:NSImageView? @IBOutlet var dontSeeDeviceButton: NSButton? private var qrCodeSheetView: NSPanel? = nil private var sheetAttachedWindow: NSWindow? = nil override var nibName: NSNib.Name? { - return NSNib.Name("ShareViewController") - } - - override func loadView() { - super.loadView() - - // Insert code here to customize the view - let item = self.extensionContext!.inputItems[0] as! NSExtensionItem - if let attachments = item.attachments { - for attachment in attachments as NSArray{ - let provider=attachment as! NSItemProvider - provider.loadItem(forTypeIdentifier: kUTTypeURL as String) { data, err in - if let urlData=data as? Data{ - if let url=URL(dataRepresentation: urlData, relativeTo: nil, isAbsolute: false){ - self.urls.append(url) - if self.urls.count==attachments.count{ - DispatchQueue.main.async { - self.urlsReady() - } - } - } - }else if let url=data as? NSURL{ - self.urls.append(url as URL) - if self.urls.count==attachments.count{ - DispatchQueue.main.async { - self.urlsReady() - } - } - } - } - } - } else { - let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) - self.extensionContext!.cancelRequest(withError: cancelError) - return - } - - contentWrap!.addSubview(listViewWrapper!) - contentWrap!.addSubview(loadingOverlay!) - contentWrap!.addSubview(progressView!) - progressView!.isHidden=true - - listViewWrapper!.translatesAutoresizingMaskIntoConstraints=false - loadingOverlay!.translatesAutoresizingMaskIntoConstraints=false - progressView!.translatesAutoresizingMaskIntoConstraints=false - NSLayoutConstraint.activate([ - NSLayoutConstraint(item: listViewWrapper!, attribute: .width, relatedBy: .equal, toItem: contentWrap, attribute: .width, multiplier: 1, constant: 0), - NSLayoutConstraint(item: listViewWrapper!, attribute: .height, relatedBy: .equal, toItem: contentWrap, attribute: .height, multiplier: 1, constant: 0), - - NSLayoutConstraint(item: loadingOverlay!, attribute: .width, relatedBy: .equal, toItem: contentWrap, attribute: .width, multiplier: 1, constant: 0), - NSLayoutConstraint(item: loadingOverlay!, attribute: .centerY, relatedBy: .equal, toItem: contentWrap, attribute: .centerY, multiplier: 1, constant: 0), - - NSLayoutConstraint(item: progressView!, attribute: .width, relatedBy: .equal, toItem: contentWrap, attribute: .width, multiplier: 1, constant: 0), - NSLayoutConstraint(item: progressView!, attribute: .centerY, relatedBy: .equal, toItem: contentWrap, attribute: .centerY, multiplier: 1, constant: 0) - ]) - - largeProgress!.startAnimation(nil) - let flowLayout=NSCollectionViewFlowLayout() - flowLayout.itemSize=NSSize(width: 75, height: 90) - flowLayout.sectionInset=NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) - flowLayout.minimumInteritemSpacing=10 - flowLayout.minimumLineSpacing=10 - listView!.collectionViewLayout=flowLayout - listView!.dataSource=self - - progressDeviceIconWrap!.wantsLayer=true - progressDeviceIconWrap!.layer!.masksToBounds=false - } - - override func viewDidLoad(){ - super.viewDidLoad() + return NSNib.Name("ShareViewController") + } + + override func loadView() { + super.loadView() - launchMainApp() - - DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { - NearbyConnectionManager.shared.startDeviceDiscovery() - self.isDiscovering = true + // Insert code here to customize the view + let item = self.extensionContext!.inputItems[0] as! NSExtensionItem + if let attachments = item.attachments { + for attachment in attachments as NSArray{ + let provider=attachment as! NSItemProvider + provider.loadItem(forTypeIdentifier: kUTTypeURL as String) { data, err in + if let urlData=data as? Data{ + if let url=URL(dataRepresentation: urlData, relativeTo: nil, isAbsolute: false){ + self.urls.append(url) + if self.urls.count==attachments.count{ + DispatchQueue.main.async { + self.urlsReady() + } + } + } + }else if let url=data as? NSURL{ + self.urls.append(url as URL) + if self.urls.count==attachments.count{ + DispatchQueue.main.async { + self.urlsReady() + } + } + } + } + } + } else { + let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) + self.extensionContext!.cancelRequest(withError: cancelError) + return } - NearbyConnectionManager.shared.addShareExtensionDelegate(self) - } - - override func viewWillDisappear() { + contentWrap!.addSubview(listViewWrapper!) + contentWrap!.addSubview(loadingOverlay!) + contentWrap!.addSubview(progressView!) + progressView!.isHidden=true - if chosenDevice==nil{ + listViewWrapper!.translatesAutoresizingMaskIntoConstraints=false + loadingOverlay!.translatesAutoresizingMaskIntoConstraints=false + progressView!.translatesAutoresizingMaskIntoConstraints=false + NSLayoutConstraint.activate([ + NSLayoutConstraint(item: listViewWrapper!, attribute: .width, relatedBy: .equal, toItem: contentWrap, attribute: .width, multiplier: 1, constant: 0), + NSLayoutConstraint(item: listViewWrapper!, attribute: .height, relatedBy: .equal, toItem: contentWrap, attribute: .height, multiplier: 1, constant: 0), + + NSLayoutConstraint(item: loadingOverlay!, attribute: .width, relatedBy: .equal, toItem: contentWrap, attribute: .width, multiplier: 1, constant: 0), + NSLayoutConstraint(item: loadingOverlay!, attribute: .centerY, relatedBy: .equal, toItem: contentWrap, attribute: .centerY, multiplier: 1, constant: 0), + + NSLayoutConstraint(item: progressView!, attribute: .width, relatedBy: .equal, toItem: contentWrap, attribute: .width, multiplier: 1, constant: 0), + NSLayoutConstraint(item: progressView!, attribute: .centerY, relatedBy: .equal, toItem: contentWrap, attribute: .centerY, multiplier: 1, constant: 0) + ]) + + largeProgress!.startAnimation(nil) + let flowLayout=NSCollectionViewFlowLayout() + flowLayout.itemSize=NSSize(width: 75, height: 90) + flowLayout.sectionInset=NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) + flowLayout.minimumInteritemSpacing=10 + flowLayout.minimumLineSpacing=10 + listView!.collectionViewLayout=flowLayout + listView!.dataSource=self + + progressDeviceIconWrap!.wantsLayer=true + progressDeviceIconWrap!.layer!.masksToBounds=false + } + + + override func viewDidLoad(){ + super.viewDidLoad() + + launchMainApp() + NearbyConnectionManager.shared.addShareExtensionDelegate(self) + } + + + override func viewWillDisappear() { + + log("ShareViewController: viewWillDisappear") + + timeoutDispatchWorkItem?.cancel() + + if chosenDevice==nil{ isDiscovering = false refreshTimer?.invalidate() NearbyConnectionManager.shared.stopDeviceDiscovery() - } - NearbyConnectionManager.shared.removeShareExtensionDelegate(self) - } - - @IBAction func cancel(_ sender: AnyObject?) { + } + NearbyConnectionManager.shared.removeShareExtensionDelegate(self) + } + + + @IBAction func cancel(_ sender: AnyObject?) { if let device=chosenDevice{ - NearbyConnectionManager.shared.cancelOutgoingTransfer(id: device.id!) - } - let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) - self.extensionContext!.cancelRequest(withError: cancelError) - } - - private func closeQrCodeView() { - if let mainWindow = sheetAttachedWindow, let qrCodeView = self.qrCodeSheetView { - mainWindow.endSheet(qrCodeView) - - self.qrCodeSheetView = nil - self.sheetAttachedWindow = nil + NearbyConnectionManager.shared.cancelOutgoingTransfer(id: device.id!) } + let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) + self.extensionContext!.cancelRequest(withError: cancelError) } + @IBAction func dontSeeDeviceButton(_ sender: AnyObject?) { let contentView = QrCodeView { @@ -177,11 +171,21 @@ class ShareViewController: NSViewController, ShareExtensionDelegate{ } - private func urlsReady(){ - for url in urls{ - if url.isFileURL{ - let isDirectory=UnsafeMutablePointer.allocate(capacity: 1) - if FileManager.default.fileExists(atPath: url.path, isDirectory: isDirectory) && isDirectory.pointee.boolValue{ + private func closeQrCodeView() { + if let mainWindow = sheetAttachedWindow, let qrCodeView = self.qrCodeSheetView { + mainWindow.endSheet(qrCodeView) + + self.qrCodeSheetView = nil + self.sheetAttachedWindow = nil + } + } + + + private func urlsReady() { + for url in urls { + if url.isFileURL { + let isDirectory = UnsafeMutablePointer.allocate(capacity: 1) + if FileManager.default.fileExists(atPath: url.path, isDirectory: isDirectory) && isDirectory.pointee.boolValue { do { let zipUrl = try createZipAtTmp(zipFilename: url.lastPathComponent, fromDirectory: url) @@ -191,7 +195,7 @@ class ShareViewController: NSViewController, ShareExtensionDelegate{ } catch { log("Error creating zip file: \(error)") - + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { log("Canceling share request because URL \(url) is a directory") @@ -202,125 +206,133 @@ class ShareViewController: NSViewController, ShareExtensionDelegate{ alert.informativeText = "TypeNotSupportedDescription".localized() alert.addButton(withTitle: "TypeNotSupportedButton".localized()) - let _ = alert.runModal() - let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) - - self.extensionContext!.cancelRequest(withError: cancelError) + alert.beginSheetModal(for: self.view.window!) { resp in + let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil) + self.extensionContext!.cancelRequest(withError: cancelError) + } } return } - } - } - } - if urls.count==1{ - if urls[0].isFileURL{ - filesLabel!.stringValue=urls[0].lastPathComponent - filesIcon!.image=NSWorkspace.shared.icon(forFile: urls[0].path) - }else if urls[0].scheme=="http" || urls[0].scheme=="https"{ - filesLabel!.stringValue=urls[0].absoluteString - filesIcon!.image=NSImage(named: NSImage.networkName) - } - }else{ - filesLabel!.stringValue=String.localizedStringWithFormat(NSLocalizedString("NFiles", value: "%d files", comment: ""), urls.count) - filesIcon!.image=NSImage(named: NSImage.multipleDocumentsName) - } - } - - func addDevice(device: RemoteDeviceInfo) { - if foundDevices.isEmpty{ - loadingOverlay?.animator().isHidden=true - } - foundDevices.append(device) - listView?.animator().insertItems(at: [[0, foundDevices.count-1]]) + } + } + } + + if urls.count == 1 { + if urls[0].isFileURL { + filesLabel!.stringValue = urls[0].lastPathComponent + filesIcon!.image = NSWorkspace.shared.icon(forFile: urls[0].path) + } + else if urls[0].scheme == "http" || urls[0].scheme == "https" { + + filesLabel!.stringValue = urls[0].absoluteString + filesIcon!.image = NSImage(named: NSImage.networkName) + } + } + else { + filesLabel!.stringValue = String.localizedStringWithFormat(NSLocalizedString("NFiles", value: "%d files", comment: ""), urls.count) + filesIcon!.image = NSImage(named: NSImage.multipleDocumentsName) + } + } + + func addDevice(device: RemoteDeviceInfo) { + if foundDevices.isEmpty{ + loadingOverlay?.animator().isHidden=true + } + foundDevices.append(device) + listView?.animator().insertItems(at: [[0, foundDevices.count-1]]) closeQrCodeView() - } - - func removeDevice(id: String){ - if chosenDevice != nil{ - return - } - for i in foundDevices.indices{ - if foundDevices[i].id==id{ - foundDevices.remove(at: i) - listView?.animator().deleteItems(at: [[0, i]]) - break - } - } - if foundDevices.isEmpty{ - loadingOverlay?.animator().isHidden=false - } - } - - func connectionWasEstablished(pinCode: String) { + } + + func removeDevice(id: String) { + if chosenDevice != nil { + return + } + for i in foundDevices.indices { + if foundDevices[i].id==id { + foundDevices.remove(at: i) + listView?.animator().deleteItems(at: [[0, i]]) + break + } + } + if foundDevices.isEmpty { + loadingOverlay?.animator().isHidden=false + } + } + + func connectionWasEstablished(pinCode: String) { connectionEstablished = true - progressState?.stringValue=String(format:NSLocalizedString("PinCode", value: "PIN: %@", comment: ""), arguments: [pinCode]) - progressProgressBar?.isIndeterminate=false - progressProgressBar?.maxValue=1000 - progressProgressBar?.doubleValue=0 - } - - func connectionFailed(with error: Error) { - progressProgressBar?.isIndeterminate=false - progressProgressBar?.maxValue=1000 - progressProgressBar?.doubleValue=0 - lastError=error - if let ne=(error as? NearbyError), case let .canceled(reason)=ne{ - switch reason{ - case .userRejected: - progressState?.stringValue=NSLocalizedString("TransferDeclined", value: "Declined", comment: "") - case .userCanceled: - progressState?.stringValue=NSLocalizedString("TransferCanceled", value: "Canceled", comment: "") - case .notEnoughSpace: - progressState?.stringValue=NSLocalizedString("NotEnoughSpace", value: "Not enough disk space", comment: "") - case .unsupportedType: - progressState?.stringValue=NSLocalizedString("UnsupportedType", value: "Attachment type not supported", comment: "") - case .timedOut: - progressState?.stringValue=NSLocalizedString("TransferTimedOut", value: "Timed out", comment: "") - } - progressDeviceSecondaryIcon?.isHidden=false - dismissDelayed() - }else{ - let alert=NSAlert(error: error) - alert.beginSheetModal(for: view.window!) { resp in - self.extensionContext!.cancelRequest(withError: error) - } - } - } - - func transferAccepted() { - progressState?.stringValue=NSLocalizedString("Sending", value: "Sending...", comment: "") - } - - func transferProgress(progress: Double) { - progressProgressBar!.doubleValue=progress*progressProgressBar!.maxValue - } - - func transferFinished() { - progressState?.stringValue=NSLocalizedString("TransferFinished", value: "Transfer finished", comment: "") - dismissDelayed() - } - - func selectDevice(device:RemoteDeviceInfo){ - + progressState?.stringValue=String(format:NSLocalizedString("PinCode", value: "PIN: %@", comment: ""), arguments: [pinCode]) + progressProgressBar?.isIndeterminate = false + progressProgressBar?.maxValue = 1000 + progressProgressBar?.doubleValue = 0 + } + + func connectionFailed(with error: Error) { + + progressProgressBar?.isIndeterminate = false + progressProgressBar?.maxValue = 1000 + progressProgressBar?.doubleValue = 0 + lastError = error + + if let ne = (error as? NearbyError), case let .canceled(reason) = ne{ + switch reason { + case .userRejected: + progressState?.stringValue=NSLocalizedString("TransferDeclined", value: "Declined", comment: "") + case .userCanceled: + progressState?.stringValue=NSLocalizedString("TransferCanceled", value: "Canceled", comment: "") + case .notEnoughSpace: + progressState?.stringValue=NSLocalizedString("NotEnoughSpace", value: "Not enough disk space", comment: "") + case .unsupportedType: + progressState?.stringValue=NSLocalizedString("UnsupportedType", value: "Attachment type not supported", comment: "") + case .timedOut: + progressState?.stringValue=NSLocalizedString("TransferTimedOut", value: "Timed out", comment: "") + } + progressDeviceSecondaryIcon?.isHidden=false + dismissDelayed() + } else { + + let alert = NSAlert(error: error) + + alert.beginSheetModal(for: view.window!) { resp in + self.extensionContext!.cancelRequest(withError: error) + } + } + } + + func transferAccepted() { + progressState?.stringValue=NSLocalizedString("Sending", value: "Sending...", comment: "") + } + + func transferProgress(progress: Double) { + progressProgressBar!.doubleValue=progress*progressProgressBar!.maxValue + } + + func transferFinished() { + progressState?.stringValue=NSLocalizedString("TransferFinished", value: "Transfer finished", comment: "") + dismissDelayed() + } + + func selectDevice(device:RemoteDeviceInfo){ + isDiscovering = false refreshTimer?.invalidate() - NearbyConnectionManager.shared.stopDeviceDiscovery() + NearbyConnectionManager.shared.stopDeviceDiscovery() - listViewWrapper?.animator().isHidden=true + listViewWrapper?.animator().isHidden=true dontSeeDeviceButton?.animator().isHidden=true - progressView?.animator().isHidden=false + progressView?.animator().isHidden=false progressDeviceName?.stringValue=getDeviceName(device: device) - progressDeviceIcon?.image=imageForDeviceType(type: device.type) - progressProgressBar?.startAnimation(nil) - progressState?.stringValue=NSLocalizedString("Connecting", value: "Connecting...", comment: "") - chosenDevice=device - NearbyConnectionManager.shared.startOutgoingTransfer(deviceID: device.id!, delegate: self, urls: urls) + progressDeviceIcon?.image=imageForDeviceType(type: device.type) + progressProgressBar?.startAnimation(nil) + progressState?.stringValue=NSLocalizedString("Connecting", value: "Connecting...", comment: "") + chosenDevice=device + NearbyConnectionManager.shared.startOutgoingTransfer(deviceID: device.id!, delegate: self, urls: urls) - DispatchQueue.main.asyncAfter(deadline: .now() + 13.0) { + let timeoutAlert = DispatchWorkItem { if !self.connectionEstablished { let alert = NSAlert() @@ -330,56 +342,95 @@ class ShareViewController: NSViewController, ShareExtensionDelegate{ alert.informativeText = "TimeoutDescription".localized() alert.addButton(withTitle: "TimeoutButton".localized()) - let _ = alert.runModal() + + alert.beginSheetModal(for: self.view.window!) { _ in } } } - } - - private func dismissDelayed(){ - DispatchQueue.main.asyncAfter(deadline: .now()+2.0){ - if let error=self.lastError{ - self.extensionContext!.cancelRequest(withError: error) - }else{ - self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil) - } - } - } + + self.timeoutDispatchWorkItem = timeoutAlert + DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: timeoutAlert) + } + + private func dismissDelayed(){ + DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { + + if let error=self.lastError { + self.extensionContext!.cancelRequest(withError: error) + } + else { + self.extensionContext!.completeRequest(returningItems: nil, completionHandler: nil) + } + } + } + + private func launchMainApp() { + let bundleIdentifier = "com.leonboettger.neardrop" + let runningApps = NSWorkspace.shared.runningApplications + + // Check if the app is already running + let isRunning = runningApps.contains { $0.bundleIdentifier == bundleIdentifier } + + if !isRunning { + log("Launching main app") + NSWorkspace.shared.launchApplication(withBundleIdentifier: bundleIdentifier, + options: [.default], + additionalEventParamDescriptor: nil, + launchIdentifier: nil) + + DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { + NearbyConnectionManager.shared.startDeviceDiscovery() + self.isDiscovering = true + } + } + else { + log("Main app is already running") + NearbyConnectionManager.shared.startDeviceDiscovery() + self.isDiscovering = true + } + } } + fileprivate func imageForDeviceType(type:RemoteDeviceInfo.DeviceType)->NSImage{ - let imageName:String - switch type{ - case .tablet: - imageName="com.apple.ipad" - case .computer: - imageName="com.apple.macbookpro-13-unibody" - default: // also .phone - imageName="com.apple.iphone" - } - return NSImage(contentsOfFile: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/\(imageName).icns")! + let imageName:String + switch type{ + case .tablet: + imageName="com.apple.ipad" + case .computer: + imageName="com.apple.macbookpro-13-unibody" + default: // also .phone + imageName="com.apple.iphone" + } + return NSImage(contentsOfFile: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/\(imageName).icns")! } -extension ShareViewController:NSCollectionViewDataSource{ - func numberOfSections(in collectionView: NSCollectionView) -> Int { - return 1 - } - - func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { - return foundDevices.count - } - - func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { - let item=collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "DeviceListCell"), for: indexPath) - guard let collectionViewItem = item as? DeviceListCell else {return item} - let device=foundDevices[indexPath[1]] - collectionViewItem.textField?.stringValue=getDeviceName(device: device) - collectionViewItem.imageView?.image=imageForDeviceType(type: device.type) - // TODO maybe there's a better way to handle clicks on collection view items? I'm still new to Apple's way of doing UIs so I may do dumb shit occasionally - collectionViewItem.clickHandler={ - self.selectDevice(device: device) - } - return collectionViewItem - } + +extension ShareViewController:NSCollectionViewDataSource { + + func numberOfSections(in collectionView: NSCollectionView) -> Int { + return 1 + } + + func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { + return foundDevices.count + } + + func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { + + let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "DeviceListCell"), for: indexPath) + + guard let collectionViewItem = item as? DeviceListCell else { return item } + + let device = foundDevices[indexPath[1]] + + collectionViewItem.textField?.stringValue = getDeviceName(device: device) + collectionViewItem.imageView?.image = imageForDeviceType(type: device.type) + collectionViewItem.clickHandler = { + self.selectDevice(device: device) + } + + return collectionViewItem + } func getDeviceName(device: RemoteDeviceInfo) -> String { if device.name.count <= 1 { @@ -388,23 +439,3 @@ extension ShareViewController:NSCollectionViewDataSource{ return device.name } } - - -func launchMainApp() { - let bundleIdentifier = "com.leonboettger.neardrop" - let runningApps = NSWorkspace.shared.runningApplications - - // Check if the app is already running - let isRunning = runningApps.contains { $0.bundleIdentifier == bundleIdentifier } - - if !isRunning { - log("Launching main app") - NSWorkspace.shared.launchApplication(withBundleIdentifier: bundleIdentifier, - options: [.default], - additionalEventParamDescriptor: nil, - launchIdentifier: nil) - } - else { - log("Main app is already running") - } -}