OSDN Git Service

AppDelegateからウインドウに関する部分を分離した
[kcd/KCD.git] / KCD / ScreenshotInformation.swift
1 //
2 //  ScreenshotInformation.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/01/28.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 class ScreenshotModel: NSObject {
12     dynamic var screenshots: [ScreenshotInformation] = []
13     dynamic var sortDescriptors: [NSSortDescriptor]?
14     dynamic var selectedIndexes: IndexSet?
15     dynamic var filterPredicate: NSPredicate?
16 }
17
18 class ScreenshotInformation: NSObject, NSCoding {
19     let url: URL
20     var creationDate: Date? {
21         let attr = try? url.resourceValues(forKeys: [.creationDateKey])
22         return attr?.creationDate
23     }
24     var tags: [String]? {
25         get {
26             let attr = try? url.resourceValues(forKeys: [.tagNamesKey])
27             return attr?.tagNames
28         }
29         set {
30             let url = self.url as NSURL
31             do {
32                 if let array = newValue {
33                     try url.setResourceValue(array as NSArray, forKey: .tagNamesKey)
34                 } else {
35                     try url.setResourceValue([] as NSArray, forKey: .tagNamesKey)
36                 }
37             } catch {
38                 print("Can not set tagNames")
39             }
40         }
41     }
42     private(set) var version: Int
43     
44     init(url: URL, version: Int = 0) {
45         self.url = url
46         self.version = version
47         super.init()
48     }
49     
50     func incrementVersion() { version = version + 1 }
51     
52     // MARK: - NSCoding
53     struct CodingKey {
54         static let url = "Url"
55         static let version = "Version"
56     }
57     required convenience init?(coder aDecoder: NSCoder) {
58         guard let u = aDecoder.decodeObject(forKey: CodingKey.url) as? URL
59             else { return nil }
60         self.init(url: u)
61     }
62     func encode(with aCoder: NSCoder) {
63         aCoder.encode(url, forKey: CodingKey.url)
64     }
65 }
66
67 fileprivate let dateFormatter: DateFormatter = {
68     let f = DateFormatter()
69     f.dateStyle = .short
70     f.timeStyle = .short
71     f.doesRelativeDateFormatting = true
72     return f
73 }()
74
75 extension ScreenshotInformation {
76     var name: String? {
77         let attr = try? url.resourceValues(forKeys: [.localizedNameKey])
78         return attr?.localizedName
79     }
80     var creationDateString: String? {
81         return creationDate
82             .map { dateFormatter.string(from: $0) }
83     }
84 }