KMMainDocument.swift 61 KB

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