KMMainDocument.swift 65 KB

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