KMMainDocument.swift 65 KB

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