KMTools.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. //
  2. // KMTools.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2023/3/7.
  6. //
  7. import Cocoa
  8. @objc class KMTools: NSObject {
  9. // MARK: -
  10. // MARK: 获取已打开的文件
  11. @objc class func getOpenDocumentURLs() -> [URL] {
  12. var files:[URL] = []
  13. for window in NSApp.windows {
  14. if ((window.windowController is KMBrowserWindowController) == false) {
  15. continue
  16. }
  17. let controller: KMBrowserWindowController = window.windowController as! KMBrowserWindowController
  18. let model = controller.browser?.tabStripModel
  19. guard let count = model?.count() else {
  20. continue
  21. }
  22. if (count <= 0) {
  23. continue
  24. }
  25. for i in 0 ..< count {
  26. let document = model?.tabContents(at: Int32(i))
  27. // if (document?.windowControllers == nil || document?.windowControllers.count == 0) {
  28. // continue
  29. // }
  30. if (document?.fileURL == nil) {
  31. continue
  32. }
  33. if (document?.isHome == nil || document!.isHome) {
  34. continue
  35. }
  36. files.append((document?.fileURL)!)
  37. }
  38. }
  39. return files
  40. }
  41. // MARK: -
  42. // MARK: 无法区分 [权限+开启] [开启] 这两种情况 请不要使用
  43. private class func isDocumentHasPermissionsPassword(_ url: URL) -> Bool {
  44. let document = PDFDocument(url: url)
  45. if (document == nil) {
  46. return false
  47. }
  48. if (document?.permissionsStatus == .user) {
  49. return true
  50. }
  51. // document?.permissionsStatus == .none
  52. if (document!.isLocked == false) { // 没有加锁
  53. return false
  54. }
  55. // 已加锁 [权限+开启] [开启]
  56. if (KMTools.hasPermissionsLimit(document!)) { // 有权限限制
  57. return true
  58. }
  59. return false
  60. }
  61. // MARK: -
  62. // MARK: 暂时只处理了复制和打印两项(后续项目需求有新增时,可以再此方法里扩展)
  63. @objc class func hasPermissionsLimit(_ document: PDFDocument) -> Bool {
  64. if (document.allowsCopying == false) {
  65. return true
  66. }
  67. if (document.allowsPrinting == false) {
  68. return true
  69. }
  70. return false
  71. }
  72. // MARK: -
  73. // MARK: 打开网页
  74. @objc class func openURL(url: URL?) {
  75. guard let _url = url else {
  76. KMPrint("url invalid.")
  77. return
  78. }
  79. NSWorkspace.shared.open(_url)
  80. }
  81. @objc class func openURL(urlString: String?) {
  82. guard let _urlString = urlString else {
  83. KMPrint("url invalid.")
  84. return
  85. }
  86. KMTools.openURL(url: URL(string: _urlString))
  87. }
  88. // MARK: -
  89. // MARK: 获取 App 版本号
  90. @objc class func getAppVersion() -> String {
  91. let infoDictionary = Bundle.main.infoDictionary
  92. if (infoDictionary == nil) {
  93. return "1.0.0"
  94. }
  95. var version = infoDictionary!["CFBundleShortVersionString"]
  96. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  97. return version as! String
  98. }
  99. version = infoDictionary!["CFBundleVersion"]
  100. if (version != nil && (version is String) && (version as! String).isEmpty == false) {
  101. return version as! String
  102. }
  103. return "1.0.0"
  104. }
  105. class func getSystemVersion() -> (Int, Int, Int) {
  106. let versionInfo = ProcessInfo.processInfo.operatingSystemVersion
  107. return (versionInfo.majorVersion, versionInfo.minorVersion, versionInfo.patchVersion)
  108. }
  109. @objc class func isDefaultPDFReader() -> Bool {
  110. let app = LSCopyDefaultRoleHandlerForContentType("pdf" as CFString, LSRolesMask.all)?.takeUnretainedValue()
  111. if (app == nil) {
  112. return false
  113. }
  114. return (app! as String) == Bundle.main.bundleIdentifier!
  115. }
  116. @objc class func setDefaultPDFReader(_ isOrNo: Bool) -> Bool {
  117. var bid = "com.apple.Preview"
  118. if (isOrNo) {
  119. bid = Bundle.main.bundleIdentifier!
  120. }
  121. let status: OSStatus = LSSetDefaultRoleHandlerForContentType(KMTools.UTIforFileExtension("pdf") as CFString, LSRolesMask.all, bid as CFString)
  122. if (status == 0) {
  123. return true
  124. }
  125. return false
  126. }
  127. @objc class func UTIforFileExtension(_ exn: String) -> String {
  128. return (UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, exn as CFString, nil)?.takeUnretainedValue())! as String
  129. }
  130. // MARK: -
  131. // MARK: 是否全屏
  132. @objc class func isFullScreen(_ window: NSWindow) -> Bool {
  133. return window.styleMask.contains(.fullScreen)
  134. }
  135. // MARK: -
  136. // MARK: 文件类型
  137. static let imageExtensions = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif",/*@"pic",*/"ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  138. static let pdfExtensions = ["pdf"]
  139. static let officeExtensions = ["doc", "docx", "xls", "xlsx", "ppt", "pptx"]
  140. @objc class func isImageType(_ exn: String) -> Bool {
  141. return KMTools.imageExtensions.contains(exn.lowercased())
  142. }
  143. @objc class func isPDFType(_ exn: String) -> Bool {
  144. return KMTools.pdfExtensions.contains(exn.lowercased())
  145. }
  146. @objc class func isOfficeType(_ exn: String) -> Bool {
  147. return KMTools.officeExtensions.contains(exn.lowercased())
  148. }
  149. @objc class func getUniqueFilePath(filePath: String) -> String {
  150. var isDirectory: ObjCBool = false
  151. var uniqueFilePath = filePath
  152. let fileManager = FileManager.default
  153. fileManager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
  154. var i = 0
  155. if (isDirectory.boolValue) {
  156. while fileManager.fileExists(atPath: uniqueFilePath) {
  157. i += 1
  158. uniqueFilePath = "\(filePath)(\(i))"
  159. }
  160. } else {
  161. let fileURL = URL(fileURLWithPath: filePath)
  162. let path = fileURL.deletingPathExtension().path
  163. while fileManager.fileExists(atPath: uniqueFilePath) {
  164. i += 1
  165. uniqueFilePath = "\(path)(\(i).\(fileURL.pathExtension)"
  166. }
  167. }
  168. return uniqueFilePath
  169. }
  170. @objc class func getTempFloderPath() -> String? {
  171. return NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("KMTemp")
  172. }
  173. }
  174. // MARK: -
  175. // MARK: PDFMaster
  176. let kKMPurchaseProductURLString = "https://www.pdfreaderpro.com/store"
  177. extension KMTools {
  178. // 打开 [快速教学]
  179. @objc class func openQuickStartStudy() {
  180. // MARK: -
  181. // MARK: 内嵌文档需要替换
  182. var fileName = "PDF Master User Guide"
  183. let fileType = "pdf"
  184. let path = Bundle.main.path(forResource: fileName, ofType: fileType)
  185. if (path == nil || FileManager.default.fileExists(atPath: path!) == false) {
  186. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/help"))
  187. return
  188. }
  189. let version = KMTools.getAppVersion()
  190. fileName.append(" v\(version).\(fileType)")
  191. let folderPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.appending("/\(Bundle.main.bundleIdentifier!)")
  192. if (FileManager.default.fileExists(atPath: folderPath!) == false) {
  193. try?FileManager.default.createDirectory(atPath: folderPath!, withIntermediateDirectories: false)
  194. }
  195. let toPath = "\(folderPath!)/\(fileName)"
  196. if (FileManager.default.fileExists(atPath: toPath)) {
  197. try?FileManager.default.removeItem(atPath: toPath)
  198. }
  199. try?FileManager.default.copyItem(atPath: path!, toPath: toPath)
  200. if !toPath.isPDFValid() {
  201. let alert = NSAlert()
  202. alert.alertStyle = .critical
  203. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  204. alert.runModal()
  205. return
  206. }
  207. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: toPath), display: true) { document, result, error in
  208. if (error != nil) {
  209. NSApp.presentError(error!)
  210. }
  211. }
  212. }
  213. // 打开 [FAQ] 网站
  214. @objc class func openFAQWebsite() {
  215. // KMTools.openURL(URL(string: "")!)
  216. }
  217. // 打开 [更多产品] 网站
  218. @objc class func openMoreProductWebsite() {
  219. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/product?utm_source=MacApp&utm_campaign=ProductLink&utm_medium=PdfProduct"))
  220. }
  221. // 打开 [免费 PDF 模板] 网站
  222. @objc class func openFreePDFTemplatesWebsite() {
  223. KMTools.openURL(url: URL(string: "https://www.pdfreaderpro.com/templates?utm_source=MacApp&utm_campaign=TemplatesLink&utm_medium=PdfTemplates"))
  224. }
  225. // 打开 [ComPDFKit 授权] 网站
  226. @objc class func openComPDFKitPowerWebsite() {
  227. KMTools.openURL(url: URL(string: "https://www.compdf.com/?utm_source=macapp&utm_medium=pdfmac&utm_campaign=compdfkit-promp"))
  228. }
  229. // 打开 [官网 下载页] 网站
  230. // 测试环境 http://test-pdf-pro.kdan.cn:3021/pdf-master-mac-download
  231. @objc class func openDownloadDMGWebsite() {
  232. KMTools.openURL(urlString: "https://www.pdfreaderpro.com/pdf-master-mac-download")
  233. }
  234. @objc class func openPurchaseProductWebsite() {
  235. KMTools.openURL(urlString: kKMPurchaseProductURLString)
  236. }
  237. // 意见反馈
  238. @objc class func feekback() {
  239. let (major, minor, bugFix) = KMTools.getSystemVersion()
  240. let versionInfoString = "\(KMTools.getRawSystemInfo()) - \(major).\(minor).\(bugFix)"
  241. let appVersion = KMTools.getAppVersion()
  242. let appName = KMTools.getAppName()
  243. let subjects = "\(appName) - \(appVersion);\(NSLocalizedString("Propose a New Feature", comment: ""));\(versionInfoString)"
  244. // MARK: -
  245. // MARK TODO: 邮箱域名需要替换
  246. let email = "support@pdfreaderpro.com"
  247. // MARK: -
  248. // MARK TODO: 邮箱域名需要替换
  249. KMMailHelper.newEmail(withContacts: email, andSubjects: subjects)
  250. }
  251. @objc class func getRawSystemInfo() -> String {
  252. let info = GBDeviceInfo.deviceInfo().rawSystemInfoString
  253. if (info == nil) {
  254. return ""
  255. }
  256. return info!
  257. }
  258. @objc class func getAppName() -> String {
  259. let appTarget = KMTools_OC.getAppTarget()
  260. if (appTarget == .free) {
  261. return "PDF Master"
  262. } else if (appTarget == .pro) {
  263. return "PDF Master Pro"
  264. } else if (appTarget == .DMG) {
  265. // return "PDF Master DMG"
  266. return "PDF Master"
  267. }
  268. return "PDF Master"
  269. }
  270. @objc class func pageRangeTypeString(pageRange: KMPageRange) -> String {
  271. switch pageRange {
  272. case .all:
  273. return NSLocalizedString("All Pages", comment: "")
  274. case .current:
  275. return NSLocalizedString("Current Page", comment: "")
  276. case .odd:
  277. return NSLocalizedString("Odd Pages", comment: "")
  278. case .even:
  279. return NSLocalizedString("Even Pages", comment: "")
  280. case .custom:
  281. return NSLocalizedString("Customize", comment: "")
  282. case .horizontal:
  283. return NSLocalizedString("Horizontal Pages", comment: "")
  284. case .vertical:
  285. return NSLocalizedString("Vertical Pages", comment: "")
  286. }
  287. }
  288. @objc class func pageRangePlaceholderString() -> String {
  289. return NSLocalizedString("e.g. 1,3-5,10", comment: "")
  290. }
  291. @objc class func saveWatermarkDocument(document: CPDFDocument, to url: URL, secureOptions: [CPDFDocumentWriteOption : Any]? = nil, removePWD: Bool = false) -> URL? {
  292. guard let _document = self._saveDocumentForWatermark(document: document) else {
  293. return nil
  294. }
  295. // 保存文档
  296. if let data = secureOptions, !data.isEmpty {
  297. _document.write(to: url, withOptions: data)
  298. } else if (removePWD) {
  299. _document.writeDecrypt(to: url)
  300. } else {
  301. _document.write(to: url)
  302. }
  303. // 清除临时数据
  304. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  305. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  306. }
  307. return url
  308. }
  309. @objc class func saveWatermarkDocumentForCompress(document: CPDFDocument, to url: URL, imageQuality: Int) -> URL? {
  310. guard let _document = self._saveDocumentForWatermark(document: document) else {
  311. return nil
  312. }
  313. // _document.write(to: _document.documentURL)
  314. // 保存文档
  315. let result = _document.writeOptimize(to: url, withOptions: [.imageQualityOption : imageQuality])
  316. // 清除临时数据
  317. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  318. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  319. }
  320. if (result) {
  321. return url
  322. }
  323. return nil
  324. }
  325. @objc class func saveWatermarkDocumentForFlatten(document: CPDFDocument, to url: URL) -> URL? {
  326. guard let _document = self._saveDocumentForWatermark(document: document) else {
  327. return nil
  328. }
  329. // 保存文档
  330. let result = _document.writeFlatten(to: url)
  331. // 清除临时数据
  332. if let _fileUrl = _document.documentURL, FileManager.default.fileExists(atPath: _fileUrl.path) {
  333. try?FileManager.default.removeItem(atPath: _fileUrl.path)
  334. }
  335. if (result) {
  336. return url
  337. }
  338. return nil
  339. }
  340. @objc class func saveDocumentToTemp(document: CPDFDocument, fileID: String, needUnlock: Bool = true) -> URL? {
  341. // 将文档存入临时目录
  342. if let data = self.getTempFloderPath(), !FileManager.default.fileExists(atPath: data) {
  343. try?FileManager.default.createDirectory(atPath: data, withIntermediateDirectories: false)
  344. }
  345. guard let filePath = self.getTempFloderPath()?.stringByAppendingPathComponent("temp_saveDocumentFor\(fileID).pdf") else {
  346. return nil
  347. }
  348. // 清除临时数据
  349. if (FileManager.default.fileExists(atPath: filePath)) {
  350. try?FileManager.default.removeItem(atPath: filePath)
  351. }
  352. document.write(toFile: filePath)
  353. if (!FileManager.default.fileExists(atPath: filePath)) {
  354. return nil
  355. }
  356. guard let _document = CPDFDocument(url: URL(fileURLWithPath: filePath)) else {
  357. return nil
  358. }
  359. if (!needUnlock) {
  360. return _document.documentURL
  361. }
  362. // 如果加锁,则去解锁
  363. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  364. _document.unlock(withPassword: document.password)
  365. }
  366. if (_document.isLocked) {
  367. return nil
  368. }
  369. return _document.documentURL
  370. }
  371. // MARK: - Private Methods
  372. @objc fileprivate class func _documentAddWatermark(document: CPDFDocument) -> CPDFDocument? {
  373. // 添加水印
  374. let watermark = CPDFWatermark(document: document, type: .image)
  375. watermark?.image = NSImage(named: "KMImageNameWatermark")
  376. watermark?.horizontalPosition = .left
  377. watermark?.verticalPosition = .top
  378. watermark?.scale = 0.3
  379. document.addWatermark(watermark)
  380. // 添加 link注释
  381. var watermarkAnnoBounds = NSMakeRect(0, 0, 72, 20)
  382. for i in 0 ..< document.pageCount {
  383. guard let page = document.page(at: i) else {
  384. continue
  385. }
  386. // 水印注释 frame
  387. watermarkAnnoBounds.origin.y = page.bounds.size.height-watermarkAnnoBounds.size.height
  388. // 找到需要删除的水印注释(之前添加)
  389. var flagAnnos: [CPDFAnnotation] = []
  390. for anno in page.annotations {
  391. if let anno_link = anno as? CPDFLinkAnnotation, anno_link.url() == kKMPurchaseProductURLString, anno_link.bounds.equalTo(watermarkAnnoBounds) {
  392. flagAnnos.append(anno_link)
  393. }
  394. }
  395. // 删除之前的水印注释
  396. for anno in flagAnnos {
  397. page.removeAnnotation(anno)
  398. }
  399. // 新增新的水印注释
  400. let anno = CPDFLinkAnnotation(document: document)
  401. anno?.bounds = watermarkAnnoBounds
  402. anno?.setURL(kKMPurchaseProductURLString)
  403. page.addAnnotation(anno)
  404. }
  405. return document
  406. }
  407. @objc fileprivate class func _saveDocumentForWatermark(document: CPDFDocument) -> CPDFDocument? {
  408. // 将文档存入临时目录
  409. guard let _fileUrl = self.saveDocumentToTemp(document: document, fileID: "Watermark") else {
  410. return nil
  411. }
  412. guard let _document = CPDFDocument(url: _fileUrl) else {
  413. return nil
  414. }
  415. // 如果加锁,则去解锁
  416. if let pwd = document.password, !pwd.isEmpty, _document.isLocked {
  417. _document.unlock(withPassword: pwd)
  418. }
  419. // 添加水印
  420. return self._documentAddWatermark(document: _document)
  421. }
  422. }