KMMainDocument.swift 57 KB

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