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 Future<[ScreenshotInformation]> {
215 ScreenshotLoader(self.screenshotSaveDirectoryURL).merge(screenshots: [])
218 .onSuccess { screenshots in
220 DispatchQueue.main.async {
222 self.screenshots.screenshots = screenshots
224 self.collectionView.selectionIndexPaths = [NSIndexPath(forItem: 0, inSection: 0) as IndexPath]
226 self.reloadHandler?()
234 extension ScreenshotListViewController {
236 @IBAction func reloadContent(_ sender: AnyObject?) {
241 @IBAction func reloadData(_ sender: AnyObject?) {
246 private func moveToTrash(_ urls: [URL]) {
248 let list = urls.map { $0.path }
249 .map { "(\"\($0)\" as POSIX file)" }
250 .joined(separator: " , ")
251 let script = "tell application \"Finder\"\n"
252 + " delete { \(list) }\n"
255 guard let aps = NSAppleScript(source: script) else {
260 aps.executeAndReturnError(nil)
263 @IBAction func delete(_ sender: AnyObject?) {
265 let selectionURLs = selectionInformations.map { $0.url }
267 let selectionIndexes = screenshotsController.selectionIndexes
268 screenshotsController.remove(atArrangedObjectIndexes: selectionIndexes)
271 guard var index = selectionIndexes.first else {
276 if arrangedInformations.count <= index {
278 index = arrangedInformations.count - 1
280 collectionView.selectionIndexPaths = [NSIndexPath(forItem: index, inSection: 0) as IndexPath]
282 moveToTrash(selectionURLs)
285 @IBAction func revealInFinder(_ sender: AnyObject?) {
287 let urls = selectionInformations.map { $0.url }
288 NSWorkspace.shared.activateFileViewerSelecting(urls)
292 extension ScreenshotListViewController: NSCollectionViewDelegateFlowLayout {
294 func collectionView(_ collectionView: NSCollectionView,
295 layout collectionViewLayout: NSCollectionViewLayout,
296 sizeForItemAt indexPath: IndexPath) -> NSSize {
298 let size = sizeFrom(zoom: zoom)
300 return NSSize(width: size, height: size)
304 func collectionView(_ collectionView: NSCollectionView, canDragItemsAt indexPaths: Set<IndexPath>, with event: NSEvent) -> Bool {
309 func collectionView(_ collectionView: NSCollectionView, pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
311 return arrangedInformations[indexPath.item].url.absoluteURL as NSURL
314 func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItemsAt indexPaths: Set<IndexPath>) {
316 indexPathsOfItemsBeingDragged = indexPaths
319 func collectionView(_ collectionView: NSCollectionView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, dragOperation operation: NSDragOperation) {
321 defer { indexPathsOfItemsBeingDragged = nil }
323 guard let dragged = indexPathsOfItemsBeingDragged else {
327 guard operation.contains(.move) || operation.contains(.delete) else {
332 var indexes = IndexSet()
333 dragged.forEach { indexes.insert($0.item) }
335 screenshotsController.remove(atArrangedObjectIndexes: indexes)
340 @available(OSX 10.12.2, *)
341 private var kTouchBars: [Int: NSTouchBar] = [:]
342 @available(OSX 10.12.2, *)
343 private var kScrubbers: [Int: NSScrubber] = [:]
344 @available(OSX 10.12.2, *)
345 private var kPickers: [Int: NSSharingServicePickerTouchBarItem] = [:]
347 @available(OSX 10.12.2, *)
348 extension ScreenshotListViewController: NSTouchBarDelegate {
350 static let ServicesItemIdentifier: NSTouchBarItem.Identifier
351 = NSTouchBarItem.Identifier(rawValue: "com.masakih.sharingTouchBarItem")
353 @IBOutlet private var screenshotTouchBar: NSTouchBar! {
355 get { return kTouchBars[hashValue] }
356 set { kTouchBars[hashValue] = newValue }
359 @IBOutlet private var scrubber: NSScrubber! {
361 get { return kScrubbers[hashValue] }
362 set { kScrubbers[hashValue] = newValue }
365 @IBOutlet private var sharingItem: NSSharingServicePickerTouchBarItem! {
367 get { return kPickers[hashValue] }
368 set { kPickers[hashValue] = newValue }
371 override func makeTouchBar() -> NSTouchBar? {
373 Bundle.main.loadNibNamed(NSNib.Name("ScreenshotTouchBar"), owner: self, topLevelObjects: nil)
374 let identifiers = self.screenshotTouchBar.defaultItemIdentifiers
375 + [type(of: self).ServicesItemIdentifier]
376 screenshotTouchBar.defaultItemIdentifiers = identifiers
378 if collectionVisibleDidChangeHandler == nil {
380 collectionVisibleDidChangeHandler = { [weak self] in
382 guard let `self` = self else {
386 guard let index = $0.first else {
391 let middle = index.item + $0.count / 2
393 if middle < self.arrangedInformations.count - 1 {
395 self.scrubber.scrollItem(at: middle, to: .none)
400 if collectionSelectionDidChangeHandler == nil {
402 collectionSelectionDidChangeHandler = { [weak self] in
404 self?.scrubber.selectedIndex = $0
408 if reloadHandler == nil {
410 reloadHandler = { [weak self] in
412 self?.scrubber.reloadData()
416 return screenshotTouchBar
419 func touchBar(_ touchBar: NSTouchBar,
420 makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
422 guard identifier == type(of: self).ServicesItemIdentifier else {
427 if sharingItem == nil {
429 sharingItem = NSSharingServicePickerTouchBarItem(identifier: identifier)
431 if let w = view.window?.windowController as? NSSharingServicePickerTouchBarItemDelegate {
433 sharingItem.delegate = w
441 @available(OSX 10.12.2, *)
442 extension ScreenshotListViewController: NSScrubberDataSource, NSScrubberDelegate {
444 func numberOfItems(for scrubber: NSScrubber) -> Int {
446 return arrangedInformations.count
449 func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView {
451 guard case 0..<arrangedInformations.count = index else {
453 return NSScrubberImageItemView()
456 let info = arrangedInformations[index]
457 let itemView = NSScrubberImageItemView()
459 if let image = NSImage(contentsOf: info.url) {
461 itemView.image = image
467 func scrubber(_ scrubber: NSScrubber, didSelectItemAt selectedIndex: Int) {
469 let p = NSIndexPath(forItem: selectedIndex, inSection: 0) as IndexPath
471 collectionView.selectionIndexPaths = [p]
474 func scrubber(_ scrubber: NSScrubber, didChangeVisibleRange visibleRange: NSRange) {
481 let center = visibleRange.location + visibleRange.length / 2
482 let p = NSIndexPath(forItem: center, inSection: 0) as IndexPath
483 collectionView.scrollToItems(at: [p], scrollPosition: [.centeredVertically])