KMMainDocument.swift 65 KB

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