KMMainDocument.swift 58 KB

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