KMMainDocument.swift 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508
  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() || KMPreference.shared.openDocumentType == .newWindow){
  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. guard let annotation = dic?["object"] as? CPDFAnnotation else { return }
  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. self.mainViewController?.saveDocument()
  731. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.mainViewController?.document, inputPageRange: KMPrintPageRange())
  732. }
  733. @IBAction func performFindPanelAction(_ sender: Any?) {
  734. self.mainViewController?.toolbarController.showFindBar()
  735. }
  736. @IBAction func addBookmark(_ sender: Any?) {
  737. guard let item = sender as? NSMenuItem else {
  738. return
  739. }
  740. // let bookmarkSheetController = SKBookmarkSheetController(windowNibName: "BookmarkSheet")
  741. // NSWindow.currentWindow().beginSheet(bookmarkSheetController.window!) { resoponse in
  742. //
  743. // }
  744. // bookmarkSheetController.textField.stringValue = self.displayName
  745. // bookmarkSheetController.beginSheetModal(for: self.windowForSheet) { [unowned self] result in
  746. // if (result == NSApplication.ModalResponse.OK.rawValue) {
  747. // let label = bookmarkSheetController.textField.stringValue;
  748. // let folder: SKBookmark = bookmarkSheetController.selectedFolder ?? SKBookmarkController.shared().bookmarkRoot
  749. // var bookmark = SKBookmark()
  750. // switch (item.tag) {
  751. // case 0:
  752. // let mainViewController = self.mainViewController
  753. // let page = mainViewController?.listView.currentPage()
  754. // bookmark = SKBookmark.bookmark(with: self.fileURL, pageIndex: (page?.pageIndex())!, label: label) as! SKBookmark
  755. // case 1:
  756. // let setup = self.currentDocumntSetup()
  757. // bookmark = SKBookmark.bookmark(withSetup: setup, label: label) as! SKBookmark
  758. //
  759. // case 2:
  760. // let setups = NSApp.orderedDocuments.map { $0.value(forKey: "currentDocumentSetup") }
  761. // bookmark = SKBookmark.bookmarkSession(withSetups: setups as [Any], label: label) as! SKBookmark
  762. //
  763. // default:
  764. // break;
  765. // }
  766. // folder.mutableArrayValue(forKey: "children").add(bookmark)
  767. // }
  768. // }
  769. if item.tag == 3 {
  770. KMPrint("Edit Bookmark")
  771. bookmarkController = KMBookmarkController.showBookmarkController()
  772. } else if item.tag == 2 {
  773. KMPrint("session Bookmark")
  774. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .session)
  775. } else if item.tag == 0 {
  776. KMPrint("add Bookmark")
  777. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .bookmark)
  778. }
  779. bookmarkSheetController?.stringValue = self.displayName
  780. bookmarkSheetController?.cancelAction = { [unowned self] controller, type in
  781. }
  782. //
  783. bookmarkSheetController?.doneAction = { [unowned self] controller, type, label in
  784. let folder = controller.selectedFolder
  785. var bookmark: KMBookmark?
  786. switch type {
  787. case .bookmark:
  788. let mainViewController = mainViewController
  789. if let page = mainViewController?.listView.currentPage() {
  790. let index: UInt = page.pageIndex()
  791. bookmark = KMBookmark.bookmark(url: self.fileURL!, pageIndex: index, label: label)
  792. }
  793. case .setup: break
  794. let setup = currentDocumentSetup
  795. bookmark = KMBookmark.bookmark(setup: setup, label: label)
  796. case .session:
  797. let setups = NSApp.orderedDocuments.compactMap { $0.value(forKey:"currentDocumentSetup") }
  798. bookmark = KMSessionBookmark.bookmarkSession(setups: setups as NSArray, label: label)
  799. default:
  800. break
  801. }
  802. if let bookmark = bookmark {
  803. folder?.children.append(bookmark)
  804. }
  805. KMBookmarkManager.manager.saveData()
  806. }
  807. }
  808. func currentDocumntSetup() -> [String: Any] {
  809. var setup: [String: Any] = [:]
  810. let data = SKAlias.init(url: fileURL).data
  811. if (data != nil) {
  812. setup.updateValue(data as Any, forKey: "_BDAlias")
  813. } else {
  814. setup.updateValue(fileURL?.path as Any, forKey: "fileName")
  815. }
  816. return setup;
  817. }
  818. @IBAction func showWindow(_ sender: Any?) {
  819. KMPrint("showWindow")
  820. }
  821. // MARK: - Private Methods
  822. private func _PDFBundleFileWrapper(for name: String) -> FileWrapper {
  823. var aName = name
  824. if name.isCaseInsensitiveEqual(Self.kBundleDataFilename) {
  825. aName = aName + "1"
  826. }
  827. // var data: Data?
  828. let fileWrapper = FileWrapper(directoryWithFileWrappers: [:])
  829. let info = KMInfoWindowController.shared.info(for: self)
  830. // NSDictionary *options = [[self mainWindowController] presentationOptions];
  831. // if (options) {
  832. // info = [[info mutableCopy] autorelease];
  833. // [(NSMutableDictionary *)info setObject:options forKey:SKPresentationOptionsKey];
  834. // }
  835. if let data = self.pdfData {
  836. fileWrapper.addRegularFile(withContents: data, preferredFilename: aName + ".pdf")
  837. }
  838. if let data = self.mainViewController?.document?.string()?.data(using: .utf8) {
  839. fileWrapper.addRegularFile(withContents: data, preferredFilename: Self.kBundleDataFilename + ".txt")
  840. }
  841. if let data = try?PropertyListSerialization.data(fromPropertyList: info, format: .xml, options: PropertyListSerialization.WriteOptions(0)) {
  842. fileWrapper.addRegularFile(withContents: data, preferredFilename: Self.kBundleDataFilename + ".plist")
  843. }
  844. // if ((data = [NSPropertyListSerialization dataWithPropertyList:info format:NSPropertyListXMLFormat_v1_0 options:0 error:NULL]))
  845. // [fileWrapper addRegularFileWithContents:data preferredFilename:[BUNDLE_DATA_FILENAME stringByAppendingPathExtension:@"plist"]];
  846. // if ([[self notes] count] > 0) {
  847. // if ((data = [self notesData]))
  848. // [fileWrapper addRegularFileWithContents:data preferredFilename:[name stringByAppendingPathExtension:@"skim"]];
  849. // if ((data = [[self notesString] dataUsingEncoding:NSUTF8StringEncoding]))
  850. // [fileWrapper addRegularFileWithContents:data preferredFilename:[name stringByAppendingPathExtension:@"txt"]];
  851. // if ((data = [self notesRTFData]))
  852. // [fileWrapper addRegularFileWithContents:data preferredFilename:[name stringByAppendingPathExtension:@"rtf"]];
  853. // if ((data = [self notesFDFDataForFile:[name stringByAppendingPathExtension:@"pdf"] fileIDStrings:[[self pdfDocument] fileIDStrings]]))
  854. // [fileWrapper addRegularFileWithContents:data preferredFilename:[name stringByAppendingPathExtension:@"fdf"]];
  855. // }
  856. return fileWrapper
  857. }
  858. private func _km_write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  859. if typeName == KMPDFBundleDocumentType {
  860. // NSFileWrapper *fileWrapper = [self PDFBundleFileWrapperForName:[[absoluteURL lastPathComponent] stringByDeletingPathExtension]];
  861. // if (fileWrapper)
  862. // didWrite = [fileWrapper writeToURL:absoluteURL options:0 originalContentsURL:nil error:&error];
  863. // else
  864. // error = [NSError writeFileErrorWithLocalizedDescription:NSLocalizedString(@"Unable to write file", @"Error description")];
  865. let fileWrapper = self._PDFBundleFileWrapper(for: url.deletingPathExtension().lastPathComponent)
  866. do {
  867. try fileWrapper.write(to: url, options: FileWrapper.WritingOptions(rawValue: 0), originalContentsURL: nil)
  868. } catch {
  869. NSApp.presentError(error)
  870. }
  871. return
  872. }
  873. var success = true
  874. if !self.isHome {
  875. if mainViewController != nil {
  876. mainViewController?.savePdfAlertView()
  877. if mainViewController?.document != nil {
  878. self.mainViewController?.commitEditingIfNeed()
  879. // if mainViewController!.document!.isEncrypted {
  880. // success = mainViewController!.document!.write(to: url)
  881. // } else {
  882. if (mainViewController!.needSave) {
  883. if let options = self.mainViewController?.secureOptions, !options.isEmpty {
  884. self.mainViewController!.document?.setDocumentAttributes(self.mainViewController?.documentAttribute)
  885. success = self.mainViewController!.document!.write(to: url, withOptions: options)
  886. } else if let flag = self.mainViewController?.removeSecureFlag, flag {
  887. success = self.mainViewController!.document!.writeDecrypt(to: url)
  888. } else {
  889. success = mainViewController!.document!.write(to: url)
  890. }
  891. } else {
  892. success = mainViewController!.document!.write(to: url)
  893. }
  894. // }
  895. self.mainViewController?.needSave = false
  896. self.mainViewController?.clearSecureOptions()
  897. self.mainViewController?.clearRemoveSecureFlag()
  898. }
  899. }
  900. } else {
  901. success = false
  902. }
  903. if (success && self._saveAsing) {
  904. if let tabView = self.browser?.windowController?.tabStripController?.activeTabView() as? CTTabView {
  905. tabView.controller()?.title = url.lastPathComponent
  906. }
  907. self._saveAsing = false
  908. }
  909. if success && isNewCreated && NSDocument.SaveOperationType.saveAsOperation == saveOperation {
  910. isNewCreated = false
  911. }
  912. if mainViewController != nil {
  913. mainViewController?.savePdfFinishAlertView()
  914. }
  915. }
  916. private func _km_saveForWatermark(openAccessoryView: Bool = true, subscribeDidClick: (()->Void)? = nil, callback:@escaping (_ needSave: Bool, _ param: Any...)->Void) {
  917. Task { @MainActor in
  918. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  919. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue:false, type: .save) {
  920. if let _callback = subscribeDidClick {
  921. _callback()
  922. }
  923. } completion: { isSubscribeSuccess, isWaterMarkExport, isClose in
  924. if (isClose) {
  925. callback(false, KMResult.cancel, false)
  926. return
  927. }
  928. if (isSubscribeSuccess) {
  929. callback(true)
  930. return
  931. }
  932. if (isWaterMarkExport) {
  933. guard let _document = self.mainViewController?.document else {
  934. callback(false, KMResult.failure)
  935. return
  936. }
  937. // 提交文本编辑的内容
  938. self.mainViewController?.commitEditingIfNeed()
  939. DispatchQueue.main.async {
  940. NSPanel.savePanel(NSApp.mainWindow!, openAccessoryView, panel:{ panel in
  941. if (!self.isNewCreated) {
  942. panel.directoryURL = _document.documentURL.deletingLastPathComponent()
  943. }
  944. panel.nameFieldStringValue = _document.documentURL.lastPathComponent
  945. }) { response, url, isOpen in
  946. if (response == .cancel) {
  947. callback(false, KMResult.cancel, true)
  948. return
  949. }
  950. guard let _url = KMTools.saveWatermarkDocument(document: _document, to: url!, secureOptions: self.mainViewController?.secureOptions, documentAttribute: self.mainViewController?.documentAttribute,removePWD: self.mainViewController!.removeSecureFlag) else {
  951. callback(false, KMResult.failure)
  952. return
  953. }
  954. callback(false, KMResult.success)
  955. if (isOpen) {
  956. NSDocumentController.shared.km_safe_openDocument(withContentsOf: _url, display: true) { _, _, _ in
  957. }
  958. } else {
  959. NSWorkspace.shared.activateFileViewerSelecting([_url])
  960. }
  961. }
  962. }
  963. return
  964. }
  965. callback(false, KMResult.cancel, false)
  966. }
  967. return
  968. }
  969. callback(true)
  970. }
  971. }
  972. private func _km_save(_ sender: Any?) {
  973. super.save(sender)
  974. }
  975. private func _km_save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  976. self._saveToURL = url
  977. super.save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  978. // self.mdFlags?.exportUsingPanel = 0
  979. // self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  980. }
  981. private func _km_saveAs(_ sender: Any?) {
  982. super.saveAs(sender)
  983. self._saveAsing = true
  984. }
  985. private func _km_runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  986. super.runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  987. }
  988. private func _updateExportAccessoryView() {
  989. let typeName = self.fileTypeFromLastRunSavePanel ?? ""
  990. let matrix = self.exportAccessoryC?.matrix
  991. matrix?.selectCell(withTag: Int(self.mdFlags?.exportOption ?? 0))
  992. if self._canAttachNotesForType(typeName) {
  993. matrix?.isHidden = false
  994. let ws = NSWorkspace.shared
  995. let isLocked = self.mainViewController?.listView.document.isLocked ?? false
  996. let allowsPrinting = self.mainViewController?.listView.document.allowsPrinting ?? false
  997. if ws.type(typeName, conformsToType: KMPDFDocumentType) && isLocked == false && allowsPrinting {
  998. (matrix?.cell(withTag: KMExportOption.withEmbeddedNotes.rawValue))?.isEnabled = true
  999. } else {
  1000. (matrix?.cell(withTag: KMExportOption.withEmbeddedNotes.rawValue))?.isEnabled = false
  1001. if let data = self.mdFlags?.exportOption, data == KMExportOption.withEmbeddedNotes.rawValue {
  1002. self.mdFlags?.exportOption = UInt32(KMExportOption.default.rawValue)
  1003. matrix?.selectCell(withTag: KMExportOption.default.rawValue)
  1004. }
  1005. }
  1006. } else {
  1007. matrix?.isHidden = true
  1008. }
  1009. }
  1010. private func _canAttachNotesForType(_ typeName: String) -> Bool {
  1011. let ws = NSWorkspace.shared
  1012. return ws.type(typeName, conformsToType: KMPDFDocumentType) || ws.type(typeName, conformsToType: KMPostScriptDocumentType) || ws.type(typeName, conformsToType: KMDVIDocumentType) || ws.type(typeName, conformsToType: KMXDVDocumentType)
  1013. }
  1014. private func _removeSavePanelOfFormatPopupItems(_ savePanel: NSSavePanel) {
  1015. var formatPopup: NSPopUpButton?
  1016. let svs = savePanel.accessoryView?.subviews.first?.subviews ?? []
  1017. for sv in svs {
  1018. if let data = sv as? NSPopUpButton {
  1019. formatPopup = data
  1020. break
  1021. }
  1022. }
  1023. if let item = formatPopup?.item(withTitle: "Notes as Text") {
  1024. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1025. }
  1026. if let item = formatPopup?.item(withTitle: "Notes as FDF") {
  1027. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1028. }
  1029. if let item = formatPopup?.item(withTitle: "Notes as RTFD") {
  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: NSLocalizedString("text", comment: "")) {
  1036. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1037. }
  1038. if let item = formatPopup?.item(withTitle: "PDF Reader Pro Edition Notes") {
  1039. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1040. }
  1041. if let item = formatPopup?.item(withTitle: "XDV") {
  1042. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1043. }
  1044. if let item = formatPopup?.item(withTitle: "DVI") {
  1045. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1046. }
  1047. if let item = formatPopup?.item(withTitle: "Images") {
  1048. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1049. }
  1050. if let item = formatPopup?.item(withTitle: "Encapsulated PostScript") {
  1051. formatPopup?.removeItem(at: formatPopup!.index(of: item))
  1052. }
  1053. }
  1054. // MARK: - Printing
  1055. override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey : Any]) throws -> NSPrintOperation {
  1056. let printInfo = self.printInfo.copy() as! NSPrintInfo
  1057. printInfo.dictionary().addEntries(from: printSettings)
  1058. var printOperation: NSPrintOperation?
  1059. if self.isHome {
  1060. return NSPrintOperation()
  1061. }
  1062. let documentURL = self.mainViewController?.document?.documentURL
  1063. if documentURL == nil {
  1064. return NSPrintOperation()
  1065. }
  1066. guard let pdfDoc = PDFDocument(url: documentURL!) else {
  1067. return NSPrintOperation()
  1068. }
  1069. if pdfDoc.responds(to: #selector(PDFDocument.printOperation(for:scalingMode:autoRotate:))) {
  1070. printOperation = pdfDoc.printOperation(for: printInfo, scalingMode: .pageScaleNone, autoRotate: true)
  1071. } else if pdfDoc.responds(to: #selector(PDFDocument.getPrintOperation(for:autoRotate:))) {
  1072. printOperation = pdfDoc.getPrintOperation(for: printInfo, autoRotate: true)
  1073. }
  1074. // NSPrintProtected is a private key that disables the items in the PDF popup of the Print panel, and is set for encrypted documents
  1075. if pdfDoc.isEncrypted {
  1076. printOperation?.printInfo.dictionary().setValue(false, forKey: "NSPrintProtected")
  1077. }
  1078. let printPanel = printOperation?.printPanel
  1079. printPanel?.options = [.showsCopies, .showsPageRange, .showsPaperSize, .showsOrientation, .showsScaling, .showsPreview]
  1080. if printOperation == nil {
  1081. throw NSError.printDocumentError(withLocalizedDescription: "")
  1082. }
  1083. return printOperation!
  1084. }
  1085. override func runModalPrintOperation(_ printOperation: NSPrintOperation, delegate: Any?, didRun didRunSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  1086. printOperation.run()
  1087. }
  1088. }
  1089. extension PDFDocument {
  1090. @objc func getPrintOperation(for printInfo: NSPrintInfo, autoRotate: Bool) -> NSPrintOperation {
  1091. // 在此处实现方法的具体逻辑
  1092. return NSPrintOperation()
  1093. }
  1094. }
  1095. extension KMMainDocument {
  1096. override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  1097. if (menuItem.action == #selector(save(_ :))) {
  1098. if (self.isHome) {
  1099. return false
  1100. }
  1101. if (self.isDocumentEdited) {
  1102. return self.isDocumentEdited
  1103. }
  1104. guard let mainVC = self.mainViewController else {
  1105. return false
  1106. }
  1107. return mainVC.isPDFDocumentEdited || mainVC.needSave
  1108. } else if (menuItem.action == #selector(saveAs(_ :))) {
  1109. return !self.isHome
  1110. } else if menuItem.action == #selector(batchRemovPrivatySecurity) {
  1111. if self.isHome {
  1112. return false
  1113. }
  1114. guard let doc = self.mainViewController?.listView?.document else {
  1115. return false
  1116. }
  1117. let allowsPrinting = doc.allowsPrinting
  1118. let allowsCopying = doc.allowsCopying
  1119. if allowsCopying && allowsPrinting {
  1120. return false
  1121. }
  1122. return true
  1123. } else if menuItem.action == #selector(saveArchive) {
  1124. return !self.isHome
  1125. } else if (menuItem.action == #selector(saveTo(_ :))) {
  1126. return !self.isHome
  1127. } else if (menuItem.action == #selector(batchRemovePassWord)) {
  1128. return !self.isHome
  1129. } else if (menuItem.action == #selector(addBookmark)) {
  1130. if menuItem.tag == 3 {
  1131. return true
  1132. }else {
  1133. return !self.isHome
  1134. }
  1135. }
  1136. return super.validateMenuItem(menuItem)
  1137. }
  1138. }
  1139. extension NSDocument {
  1140. @objc class func isDamage(url: URL) -> Bool {
  1141. // 文件路径是否存在
  1142. if (FileManager.default.fileExists(atPath: url.path) == false) {
  1143. return true
  1144. }
  1145. /// PDF 格式文件
  1146. if (url.pathExtension.lowercased() == "pdf") {
  1147. let document = PDFDocument(url: url)
  1148. if (document == nil) {
  1149. return true
  1150. }
  1151. if (document!.isLocked) { // 加锁文件不在这里判断
  1152. return false
  1153. }
  1154. if (document!.pageCount <= 0) {
  1155. return true
  1156. }
  1157. return false
  1158. }
  1159. // 支持的图片格式
  1160. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  1161. let isImage = imageExts.contains(url.pathExtension.lowercased())
  1162. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  1163. return false
  1164. }
  1165. // 图片格式
  1166. let image = NSImage(contentsOf: url)
  1167. let data = image?.tiffRepresentation
  1168. if (data == nil) {
  1169. return true
  1170. }
  1171. let imageRep = NSBitmapImageRep(data: data!)
  1172. imageRep!.size = image!.size
  1173. var imageData: NSData?
  1174. if (url.pathExtension.lowercased() == "png") {
  1175. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  1176. } else {
  1177. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  1178. }
  1179. if (imageData == nil) {
  1180. return true
  1181. }
  1182. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1183. if (FileManager.default.fileExists(atPath: path!) == false) {
  1184. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  1185. }
  1186. var tagString: String = ""
  1187. let dateFormatter = DateFormatter()
  1188. dateFormatter.dateFormat = "yyMMddHHmmss"
  1189. tagString.append(dateFormatter.string(from: Date()))
  1190. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  1191. let filePath = path?.appending("/\(tagString).png")
  1192. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  1193. return true
  1194. }
  1195. // 删除临时图片
  1196. try?FileManager.default.removeItem(atPath: filePath!)
  1197. return false
  1198. }
  1199. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  1200. let result = self.isDamage(url: url)
  1201. if (result == false) {
  1202. return false
  1203. }
  1204. if (need == false) {
  1205. return true
  1206. }
  1207. let alert = NSAlert()
  1208. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1209. alert.runModal()
  1210. return true
  1211. }
  1212. }
  1213. // MARK: -
  1214. // MARK: 保存密码
  1215. extension NSDocument {
  1216. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  1217. if (document.isLocked || password.isEmpty) {
  1218. return
  1219. }
  1220. let fileId = self.fileId(for: document)
  1221. if (fileId.isEmpty) {
  1222. return
  1223. }
  1224. // let status: SKPasswordStatus =
  1225. let label = "PDF Reader Pro: \(self.displayName!)"
  1226. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  1227. }
  1228. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  1229. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  1230. // if (status == .found) {
  1231. // }
  1232. }
  1233. fileprivate func fileId(for document: CPDFDocument) -> String {
  1234. return "\(document.documentURL.path.hash)"
  1235. }
  1236. private func passwordServiceName() -> String {
  1237. return "PDF Reader Pro password"
  1238. }
  1239. }
  1240. extension KMMainDocument: SKPDFSynchronizerDelegate {
  1241. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLine line: Int, inFile file: String!) {
  1242. if FileManager.default.fileExists(atPath: file) {
  1243. let defaults = UserDefaults.standard
  1244. var editorPreset = defaults.string(forKey: SKTeXEditorPresetKey) ?? ""
  1245. var editorCmd: String?
  1246. var editorArgs: String?
  1247. var cmdString: String?
  1248. if !KMSyncPreferences.getTeXEditorCommand(command: &editorCmd, arguments: &editorArgs, forPreset: editorPreset) {
  1249. editorCmd = defaults.string(forKey: SKTeXEditorCommandKey)
  1250. editorArgs = defaults.string(forKey: SKTeXEditorArgumentsKey)
  1251. }
  1252. if var cmdString = editorArgs {
  1253. if !editorCmd!.hasPrefix("/") {
  1254. var searchPaths = ["/usr/bin", "/usr/local/bin"]
  1255. var toolPath: String?
  1256. let fm = FileManager.default
  1257. if !(editorPreset.isEmpty) {
  1258. if let path = NSWorkspace.shared.fullPath(forApplication: editorPreset) {
  1259. if let appBundle = Bundle(path: path) {
  1260. if let contentsPath = appBundle.path(forResource: "Contents", ofType: nil) {
  1261. searchPaths.insert(contentsPath, at: 0)
  1262. }
  1263. if editorPreset != "BBEdit", let execPath = appBundle.executablePath {
  1264. searchPaths.insert(execPath, at: 0)
  1265. }
  1266. if let resourcePath = appBundle.resourcePath {
  1267. searchPaths.insert(resourcePath, at: 0)
  1268. }
  1269. if let sharedSupportPath = appBundle.sharedSupportPath {
  1270. searchPaths.insert(sharedSupportPath, at: 0)
  1271. }
  1272. }
  1273. }
  1274. } else {
  1275. let appSupportDirs = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
  1276. let appSupportPaths = appSupportDirs.map { $0.path }
  1277. searchPaths.append(contentsOf: appSupportPaths)
  1278. }
  1279. for path in searchPaths {
  1280. toolPath = (path as NSString).appendingPathComponent(editorCmd!)
  1281. if fm.isExecutableFile(atPath: toolPath!) {
  1282. editorCmd = toolPath
  1283. break
  1284. }
  1285. toolPath = ((path as NSString).appendingPathComponent("bin") as NSString).appendingPathComponent(editorCmd!)
  1286. if fm.isExecutableFile(atPath: toolPath!) {
  1287. editorCmd = toolPath
  1288. break
  1289. }
  1290. }
  1291. }
  1292. cmdString = cmdString.replacingOccurrences(of: "%line", with: "\(line + 1)")
  1293. cmdString = cmdString.replacingOccurrences(of: "%file", with: file)
  1294. cmdString = cmdString.replacingOccurrences(of: "%output", with: fileURL?.path ?? "")
  1295. cmdString.insert(contentsOf: "\" ", at: cmdString.startIndex)
  1296. cmdString.insert(contentsOf: editorCmd!, at: cmdString.startIndex)
  1297. cmdString.insert("\"", at: cmdString.startIndex)
  1298. let ws = NSWorkspace.shared
  1299. if let theUTI = try? ws.type(ofFile: editorCmd!) {
  1300. if ws.type(theUTI, conformsToType: "com.apple.applescript.script") || ws.type(theUTI, conformsToType: "com.apple.applescript.text") {
  1301. cmdString.insert(contentsOf: "/usr/bin/osascript ", at: cmdString.startIndex)
  1302. }
  1303. }
  1304. let task = Process()
  1305. task.launchPath = "/bin/sh"
  1306. task.currentDirectoryPath = (file as NSString).deletingLastPathComponent
  1307. task.arguments = ["-c", cmdString]
  1308. task.standardOutput = FileHandle.nullDevice
  1309. task.standardError = FileHandle.nullDevice
  1310. do {
  1311. try task.run()
  1312. } catch let error {
  1313. Swift.print("command failed: \(cmdString ?? ""): \(error)")
  1314. }
  1315. }
  1316. }
  1317. }
  1318. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLocation point: NSPoint, atPageIndex pageIndex: UInt, options: Int) {
  1319. guard let pdfDoc = self.mainViewController?.document else { return }
  1320. if pageIndex < pdfDoc.pageCount {
  1321. if let page = pdfDoc.page(at: pageIndex) {
  1322. var adjustedPoint = point
  1323. if options & SKPDFSynchronizerFlippedMask != 0 {
  1324. let mediaBox = page.bounds(for: .mediaBox)
  1325. adjustedPoint.y = NSMaxY(mediaBox) - adjustedPoint.y
  1326. }
  1327. self.mainViewController?.listView.displayLine(at: adjustedPoint, inPageAtIndex: Int(pageIndex), showReadingBar: options & SKPDFSynchronizerShowReadingBarMask != 0)
  1328. }
  1329. }
  1330. }
  1331. }
  1332. extension KMMainDocument {
  1333. }