KMMainDocument.swift 66 KB

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