2 // ScreenshotListViewController.swift
5 // Created by Hori,Masaki on 2016/12/30.
6 // Copyright © 2016年 Hori,Masaki. All rights reserved.
11 extension NSUserInterfaceItemIdentifier {
13 static let item = NSUserInterfaceItemIdentifier("item")
16 final class ScreenshotListViewController: NSViewController {
18 private static let maxImageSize = 800.0
19 private static let leftMergin = 8.0 + 1.0
20 private static let rightMergin = 8.0 + 1.0
22 var screenshots: ScreenshotModel = ScreenshotModel()
24 @IBOutlet private var screenshotsController: NSArrayController!
25 @IBOutlet private weak var collectionView: NSCollectionView!
27 private var selectionObservation: NSKeyValueObservation?
29 @objc dynamic var zoom: Double = UserDefaults.standard[.screenshotPreviewZoomValue] {
33 collectionView.reloadData()
34 UserDefaults.standard[.screenshotPreviewZoomValue] = zoom
37 @objc dynamic var maxZoom: Double = 1.0
39 private var collectionVisibleDidChangeHandler: ((Set<IndexPath>) -> Void)?
40 private var reloadHandler: (() -> Void)?
41 private var collectionSelectionDidChangeHandler: ((Int) -> Void)?
42 private(set) var inLiveScrolling = false
44 private var arrangedInformations: [ScreenshotInformation] {
46 return screenshotsController.arrangedObjects as? [ScreenshotInformation] ?? []
49 private var selectionInformations: [ScreenshotInformation] {
51 return screenshotsController.selectedObjects as? [ScreenshotInformation] ?? []
54 private var dirName: String {
56 guard let name = Bundle.main.localizedInfoDictionary?["CFBundleName"] as? String,
65 private var screenshotSaveDirectoryURL: URL {
67 let parentURL = URL(fileURLWithPath: AppDelegate.shared.screenShotSaveDirectory)
68 let url = parentURL.appendingPathComponent(dirName)
69 let fm = FileManager.default
70 var isDir: ObjCBool = false
74 if !fm.fileExists(atPath: url.path, isDirectory: &isDir) {
76 try fm.createDirectory(at: url, withIntermediateDirectories: false)
78 } else if !isDir.boolValue {
80 Logger.shared.log("\(url) is regular file, not direcory.")
87 Logger.shared.log("Can not create screenshot save directory.")
95 var indexPathsOfItemsBeingDragged: Set<IndexPath>?
98 override func viewDidLoad() {
102 let nib = NSNib(nibNamed: ScreenshotCollectionViewItem.nibName, bundle: nil)
103 collectionView.register(nib, forItemWithIdentifier: .item)
105 screenshots.sortDescriptors = [NSSortDescriptor(key: #keyPath(ScreenshotInformation.creationDate), ascending: false)]
106 selectionObservation = collectionView.observe(\NSCollectionView.selectionIndexPaths) { [weak self] (_, _) in
108 guard let `self` = self else {
113 let selections = self.collectionView.selectionIndexPaths
114 let selectionIndexes = selections.reduce(into: IndexSet()) { $0.insert($1.item) }
115 self.screenshots.selectedIndexes = selectionIndexes
116 selectionIndexes.first.map { self.collectionSelectionDidChangeHandler?($0) }
118 collectionView.postsFrameChangedNotifications = true
120 let nc = NotificationCenter.default
121 let scrollView = collectionView.enclosingScrollView
123 nc.addObserver(forName: NSView.frameDidChangeNotification, object: collectionView, queue: nil, using: viewFrameDidChange)
124 nc.addObserver(forName: NSScrollView.didLiveScrollNotification,
125 object: collectionView.enclosingScrollView, queue: nil) { _ in
127 let visibleItems = self.collectionView.indexPathsForVisibleItems()
128 self.collectionVisibleDidChangeHandler?(visibleItems)
130 nc.addObserver(forName: NSScrollView.willStartLiveScrollNotification, object: scrollView, queue: nil) { _ in
132 self.inLiveScrolling = true
134 nc.addObserver(forName: NSScrollView.didEndLiveScrollNotification, object: scrollView, queue: nil) { _ in
136 self.inLiveScrolling = false
138 nc.addObserver(forName: .didRegisterScreenshot,
140 queue: .main) { notification in
142 guard let url = notification.userInfo?[ScreenshotRegister.screenshotURLKey] as? URL else {
147 let info = ScreenshotInformation(url: url)
149 self.screenshotsController.insert(info, atArrangedObjectIndex: 0)
150 let set: Set<IndexPath> = [NSIndexPath(forItem: 0, inSection: 0) as IndexPath]
151 self.collectionView.selectionIndexPaths = set
153 self.collectionView.scrollToItems(at: set, scrollPosition: .nearestHorizontalEdge)
154 if UserDefaults.standard[.showsListWindowAtScreenshot] {
156 self.view.window?.makeKeyAndOrderFront(nil)
160 collectionView.setDraggingSourceOperationMask([.move, .copy, .delete], forLocal: false)
162 viewFrameDidChange(nil)
164 DispatchQueue.main.asyncAfter(deadline: .now() + 0.0001, execute: self.reloadData)
167 override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
169 guard let vc = segue.destinationController as? NSViewController else {
174 vc.representedObject = screenshots
177 func viewFrameDidChange(_ notification: Notification?) {
179 maxZoom = calcMaxZoom()
180 if zoom > maxZoom { zoom = maxZoom }
183 /// 画像の大きさの変化が自然になるようにzoom値から画像サイズを計算
184 private func sizeFrom(zoom: Double) -> CGFloat {
188 return CGFloat(type(of: self).maxImageSize * zoom * 0.6)
191 return CGFloat(type(of: self).maxImageSize * (0.8 * zoom * zoom * zoom + 0.2))
194 /// ビューの幅に合わせたzoomの最大値を計算
195 private func calcMaxZoom() -> Double {
197 let effectiveWidth = Double(collectionView.frame.size.width) - type(of: self).leftMergin - type(of: self).rightMergin
199 if effectiveWidth < 240 {
201 return effectiveWidth / type(of: self).maxImageSize / 0.6
203 if effectiveWidth > 800 {
208 return pow((effectiveWidth / type(of: self).maxImageSize - 0.2) / 0.8, 1.0 / 3.0)
211 private func reloadData() {
213 Promise<[ScreenshotInformation]>()
216 Result(ScreenshotLoader(self.screenshotSaveDirectoryURL).merge(screenshots: []))
219 .onSuccess { screenshots in
221 DispatchQueue.main.async {
223 self.screenshots.screenshots = screenshots
225 self.collectionView.selectionIndexPaths = [NSIndexPath(forItem: 0, inSection: 0) as IndexPath]
227 self.reloadHandler?()
235 extension ScreenshotListViewController {
237 @IBAction func reloadContent(_ sender: AnyObject?) {
242 @IBAction func reloadData(_ sender: AnyObject?) {
247 private func moveToTrash(_ urls: [URL]) {
249 let list = urls.map { $0.path }
250 .map { "(\"\($0)\" as POSIX file)" }
251 .joined(separator: " , ")
252 let script = "tell application \"Finder\"\n"
253 + " delete { \(list) }\n"
256 guard let aps = NSAppleScript(source: script) else {
261 aps.executeAndReturnError(nil)
264 @IBAction func delete(_ sender: AnyObject?) {
266 let selectionURLs = selectionInformations.map { $0.url }
268 let selectionIndexes = screenshotsController.selectionIndexes
269 screenshotsController.remove(atArrangedObjectIndexes: selectionIndexes)
272 guard var index = selectionIndexes.first else {
277 if arrangedInformations.count <= index {
279 index = arrangedInformations.count - 1
281 collectionView.selectionIndexPaths = [NSIndexPath(forItem: index, inSection: 0) as IndexPath]
283 moveToTrash(selectionURLs)
286 @IBAction func revealInFinder(_ sender: AnyObject?) {
288 let urls = selectionInformations.map { $0.url }
289 NSWorkspace.shared.activateFileViewerSelecting(urls)
293 extension ScreenshotListViewController: NSCollectionViewDelegateFlowLayout {
295 func collectionView(_ collectionView: NSCollectionView,
296 layout collectionViewLayout: NSCollectionViewLayout,
297 sizeForItemAt indexPath: IndexPath) -> NSSize {
299 let size = sizeFrom(zoom: zoom)
301 return NSSize(width: size, height: size)
305 func collectionView(_ collectionView: NSCollectionView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
310 func collectionView(_ collectionView: NSCollectionView, pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
312 return arrangedInformations[indexPath.item].url.absoluteURL as NSURL
315 func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexPaths: Set<IndexPath>) {
317 indexPathsOfItemsBeingDragged = indexPaths
320 func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
322 defer { indexPathsOfItemsBeingDragged = nil }
324 guard let dragged = indexPathsOfItemsBeingDragged else {
328 guard operation.contains(.move) || operation.contains(.delete) else {
333 var indexes = IndexSet()
334 dragged.forEach { indexes.insert($0.item) }
336 screenshotsController.remove(atArrangedObjectIndexes: indexes)
341 @available(OSX 10.12.2, *)
342 private var kTouchBars: [Int: NSTouchBar] = [:]
343 @available(OSX 10.12.2, *)
344 private var kScrubbers: [Int: NSScrubber] = [:]
345 @available(OSX 10.12.2, *)
346 private var kPickers: [Int: NSSharingServicePickerTouchBarItem] = [:]
348 @available(OSX 10.12.2, *)
349 extension ScreenshotListViewController: NSTouchBarDelegate {
351 static let ServicesItemIdentifier: NSTouchBarItem.Identifier
352 = NSTouchBarItem.Identifier(rawValue: "com.masakih.sharingTouchBarItem")
354 @IBOutlet private var screenshotTouchBar: NSTouchBar! {
356 get { return kTouchBars[hashValue] }
357 set { kTouchBars[hashValue] = newValue }
360 @IBOutlet private var scrubber: NSScrubber! {
362 get { return kScrubbers[hashValue] }
363 set { kScrubbers[hashValue] = newValue }
366 @IBOutlet private var sharingItem: NSSharingServicePickerTouchBarItem! {
368 get { return kPickers[hashValue] }
369 set { kPickers[hashValue] = newValue }
372 override func makeTouchBar() -> NSTouchBar? {
374 Bundle.main.loadNibNamed(NSNib.Name("ScreenshotTouchBar"), owner: self, topLevelObjects: nil)
375 let identifiers = self.screenshotTouchBar.defaultItemIdentifiers
376 + [type(of: self).ServicesItemIdentifier]
377 screenshotTouchBar.defaultItemIdentifiers = identifiers
379 if collectionVisibleDidChangeHandler == nil {
381 collectionVisibleDidChangeHandler = { [weak self] in
383 guard let `self` = self else {
387 guard let index = $0.first else {
392 let middle = index.item + $0.count / 2
394 if middle < self.arrangedInformations.count - 1 {
396 self.scrubber.scrollItem(at: middle, to: .none)
401 if collectionSelectionDidChangeHandler == nil {
403 collectionSelectionDidChangeHandler = { [weak self] in
405 self?.scrubber.selectedIndex = $0
409 if reloadHandler == nil {
411 reloadHandler = { [weak self] in
413 self?.scrubber.reloadData()
417 return screenshotTouchBar
420 func touchBar(_ touchBar: NSTouchBar,
421 makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
423 guard identifier == type(of: self).ServicesItemIdentifier else {
428 if sharingItem == nil {
430 sharingItem = NSSharingServicePickerTouchBarItem(identifier: identifier)
432 if let w = view.window?.windowController as? NSSharingServicePickerTouchBarItemDelegate {
434 sharingItem.delegate = w
442 @available(OSX 10.12.2, *)
443 extension ScreenshotListViewController: NSScrubberDataSource, NSScrubberDelegate {
445 func numberOfItems(for scrubber: NSScrubber) -> Int {
447 return arrangedInformations.count
450 func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView {
452 guard case 0..<arrangedInformations.count = index else {
454 return NSScrubberImageItemView()
457 let info = arrangedInformations[index]
458 let itemView = NSScrubberImageItemView()
460 if let image = NSImage(contentsOf: info.url) {
462 itemView.image = image
468 func scrubber(_ scrubber: NSScrubber, didSelectItemAt selectedIndex: Int) {
470 let p = NSIndexPath(forItem: selectedIndex, inSection: 0) as IndexPath
472 collectionView.selectionIndexPaths = [p]
475 func scrubber(_ scrubber: NSScrubber, didChangeVisibleRange visibleRange: NSRange) {
482 let center = visibleRange.location + visibleRange.length / 2
483 let p = NSIndexPath(forItem: center, inSection: 0) as IndexPath
484 collectionView.scrollToItems(at: [p], scrollPosition: [.centeredVertically])