KMMainDocument.swift 60 KB

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