KMMainDocument.swift 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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. }
  954. return super.validateMenuItem(menuItem)
  955. }
  956. }
  957. extension NSDocument {
  958. @objc class func isDamage(url: URL) -> Bool {
  959. // 文件路径是否存在
  960. if (FileManager.default.fileExists(atPath: url.path) == false) {
  961. return true
  962. }
  963. /// PDF 格式文件
  964. if (url.pathExtension.lowercased() == "pdf") {
  965. let document = PDFDocument(url: url)
  966. if (document == nil) {
  967. return true
  968. }
  969. if (document!.isLocked) { // 加锁文件不在这里判断
  970. return false
  971. }
  972. if (document!.pageCount <= 0) {
  973. return true
  974. }
  975. return false
  976. }
  977. // 支持的图片格式
  978. let imageExts = ["jpg","cur","bmp","jpeg","gif","png","tiff","tif","ico","icns","tga","psd","eps","hdr","jp2","jpc","pict","sgi","heic"]
  979. let isImage = imageExts.contains(url.pathExtension.lowercased())
  980. if (isImage == false) { // 其他格式目前返回没损坏,后续再补充(如果有需求)
  981. return false
  982. }
  983. // 图片格式
  984. let image = NSImage(contentsOf: url)
  985. let data = image?.tiffRepresentation
  986. if (data == nil) {
  987. return true
  988. }
  989. let imageRep = NSBitmapImageRep(data: data!)
  990. imageRep!.size = image!.size
  991. var imageData: NSData?
  992. if (url.pathExtension.lowercased() == "png") {
  993. imageData = imageRep?.representation(using: .png, properties: [:]) as NSData?
  994. } else {
  995. imageData = imageRep?.representation(using: .jpeg, properties: [:]) as NSData?
  996. }
  997. if (imageData == nil) {
  998. return true
  999. }
  1000. let path = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  1001. if (FileManager.default.fileExists(atPath: path!) == false) {
  1002. try?FileManager.default.createDirectory(atPath: path!, withIntermediateDirectories: false)
  1003. }
  1004. var tagString: String = ""
  1005. let dateFormatter = DateFormatter()
  1006. dateFormatter.dateFormat = "yyMMddHHmmss"
  1007. tagString.append(dateFormatter.string(from: Date()))
  1008. tagString = tagString.appendingFormat("%04d", arc4random()%10000)
  1009. let filePath = path?.appending("/\(tagString).png")
  1010. if (imageData!.write(toFile: filePath!, atomically: true) == false) {
  1011. return true
  1012. }
  1013. // 删除临时图片
  1014. try?FileManager.default.removeItem(atPath: filePath!)
  1015. return false
  1016. }
  1017. @objc class func isDamage(url: URL, needAlertIfDamage need: Bool) -> Bool {
  1018. let result = self.isDamage(url: url)
  1019. if (result == false) {
  1020. return false
  1021. }
  1022. if (need == false) {
  1023. return true
  1024. }
  1025. let alert = NSAlert()
  1026. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1027. alert.runModal()
  1028. return true
  1029. }
  1030. }
  1031. // MARK: -
  1032. // MARK: 保存密码
  1033. extension NSDocument {
  1034. func savePasswordInKeychain(_ password: String, _ document: CPDFDocument) {
  1035. if (document.isLocked || password.isEmpty) {
  1036. return
  1037. }
  1038. let fileId = self.fileId(for: document)
  1039. if (fileId.isEmpty) {
  1040. return
  1041. }
  1042. // let status: SKPasswordStatus =
  1043. let label = "PDF Reader Pro: \(self.displayName!)"
  1044. SKKeychain.setPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId, label: label, comment: self.fileURL?.path)
  1045. }
  1046. func getPassword(_ password: AutoreleasingUnsafeMutablePointer<NSString?>, fileId: String) {
  1047. let status = SKKeychain.getPassword(password, item: nil, forService: self.passwordServiceName(), account: fileId)
  1048. // if (status == .found) {
  1049. // }
  1050. }
  1051. fileprivate func fileId(for document: CPDFDocument) -> String {
  1052. return "\(document.documentURL.path.hash)"
  1053. }
  1054. private func passwordServiceName() -> String {
  1055. return "PDF Reader Pro password"
  1056. }
  1057. }
  1058. extension KMMainDocument: SKPDFSynchronizerDelegate {
  1059. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLine line: Int, inFile file: String!) {
  1060. if FileManager.default.fileExists(atPath: file) {
  1061. let defaults = UserDefaults.standard
  1062. var editorPreset = defaults.string(forKey: SKTeXEditorPresetKey) ?? ""
  1063. var editorCmd: String?
  1064. var editorArgs: String?
  1065. var cmdString: String?
  1066. if !KMSyncPreferences.getTeXEditorCommand(command: &editorCmd, arguments: &editorArgs, forPreset: editorPreset) {
  1067. editorCmd = defaults.string(forKey: SKTeXEditorCommandKey)
  1068. editorArgs = defaults.string(forKey: SKTeXEditorArgumentsKey)
  1069. }
  1070. if var cmdString = editorArgs {
  1071. if !editorCmd!.hasPrefix("/") {
  1072. var searchPaths = ["/usr/bin", "/usr/local/bin"]
  1073. var toolPath: String?
  1074. let fm = FileManager.default
  1075. if !(editorPreset.isEmpty) {
  1076. if let path = NSWorkspace.shared.fullPath(forApplication: editorPreset) {
  1077. if let appBundle = Bundle(path: path) {
  1078. if let contentsPath = appBundle.path(forResource: "Contents", ofType: nil) {
  1079. searchPaths.insert(contentsPath, at: 0)
  1080. }
  1081. if editorPreset != "BBEdit", let execPath = appBundle.executablePath {
  1082. searchPaths.insert(execPath, at: 0)
  1083. }
  1084. if let resourcePath = appBundle.resourcePath {
  1085. searchPaths.insert(resourcePath, at: 0)
  1086. }
  1087. if let sharedSupportPath = appBundle.sharedSupportPath {
  1088. searchPaths.insert(sharedSupportPath, at: 0)
  1089. }
  1090. }
  1091. }
  1092. } else {
  1093. let appSupportDirs = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
  1094. let appSupportPaths = appSupportDirs.map { $0.path }
  1095. searchPaths.append(contentsOf: appSupportPaths)
  1096. }
  1097. for path in searchPaths {
  1098. toolPath = (path as NSString).appendingPathComponent(editorCmd!)
  1099. if fm.isExecutableFile(atPath: toolPath!) {
  1100. editorCmd = toolPath
  1101. break
  1102. }
  1103. toolPath = ((path as NSString).appendingPathComponent("bin") as NSString).appendingPathComponent(editorCmd!)
  1104. if fm.isExecutableFile(atPath: toolPath!) {
  1105. editorCmd = toolPath
  1106. break
  1107. }
  1108. }
  1109. }
  1110. cmdString = cmdString.replacingOccurrences(of: "%line", with: "\(line + 1)")
  1111. cmdString = cmdString.replacingOccurrences(of: "%file", with: file)
  1112. cmdString = cmdString.replacingOccurrences(of: "%output", with: fileURL?.path ?? "")
  1113. cmdString.insert(contentsOf: "\" ", at: cmdString.startIndex)
  1114. cmdString.insert(contentsOf: editorCmd!, at: cmdString.startIndex)
  1115. cmdString.insert("\"", at: cmdString.startIndex)
  1116. let ws = NSWorkspace.shared
  1117. if let theUTI = try? ws.type(ofFile: editorCmd!) {
  1118. if ws.type(theUTI, conformsToType: "com.apple.applescript.script") || ws.type(theUTI, conformsToType: "com.apple.applescript.text") {
  1119. cmdString.insert(contentsOf: "/usr/bin/osascript ", at: cmdString.startIndex)
  1120. }
  1121. }
  1122. let task = Process()
  1123. task.launchPath = "/bin/sh"
  1124. task.currentDirectoryPath = (file as NSString).deletingLastPathComponent
  1125. task.arguments = ["-c", cmdString]
  1126. task.standardOutput = FileHandle.nullDevice
  1127. task.standardError = FileHandle.nullDevice
  1128. do {
  1129. try task.run()
  1130. } catch let error {
  1131. Swift.print("command failed: \(cmdString ?? ""): \(error)")
  1132. }
  1133. }
  1134. }
  1135. }
  1136. func synchronizer(_ synchronizer: SKPDFSynchronizer!, foundLocation point: NSPoint, atPageIndex pageIndex: UInt, options: Int) {
  1137. guard let pdfDoc = self.mainViewController?.document else { return }
  1138. if pageIndex < pdfDoc.pageCount {
  1139. if let page = pdfDoc.page(at: pageIndex) {
  1140. var adjustedPoint = point
  1141. if options & SKPDFSynchronizerFlippedMask != 0 {
  1142. let mediaBox = page.bounds(for: .mediaBox)
  1143. adjustedPoint.y = NSMaxY(mediaBox) - adjustedPoint.y
  1144. }
  1145. self.mainViewController?.listView.displayLine(at: adjustedPoint, inPageAtIndex: Int(pageIndex), showReadingBar: options & SKPDFSynchronizerShowReadingBarMask != 0)
  1146. }
  1147. }
  1148. }
  1149. }
  1150. extension KMMainDocument {
  1151. }