KMMainDocument.swift 66 KB

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