KMMainDocument.swift 55 KB

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