KMMainDocument.swift 54 KB

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