KMMainDocument.swift 66 KB

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