KMMainDocument.swift 64 KB

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