KMMainDocument.swift 60 KB

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