KMMainDocument.swift 56 KB

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