KMMainDocument.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. typealias KMMainDocumentCloudUploadHanddler = (@escaping(Bool, String)->()) -> ()
  14. @objcMembers class KMMainDocument: CTTabContents {
  15. struct MDFlags {
  16. var exportOption: UInt32 // assuming this is a 2-bit field, change to appropriate data type
  17. var exportUsingPanel: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  18. var gettingFileType: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  19. var convertingNotes: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  20. var needsPasswordToConvert: UInt32 // assuming this is a 1-bit field, change to appropriate data type
  21. }
  22. var mainViewController: KMMainViewController?
  23. var homeWindowController: KMHomeWindowController?
  24. var homeViewController: KMHomeViewController?
  25. var bookmarkSheetController: KMBookmarkSheetController?
  26. var bookmarkController: KMBookmarkController?
  27. var isNewCreated: Bool = false
  28. var closedByUserGestureFlag: Bool = false // 标记 closedByUserGesture 这个状态需要延后存储(如果需要)
  29. var cloud: Bool = false
  30. var cloudUploadHanddler: KMMainDocumentCloudUploadHanddler?
  31. var isUnlockFromKeychain: Bool = false
  32. private var _saveAsing = false
  33. var fileUpdateChecker: SKFileUpdateChecker?
  34. var mdFlags: MDFlags?
  35. private var _saveToURL: URL?
  36. var saveToURL: URL? {
  37. get {
  38. return self._saveToURL
  39. }
  40. }
  41. weak var watermarkSaveDelegate: AnyObject?
  42. private var _trackEvents = IndexSet()
  43. override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  44. if (self.isNewCreated) {
  45. // if let data = self.mainViewController, !data.isPDFDocumentEdited && !data.needSave && !self.isDocumentEdited {
  46. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  47. return
  48. // }
  49. }
  50. if (!self.needSaveWatermark()) {
  51. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  52. return
  53. }
  54. var openAccessoryView = self.watermarkSaveDelegate != nil
  55. if (openAccessoryView) {
  56. if let _browser = self.watermarkSaveDelegate as? KMBrowser, _browser.isCloseAllTabViewItem {
  57. openAccessoryView = false
  58. }
  59. }
  60. self._km_saveForWatermark(openAccessoryView: openAccessoryView) { [unowned self] in
  61. self.trackEvents()
  62. } callback: { [unowned self] needSave, params in
  63. if (needSave) {
  64. self._km_save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  65. } else { // 水印保存
  66. if (self.watermarkSaveDelegate == nil) {
  67. if let data = params.first as? KMResult, data == .cancel {
  68. if let shouldClose = params.last as? Bool, shouldClose {
  69. DispatchQueue.main.async {
  70. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  71. }
  72. }
  73. } else {
  74. DispatchQueue.main.async {
  75. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  76. }
  77. }
  78. return
  79. }
  80. if let data = params.first as? KMResult, data == .cancel {
  81. if var shouldClose = params.last as? Bool {
  82. if let _browser = self.watermarkSaveDelegate as? KMBrowser, _browser.isCloseAllTabViewItem {
  83. shouldClose = true
  84. }
  85. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: shouldClose, contextInfo: nil)
  86. }
  87. } else {
  88. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: true, contextInfo: nil)
  89. }
  90. self.watermarkSaveDelegate = nil
  91. }
  92. }
  93. }
  94. override func makeWindowControllers() {
  95. // Returns the storyboard that contains your document window.
  96. if ((self.fileURL?.path) != nil) {
  97. if !self.fileURL!.path.isPDFValid() {
  98. let alert = NSAlert()
  99. alert.alertStyle = .critical
  100. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  101. alert.runModal()
  102. return
  103. }
  104. }
  105. let mainWindow = NSApp.mainWindow
  106. var currentWindowController: KMBrowserWindowController?
  107. if mainWindow != nil {
  108. let windowController = mainWindow!.windowController
  109. if windowController is KMBrowserWindowController {
  110. currentWindowController = (windowController as! KMBrowserWindowController)
  111. } else {
  112. for window in NSApp.windows {
  113. let windowController = window.windowController
  114. if windowController is KMBrowserWindowController {
  115. currentWindowController = (windowController as! KMBrowserWindowController)
  116. break
  117. }
  118. }
  119. }
  120. } else {
  121. for window in NSApp.windows {
  122. let windowController = window.windowController
  123. if windowController is KMBrowserWindowController {
  124. currentWindowController = (windowController as! KMBrowserWindowController)
  125. break
  126. }
  127. }
  128. }
  129. if (currentWindowController == nil) && (self.fileURL != nil) {
  130. let browser = KMBrowser.init() as KMBrowser
  131. browser.addHomeTabContents()
  132. browser.windowController = KMBrowserWindowController.init(browser: browser)
  133. currentWindowController = browser.windowController as? KMBrowserWindowController
  134. }
  135. if currentWindowController?.browser == nil && (self.fileURL != nil) {
  136. let browser: KMBrowser = KMBrowser.init()
  137. browser.windowController = KMBrowserWindowController.init(browser: browser)
  138. browser.addHomeTabContents()
  139. currentWindowController = browser.windowController as? KMBrowserWindowController
  140. browser.windowController.showWindow(self)
  141. }
  142. mainViewController = KMMainViewController.init()
  143. mainViewController?.myDocument = self
  144. if ((self.fileURL?.path) != nil) {
  145. let pdfDocument = CPDFDocument.init(url: URL(fileURLWithPath: self.fileURL!.path))
  146. mainViewController?.document = pdfDocument
  147. }
  148. self.view = mainViewController?.view
  149. if currentWindowController != nil {
  150. if currentWindowController?.browser != nil {
  151. // currentWindowController?.browser.add(self, at: Int32()-1, inForeground: true)
  152. // self.addWindowController(currentWindowController!)
  153. // mainViewController.browserWindowController = currentWindowController
  154. let activeBrowser = (currentWindowController?.browser.activeTabContents())! as CTTabContents
  155. let activeIndex = Int((currentWindowController?.browser.activeTabIndex())!)
  156. self.addWindowController(currentWindowController!)
  157. self.mainViewController?.browserWindowController = currentWindowController
  158. let ishome = activeBrowser.isHome as Bool
  159. let isfirstTab = (activeIndex == 0)
  160. if ishome && !isfirstTab {
  161. // 替换 document
  162. currentWindowController?.browser.replaceTabContents(at: Int32(activeIndex), with: self)
  163. // 刷新标签
  164. currentWindowController?.browser.updateTabState(at: Int32(activeIndex))
  165. // 刷新 home icon
  166. if let tabStripController = currentWindowController?.tabStripController {
  167. if let view = tabStripController.view(at: UInt(activeIndex)) as? CTTabView {
  168. view.controller().isHome = self.isHome
  169. view.controller().isNewTab = self.isNewTab
  170. view.controller().updateUI()
  171. }
  172. }
  173. } else {
  174. currentWindowController?.browser.add(self, at: Int32()-1, inForeground: true)
  175. }
  176. }
  177. }
  178. }
  179. override func showWindows() {
  180. super.showWindows()
  181. self.setDataFromTmpData()
  182. }
  183. override func windowControllerDidLoadNib(_ aController: NSWindowController) {
  184. super.windowControllerDidLoadNib(aController)
  185. self.setDataFromTmpData()
  186. fileUpdateChecker = SKFileUpdateChecker.init(for: self)
  187. fileUpdateChecker?.isEnabled = true
  188. }
  189. override func save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType) async throws {
  190. do {
  191. try await super.save(to: url, ofType: typeName, for: saveOperation)
  192. } catch let outError {
  193. Swift.print(outError)
  194. }
  195. }
  196. override func write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  197. try self._km_write(to: url, ofType: typeName, for: saveOperation, originalContentsURL: absoluteOriginalContentsURL)
  198. }
  199. override func canClose(withDelegate delegate: Any, shouldClose shouldCloseSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  200. let isPrompt = KMPreferenceManager.shared.closeFileIsPrompt()
  201. if (isPrompt) {
  202. super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
  203. return
  204. }
  205. if (self.isNewCreated) {
  206. self.save(nil)
  207. } else if (self.isDocumentEdited) {
  208. self.save(nil)
  209. } else if (mainViewController != nil) {
  210. if self.mainViewController!.isPDFDocumentEdited || self.mainViewController!.needSave {
  211. self.save(nil)
  212. }
  213. }
  214. super.canClose(withDelegate: delegate, shouldClose: shouldCloseSelector, contextInfo: contextInfo)
  215. }
  216. override func saveAs(_ sender: Any?) {
  217. if (!self.needSaveWatermark()) {
  218. self._km_saveAs(sender)
  219. return
  220. }
  221. self._km_saveForWatermark { [unowned self] needSave, _ in
  222. if (needSave) {
  223. self._km_saveAs(sender)
  224. }
  225. }
  226. }
  227. override func runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  228. if (self.isNewCreated) {
  229. // if let data = self.mainViewController, !data.isPDFDocumentEdited && !data.needSave && !self.isDocumentEdited {
  230. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  231. return
  232. // }
  233. }
  234. if (!self.needSaveWatermark()) {
  235. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  236. return
  237. }
  238. self._km_saveForWatermark { [unowned self] needSave, _ in
  239. if (needSave) {
  240. self._km_runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  241. }
  242. }
  243. }
  244. override func save(_ sender: Any?) {
  245. if (!self.needSaveWatermark()) {
  246. self._km_save(sender)
  247. return
  248. }
  249. self._km_saveForWatermark { [unowned self] in
  250. self.trackEvents()
  251. } callback: { [unowned self] needSave, _ in
  252. if (needSave) {
  253. self._km_save(sender)
  254. }
  255. }
  256. }
  257. func systemInteractionMode() -> KMInteractionMode {
  258. let mainWindow = NSApp.mainWindow
  259. if mainWindow != nil {
  260. let windowController = mainWindow!.windowController
  261. if windowController?.window?.screen?.isEqual(NSScreen.screens[0]) ?? false{
  262. return mainViewController?.interactionMode ?? .normal
  263. }
  264. }
  265. return .normal
  266. }
  267. func saveForWatermark() {
  268. if (!self.needSaveWatermark()) {
  269. self._km_save(nil)
  270. return
  271. }
  272. self._km_saveForWatermark { [unowned self] in
  273. self.trackEvents()
  274. } callback: { [unowned self] needSave, params in
  275. if (needSave) {
  276. self._km_save(nil)
  277. } else { // 水印保存
  278. if (self.watermarkSaveDelegate == nil) {
  279. if let data = params.first as? KMResult, data == .cancel {
  280. if let shouldClose = params.last as? Bool, shouldClose {
  281. DispatchQueue.main.async {
  282. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  283. }
  284. }
  285. } else {
  286. DispatchQueue.main.async {
  287. self.mainViewController?.browserWindowController?.browser.windowDidBeginToClose()
  288. }
  289. }
  290. return
  291. }
  292. if let data = params.first as? KMResult, data == .cancel {
  293. if var shouldClose = params.last as? Bool {
  294. if let _browser = self.watermarkSaveDelegate as? KMBrowser, _browser.isCloseAllTabViewItem {
  295. shouldClose = true
  296. }
  297. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: shouldClose, contextInfo: nil)
  298. }
  299. } else {
  300. (self.watermarkSaveDelegate as? KMBrowser)?.document(self, shouldClose: true, contextInfo: nil)
  301. }
  302. self.watermarkSaveDelegate = nil
  303. }
  304. }
  305. }
  306. override func read(from absoluteURL: URL, ofType typeName: String) throws {
  307. do {
  308. try super.read(from: absoluteURL, ofType: typeName)
  309. updateChangeCount(.changeCleared)
  310. } catch let outError {
  311. Swift.print(outError)
  312. }
  313. }
  314. override func read(from data: Data, ofType typeName: String) throws {
  315. // Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
  316. // 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.
  317. let pdfDocument = CPDFDocument.init(data: data)
  318. if pdfDocument == nil {
  319. throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
  320. }
  321. }
  322. // MARK: Autosaving
  323. override func close() {
  324. if self.isActive {
  325. if browser != nil {
  326. var activeIndex = 0
  327. let dex = browser.index(of: self)
  328. if dex == browser.tabCount() - 1 {
  329. activeIndex = Int(browser.tabCount()-2)
  330. } else {
  331. activeIndex = Int(dex + 1)
  332. }
  333. let activeContents = browser.tabContents(at: Int32(activeIndex))
  334. activeContents?.addWindowController(browser.windowController)
  335. }
  336. }
  337. super.close()
  338. }
  339. // MARK: init
  340. override init() {
  341. super.init()
  342. // Add your subclass-specific initialization here.
  343. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewAnnotationsAttributeHasChangeNotification"), object: nil)
  344. // NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFViewDocumentChangedNotification"), object: nil)
  345. // NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFViewPageChangedNotification"), object: nil)
  346. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.init(rawValue: "CPDFListViewDidAddAnnotationNotification"), object: nil)
  347. NotificationCenter.default.addObserver(self, selector: #selector(pdfChangedNotification(_:)), name: NSNotification.Name.CPDFViewPageChanged, object: nil)
  348. }
  349. override init?(baseTabContents baseContents: CTTabContents?) {
  350. super.init(baseTabContents: baseContents)
  351. if isHome {
  352. homeViewController = KMHomeViewController.init()
  353. homeViewController?.myDocument = self
  354. self.view = homeViewController?.view
  355. }
  356. }
  357. // MARK: Handling User Actions
  358. override var title: String? {
  359. get {
  360. if isHome {
  361. if (self.isNewTab) {
  362. return NSLocalizedString("New Tab", comment: "")
  363. } else {
  364. return NSLocalizedString("Home", comment: "")
  365. }
  366. } else {
  367. return fileURL?.lastPathComponent
  368. }
  369. }
  370. set {
  371. super.title = newValue
  372. }
  373. }
  374. func needSaveWatermark() -> Bool {
  375. if let need = self.mainViewController?.saveWatermarkFlag {
  376. return need
  377. }
  378. return false
  379. }
  380. // MARK: Private Methods
  381. func pdfChangedNotification(_ notification: Notification) -> Void {
  382. if !isHome {
  383. let mainViewController = mainViewController
  384. var document: CPDFDocument!
  385. let dic = notification.object as? NSDictionary
  386. if dic?["object"] is CPDFAnnotation {
  387. let annotation : CPDFAnnotation = dic?["object"] as? CPDFAnnotation ?? CPDFAnnotation()
  388. document = annotation.page.document
  389. } else if dic?["object"] is CPDFListView {
  390. let pdflistView = notification.object as? CPDFListView
  391. document = pdflistView?.document
  392. }
  393. if mainViewController != nil {
  394. if document == mainViewController!.document {
  395. updateChangeCount(.changeDone)
  396. }
  397. }
  398. }
  399. }
  400. override func updateChangeCount(_ change: NSDocument.ChangeType) {
  401. let mainWindow = NSApp.mainWindow
  402. var currentWindowController: KMBrowserWindowController?
  403. if mainWindow != nil {
  404. let windowController = mainWindow!.windowController
  405. if windowController is KMBrowserWindowController {
  406. currentWindowController = (windowController as! KMBrowserWindowController)
  407. } else {
  408. for window in NSApp.windows {
  409. let windowController = window.windowController
  410. if windowController is KMBrowserWindowController {
  411. currentWindowController = (windowController as! KMBrowserWindowController)
  412. break
  413. }
  414. }
  415. }
  416. } else {
  417. for window in NSApp.windows {
  418. let windowController = window.windowController
  419. if windowController is KMBrowserWindowController {
  420. currentWindowController = (windowController as! KMBrowserWindowController)
  421. break
  422. }
  423. }
  424. }
  425. if currentWindowController != nil {
  426. if currentWindowController?.browser != nil {
  427. let activeBrowser = (currentWindowController?.browser.activeTabContents())! as CTTabContents
  428. let activeIndex = Int((currentWindowController?.browser.activeTabIndex())!)
  429. if self == activeBrowser {
  430. super.updateChangeCount(change)
  431. return
  432. }
  433. }
  434. }
  435. super.updateChangeCount(.changeCleared)
  436. }
  437. func uploadToCloud(_ callback: (@escaping(Bool, String)->())) {
  438. guard let handdler = self.cloudUploadHanddler else {
  439. return
  440. }
  441. handdler(callback)
  442. }
  443. func isPDFDocument() -> Bool {
  444. return true
  445. }
  446. func setDataFromTmpData() {
  447. guard let _document = self.mainViewController?.document else {
  448. return
  449. }
  450. // self.tryToUnlockDocument(document!)
  451. if (_document.permissionsStatus != .owner) {
  452. var password: NSString? = nil
  453. let fileId = self.fileId(for: _document)
  454. if (fileId.isEmpty) {
  455. return
  456. }
  457. self.getPassword(&password, fileId: fileId)
  458. if (password != nil) {
  459. self.isUnlockFromKeychain = true
  460. // document.unlock(withPassword: password! as String)
  461. self.mainViewController?.password = password as String?
  462. }
  463. }
  464. }
  465. func tryToUnlockDocument(_ document: CPDFDocument) {
  466. if (document.permissionsStatus != .owner) {
  467. var password: NSString? = nil
  468. let fileId = self.fileId(for: document)
  469. if (fileId.isEmpty) {
  470. return
  471. }
  472. self.getPassword(&password, fileId: fileId)
  473. if (password != nil) {
  474. self.isUnlockFromKeychain = true
  475. document.unlock(withPassword: password! as String)
  476. }
  477. }
  478. }
  479. func km_updateChangeCount(_ change: NSDocument.ChangeType) {
  480. super.updateChangeCount(change)
  481. }
  482. func trackEvents() {
  483. km_synchronized(self) {
  484. for i in self._trackEvents {
  485. if let type = KMSubscribeWaterMarkType(rawValue: i) {
  486. KMTools.trackEvent(type: type)
  487. }
  488. }
  489. }
  490. self.clearTrackEvents()
  491. }
  492. func recordTrackEvent(type: KMSubscribeWaterMarkType) {
  493. if (type == .none) {
  494. return
  495. }
  496. km_synchronized(self) {
  497. self._trackEvents.insert(type.rawValue)
  498. }
  499. }
  500. func clearTrackEvents() {
  501. km_synchronized(self) {
  502. self._trackEvents.removeAll()
  503. }
  504. }
  505. @IBAction func saveArchive(_ sender: Any?) {
  506. guard let item = sender as? NSMenuItem else {
  507. NSSound.beep()
  508. return
  509. }
  510. guard let fileURL = self.fileURL else {
  511. NSSound.beep()
  512. return
  513. }
  514. let check = try?fileURL.checkResourceIsReachable()
  515. if check == false || self.isDocumentEdited {
  516. let msg = KMLocalizedString("You must save this file first", "Alert text when trying to create archive for unsaved document")
  517. let inf = KMLocalizedString("The document has unsaved changes, or has not previously been saved to disk.", "Informative text in alert dialog")
  518. Task {
  519. _ = await KMAlertTool.runModel(message: msg, informative: inf)
  520. }
  521. return
  522. }
  523. // NSString *ext = ([sender tag] | SKArchiveDiskImageMask) ? @"dmg" : @"tgz";
  524. let idx = item.tag
  525. let ext = "dmg"
  526. let isEmail = true
  527. if isEmail {
  528. // if (([sender tag] | SKArchiveEmailMask)) {
  529. let tmpDirURL = FileManager.default.uniqueChewableItemsDirectoryURL()
  530. let tmpFileURL = tmpDirURL.appendingPathComponent(fileURL.lastPathComponentReplacingPathExtension(ext))
  531. self.newSaveArchive(to: tmpFileURL, email: true)
  532. } else {
  533. let sp = NSSavePanel()
  534. sp.allowedFileTypes = [ext]
  535. sp.canCreateDirectories = true
  536. // [sp setNameFieldStringValue:[fileURL lastPathComponentReplacingPathExtension:ext]];
  537. sp.beginSheetModal(for: self.windowForSheet!) { result in
  538. if result == .OK {
  539. self.newSaveArchive(to: sp.url!, email: false)
  540. }
  541. }
  542. }
  543. }
  544. // func saveArchiveToURL(to fileURL: URL, email: Bool) {
  545. // NSTask *task = [[[NSTask alloc] init] autorelease];
  546. // let task = Task()
  547. // if fileURL.pathExtension == "dmg" {
  548. // [task setLaunchPath:@""];
  549. // task.launchPath = "/usr/bin/hdiutil"
  550. // [task setArguments:[NSArray arrayWithObjects:@"create", @"-srcfolder", [[self fileURL] path], @"-format", @"UDZO", @"-volname", [[fileURL lastPathComponent] stringByDeletingPathExtension], [fileURL path], nil]];
  551. // } else {
  552. // [task setLaunchPath:@"/usr/bin/tar"];
  553. // [task setArguments:[NSArray arrayWithObjects:@"-czf", [fileURL path], [[self fileURL] lastPathComponent], nil]];
  554. // }
  555. // [task setCurrentDirectoryPath:[[[self fileURL] URLByDeletingLastPathComponent] path]];
  556. // [task setStandardOutput:[NSFileHandle fileHandleWithNullDevice]];
  557. // [task setStandardError:[NSFileHandle fileHandleWithNullDevice]];
  558. //
  559. // SKAttachmentEmailer *emailer = nil;
  560. // if (email)
  561. // emailer = [SKAttachmentEmailer attachmentEmailerWithFileURL:fileURL subject:[self displayName] waitingForTask:task];
  562. //
  563. // @try {
  564. // [task launch];
  565. // }
  566. // @catch (id exception) {
  567. // [emailer taskFailed];
  568. // }
  569. // }
  570. @IBAction func readNotes(_ sender: Any?) {
  571. KMPrint("readNotes")
  572. }
  573. @IBAction func convertNotes(_ sender: Any?) {
  574. KMPrint("convertNotes")
  575. }
  576. @IBAction func batchRemovePassWord(_ sender: Any?) {
  577. self.mainViewController?.removeOwnerPassword()
  578. }
  579. @IBAction func batchRemovPrivatySecurity(_ sender: Any?) {
  580. KMPrint("batchRemovPrivatySecurity")
  581. }
  582. @IBAction func printPDFDocument(_ sender: Any?) {
  583. KMPrint("printPDFDocument")
  584. KMPrintWindowController.showNewPrintWindowControll(inputDocument: self.mainViewController?.document, inputPageRange: KMPrintPageRange())
  585. }
  586. @IBAction func performFindPanelAction(_ sender: Any?) {
  587. KMPrint("performFindPanelAction")
  588. self.mainViewController?.toolbarController.showFindBar()
  589. }
  590. @IBAction func addBookmark(_ sender: Any?) {
  591. guard let item = sender as? NSMenuItem else {
  592. return
  593. }
  594. // let bookmarkSheetController = SKBookmarkSheetController(windowNibName: "BookmarkSheet")
  595. // NSWindow.currentWindow().beginSheet(bookmarkSheetController.window!) { resoponse in
  596. //
  597. // }
  598. // bookmarkSheetController.textField.stringValue = self.displayName
  599. // bookmarkSheetController.beginSheetModal(for: self.windowForSheet) { [unowned self] result in
  600. // if (result == NSApplication.ModalResponse.OK.rawValue) {
  601. // let label = bookmarkSheetController.textField.stringValue;
  602. // let folder: SKBookmark = bookmarkSheetController.selectedFolder ?? SKBookmarkController.shared().bookmarkRoot
  603. // var bookmark = SKBookmark()
  604. // switch (item.tag) {
  605. // case 0:
  606. // let mainViewController = self.mainViewController
  607. // let page = mainViewController?.listView.currentPage()
  608. // bookmark = SKBookmark.bookmark(with: self.fileURL, pageIndex: (page?.pageIndex())!, label: label) as! SKBookmark
  609. // case 1:
  610. // let setup = self.currentDocumntSetup()
  611. // bookmark = SKBookmark.bookmark(withSetup: setup, label: label) as! SKBookmark
  612. //
  613. // case 2:
  614. // let setups = NSApp.orderedDocuments.map { $0.value(forKey: "currentDocumentSetup") }
  615. // bookmark = SKBookmark.bookmarkSession(withSetups: setups as [Any], label: label) as! SKBookmark
  616. //
  617. // default:
  618. // break;
  619. // }
  620. // folder.mutableArrayValue(forKey: "children").add(bookmark)
  621. // }
  622. // }
  623. if item.tag == 3 {
  624. KMPrint("Edit Bookmark")
  625. bookmarkController = KMBookmarkController.showBookmarkController()
  626. } else if item.tag == 2 {
  627. KMPrint("session Bookmark")
  628. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .session)
  629. } else if item.tag == 0 {
  630. KMPrint("add Bookmark")
  631. bookmarkSheetController = KMBookmarkSheetController.showBookmarkSheetController(type: .bookmark)
  632. }
  633. bookmarkSheetController?.stringValue = self.displayName
  634. bookmarkSheetController?.cancelAction = { [unowned self] controller, type in
  635. }
  636. //
  637. bookmarkSheetController?.doneAction = { [unowned self] controller, type, label in
  638. let folder = controller.selectedFolder
  639. var bookmark: KMBookmark?
  640. switch type {
  641. case .bookmark:
  642. let mainViewController = mainViewController
  643. if let page = mainViewController?.listView.currentPage() {
  644. let index: UInt = page.pageIndex()
  645. bookmark = KMBookmark.bookmark(url: self.fileURL!, pageIndex: index, label: label)
  646. }
  647. // case .setup:
  648. // if let setup = currentDocumentSetup {
  649. // bookmark = SKBookmark.bookmark(withSetup: setup, label: label)
  650. // }
  651. case .session:
  652. let setups = NSApp.orderedDocuments.compactMap { $0.value(forKey:"currentDocumentSetup") }
  653. bookmark = KMSessionBookmark.bookmarkSession(setups: setups as NSArray, label: label)
  654. default:
  655. break
  656. }
  657. if let bookmark = bookmark {
  658. folder?.children.append(bookmark)
  659. }
  660. }
  661. }
  662. func currentDocumntSetup() -> [String: Any] {
  663. var setup: [String: Any] = [:]
  664. let data = SKAlias.init(url: fileURL).data
  665. if (data != nil) {
  666. setup.updateValue(data as Any, forKey: "_BDAlias")
  667. } else {
  668. setup.updateValue(fileURL?.path as Any, forKey: "fileName")
  669. }
  670. return setup;
  671. }
  672. @IBAction func showWindow(_ sender: Any?) {
  673. KMPrint("showWindow")
  674. }
  675. // MARK: - Private Methods
  676. private func _km_write(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, originalContentsURL absoluteOriginalContentsURL: URL?) throws {
  677. var success = true
  678. if !self.isHome {
  679. if mainViewController != nil {
  680. if mainViewController?.document != nil {
  681. self.mainViewController?.commitEditingIfNeed()
  682. // if mainViewController!.document!.isEncrypted {
  683. // success = mainViewController!.document!.write(to: url)
  684. // } else {
  685. if (mainViewController!.needSave) {
  686. if let options = self.mainViewController?.secureOptions, !options.isEmpty {
  687. self.mainViewController!.document?.setDocumentAttributes(self.mainViewController?.documentAttribute)
  688. success = self.mainViewController!.document!.write(to: url, withOptions: options)
  689. } else if let flag = self.mainViewController?.removeSecureFlag, flag {
  690. success = self.mainViewController!.document!.writeDecrypt(to: url)
  691. } else {
  692. success = mainViewController!.document!.write(to: url)
  693. }
  694. } else {
  695. success = mainViewController!.document!.write(to: url)
  696. }
  697. // }
  698. self.mainViewController?.needSave = false
  699. self.mainViewController?.clearSecureOptions()
  700. self.mainViewController?.clearRemoveSecureFlag()
  701. }
  702. }
  703. } else {
  704. success = false
  705. }
  706. if (success && self._saveAsing) {
  707. if let tabView = self.browser?.windowController?.tabStripController?.activeTabView() as? CTTabView {
  708. tabView.controller()?.title = url.lastPathComponent
  709. }
  710. self._saveAsing = false
  711. }
  712. if success && isNewCreated && NSDocument.SaveOperationType.saveAsOperation == saveOperation {
  713. isNewCreated = false
  714. }
  715. }
  716. private func _km_saveForWatermark(openAccessoryView: Bool = true, subscribeDidClick: (()->Void)? = nil, callback:@escaping (_ needSave: Bool, _ param: Any...)->Void) {
  717. Task { @MainActor in
  718. if await (KMLightMemberManager.manager.canPayFunction() == false) {
  719. let _ = KMSubscribeWaterMarkWindowController.show(window: NSApp.mainWindow!, isContinue:false, type: .save) {
  720. if let _callback = subscribeDidClick {
  721. _callback()
  722. }
  723. } completion: { isSubscribeSuccess, isWaterMarkExport, isClose in
  724. if (isClose) {
  725. callback(false, KMResult.cancel, false)
  726. return
  727. }
  728. if (isSubscribeSuccess) {
  729. callback(true)
  730. return
  731. }
  732. if (isWaterMarkExport) {
  733. guard let _document = self.mainViewController?.document else {
  734. callback(false, KMResult.failure)
  735. return
  736. }
  737. // 提交文本编辑的内容
  738. self.mainViewController?.commitEditingIfNeed()
  739. DispatchQueue.main.async {
  740. NSPanel.savePanel(NSApp.mainWindow!, openAccessoryView, panel:{ panel in
  741. if (!self.isNewCreated) {
  742. panel.directoryURL = _document.documentURL.deletingLastPathComponent()
  743. }
  744. panel.nameFieldStringValue = _document.documentURL.lastPathComponent
  745. }) { response, url, isOpen in
  746. if (response == .cancel) {
  747. callback(false, KMResult.cancel, true)
  748. return
  749. }
  750. guard let _url = KMTools.saveWatermarkDocument(document: _document, to: url!, secureOptions: self.mainViewController?.secureOptions, documentAttribute: self.mainViewController?.documentAttribute,removePWD: self.mainViewController!.removeSecureFlag) else {
  751. callback(false, KMResult.failure)
  752. return
  753. }
  754. callback(false, KMResult.success)
  755. if (isOpen) {
  756. NSDocumentController.shared.km_safe_openDocument(withContentsOf: _url, display: true) { _, _, _ in
  757. }
  758. } else {
  759. NSWorkspace.shared.activateFileViewerSelecting([_url])
  760. }
  761. }
  762. }
  763. return
  764. }
  765. callback(false, KMResult.cancel, false)
  766. }
  767. return
  768. }
  769. callback(true)
  770. }
  771. }
  772. private func _km_save(_ sender: Any?) {
  773. super.save(sender)
  774. }
  775. private func _km_save(to url: URL, ofType typeName: String, for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  776. self._saveToURL = url
  777. super.save(to: url, ofType: typeName, for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  778. }
  779. private func _km_saveAs(_ sender: Any?) {
  780. super.saveAs(sender)
  781. self._saveAsing = true
  782. }
  783. private func _km_runModalSavePanel(for saveOperation: NSDocument.SaveOperationType, delegate: Any?, didSave didSaveSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
  784. super.runModalSavePanel(for: saveOperation, delegate: delegate, didSave: didSaveSelector, contextInfo: contextInfo)
  785. }
  786. }
  787. extension KMMainDocument {
  788. override func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
  789. if (menuItem.action == #selector(save(_ :))) {
  790. if (self.isHome) {
  791. return false
  792. }
  793. if (self.isDocumentEdited) {
  794. return self.isDocumentEdited
  795. }
  796. guard let mainVC = self.mainViewController else {
  797. return false
  798. }
  799. return mainVC.isPDFDocumentEdited || mainVC.needSave
  800. } else if (menuItem.action == #selector(saveAs(_ :))) {
  801. return !self.isHome
  802. } else if menuItem.action == #selector(batchRemovePassWord) {
  803. if self.isHome {
  804. return false
  805. }
  806. guard let doc = self.mainViewController?.listView?.document else {
  807. return false
  808. }
  809. let allowsPrinting = doc.allowsPrinting
  810. let allowsCopying = doc.allowsCopying
  811. if allowsCopying && allowsPrinting {
  812. return false
  813. }
  814. return true
  815. } else if menuItem.action == #selector(saveArchive) {
  816. return !self.isHome
  817. }
  818. return super.validateMenuItem(menuItem)
  819. }
  820. }
  821. extension NSDocument {
  822. @objc class func isDamage(url: URL) -> Bool {
  823. // 文件路径是否存在
  824. if (FileManager.default.fileExists(atPath: url.path) == false) {
  825. return true
  826. }
  827. /// PDF 格式文件
  828. if (url.pathExtension.lowercased() == "pdf") {
  829. let document = PDFDocument(url: url)
  830. if (document == nil) {
  831. return true
  832. }
  833. if (document!.isLocked) { // 加锁文件不在这里判断
  834. return false
  835. }
  836. if (document!.pageCount <= 0) {
  837. return true
  838. }
  839. return false
  840. }
  841. // 支持的图片格式
  842. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  843. let isImage = imageExts.contains(url.pathExtension.lowercased())
  844. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  845. return false
  846. }
  847. // 图片格式
  848. let image = NSImage(contentsOf: url)
  849. let data = image?.tiffRepresentation
  850. if (data == nil) {
  851. return true
  852. }
  853. let imageRep = NSBitmapImageRep(data: data!)
  854. imageRep!.size = image!.size
  855. var imageData: NSData?
  856. if (url.pathExtension.lowercased() == "png") {
  857. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  858. } else {
  859. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  860. }
  861. if (imageData == nil) {
  862. return true
  863. }
  864. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  865. if (FileManager.default.fileExists(atPath: path!) == false) {
  866. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  867. }
  868. var tagString: String = ""
  869. let dateFormatter = DateFormatter()
  870. dateFormatter.dateFormat = "yyMMddHHmmss"
  871. tagString.append(dateFormatter.string(from: Date()))
  872. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  873. let filePath = path?.appending("/\(tagString).png")
  874. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  875. return true
  876. }
  877. // 删除临时图片
  878. try?FileManager.default.removeItem(atPath: filePath!)
  879. return false
  880. }
  881. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  882. let result = self.isDamage(url: url)
  883. if (result == false) {
  884. return false
  885. }
  886. if (need == false) {
  887. return true
  888. }
  889. let alert = NSAlert()
  890. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  891. alert.runModal()
  892. return true
  893. }
  894. }
  895. // MARK: -
  896. // MARK: 保存密码
  897. extension NSDocument {
  898. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  899. if (document.isLocked || password.isEmpty) {
  900. return
  901. }
  902. let fileId = self.fileId(for: document)
  903. if (fileId.isEmpty) {
  904. return
  905. }
  906. // let status: SKPasswordStatus =
  907. let label = "PDF Reader Pro: \(self.displayName!)"
  908. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  909. }
  910. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  911. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  912. // if (status == .found) {
  913. // }
  914. }
  915. fileprivate func fileId(for document: CPDFDocument) -> String {
  916. return "\(document.documentURL.path.hash)"
  917. }
  918. private func passwordServiceName() -> String {
  919. return "PDF Reader Pro password"
  920. }
  921. }
  922. extension KMMainDocument: SKPDFSynchronizerDelegate {
  923. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLine line: Int, inFile file: String!) {
  924. if FileManager.default.fileExists(atPath: file) {
  925. let defaults = UserDefaults.standard
  926. var editorPreset = defaults.string(forKey: SKTeXEditorPresetKey) ?? ""
  927. var editorCmd: String?
  928. var editorArgs: String?
  929. var cmdString: String?
  930. if !KMSyncPreferences.getTeXEditorCommand(command: &editorCmd, arguments: &editorArgs, forPreset: editorPreset) {
  931. editorCmd = defaults.string(forKey: SKTeXEditorCommandKey)
  932. editorArgs = defaults.string(forKey: SKTeXEditorArgumentsKey)
  933. }
  934. if var cmdString = editorArgs {
  935. if !editorCmd!.hasPrefix("/") {
  936. var searchPaths = ["/usr/bin", "/usr/local/bin"]
  937. var toolPath: String?
  938. let fm = FileManager.default
  939. if !(editorPreset.isEmpty) {
  940. if let path = NSWorkspace.shared.fullPath(forApplication: editorPreset) {
  941. if let appBundle = Bundle(path: path) {
  942. if let contentsPath = appBundle.path(forResource: "Contents", ofType: nil) {
  943. searchPaths.insert(contentsPath, at: 0)
  944. }
  945. if editorPreset != "BBEdit", let execPath = appBundle.executablePath {
  946. searchPaths.insert(execPath, at: 0)
  947. }
  948. if let resourcePath = appBundle.resourcePath {
  949. searchPaths.insert(resourcePath, at: 0)
  950. }
  951. if let sharedSupportPath = appBundle.sharedSupportPath {
  952. searchPaths.insert(sharedSupportPath, at: 0)
  953. }
  954. }
  955. }
  956. } else {
  957. let appSupportDirs = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
  958. let appSupportPaths = appSupportDirs.map { $0.path }
  959. searchPaths.append(contentsOf: appSupportPaths)
  960. }
  961. for path in searchPaths {
  962. toolPath = (path as NSString).appendingPathComponent(editorCmd!)
  963. if fm.isExecutableFile(atPath: toolPath!) {
  964. editorCmd = toolPath
  965. break
  966. }
  967. toolPath = ((path as NSString).appendingPathComponent("bin") as NSString).appendingPathComponent(editorCmd!)
  968. if fm.isExecutableFile(atPath: toolPath!) {
  969. editorCmd = toolPath
  970. break
  971. }
  972. }
  973. }
  974. cmdString = cmdString.replacingOccurrences(of: "%line", with: "\(line + 1)")
  975. cmdString = cmdString.replacingOccurrences(of: "%file", with: file)
  976. cmdString = cmdString.replacingOccurrences(of: "%output", with: fileURL?.path ?? "")
  977. cmdString.insert(contentsOf: "\" ", at: cmdString.startIndex)
  978. cmdString.insert(contentsOf: editorCmd!, at: cmdString.startIndex)
  979. cmdString.insert("\"", at: cmdString.startIndex)
  980. let ws = NSWorkspace.shared
  981. if let theUTI = try? ws.type(ofFile: editorCmd!) {
  982. if ws.type(theUTI, conformsToType: "com.apple.applescript.script") || ws.type(theUTI, conformsToType: "com.apple.applescript.text") {
  983. cmdString.insert(contentsOf: "/usr/bin/osascript ", at: cmdString.startIndex)
  984. }
  985. }
  986. let task = Process()
  987. task.launchPath = "/bin/sh"
  988. task.currentDirectoryPath = (file as NSString).deletingLastPathComponent
  989. task.arguments = ["-c", cmdString]
  990. task.standardOutput = FileHandle.nullDevice
  991. task.standardError = FileHandle.nullDevice
  992. do {
  993. try task.run()
  994. } catch let error {
  995. Swift.print("command failed: \(cmdString ?? ""): \(error)")
  996. }
  997. }
  998. }
  999. }
  1000. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLocation point: NSPoint, atPageIndex pageIndex: UInt, options: Int) {
  1001. guard let pdfDoc = self.mainViewController?.document else { return }
  1002. if pageIndex < pdfDoc.pageCount {
  1003. if let page = pdfDoc.page(at: pageIndex) {
  1004. var adjustedPoint = point
  1005. if options & SKPDFSynchronizerFlippedMask != 0 {
  1006. let mediaBox = page.bounds(for: .mediaBox)
  1007. adjustedPoint.y = NSMaxY(mediaBox) - adjustedPoint.y
  1008. }
  1009. self.mainViewController?.listView.displayLine(at: adjustedPoint, inPageAtIndex: Int(pageIndex), showReadingBar: options & SKPDFSynchronizerShowReadingBarMask != 0)
  1010. }
  1011. }
  1012. }
  1013. }