KMMainDocument.swift 56 KB

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