KMMainDocument.swift 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. //
  2. // KMMainDocument.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/6.
  6. //
  7. import Cocoa
  8. import CoreFoundation
  9. @objc enum KMArchiveMask: Int {
  10. case diskImage = 1
  11. case email = 2
  12. }
  13. @objc enum KMExportOption: Int {
  14. case `default` = 0
  15. case withoutNotes
  16. case withEmbeddedNotes
  17. }
  18. typealias KMMainDocumentCloudUploadHanddler = (@escaping(Bool, String)->()) -> ()
  19. @objcMembers class KMMainDocument: CTTabContents {
  20. struct MDFlags {
  21. var exportOption: UInt32 // assuming this is a 2-bit field, change to appropriate data type
  22. var exportUsingPanel: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  23. var gettingFileType: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  24. var convertingNotes: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  25. var needsPasswordToConvert: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  26. }
  27. static let kLastExportedTypeKey = "SKLastExportedType"
  28. static let kLastExportedOptionKey = "SKLastExportedOption"
  29. static let kBundleDataFilename = "data"
  30. var mainViewController: KMMainViewController?
  31. var homeViewController: KMNHomeViewController?
  32. var bookmarkSheetController: KMBookmarkSheetController?
  33. var bookmarkController: KMBookmarkController?
  34. var isNewCreated: Bool = false
  35. var closedByUserGestureFlag: Bool = false // 标记 closedByUserGesture 这个状态需要延后存储(如果需要)
  36. var cloud: Bool = false
  37. var cloudUploadHanddler: KMMainDocumentCloudUploadHanddler?
  38. var isUnlockFromKeychain: Bool = false
  39. private var _saveAsing = false
  40. var fileUpdateChecker: SKFileUpdateChecker?
  41. var mdFlags: MDFlags?
  42. var currentDocumentSetup: [String: Any] {
  43. get {
  44. var tempSetup: [String: Any] = [:]
  45. let tempMainSetup: [String: Any] = mainViewController?.currentSetup() ?? [:]
  46. let filePath = fileURL?.path ?? ""
  47. if filePath.count > 0{
  48. tempSetup.updateValue(filePath, forKey: KMDocumentSetupFileNameKey)
  49. }else {
  50. return tempSetup
  51. }
  52. if let alias = SKAlias.init(url: fileURL){
  53. if let data = alias.data{
  54. tempSetup.updateValue(data as Any, forKey: KMDocumentSetupAliasKey)
  55. }
  56. }
  57. if tempSetup.count > 0 {
  58. tempSetup.merge(tempMainSetup) { (_, new) in new }
  59. }
  60. return tempSetup
  61. }
  62. set {
  63. }
  64. }
  65. private var _saveToURL: URL?
  66. var saveToURL: URL? {
  67. get {
  68. return self._saveToURL
  69. }
  70. }
  71. var exportAccessoryC: SKExportAccessoryController?
  72. var pdfData: Data?
  73. weak var watermarkSaveDelegate: AnyObject?
  74. private var _trackEvents = IndexSet()
  75. override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  76. if (self.isNewCreated) {
  77. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  78. return
  79. }
  80. if (!self.needSaveWatermark()) {
  81. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  82. return
  83. }
  84. var openAccessoryView = self.watermarkSaveDelegate != nil
  85. if (openAccessoryView) {
  86. if let _browser = self.watermarkSaveDelegate as? KMBrowser, _browser.isCloseAllTabViewItem {
  87. openAccessoryView = false
  88. }
  89. }
  90. self._km_saveForWatermark(openAccessoryView: openAccessoryView) { [unowned self] in
  91. self.trackEvents()
  92. } callback: { [unowned self] needSave, params in
  93. if (needSave) {
  94. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  95. } else { // 水印保存
  96. if (self.watermarkSaveDelegate == nil) {
  97. if let data = params.first as? KMResult, data == .cancel {
  98. if let shouldClose = params.last as? Bool, shouldClose {
  99. DispatchQueue.main.async {
  100. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  101. }
  102. }
  103. } else {
  104. DispatchQueue.main.async {
  105. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  106. }
  107. }
  108. return
  109. }
  110. if let data = params.first as? KMResult, data == .cancel {
  111. if var shouldClose = params.last as? Bool {
  112. if let _browser = self.watermarkSaveDelegate as? KMBrowser, _browser.isCloseAllTabViewItem {
  113. shouldClose = true
  114. }
  115. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: shouldClose, contextInfo: nil)
  116. }
  117. } else {
  118. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: true, contextInfo: nil)
  119. }
  120. self.watermarkSaveDelegate = nil
  121. }
  122. }
  123. }
  124. override func makeWindowControllers() {
  125. // Returns the storyboard that contains your document window.
  126. if ((self.fileURL?.path) != nil) {
  127. if !self.fileURL!.path.isPDFValid() {
  128. let alert = NSAlert()
  129. alert.alertStyle = .critical
  130. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  131. alert.runModal()
  132. return
  133. }
  134. }
  135. let mainWindow = NSApp.mainWindow
  136. var currentWindowController: KMBrowserWindowController?
  137. if mainWindow != nil {
  138. let windowController = mainWindow!.windowController
  139. if windowController is KMBrowserWindowController {
  140. currentWindowController = (windowController as! KMBrowserWindowController)
  141. } else {
  142. for window in NSApp.windows {
  143. let windowController = window.windowController
  144. if windowController is KMBrowserWindowController {
  145. currentWindowController = (windowController as! KMBrowserWindowController)
  146. break
  147. }
  148. }
  149. }
  150. } else {
  151. for window in NSApp.windows {
  152. let windowController = window.windowController
  153. if windowController is KMBrowserWindowController {
  154. currentWindowController = (windowController as! KMBrowserWindowController)
  155. break
  156. }
  157. }
  158. }
  159. if currentWindowController?.browser == nil && (self.fileURL != nil) {
  160. let browser: KMBrowser = KMBrowser.init()
  161. browser.windowController = KMBrowserWindowController.init(browser: browser)
  162. browser.addHomeTabContents()
  163. currentWindowController = browser.windowController as? KMBrowserWindowController
  164. browser.windowController.showWindow(self)
  165. }
  166. mainViewController = KMMainViewController.init()
  167. mainViewController?.myDocument = self
  168. self.mdFlags = MDFlags(exportOption: 0, exportUsingPanel: 0, gettingFileType: 0, convertingNotes: 0, needsPasswordToConvert: 0)
  169. if ((self.fileURL?.path) != nil) {
  170. let pdfDocument = CPDFDocument.init(url: URL(fileURLWithPath: self.fileURL!.path))
  171. mainViewController?.document = pdfDocument
  172. }
  173. if mainViewController?.document == nil {
  174. return
  175. }
  176. self.view = mainViewController?.view
  177. if let url = self.fileURL {
  178. AppSandboxFileAccess().persistPermissionURL(url as URL)
  179. let bookmarkData = try?url.bookmarkData(options: NSURL.BookmarkCreationOptions.withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
  180. if bookmarkData != nil {
  181. AppSandboxFileAccess().bookmarkPersistanceDelegate.setBookmarkData(bookmarkData! as Data, for: url as URL)
  182. AppSandboxFileAccess().bookmarkPersistanceDelegate.setBookmarkData(bookmarkData! as Data, for: NSURL(fileURLWithPath: url.path) as URL)
  183. }
  184. }
  185. if let currentBrowser = currentWindowController?.browser {
  186. let activeBrowser = currentBrowser.activeTabContents()
  187. let activeIndex = currentBrowser.activeTabIndex()
  188. let ishome = activeBrowser?.isHome ?? false
  189. let isfirstTab = (activeIndex == 0)
  190. if ishome && !isfirstTab { // 替换 【标签需要被替换】
  191. self.addWindowController(currentWindowController!)
  192. self.mainViewController?.browserWindowController = currentWindowController
  193. // 替换 document
  194. currentWindowController?.browser.replaceTabContents(at: Int32(activeIndex), with: self)
  195. // 刷新标签
  196. currentWindowController?.browser.updateTabState(at: Int32(activeIndex))
  197. // 刷新 home icon
  198. if let tabStripController = currentWindowController?.tabStripController {
  199. if let view = tabStripController.view(at: UInt(activeIndex)) as? CTTabView {
  200. view.controller().isHome = self.isHome
  201. view.controller().isNewTab = self.isNewTab
  202. view.controller().updateUI()
  203. }
  204. }
  205. } else {
  206. if currentWindowController?.browser.tabCount() ?? 0 > 1 && (!IAPProductsManager.default().isAvailableAllFunction() || KMPreference.shared.openDocumentType == .newWindow){
  207. // 开启新窗口
  208. let browser = KMBrowser.init() as KMBrowser
  209. browser.windowController = KMBrowserWindowController.init(browser: browser)
  210. browser.addHomeTabContents()
  211. browser.windowController.showWindow(self)
  212. browser.add(self, at: Int32()-1, inForeground: true)
  213. self.addWindowController(browser.windowController)
  214. self.mainViewController?.browserWindowController = browser.windowController as? KMBrowserWindowController
  215. }else { // 正常拼接到后面
  216. self.addWindowController(currentWindowController!)
  217. self.mainViewController?.browserWindowController = currentWindowController
  218. currentWindowController?.browser.add(self, at: Int32()-1, inForeground: true)
  219. }
  220. }
  221. }
  222. }
  223. override func showWindows() {
  224. super.showWindows()
  225. self.setDataFromTmpData()
  226. }
  227. override func windowControllerDidLoadNib(_ aController: NSWindowController) {
  228. super.windowControllerDidLoadNib(aController)
  229. self.setDataFromTmpData()
  230. fileUpdateChecker = SKFileUpdateChecker.init(for: self)
  231. fileUpdateChecker?.isEnabled = true
  232. }
  233. override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) async throws {
  234. do {
  235. try await super.save(to: url, ofType: typeName, for: saveOperation)
  236. } catch let outError {
  237. NSApp.presentError(outError)
  238. }
  239. if saveOperation == .saveToOperation {
  240. if let data = self.mdFlags?.exportUsingPanel, data == 1 {
  241. if FileManager.default.fileExists(atPath: url.path) {
  242. let ws = NSWorkspace.shared
  243. ws.activateFileViewerSelecting([url])
  244. }
  245. }
  246. }
  247. self.mdFlags?.exportUsingPanel = 0
  248. self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  249. }
  250. override func write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  251. try self._km_write(to: url, ofType: typeName, for: saveOperation, originalContentsURL: absoluteOriginalContentsURL)
  252. }
  253. override func canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  254. let isPrompt = SettingsManager.sharedInstance.closeFileIsPrompt()
  255. if (isPrompt) {
  256. super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
  257. return
  258. }
  259. if (self.isNewCreated) {
  260. self.save(nil)
  261. } else if (self.isDocumentEdited) {
  262. self.save(nil)
  263. } else if (mainViewController != nil) {
  264. if self.mainViewController!.isPDFDocumentEdited || self.mainViewController!.needSave {
  265. self.save(nil)
  266. }
  267. }
  268. super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
  269. }
  270. override func saveAs(_ sender: Any?) {
  271. if (!self.needSaveWatermark()) {
  272. self._km_saveAs(sender)
  273. return
  274. }
  275. self._km_saveForWatermark { [weak self] needSave, _ in
  276. if (needSave) {
  277. self?._km_saveAs(sender)
  278. }
  279. }
  280. }
  281. override func saveTo(_ sender: Any?) {
  282. guard let pdfDoc = self.mainViewController?.listView.document else {
  283. NSSound.beep()
  284. return
  285. }
  286. if pdfDoc.allowsPrinting == false || pdfDoc.allowsCopying == false {
  287. Task {
  288. _ = await KMAlertTool.runModel(message: NSLocalizedString("This is a secured document. Editing is not permitted.", comment: ""))
  289. }
  290. return
  291. }
  292. let idx = (sender as? NSMenuItem)?.tag ?? 0
  293. var typeName = KMPDFDocumentType
  294. if idx == 0 {
  295. typeName = KMPDFDocumentType
  296. } else if idx == 1 {
  297. typeName = KMPDFBundleDocumentType
  298. } else if idx == 2 {
  299. typeName = KMNotesDocumentType
  300. } else if idx == 3 {
  301. typeName = KMNotesTextDocumentType
  302. } else if idx == 4 {
  303. typeName = KMNotesRTFDocumentType
  304. } else if idx == 5 {
  305. typeName = KMNotesRTFDDocumentType
  306. } else if idx == 6 {
  307. typeName = KMNotesDocumentType
  308. }
  309. KMDataManager.ud_set(typeName, forKey: Self.kLastExportedTypeKey)
  310. super.saveTo(sender)
  311. }
  312. override func prepareSavePanel(_ savePanel: NSSavePanel) -> Bool {
  313. let success = super.prepareSavePanel(savePanel)
  314. let exportUsingPanel = self.mdFlags?.exportUsingPanel ?? 0
  315. if success && exportUsingPanel > 0 {
  316. var formatPopup: NSPopUpButton?
  317. let svs = savePanel.accessoryView?.subviews.first?.subviews ?? []
  318. for sv in svs {
  319. if let data = sv as? NSPopUpButton {
  320. formatPopup = data
  321. break
  322. }
  323. }
  324. self._removeSavePanelOfFormatPopupItems(savePanel)
  325. if (formatPopup != nil) {
  326. let lastExportedType = KMDataManager.ud_string(forKey: Self.kLastExportedTypeKey)
  327. var lastExportedOption = KMDataManager.ud_integer(forKey: Self.kLastExportedOptionKey)
  328. if lastExportedOption == 0 {
  329. lastExportedOption = KMExportOption.withEmbeddedNotes.rawValue
  330. }
  331. self.mdFlags?.exportOption = UInt32(lastExportedOption)
  332. }
  333. } else if success {
  334. self._removeSavePanelOfFormatPopupItems(savePanel)
  335. }
  336. return success
  337. }
  338. override func runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  339. self.mdFlags?.exportUsingPanel = saveOperation == .saveToOperation ? 1 : 0
  340. self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  341. if (self.isNewCreated) {
  342. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  343. return
  344. }
  345. if (!self.needSaveWatermark()) {
  346. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  347. return
  348. }
  349. self._km_saveForWatermark { [weak self] needSave, _ in
  350. if (needSave) {
  351. self?._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  352. }
  353. }
  354. }
  355. override func save(_ sender: Any?) {
  356. if (!self.needSaveWatermark()) {
  357. self._km_save(sender)
  358. return
  359. }
  360. self._km_saveForWatermark { [weak self] in
  361. self?.trackEvents()
  362. } callback: { [weak self] needSave, _ in
  363. if (needSave) {
  364. self?._km_save(sender)
  365. }
  366. }
  367. }
  368. func systemInteractionMode() -> KMInteractionMode {
  369. let mainWindow = NSApp.mainWindow
  370. if mainWindow != nil {
  371. let windowController = mainWindow!.windowController
  372. if windowController?.window?.screen?.isEqual(NSScreen.screens[0]) ?? false{
  373. return mainViewController?.interactionMode ?? .normal
  374. }
  375. }
  376. return .normal
  377. }
  378. func saveForWatermark() {
  379. if (!self.needSaveWatermark()) {
  380. self._km_save(nil)
  381. return
  382. }
  383. self._km_saveForWatermark { [weak self] in
  384. self?.trackEvents()
  385. } callback: { [unowned self] needSave, params in
  386. if (needSave) {
  387. self._km_save(nil)
  388. } else { // 水印保存
  389. if (self.watermarkSaveDelegate == nil) {
  390. if let data = params.first as? KMResult, data == .cancel {
  391. if let shouldClose = params.last as? Bool, shouldClose {
  392. DispatchQueue.main.async {
  393. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  394. }
  395. }
  396. } else {
  397. DispatchQueue.main.async {
  398. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  399. }
  400. }
  401. return
  402. }
  403. if let data = params.first as? KMResult, data == .cancel {
  404. if var shouldClose = params.last as? Bool {
  405. if let _browser = self.watermarkSaveDelegate as? KMBrowser, _browser.isCloseAllTabViewItem {
  406. shouldClose = true
  407. }
  408. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: shouldClose, contextInfo: nil)
  409. }
  410. } else {
  411. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: true, contextInfo: nil)
  412. }
  413. self.watermarkSaveDelegate = nil
  414. }
  415. }
  416. }
  417. override func read(from absoluteURL: URL, ofType typeName: String) throws {
  418. do {
  419. try super.read(from: absoluteURL, ofType: typeName)
  420. updateChangeCount(.changeCleared)
  421. } catch let outError {
  422. Swift.print(outError)
  423. }
  424. }
  425. override func read(from data: Data, ofType typeName: String) throws {
  426. self.pdfData = data
  427. }
  428. // MARK: Autosaving
  429. override func close() {
  430. mainViewController?.cancelMeasureType()
  431. if self.isActive {
  432. if browser != nil {
  433. var activeIndex = 0
  434. let dex = browser.index(of: self)
  435. if dex == browser.tabCount() - 1 {
  436. activeIndex = Int(browser.tabCount()-2)
  437. } else {
  438. activeIndex = Int(dex + 1)
  439. }
  440. let activeContents = browser.tabContents(at: Int32(activeIndex))
  441. activeContents?.addWindowController(browser.windowController)
  442. }
  443. }
  444. super.close()
  445. }
  446. // MARK: init
  447. override init() {
  448. super.init()
  449. // Add your subclass-specific initialization here.
  450. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewAnnotationsAttributeHasChangeNotification"), object: nil)
  451. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewDidAddAnnotationNotification"), object: nil)
  452. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.CPDFViewPageChanged, object: nil)
  453. }
  454. override init?(baseTabContents baseContents: CTTabContents?) {
  455. super.init(baseTabContents: baseContents)
  456. if isHome {
  457. homeViewController = KMNHomeViewController.init()
  458. self.view = homeViewController?.view
  459. }
  460. }
  461. // MARK: Handling User Actions
  462. override var title: String? {
  463. get {
  464. if isHome {
  465. if (self.isNewTab) {
  466. return NSLocalizedString("New Tab", comment: "")
  467. } else {
  468. return NSLocalizedString("Home", comment: "")
  469. }
  470. } else {
  471. return fileURL?.lastPathComponent
  472. }
  473. }
  474. set {
  475. super.title = newValue
  476. }
  477. }
  478. func needSaveWatermark() -> Bool {
  479. if let need = self.mainViewController?.saveWatermarkFlag {
  480. return need
  481. }
  482. return false
  483. }
  484. func changeExportOption(_ sender: NSMatrix?) {
  485. self.mdFlags?.exportOption = UInt32(sender?.selectedCell()?.tag ?? 0)
  486. }
  487. // MARK: Private Methods
  488. func pdfChangedNotification(_ notification: Notification) -> Void {
  489. if !isHome {
  490. let mainViewController = mainViewController
  491. var document: CPDFDocument!
  492. let dic = notification.object as? NSDictionary
  493. if dic?["object"] is CPDFAnnotation {
  494. guard let annotation = dic?["object"] as? CPDFAnnotation else { return }
  495. document = annotation.page.document
  496. } else if dic?["object"] is CPDFListView {
  497. let pdflistView = notification.object as? CPDFListView
  498. document = pdflistView?.document
  499. }
  500. if mainViewController != nil {
  501. if document == mainViewController!.document {
  502. updateChangeCount(.changeDone)
  503. }
  504. }
  505. }
  506. }
  507. override func updateChangeCount(_ change: NSDocument.ChangeType) {
  508. let mainWindow = NSApp.mainWindow
  509. var currentWindowController: KMBrowserWindowController?
  510. if mainWindow != nil {
  511. let windowController = mainWindow!.windowController
  512. if windowController is KMBrowserWindowController {
  513. currentWindowController = (windowController as! KMBrowserWindowController)
  514. } else {
  515. for window in NSApp.windows {
  516. let windowController = window.windowController
  517. if windowController is KMBrowserWindowController {
  518. currentWindowController = (windowController as! KMBrowserWindowController)
  519. break
  520. }
  521. }
  522. }
  523. } else {
  524. for window in NSApp.windows {
  525. let windowController = window.windowController
  526. if windowController is KMBrowserWindowController {
  527. currentWindowController = (windowController as! KMBrowserWindowController)
  528. break
  529. }
  530. }
  531. }
  532. if let currentBroser = currentWindowController?.browser {
  533. if self.isEqual(to: currentBroser.activeTabContents()) {
  534. super.updateChangeCount(change)
  535. return
  536. }
  537. }
  538. super.updateChangeCount(.changeCleared)
  539. }
  540. func uploadToCloud(_ callback: (@escaping(Bool, String)->())) {
  541. guard let handdler = self.cloudUploadHanddler else {
  542. return
  543. }
  544. handdler(callback)
  545. }
  546. func isPDFDocument() -> Bool {
  547. return true
  548. }
  549. func setDataFromTmpData() {
  550. guard let _document = self.mainViewController?.document else {
  551. return
  552. }
  553. if (_document.permissionsStatus != .owner) {
  554. var password: NSString? = nil
  555. let fileId = self.fileId(for: _document)
  556. if (fileId.isEmpty) {
  557. return
  558. }
  559. self.getPassword(&password, fileId: fileId)
  560. if (password != nil) {
  561. self.isUnlockFromKeychain = true
  562. self.mainViewController?.model.password = password as String?
  563. }
  564. }
  565. //如果已存在,开个存在页签
  566. var selectDocument: KMMainDocument? = self
  567. if selectDocument != nil {
  568. if let browser_ = selectDocument?.browser {
  569. let currentIndex = browser_.tabStripModel.index(of: selectDocument)
  570. browser_.tabStripModel.selectTabContents(at: Int32(currentIndex), userGesture: true)
  571. if browser_.window.isVisible {
  572. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  573. browser_.window.orderFront(nil)
  574. }
  575. } else if browser_.window.isMiniaturized {
  576. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  577. browser_.window.orderFront(nil)
  578. }
  579. }
  580. }
  581. }
  582. }
  583. func tryToUnlockDocument(_ document: CPDFDocument) {
  584. if (document.permissionsStatus != .owner) {
  585. var password: NSString? = nil
  586. let fileId = self.fileId(for: document)
  587. if (fileId.isEmpty) {
  588. return
  589. }
  590. self.getPassword(&password, fileId: fileId)
  591. if (password != nil) {
  592. self.isUnlockFromKeychain = true
  593. document.unlock(withPassword: password! as String)
  594. self.mainViewController?.model.password = password as String?
  595. }
  596. }
  597. }
  598. func km_updateChangeCount(_ change: NSDocument.ChangeType) {
  599. super.updateChangeCount(change)
  600. }
  601. func trackEvents() {
  602. km_synchronized(self) {
  603. for i in self._trackEvents {
  604. }
  605. }
  606. self.clearTrackEvents()
  607. }
  608. func clearTrackEvents() {
  609. km_synchronized(self) {
  610. self._trackEvents.removeAll()
  611. }
  612. }
  613. @IBAction func saveArchive(_ sender: Any?) {
  614. guard let item = sender as? NSMenuItem else {
  615. NSSound.beep()
  616. return
  617. }
  618. guard let fileURL = self.fileURL else {
  619. NSSound.beep()
  620. return
  621. }
  622. let check = try?fileURL.checkResourceIsReachable()
  623. if check == false || self.isDocumentEdited {
  624. let msg = KMLocalizedString("You must save this file first")
  625. let inf = KMLocalizedString("The document has unsaved changes, or has not previously been saved to disk.")
  626. Task {
  627. _ = await KMAlertTool.runModel(message: msg, informative: inf)
  628. }
  629. return
  630. }
  631. // NSString *ext = ([sender tag] | SKArchiveDiskImageMask) ? @"dmg" : @"tgz";
  632. let idx = item.tag
  633. let ext = (idx == 1 || idx == 3) ? "dmg" : "tgz"
  634. let isEmail = (idx == 2 || idx == 3)
  635. if isEmail {
  636. let tmpDirURL = FileManager.default.uniqueChewableItemsDirectoryURL()
  637. let tmpFileURL = tmpDirURL.appendingPathComponent(fileURL.lastPathComponentReplacingPathExtension(ext))
  638. self.newSaveArchive(to: tmpFileURL, email: true)
  639. } else {
  640. let sp = NSSavePanel()
  641. sp.allowedFileTypes = [ext]
  642. sp.canCreateDirectories = true
  643. sp.nameFieldStringValue = fileURL.lastPathComponentReplacingPathExtension(ext)
  644. sp.beginSheetModal(for: self.windowForSheet!) { result in
  645. if result == .OK {
  646. self.newSaveArchive(to: sp.url!, email: false)
  647. }
  648. }
  649. }
  650. }
  651. @IBAction func readNotes(_ sender: Any?) {
  652. KMPrint("readNotes")
  653. }
  654. @IBAction func convertNotes(_ sender: Any?) {
  655. KMPrint("convertNotes")
  656. }
  657. @IBAction func batchRemovePassWord(_ sender: Any?) {
  658. }
  659. @IBAction func batchRemovPrivatySecurity(_ sender: Any?) {
  660. self.mainViewController?.removeOwnerPassword()
  661. }
  662. @IBAction func printPDFDocument(_ sender: Any?) {
  663. }
  664. @IBAction func performFindPanelAction(_ sender: Any?) {
  665. }
  666. @IBAction func addBookmark(_ sender: Any?) {
  667. guard let item = sender as? NSMenuItem else {
  668. return
  669. }
  670. if item.tag == 3 {
  671. KMPrint("Edit Bookmark")
  672. bookmarkController = KMBookmarkController.showBookmarkController()
  673. } else if item.tag == 2 {
  674. KMPrint("session Bookmark")
  675. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .session)
  676. } else if item.tag == 0 {
  677. KMPrint("add Bookmark")
  678. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .bookmark)
  679. }
  680. bookmarkSheetController?.stringValue = self.displayName
  681. bookmarkSheetController?.cancelAction = { [weak self] controller, type in
  682. }
  683. bookmarkSheetController?.doneAction = { [unowned self] controller, type, label in
  684. let folder = controller.selectedFolder
  685. var bookmark: KMBookmark?
  686. switch type {
  687. case .bookmark:
  688. let mainViewController = mainViewController
  689. if let page = mainViewController?.listView.currentPage() {
  690. let index: UInt = page.pageIndex()
  691. bookmark = KMBookmark.bookmark(url: self.fileURL!, pageIndex: index, label: label)
  692. }
  693. case .setup: break
  694. let setup = currentDocumentSetup
  695. bookmark = KMBookmark.bookmark(setup: setup, label: label)
  696. case .session:
  697. let setups = NSApp.orderedDocuments.compactMap { $0.value(forKey:"currentDocumentSetup") }
  698. bookmark = KMSessionBookmark.bookmarkSession(setups: setups as NSArray, label: label)
  699. default:
  700. break
  701. }
  702. if let bookmark = bookmark {
  703. folder?.children.append(bookmark)
  704. }
  705. KMBookmarkManager.manager.saveData()
  706. }
  707. }
  708. func currentDocumntSetup() -> [String: Any] {
  709. var setup: [String: Any] = [:]
  710. let data = SKAlias.init(url: fileURL).data
  711. if (data != nil) {
  712. setup.updateValue(data as Any, forKey: "_BDAlias")
  713. } else {
  714. setup.updateValue(fileURL?.path as Any, forKey: "fileName")
  715. }
  716. return setup;
  717. }
  718. @IBAction func showWindow(_ sender: Any?) {
  719. KMPrint("showWindow")
  720. }
  721. // MARK: - Private Methods
  722. private func _PDFBundleFileWrapper(for name: String) -> FileWrapper {
  723. var aName = name
  724. if name.isCaseInsensitiveEqual(Self.kBundleDataFilename) {
  725. aName = aName + "1"
  726. }
  727. let fileWrapper = FileWrapper(directoryWithFileWrappers: [:])
  728. let info = KMInfoWindowController.shared.info(for: self)
  729. if let data = self.pdfData {
  730. fileWrapper.addRegularFile(withContents: data, preferredFilename: aName + ".pdf")
  731. }
  732. if let data = self.mainViewController?.document?.string()?.data(using: .utf8) {
  733. fileWrapper.addRegularFile(withContents: data, preferredFilename: Self.kBundleDataFilename + ".txt")
  734. }
  735. if let data = try?PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: PropertyListSerialization.WriteOptions(0)) {
  736. fileWrapper.addRegularFile(withContents: data, preferredFilename: Self.kBundleDataFilename + ".plist")
  737. }
  738. return fileWrapper
  739. }
  740. private func _km_write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  741. if typeName == KMPDFBundleDocumentType {
  742. let fileWrapper = self._PDFBundleFileWrapper(for: url.deletingPathExtension().lastPathComponent)
  743. do {
  744. try fileWrapper.write(to: url, options: FileWrapper.WritingOptions(rawValue: 0), originalContentsURL: nil)
  745. } catch {
  746. NSApp.presentError(error)
  747. }
  748. return
  749. }
  750. var success = true
  751. if !self.isHome {
  752. if mainViewController != nil {
  753. mainViewController?.savePdfAlertView()
  754. if mainViewController?.document != nil {
  755. if (mainViewController!.needSave) {
  756. if let options = self.mainViewController?.secureOptions, !options.isEmpty {
  757. self.mainViewController!.document?.setDocumentAttributes(self.mainViewController?.documentAttribute)
  758. success = self.mainViewController!.document!.write(to: url, withOptions: options,isSaveFontSubset: false)
  759. } else if let flag = self.mainViewController?.removeSecureFlag, flag {
  760. success = self.mainViewController!.document!.writeDecrypt(to: url,isSaveFontSubset: false)
  761. } else {
  762. success = mainViewController!.document!.write(to: url,isSaveFontSubset: false)
  763. }
  764. } else {
  765. success = mainViewController!.document!.write(to: url,isSaveFontSubset: false)
  766. }
  767. self.mainViewController?.needSave = false
  768. self.mainViewController?.clearSecureOptions()
  769. self.mainViewController?.clearRemoveSecureFlag()
  770. }
  771. }
  772. } else {
  773. success = false
  774. }
  775. if (success && self._saveAsing) {
  776. if let tabView = self.browser?.windowController?.tabStripController?.activeTabView() as? CTTabView {
  777. tabView.controller()?.title = url.lastPathComponent
  778. }
  779. self._saveAsing = false
  780. }
  781. if success && isNewCreated && NSDocument.SaveOperationType.saveAsOperation == saveOperation {
  782. isNewCreated = false
  783. }
  784. if mainViewController != nil {
  785. mainViewController?.savePdfFinishAlertView()
  786. }
  787. }
  788. private func _km_saveForWatermark(openAccessoryView: Bool = true, subscribeDidClick: (()->Void)? = nil, callback:@escaping (_ needSave: Bool, _ param: Any...)->Void) {
  789. }
  790. private func _km_save(_ sender: Any?) {
  791. super.save(sender)
  792. }
  793. private func _km_save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  794. self._saveToURL = url
  795. super.save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  796. }
  797. private func _km_saveAs(_ sender: Any?) {
  798. super.saveAs(sender)
  799. self._saveAsing = true
  800. }
  801. private func _km_runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  802. super.runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  803. }
  804. private func _updateExportAccessoryView() {
  805. let typeName = self.fileTypeFromLastRunSavePanel ?? ""
  806. let matrix = self.exportAccessoryC?.matrix
  807. matrix?.selectCell(withTag: Int(self.mdFlags?.exportOption ?? 0))
  808. if self._canAttachNotesForType(typeName) {
  809. matrix?.isHidden = false
  810. let ws = NSWorkspace.shared
  811. let isLocked = self.mainViewController?.listView.document.isLocked ?? false
  812. let allowsPrinting = self.mainViewController?.listView.document.allowsPrinting ?? false
  813. if ws.type(typeName, conformsToType: KMPDFDocumentType) && isLocked == false && allowsPrinting {
  814. (matrix?.cell(withTag: KMExportOption.withEmbeddedNotes.rawValue))?.isEnabled = true
  815. } else {
  816. (matrix?.cell(withTag: KMExportOption.withEmbeddedNotes.rawValue))?.isEnabled = false
  817. if let data = self.mdFlags?.exportOption, data == KMExportOption.withEmbeddedNotes.rawValue {
  818. self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  819. matrix?.selectCell(withTag: KMExportOption.default.rawValue)
  820. }
  821. }
  822. } else {
  823. matrix?.isHidden = true
  824. }
  825. }
  826. private func _canAttachNotesForType(_ typeName: String) -> Bool {
  827. let ws = NSWorkspace.shared
  828. return ws.type(typeName, conformsToType: KMPDFDocumentType) || ws.type(typeName, conformsToType: KMPostScriptDocumentType) || ws.type(typeName, conformsToType: KMDVIDocumentType) || ws.type(typeName, conformsToType: KMXDVDocumentType)
  829. }
  830. private func _removeSavePanelOfFormatPopupItems(_ savePanel: NSSavePanel) {
  831. var formatPopup: NSPopUpButton?
  832. let svs = savePanel.accessoryView?.subviews.first?.subviews ?? []
  833. for sv in svs {
  834. if let data = sv as? NSPopUpButton {
  835. formatPopup = data
  836. break
  837. }
  838. }
  839. if let item = formatPopup?.item(withTitle: "Notes as Text") {
  840. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  841. }
  842. if let item = formatPopup?.item(withTitle: "Notes as FDF") {
  843. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  844. }
  845. if let item = formatPopup?.item(withTitle: "Notes as RTFD") {
  846. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  847. }
  848. if let item = formatPopup?.item(withTitle: NSLocalizedString("Text", comment: "")) {
  849. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  850. }
  851. if let item = formatPopup?.item(withTitle: NSLocalizedString("text", comment: "")) {
  852. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  853. }
  854. if let item = formatPopup?.item(withTitle: "PDF Reader Pro Edition Notes") {
  855. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  856. }
  857. if let item = formatPopup?.item(withTitle: "XDV") {
  858. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  859. }
  860. if let item = formatPopup?.item(withTitle: "DVI") {
  861. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  862. }
  863. if let item = formatPopup?.item(withTitle: "Images") {
  864. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  865. }
  866. if let item = formatPopup?.item(withTitle: "Encapsulated PostScript") {
  867. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  868. }
  869. }
  870. // MARK: - Printing
  871. override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey : Any]) throws -> NSPrintOperation {
  872. let printInfo = self.printInfo.copy() as! NSPrintInfo
  873. printInfo.dictionary().addEntries(from: printSettings)
  874. var printOperation: NSPrintOperation?
  875. if self.isHome {
  876. return NSPrintOperation()
  877. }
  878. let documentURL = self.mainViewController?.document?.documentURL
  879. if documentURL == nil {
  880. return NSPrintOperation()
  881. }
  882. guard let pdfDoc = PDFDocument(url: documentURL!) else {
  883. return NSPrintOperation()
  884. }
  885. if pdfDoc.responds(to: #selector(PDFDocument.printOperation(for:scalingMode:autoRotate:))) {
  886. printOperation = pdfDoc.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)
  887. } else if pdfDoc.responds(to: #selector(PDFDocument.getPrintOperation(for:autoRotate:))) {
  888. printOperation = pdfDoc.getPrintOperation(for: printInfo, autoRotate: true)
  889. }
  890. // NSPrintProtected is a private key that disables the items in the PDF popup of the Print panel, and is set for encrypted documents
  891. if pdfDoc.isEncrypted {
  892. printOperation?.printInfo.dictionary().setValue(false, forKey: "NSPrintProtected")
  893. }
  894. let printPanel = printOperation?.printPanel
  895. printPanel?.options = [.showsCopies, .showsPageRange, .showsPaperSize, .showsOrientation, .showsScaling, .showsPreview]
  896. if printOperation == nil {
  897. throw NSError.printDocumentError(withLocalizedDescription: "")
  898. }
  899. return printOperation!
  900. }
  901. override func runModalPrintOperation(_ printOperation: NSPrintOperation, delegate: Any?, didRun didRunSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  902. printOperation.run()
  903. }
  904. }
  905. extension PDFDocument {
  906. @objc func getPrintOperation(for printInfo: NSPrintInfo, autoRotate: Bool) -> NSPrintOperation {
  907. // 在此处实现方法的具体逻辑
  908. return NSPrintOperation()
  909. }
  910. }
  911. extension KMMainDocument {
  912. override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  913. if (menuItem.action == #selector(save(_ :))) {
  914. if (self.isHome) {
  915. return false
  916. }
  917. if (self.isDocumentEdited) {
  918. return self.isDocumentEdited
  919. }
  920. guard let mainVC = self.mainViewController else {
  921. return false
  922. }
  923. } else if (menuItem.action == #selector(saveAs(_ :))) {
  924. return !self.isHome
  925. } else if menuItem.action == #selector(batchRemovPrivatySecurity) {
  926. if self.isHome {
  927. return false
  928. }
  929. guard let doc = self.mainViewController?.document else {
  930. return false
  931. }
  932. let allowsPrinting = doc.allowsPrinting
  933. let allowsCopying = doc.allowsCopying
  934. if allowsCopying && allowsPrinting {
  935. return false
  936. }
  937. return true
  938. } else if menuItem.action == #selector(saveArchive) {
  939. return !self.isHome
  940. } else if (menuItem.action == #selector(saveTo(_ :))) {
  941. return !self.isHome
  942. } else if (menuItem.action == #selector(batchRemovePassWord)) {
  943. return !self.isHome
  944. } else if (menuItem.action == #selector(addBookmark)) {
  945. if menuItem.tag == 3 {
  946. return true
  947. }else {
  948. return !self.isHome
  949. }
  950. }
  951. return super.validateMenuItem(menuItem)
  952. }
  953. }
  954. extension NSDocument {
  955. @objc class func isDamage(url: URL) -> Bool {
  956. // 文件路径是否存在
  957. if (FileManager.default.fileExists(atPath: url.path) == false) {
  958. return true
  959. }
  960. /// PDF 格式文件
  961. if (url.pathExtension.lowercased() == "pdf") {
  962. let document = PDFDocument(url: url)
  963. if (document == nil) {
  964. return true
  965. }
  966. if (document!.isLocked) { // 加锁文件不在这里判断
  967. return false
  968. }
  969. if (document!.pageCount <= 0) {
  970. return true
  971. }
  972. return false
  973. }
  974. // 支持的图片格式
  975. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  976. let isImage = imageExts.contains(url.pathExtension.lowercased())
  977. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  978. return false
  979. }
  980. // 图片格式
  981. let image = NSImage(contentsOf: url)
  982. let data = image?.tiffRepresentation
  983. if (data == nil) {
  984. return true
  985. }
  986. let imageRep = NSBitmapImageRep(data: data!)
  987. imageRep!.size = image!.size
  988. var imageData: NSData?
  989. if (url.pathExtension.lowercased() == "png") {
  990. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  991. } else {
  992. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  993. }
  994. if (imageData == nil) {
  995. return true
  996. }
  997. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  998. if (FileManager.default.fileExists(atPath: path!) == false) {
  999. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  1000. }
  1001. var tagString: String = ""
  1002. let dateFormatter = DateFormatter()
  1003. dateFormatter.dateFormat = "yyMMddHHmmss"
  1004. tagString.append(dateFormatter.string(from: Date()))
  1005. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  1006. let filePath = path?.appending("/\(tagString).png")
  1007. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  1008. return true
  1009. }
  1010. // 删除临时图片
  1011. try?FileManager.default.removeItem(atPath: filePath!)
  1012. return false
  1013. }
  1014. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  1015. let result = self.isDamage(url: url)
  1016. if (result == false) {
  1017. return false
  1018. }
  1019. if (need == false) {
  1020. return true
  1021. }
  1022. let alert = NSAlert()
  1023. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1024. alert.runModal()
  1025. return true
  1026. }
  1027. }
  1028. // MARK: -
  1029. // MARK: 保存密码
  1030. extension NSDocument {
  1031. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  1032. if (document.isLocked || password.isEmpty) {
  1033. return
  1034. }
  1035. let fileId = self.fileId(for: document)
  1036. if (fileId.isEmpty) {
  1037. return
  1038. }
  1039. let label = "PDF Reader Pro: \(self.displayName!)"
  1040. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  1041. }
  1042. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  1043. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  1044. }
  1045. fileprivate func fileId(for document: CPDFDocument) -> String {
  1046. return "\(document.documentURL.path.hash)"
  1047. }
  1048. private func passwordServiceName() -> String {
  1049. return "PDF Reader Pro password"
  1050. }
  1051. }
  1052. extension KMMainDocument: SKPDFSynchronizerDelegate {
  1053. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLine line: Int, inFile file: String!) {
  1054. }
  1055. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLocation point: NSPoint, atPageIndex pageIndex: UInt, options: Int) {
  1056. }
  1057. }