KMMainDocument.swift 65 KB

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