KMMainDocument.swift 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  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. if let type = KMSubscribeWaterMarkType(rawValue: i) {
  643. KMTools.trackEvent(type: type)
  644. }
  645. }
  646. }
  647. self.clearTrackEvents()
  648. }
  649. func recordTrackEvent(type: KMSubscribeWaterMarkType) {
  650. if (type == .none) {
  651. return
  652. }
  653. km_synchronized(self) {
  654. self._trackEvents.insert(type.rawValue)
  655. }
  656. }
  657. func clearTrackEvents() {
  658. km_synchronized(self) {
  659. self._trackEvents.removeAll()
  660. }
  661. }
  662. @IBAction func saveArchive(_ sender: Any?) {
  663. guard let item = sender as? NSMenuItem else {
  664. NSSound.beep()
  665. return
  666. }
  667. guard let fileURL = self.fileURL else {
  668. NSSound.beep()
  669. return
  670. }
  671. let check = try?fileURL.checkResourceIsReachable()
  672. if check == false || self.isDocumentEdited {
  673. let msg = KMLocalizedString("You must save this file first")
  674. let inf = KMLocalizedString("The document has unsaved changes, or has not previously been saved to disk.")
  675. Task {
  676. _ = await KMAlertTool.runModel(message: msg, informative: inf)
  677. }
  678. return
  679. }
  680. // NSString *ext = ([sender tag] | SKArchiveDiskImageMask) ? @"dmg" : @"tgz";
  681. let idx = item.tag
  682. let ext = (idx == 1 || idx == 3) ? "dmg" : "tgz"
  683. let isEmail = (idx == 2 || idx == 3)
  684. if isEmail {
  685. // if (([sender tag] | SKArchiveEmailMask)) {
  686. let tmpDirURL = FileManager.default.uniqueChewableItemsDirectoryURL()
  687. let tmpFileURL = tmpDirURL.appendingPathComponent(fileURL.lastPathComponentReplacingPathExtension(ext))
  688. self.newSaveArchive(to: tmpFileURL, email: true)
  689. } else {
  690. let sp = NSSavePanel()
  691. sp.allowedFileTypes = [ext]
  692. sp.canCreateDirectories = true
  693. sp.nameFieldStringValue = fileURL.lastPathComponentReplacingPathExtension(ext)
  694. sp.beginSheetModal(for: self.windowForSheet!) { result in
  695. if result == .OK {
  696. self.newSaveArchive(to: sp.url!, email: false)
  697. }
  698. }
  699. }
  700. }
  701. @IBAction func readNotes(_ sender: Any?) {
  702. KMPrint("readNotes")
  703. }
  704. @IBAction func convertNotes(_ sender: Any?) {
  705. KMPrint("convertNotes")
  706. }
  707. @IBAction func batchRemovePassWord(_ sender: Any?) {
  708. self.mainViewController?.clickChildTool(type: .secure, index: 2)
  709. }
  710. @IBAction func batchRemovPrivatySecurity(_ sender: Any?) {
  711. self.mainViewController?.removeOwnerPassword()
  712. }
  713. @IBAction func printPDFDocument(_ sender: Any?) {
  714. }
  715. @IBAction func performFindPanelAction(_ sender: Any?) {
  716. }
  717. @IBAction func addBookmark(_ sender: Any?) {
  718. guard let item = sender as? NSMenuItem else {
  719. return
  720. }
  721. if item.tag == 3 {
  722. KMPrint("Edit Bookmark")
  723. bookmarkController = KMBookmarkController.showBookmarkController()
  724. } else if item.tag == 2 {
  725. KMPrint("session Bookmark")
  726. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .session)
  727. } else if item.tag == 0 {
  728. KMPrint("add Bookmark")
  729. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .bookmark)
  730. }
  731. bookmarkSheetController?.stringValue = self.displayName
  732. bookmarkSheetController?.cancelAction = { [weak self] controller, type in
  733. }
  734. bookmarkSheetController?.doneAction = { [unowned self] controller, type, label in
  735. let folder = controller.selectedFolder
  736. var bookmark: KMBookmark?
  737. switch type {
  738. case .bookmark:
  739. let mainViewController = mainViewController
  740. if let page = mainViewController?.listView.currentPage() {
  741. let index: UInt = page.pageIndex()
  742. bookmark = KMBookmark.bookmark(url: self.fileURL!, pageIndex: index, label: label)
  743. }
  744. case .setup: break
  745. let setup = currentDocumentSetup
  746. bookmark = KMBookmark.bookmark(setup: setup, label: label)
  747. case .session:
  748. let setups = NSApp.orderedDocuments.compactMap { $0.value(forKey:"currentDocumentSetup") }
  749. bookmark = KMSessionBookmark.bookmarkSession(setups: setups as NSArray, label: label)
  750. default:
  751. break
  752. }
  753. if let bookmark = bookmark {
  754. folder?.children.append(bookmark)
  755. }
  756. KMBookmarkManager.manager.saveData()
  757. }
  758. }
  759. func currentDocumntSetup() -> [String: Any] {
  760. var setup: [String: Any] = [:]
  761. let data = SKAlias.init(url: fileURL).data
  762. if (data != nil) {
  763. setup.updateValue(data as Any, forKey: "_BDAlias")
  764. } else {
  765. setup.updateValue(fileURL?.path as Any, forKey: "fileName")
  766. }
  767. return setup;
  768. }
  769. @IBAction func showWindow(_ sender: Any?) {
  770. KMPrint("showWindow")
  771. }
  772. // MARK: - Private Methods
  773. private func _PDFBundleFileWrapper(for name: String) -> FileWrapper {
  774. var aName = name
  775. if name.isCaseInsensitiveEqual(Self.kBundleDataFilename) {
  776. aName = aName + "1"
  777. }
  778. let fileWrapper = FileWrapper(directoryWithFileWrappers: [:])
  779. let info = KMInfoWindowController.shared.info(for: self)
  780. if let data = self.pdfData {
  781. fileWrapper.addRegularFile(withContents: data, preferredFilename: aName + ".pdf")
  782. }
  783. if let data = self.mainViewController?.document?.string()?.data(using: .utf8) {
  784. fileWrapper.addRegularFile(withContents: data, preferredFilename: Self.kBundleDataFilename + ".txt")
  785. }
  786. if let data = try?PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: PropertyListSerialization.WriteOptions(0)) {
  787. fileWrapper.addRegularFile(withContents: data, preferredFilename: Self.kBundleDataFilename + ".plist")
  788. }
  789. return fileWrapper
  790. }
  791. private func _km_write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  792. if typeName == KMPDFBundleDocumentType {
  793. let fileWrapper = self._PDFBundleFileWrapper(for: url.deletingPathExtension().lastPathComponent)
  794. do {
  795. try fileWrapper.write(to: url, options: FileWrapper.WritingOptions(rawValue: 0), originalContentsURL: nil)
  796. } catch {
  797. NSApp.presentError(error)
  798. }
  799. return
  800. }
  801. var success = true
  802. if !self.isHome {
  803. if mainViewController != nil {
  804. mainViewController?.savePdfAlertView()
  805. if mainViewController?.document != nil {
  806. if (mainViewController!.needSave) {
  807. if let options = self.mainViewController?.secureOptions, !options.isEmpty {
  808. self.mainViewController!.document?.setDocumentAttributes(self.mainViewController?.documentAttribute)
  809. success = self.mainViewController!.document!.write(to: url, withOptions: options)
  810. } else if let flag = self.mainViewController?.removeSecureFlag, flag {
  811. success = self.mainViewController!.document!.writeDecrypt(to: url)
  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. } else {
  820. if(mainViewController?.hasEnterRedact() == true) {
  821. success = mainViewController?.redactController.redactPdfView.document?.write(to: url) ?? false
  822. } else {
  823. success = mainViewController!.document!.write(to: url)
  824. }
  825. }
  826. self.mainViewController?.needSave = false
  827. self.mainViewController?.clearSecureOptions()
  828. self.mainViewController?.clearRemoveSecureFlag()
  829. }
  830. }
  831. } else {
  832. success = false
  833. }
  834. if (success && self._saveAsing) {
  835. if let tabView = self.browser?.windowController?.tabStripController?.activeTabView() as? CTTabView {
  836. tabView.controller()?.title = url.lastPathComponent
  837. }
  838. self._saveAsing = false
  839. }
  840. if success && isNewCreated && NSDocument.SaveOperationType.saveAsOperation == saveOperation {
  841. isNewCreated = false
  842. }
  843. if mainViewController != nil {
  844. mainViewController?.savePdfFinishAlertView()
  845. }
  846. }
  847. private func _km_saveForWatermark(openAccessoryView: Bool = true, subscribeDidClick: (()->Void)? = nil, callback:@escaping (_ needSave: Bool, _ param: Any...)->Void) {
  848. Task { @MainActor in
  849. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  850. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue:false, type: .save) {
  851. if let _callback = subscribeDidClick {
  852. _callback()
  853. }
  854. } completion: { isSubscribeSuccess, isWaterMarkExport, isClose in
  855. if (isClose) {
  856. callback(false, KMResult.cancel, false)
  857. return
  858. }
  859. if (isSubscribeSuccess) {
  860. callback(true)
  861. return
  862. }
  863. if (isWaterMarkExport) {
  864. guard let _document = self.mainViewController?.document else {
  865. callback(false, KMResult.failure)
  866. return
  867. }
  868. // 提交文本编辑的内容
  869. DispatchQueue.main.async {
  870. NSPanel.savePanel(NSApp.mainWindow!, openAccessoryView, panel:{ panel in
  871. if (!self.isNewCreated) {
  872. panel.directoryURL = _document.documentURL.deletingLastPathComponent()
  873. }
  874. panel.nameFieldStringValue = _document.documentURL.lastPathComponent
  875. }) { response, url, isOpen in
  876. if (response == .cancel) {
  877. callback(false, KMResult.cancel, true)
  878. return
  879. }
  880. guard let _url = KMTools.saveWatermarkDocument(document: _document, to: url!, secureOptions: self.mainViewController?.secureOptions, documentAttribute: self.mainViewController?.documentAttribute,removePWD: self.mainViewController!.removeSecureFlag) else {
  881. callback(false, KMResult.failure)
  882. return
  883. }
  884. callback(false, KMResult.success)
  885. if (isOpen) {
  886. NSDocumentController.shared.km_safe_openDocument(withContentsOf: _url, display: true) { _, _, _ in
  887. }
  888. } else {
  889. NSWorkspace.shared.activateFileViewerSelecting([_url])
  890. }
  891. }
  892. }
  893. return
  894. }
  895. callback(false, KMResult.cancel, false)
  896. }
  897. return
  898. }
  899. callback(true)
  900. }
  901. }
  902. private func _km_save(_ sender: Any?) {
  903. super.save(sender)
  904. }
  905. private func _km_save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  906. self._saveToURL = url
  907. super.save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  908. // self.mdFlags?.exportUsingPanel = 0
  909. // self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  910. }
  911. private func _km_saveAs(_ sender: Any?) {
  912. super.saveAs(sender)
  913. self._saveAsing = true
  914. }
  915. private func _km_runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  916. super.runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  917. }
  918. private func _updateExportAccessoryView() {
  919. let typeName = self.fileTypeFromLastRunSavePanel ?? ""
  920. let matrix = self.exportAccessoryC?.matrix
  921. matrix?.selectCell(withTag: Int(self.mdFlags?.exportOption ?? 0))
  922. if self._canAttachNotesForType(typeName) {
  923. matrix?.isHidden = false
  924. let ws = NSWorkspace.shared
  925. let isLocked = self.mainViewController?.listView.document.isLocked ?? false
  926. let allowsPrinting = self.mainViewController?.listView.document.allowsPrinting ?? false
  927. if ws.type(typeName, conformsToType: KMPDFDocumentType) && isLocked == false && allowsPrinting {
  928. (matrix?.cell(withTag: KMExportOption.withEmbeddedNotes.rawValue))?.isEnabled = true
  929. } else {
  930. (matrix?.cell(withTag: KMExportOption.withEmbeddedNotes.rawValue))?.isEnabled = false
  931. if let data = self.mdFlags?.exportOption, data == KMExportOption.withEmbeddedNotes.rawValue {
  932. self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  933. matrix?.selectCell(withTag: KMExportOption.default.rawValue)
  934. }
  935. }
  936. } else {
  937. matrix?.isHidden = true
  938. }
  939. }
  940. private func _canAttachNotesForType(_ typeName: String) -> Bool {
  941. let ws = NSWorkspace.shared
  942. return ws.type(typeName, conformsToType: KMPDFDocumentType) || ws.type(typeName, conformsToType: KMPostScriptDocumentType) || ws.type(typeName, conformsToType: KMDVIDocumentType) || ws.type(typeName, conformsToType: KMXDVDocumentType)
  943. }
  944. private func _removeSavePanelOfFormatPopupItems(_ savePanel: NSSavePanel) {
  945. var formatPopup: NSPopUpButton?
  946. let svs = savePanel.accessoryView?.subviews.first?.subviews ?? []
  947. for sv in svs {
  948. if let data = sv as? NSPopUpButton {
  949. formatPopup = data
  950. break
  951. }
  952. }
  953. if let item = formatPopup?.item(withTitle: "Notes as Text") {
  954. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  955. }
  956. if let item = formatPopup?.item(withTitle: "Notes as FDF") {
  957. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  958. }
  959. if let item = formatPopup?.item(withTitle: "Notes as RTFD") {
  960. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  961. }
  962. if let item = formatPopup?.item(withTitle: NSLocalizedString("Text", comment: "")) {
  963. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  964. }
  965. if let item = formatPopup?.item(withTitle: NSLocalizedString("text", comment: "")) {
  966. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  967. }
  968. if let item = formatPopup?.item(withTitle: "PDF Reader Pro Edition Notes") {
  969. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  970. }
  971. if let item = formatPopup?.item(withTitle: "XDV") {
  972. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  973. }
  974. if let item = formatPopup?.item(withTitle: "DVI") {
  975. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  976. }
  977. if let item = formatPopup?.item(withTitle: "Images") {
  978. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  979. }
  980. if let item = formatPopup?.item(withTitle: "Encapsulated PostScript") {
  981. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  982. }
  983. }
  984. // MARK: - Printing
  985. override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey : Any]) throws -> NSPrintOperation {
  986. let printInfo = self.printInfo.copy() as! NSPrintInfo
  987. printInfo.dictionary().addEntries(from: printSettings)
  988. var printOperation: NSPrintOperation?
  989. if self.isHome {
  990. return NSPrintOperation()
  991. }
  992. let documentURL = self.mainViewController?.document?.documentURL
  993. if documentURL == nil {
  994. return NSPrintOperation()
  995. }
  996. guard let pdfDoc = PDFDocument(url: documentURL!) else {
  997. return NSPrintOperation()
  998. }
  999. if pdfDoc.responds(to: #selector(PDFDocument.printOperation(for:scalingMode:autoRotate:))) {
  1000. printOperation = pdfDoc.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)
  1001. } else if pdfDoc.responds(to: #selector(PDFDocument.getPrintOperation(for:autoRotate:))) {
  1002. printOperation = pdfDoc.getPrintOperation(for: printInfo, autoRotate: true)
  1003. }
  1004. // NSPrintProtected is a private key that disables the items in the PDF popup of the Print panel, and is set for encrypted documents
  1005. if pdfDoc.isEncrypted {
  1006. printOperation?.printInfo.dictionary().setValue(false, forKey: "NSPrintProtected")
  1007. }
  1008. let printPanel = printOperation?.printPanel
  1009. printPanel?.options = [.showsCopies, .showsPageRange, .showsPaperSize, .showsOrientation, .showsScaling, .showsPreview]
  1010. if printOperation == nil {
  1011. throw NSError.printDocumentError(withLocalizedDescription: "")
  1012. }
  1013. return printOperation!
  1014. }
  1015. override func runModalPrintOperation(_ printOperation: NSPrintOperation, delegate: Any?, didRun didRunSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  1016. printOperation.run()
  1017. }
  1018. }
  1019. extension PDFDocument {
  1020. @objc func getPrintOperation(for printInfo: NSPrintInfo, autoRotate: Bool) -> NSPrintOperation {
  1021. // 在此处实现方法的具体逻辑
  1022. return NSPrintOperation()
  1023. }
  1024. }
  1025. extension KMMainDocument {
  1026. override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  1027. if (menuItem.action == #selector(save(_ :))) {
  1028. if (self.isHome) {
  1029. return false
  1030. }
  1031. if (self.isDocumentEdited) {
  1032. return self.isDocumentEdited
  1033. }
  1034. guard let mainVC = self.mainViewController else {
  1035. return false
  1036. }
  1037. // return mainVC.isPDFDocumentEdited || mainVC.needSave
  1038. } else if (menuItem.action == #selector(saveAs(_ :))) {
  1039. return !self.isHome
  1040. } else if menuItem.action == #selector(batchRemovPrivatySecurity) {
  1041. if self.isHome {
  1042. return false
  1043. }
  1044. guard let doc = self.mainViewController?.document else {
  1045. return false
  1046. }
  1047. let allowsPrinting = doc.allowsPrinting
  1048. let allowsCopying = doc.allowsCopying
  1049. if allowsCopying && allowsPrinting {
  1050. return false
  1051. }
  1052. return true
  1053. } else if menuItem.action == #selector(saveArchive) {
  1054. return !self.isHome
  1055. } else if (menuItem.action == #selector(saveTo(_ :))) {
  1056. return !self.isHome
  1057. } else if (menuItem.action == #selector(batchRemovePassWord)) {
  1058. return !self.isHome
  1059. } else if (menuItem.action == #selector(addBookmark)) {
  1060. if menuItem.tag == 3 {
  1061. return true
  1062. }else {
  1063. return !self.isHome
  1064. }
  1065. }
  1066. return super.validateMenuItem(menuItem)
  1067. }
  1068. }
  1069. extension NSDocument {
  1070. @objc class func isDamage(url: URL) -> Bool {
  1071. // 文件路径是否存在
  1072. if (FileManager.default.fileExists(atPath: url.path) == false) {
  1073. return true
  1074. }
  1075. /// PDF 格式文件
  1076. if (url.pathExtension.lowercased() == "pdf") {
  1077. let document = PDFDocument(url: url)
  1078. if (document == nil) {
  1079. return true
  1080. }
  1081. if (document!.isLocked) { // 加锁文件不在这里判断
  1082. return false
  1083. }
  1084. if (document!.pageCount <= 0) {
  1085. return true
  1086. }
  1087. return false
  1088. }
  1089. // 支持的图片格式
  1090. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  1091. let isImage = imageExts.contains(url.pathExtension.lowercased())
  1092. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  1093. return false
  1094. }
  1095. // 图片格式
  1096. let image = NSImage(contentsOf: url)
  1097. let data = image?.tiffRepresentation
  1098. if (data == nil) {
  1099. return true
  1100. }
  1101. let imageRep = NSBitmapImageRep(data: data!)
  1102. imageRep!.size = image!.size
  1103. var imageData: NSData?
  1104. if (url.pathExtension.lowercased() == "png") {
  1105. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  1106. } else {
  1107. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  1108. }
  1109. if (imageData == nil) {
  1110. return true
  1111. }
  1112. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1113. if (FileManager.default.fileExists(atPath: path!) == false) {
  1114. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  1115. }
  1116. var tagString: String = ""
  1117. let dateFormatter = DateFormatter()
  1118. dateFormatter.dateFormat = "yyMMddHHmmss"
  1119. tagString.append(dateFormatter.string(from: Date()))
  1120. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  1121. let filePath = path?.appending("/\(tagString).png")
  1122. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  1123. return true
  1124. }
  1125. // 删除临时图片
  1126. try?FileManager.default.removeItem(atPath: filePath!)
  1127. return false
  1128. }
  1129. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  1130. let result = self.isDamage(url: url)
  1131. if (result == false) {
  1132. return false
  1133. }
  1134. if (need == false) {
  1135. return true
  1136. }
  1137. let alert = NSAlert()
  1138. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1139. alert.runModal()
  1140. return true
  1141. }
  1142. }
  1143. // MARK: -
  1144. // MARK: 保存密码
  1145. extension NSDocument {
  1146. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  1147. if (document.isLocked || password.isEmpty) {
  1148. return
  1149. }
  1150. let fileId = self.fileId(for: document)
  1151. if (fileId.isEmpty) {
  1152. return
  1153. }
  1154. // let status: SKPasswordStatus =
  1155. let label = "PDF Reader Pro: \(self.displayName!)"
  1156. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  1157. }
  1158. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  1159. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  1160. // if (status == .found) {
  1161. // }
  1162. }
  1163. fileprivate func fileId(for document: CPDFDocument) -> String {
  1164. return "\(document.documentURL.path.hash)"
  1165. }
  1166. private func passwordServiceName() -> String {
  1167. return "PDF Reader Pro password"
  1168. }
  1169. }
  1170. extension KMMainDocument: SKPDFSynchronizerDelegate {
  1171. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLine line: Int, inFile file: String!) {
  1172. if FileManager.default.fileExists(atPath: file) {
  1173. let defaults = UserDefaults.standard
  1174. var editorPreset = defaults.string(forKey: SKTeXEditorPresetKey) ?? ""
  1175. var editorCmd: String?
  1176. var editorArgs: String?
  1177. var cmdString: String?
  1178. if !KMSyncPreferences.getTeXEditorCommand(command: &editorCmd, arguments: &editorArgs, forPreset: editorPreset) {
  1179. editorCmd = defaults.string(forKey: SKTeXEditorCommandKey)
  1180. editorArgs = defaults.string(forKey: SKTeXEditorArgumentsKey)
  1181. }
  1182. if var cmdString = editorArgs {
  1183. if !editorCmd!.hasPrefix("/") {
  1184. var searchPaths = ["/usr/bin", "/usr/local/bin"]
  1185. var toolPath: String?
  1186. let fm = FileManager.default
  1187. if !(editorPreset.isEmpty) {
  1188. if let path = NSWorkspace.shared.fullPath(forApplication: editorPreset) {
  1189. if let appBundle = Bundle(path: path) {
  1190. if let contentsPath = appBundle.path(forResource: "Contents", ofType: nil) {
  1191. searchPaths.insert(contentsPath, at: 0)
  1192. }
  1193. if editorPreset != "BBEdit", let execPath = appBundle.executablePath {
  1194. searchPaths.insert(execPath, at: 0)
  1195. }
  1196. if let resourcePath = appBundle.resourcePath {
  1197. searchPaths.insert(resourcePath, at: 0)
  1198. }
  1199. if let sharedSupportPath = appBundle.sharedSupportPath {
  1200. searchPaths.insert(sharedSupportPath, at: 0)
  1201. }
  1202. }
  1203. }
  1204. } else {
  1205. let appSupportDirs = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
  1206. let appSupportPaths = appSupportDirs.map { $0.path }
  1207. searchPaths.append(contentsOf: appSupportPaths)
  1208. }
  1209. for path in searchPaths {
  1210. toolPath = (path as NSString).appendingPathComponent(editorCmd!)
  1211. if fm.isExecutableFile(atPath: toolPath!) {
  1212. editorCmd = toolPath
  1213. break
  1214. }
  1215. toolPath = ((path as NSString).appendingPathComponent("bin") as NSString).appendingPathComponent(editorCmd!)
  1216. if fm.isExecutableFile(atPath: toolPath!) {
  1217. editorCmd = toolPath
  1218. break
  1219. }
  1220. }
  1221. }
  1222. cmdString = cmdString.replacingOccurrences(of: "%line", with: "\(line + 1)")
  1223. cmdString = cmdString.replacingOccurrences(of: "%file", with: file)
  1224. cmdString = cmdString.replacingOccurrences(of: "%output", with: fileURL?.path ?? "")
  1225. cmdString.insert(contentsOf: "\" ", at: cmdString.startIndex)
  1226. cmdString.insert(contentsOf: editorCmd!, at: cmdString.startIndex)
  1227. cmdString.insert("\"", at: cmdString.startIndex)
  1228. let ws = NSWorkspace.shared
  1229. if let theUTI = try? ws.type(ofFile: editorCmd!) {
  1230. if ws.type(theUTI, conformsToType: "com.apple.applescript.script") || ws.type(theUTI, conformsToType: "com.apple.applescript.text") {
  1231. cmdString.insert(contentsOf: "/usr/bin/osascript ", at: cmdString.startIndex)
  1232. }
  1233. }
  1234. let task = Process()
  1235. task.launchPath = "/bin/sh"
  1236. task.currentDirectoryPath = (file as NSString).deletingLastPathComponent
  1237. task.arguments = ["-c", cmdString]
  1238. task.standardOutput = FileHandle.nullDevice
  1239. task.standardError = FileHandle.nullDevice
  1240. do {
  1241. try task.run()
  1242. } catch let error {
  1243. Swift.print("command failed: \(cmdString ?? ""): \(error)")
  1244. }
  1245. }
  1246. }
  1247. }
  1248. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLocation point: NSPoint, atPageIndex pageIndex: UInt, options: Int) {
  1249. guard let pdfDoc = self.mainViewController?.document else { return }
  1250. if pageIndex < pdfDoc.pageCount {
  1251. if let page = pdfDoc.page(at: pageIndex) {
  1252. var adjustedPoint = point
  1253. if options & SKPDFSynchronizerFlippedMask != 0 {
  1254. let mediaBox = page.bounds(for: .mediaBox)
  1255. adjustedPoint.y = NSMaxY(mediaBox) - adjustedPoint.y
  1256. }
  1257. self.mainViewController?.listView.displayLine(at: adjustedPoint, inPageAtIndex: Int(pageIndex), showReadingBar: options & SKPDFSynchronizerShowReadingBarMask != 0)
  1258. }
  1259. }
  1260. }
  1261. }
  1262. extension KMMainDocument {
  1263. }