KMMainViewController.swift 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. @objcMembers class KMMainViewController: KMBaseViewController, NSTextFieldDelegate {
  9. @IBOutlet var PDFContendView: NSView!
  10. @IBOutlet var centerContentView: NSView!
  11. @IBOutlet var listView: CPDFListView!
  12. @IBOutlet var secondaryPdfView: KMSecondaryPDFView?
  13. @IBOutlet weak var readContentView: NSView!
  14. @IBOutlet weak var tipCurrentPageBox: KMBox!
  15. @IBOutlet weak var rightView: NSView!
  16. @IBOutlet weak var leftView: NSView!
  17. @IBOutlet weak var mianSplitView: KMSplitView!
  18. @IBOutlet weak var pdfSplitView: KMSplitView!
  19. @IBOutlet weak var newPDFSplitView: KMSplitView!
  20. @IBOutlet weak var pdfContentView: NSView!
  21. @IBOutlet weak var pdfSplitSecondView: NSBox!
  22. @IBOutlet weak var locationPageView: NSView!
  23. @IBOutlet weak var tipLabel: NSTextField!
  24. @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
  25. @IBOutlet var childToolbarController: KMToolbarViewController!
  26. @IBOutlet var toolbarController: KMToolbarController!
  27. @IBOutlet weak var toolbarBox: NSBox!
  28. @IBOutlet weak var heightOffset: NSLayoutConstraint!
  29. //阅读模式界面
  30. @IBOutlet weak var readModelView: KMReadModelView!
  31. @IBOutlet weak var bottomAreaView: KMBox!
  32. @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
  33. //页码显示器
  34. @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
  35. @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
  36. @IBOutlet weak var topTipBox: NSBox!
  37. @IBOutlet weak var exitFullButton: NSButton!
  38. var model = KMMainModel()
  39. var isReadMode: Bool = false
  40. var readAlertView: CustomAlertView?
  41. var readLeftMethodType: BotaType = .None
  42. var readLeftPanelOpen = false
  43. var readLastLeftPanWidth = 0.0
  44. var readLeftViewShowPanel = false
  45. var readRightPanelOpen = false
  46. var readToolbarType: KMToolbarViewType = .None
  47. var readToolbarItemIdentifier: String = ""
  48. var readToolMode: CToolMode = .textToolMode
  49. var readAnnotationType: CAnnotationType = .unkown
  50. var readSubViewType: RightSubViewType = .None
  51. //自动滚动
  52. var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
  53. //Search
  54. var searchIndex: Int = 0
  55. //Form
  56. var formAlertView: KMFormAlertView?
  57. //Secure
  58. var secureAlertView: KMSecureAlertView?
  59. //对比
  60. var isCompareModel: Bool = false {
  61. didSet {
  62. self.toolbarController.updataItemVisible()
  63. }
  64. }
  65. //合并
  66. var mergeWindowController: KMMergeWindowController?
  67. //水印
  68. var watermarkWindowController: KMWatermarkWindowController?
  69. //密码弹窗
  70. var passwordWindow: KMPasswordInputWindow?
  71. //对比
  72. var compressWIndowControllerNew: KMCompressWIndowControllerNew?
  73. //
  74. var securityWindowController: KMSecurityWindowController?
  75. //引导
  76. var guideInfoWindowController: KMGuideInfoWindowController?
  77. //春季活动
  78. var recommondPopWindowVC: KMRecommondPopWindow?
  79. private var _needSave = false
  80. var needSave: Bool {
  81. set {
  82. _needSave = newValue
  83. if (_needSave == false) {
  84. self.clearIsPDFDocumentEdited()
  85. }
  86. }
  87. get {
  88. return _needSave
  89. }
  90. }
  91. var isPDFDocumentEdited: Bool {
  92. get {
  93. return self.model.isPDFDocumentEdited
  94. }
  95. }
  96. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  97. var rightSideViewController: KMRightSideViewController!
  98. var searchResults: [KMSearchMode] = []
  99. var mwcFlags: MwcFlags = MwcFlags()
  100. var document: CPDFDocument?
  101. var myDocument: NSDocument?
  102. weak var browserWindowController: KMBrowserWindowController?
  103. var cropSettingWindowController: KMCropSettingWindowController!
  104. var currentWindowController: NSWindowController!
  105. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  106. //数字签名
  107. var digitalSignController: KMPDFDigitalSignViewController?
  108. var redactController: KMPDFRedactViewController!
  109. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  110. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  111. var extract: KMExtractImageWindowController?
  112. var functionWidth: Double {
  113. get {
  114. if self.isReadMode {
  115. if !self.model.isShowBOTA {
  116. return 0
  117. }
  118. }
  119. return 48-4
  120. }
  121. }
  122. var pageNumber: UInt?
  123. var openSecondaryPdfView: KMSecondaryViewController?
  124. var secondaryPdfContentView: NSView?
  125. var lastSplitPDFHeight: Float = 0.0
  126. var pdfEditController: KMPDFEditViewController? {
  127. get {
  128. return self.getPDFEditController()
  129. }
  130. }
  131. var autoSaveTimer: Timer?
  132. private var _documentFirstLoad: Bool = true
  133. var eventMonitor: Any?
  134. var keyEventMonitor: Any?
  135. var mouseRightMenuEvent: NSEvent?
  136. var aiTranslationWindow: KMAITranslationWindowController?
  137. var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
  138. lazy private var homeVC: KMHomeViewController? = {
  139. let vc = KMHomeViewController()
  140. return vc
  141. }()
  142. private var background_mask: NSView?
  143. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  144. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  145. get {
  146. return self._secureOptions
  147. }
  148. }
  149. var documentAttribute: [CPDFDocumentAttribute : Any]?
  150. fileprivate var _removeSecureFlag = false
  151. var removeSecureFlag: Bool {
  152. get {
  153. return self._removeSecureFlag
  154. }
  155. }
  156. fileprivate var _saveWatermarkFlag = false
  157. var saveWatermarkFlag: Bool {
  158. get {
  159. return self._saveWatermarkFlag
  160. }
  161. }
  162. private var mainWindow_: NSWindow?
  163. var mainWindow: NSWindow? {
  164. get {
  165. return self.mainWindow_
  166. }
  167. set {
  168. self.mainWindow_ = newValue
  169. }
  170. }
  171. deinit {
  172. NotificationCenter.default.removeObserver(self)
  173. self.removeEventMonitor()
  174. self.removeKeyEventMonitor()
  175. }
  176. override func awakeFromNib() {
  177. super.awakeFromNib()
  178. self.addBackgroundMaskView()
  179. self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
  180. listView.delegate = self
  181. listView.pdfListViewDelegate = self
  182. // listView.editingConfig().isSupportMultipleSelectEditingArea = true
  183. if (document != nil) {
  184. // if (self.document!.isLocked) {
  185. //
  186. // } else {
  187. listView.document = document
  188. // }
  189. listView.document.delegate = self
  190. let autoScale = listView.autoScales
  191. if !autoScale {
  192. listView.scaleFactor = 1.0
  193. }
  194. }
  195. self.initPDFLeftViewVC()
  196. self.initRightSideView()
  197. self.toolbarController.listView = self.listView
  198. self.toolbarController.mainViewController = self
  199. self.leftSideViewController.mainViewController = self
  200. self.newPDFSplitView.delegate = self
  201. }
  202. override func viewDidAppear() {
  203. super.viewDidAppear()
  204. //春季活动
  205. if ((KMAdvertisementManager.manager.info.popWindowContent) != nil) {
  206. if KMAdvertisementManager.manager.info.popWindowContent!.content!.count > 0 {
  207. let info = KMAdvertisementManager.manager.info.popWindowContent!.content?.first
  208. if KMAdvertisementManager.checkAdvertisementValid(info!) {
  209. self.loadRecommondPopWindow()
  210. }
  211. }
  212. }
  213. //刷新前一页后一页按钮
  214. self.updateNextAndPreViousButtonState()
  215. KMLightMemberManager.manager.canShowAdvancedView = false
  216. // Task { @MainActor in
  217. // await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
  218. // }
  219. // self.addEventMonitor()
  220. self.view.window?.makeFirstResponder(self.listView)
  221. // 更新属性页面的信息
  222. NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
  223. self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
  224. if (self.document == nil) {
  225. return
  226. }
  227. if (self.document == nil || self.document!.isLocked == false) {
  228. self.loadFunctionGuide()
  229. }
  230. if (self.document?.isLocked == false) {
  231. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  232. self.showConvertNotesProgress()
  233. }
  234. return
  235. }
  236. if (self.view.window == nil) {
  237. return
  238. }
  239. if (self.model.password != nil) {
  240. if self.listView.document.unlock(withPassword: self.model.password) {
  241. self.model.isSaveKeyChain = false
  242. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  243. self.showConvertNotesProgress()
  244. }
  245. return
  246. }
  247. }
  248. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  249. if self.view.window != nil && self.tabViewIsDragging() == false {
  250. self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [unowned self] result , password in
  251. if (result == .cancel) {
  252. // self.browserWindowController?.browser?.closeTab()
  253. (self.myDocument as? KMMainDocument)?.browser.closeTab()
  254. return
  255. }
  256. self.model.isSaveKeyChain = true
  257. self.listView.document = self.document
  258. self.document?.unlock(withPassword: password)
  259. }
  260. } else {
  261. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  262. self.showConvertNotesProgress()
  263. }
  264. }
  265. }
  266. }
  267. override func viewWillDisappear() {
  268. super.viewWillDisappear()
  269. self.removeEventMonitor()
  270. }
  271. override func viewWillLayout() {
  272. super.viewWillLayout()
  273. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  274. self.exitFullButton.isHidden = false
  275. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  276. } else {
  277. self.exitFullButton.isHidden = true
  278. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  279. }
  280. if let guideWC = self.guideInfoWindowController{
  281. var rect = self.view.window!.frame
  282. rect.size.height -= 20
  283. guideWC.window?.setFrame(rect, display: false)
  284. guideWC.window?.minSize = rect.size
  285. guideWC.window?.maxSize = rect.size
  286. guideWC.show()
  287. }
  288. }
  289. override func viewDidLoad() {
  290. super.viewDidLoad()
  291. mwcFlags.settingUpWindow = 1
  292. toolbarController.delegate = self
  293. //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
  294. toolbarBox.contentView = toolbarController.view
  295. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  296. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  297. UserDefaults.standard.synchronize()
  298. }
  299. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  300. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  301. UserDefaults.standard.synchronize()
  302. }
  303. let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
  304. mianSplitView.setPosition(position, ofDividerAt: 0)
  305. mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0)
  306. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0)
  307. self.locationPageView.wantsLayer = true;
  308. self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
  309. self.tipLabel.stringValue = NSLocalizedString("Please use the scroll bar, thumbnail tool to locate the target page, click or box the area to select the target range.", comment: "")
  310. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  311. if (self.listView.document != nil) {
  312. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  313. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  314. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  315. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  316. if (pageScale != nil) {
  317. self.listView.scaleFactor = CGFloat(pageScale!)
  318. }
  319. self.listView.go(toPageIndex: pageNumber!, animated: false)
  320. }
  321. } else {
  322. self._goToFirstPageForFristAppear()
  323. }
  324. }
  325. } else {
  326. self._goToFirstPageForFristAppear()
  327. }
  328. //阅读页面
  329. readModelView.delegate = self
  330. pageNumberDisplayView.delegate = self
  331. tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
  332. if !isReadMode {
  333. if mouseEntered {
  334. self.pageNumberDisplayView.hover = true
  335. } else {
  336. self.pageNumberDisplayView.hover = false
  337. }
  338. }
  339. }
  340. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  341. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  342. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  343. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  344. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  345. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  346. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  347. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  348. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  349. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  350. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.listView)
  351. NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayBoxChangedNotification), name: NSNotification.Name.CPDFViewDisplayBoxChanged, object: self.listView)
  352. // 互动模式
  353. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  354. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  355. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  356. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  357. NotificationCenter.default.addObserver(self, selector: #selector(didAddContentViewNotification), name: NSWindow.didAddContentViewNotification, object: nil)
  358. NotificationCenter.default.addObserver(self, selector: #selector(addAutoSaveEvent), name: AutoSaveManager.kTimeValueChangedNotificationName, object: nil)
  359. Task {
  360. self.addAutoSaveEvent()
  361. }
  362. self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
  363. self.closeRightPane()
  364. self.addKeyEventMonitor()
  365. self.addAdsBannerView()
  366. //检测OCR包是否需要更新
  367. #if VERSION_DMG
  368. // KMResourceDownloadManager.manager.checkDocumentAIVersion()
  369. #endif
  370. // Open snapshots?
  371. var snapshotSetups: NSArray?
  372. // if (hasWindowSetup)
  373. // snapshotSetups = [savedNormalSetup objectForKey:SNAPSHOTS_KEY];
  374. // else if ([sud boolForKey:SKRememberSnapshotsKey])
  375. if KMPreferenceManager.shared.rememberSnapshot {
  376. // snapshotSetups = [[SKBookmarkController sharedBookmarkController] snapshotsForRecentDocumentAtURL:[(NSDocument *)[self document] fileURL]];
  377. if let fileUrl = (self.myDocument as? KMMainDocument)?.fileURL {
  378. snapshotSetups = SKBookmarkController.shared().snapshotsForRecentDocument(at: fileUrl) as NSArray?
  379. }
  380. }
  381. if let cnt = snapshotSetups?.count, cnt > 0 {
  382. if let data = self.listView?.document?.isLocked, data {
  383. self.savedNormalSetup.setObject(snapshotSetups as Any, forKey: "snapshots" as NSCopying)
  384. } else {
  385. self.showSnapshots(setups: snapshotSetups)
  386. }
  387. }
  388. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  389. if readModel == true {
  390. self.openReadModel()
  391. }
  392. let hasWindowSetup = savedNormalSetup.count > 0
  393. if UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey) != nil {
  394. let pdfSettings: NSDictionary = hasWindowSetup ? savedNormalSetup : UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey)! as NSDictionary
  395. self.applyPDFSettings(pdfSettings)
  396. } else {
  397. self.applyPDFSettings(savedNormalSetup)
  398. }
  399. }
  400. //MARK: - PDFListView
  401. func initPDFLeftViewVC() {
  402. var frame = self.leftView.frame
  403. frame.size.width += 44
  404. self.leftView.frame = frame
  405. leftSideViewController.isFirst = true
  406. leftSideViewController.listView = self.listView ?? CPDFListView()
  407. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  408. leftSideViewController.view.autoresizingMask = [.height,.width]
  409. leftSideViewController.delegate = self
  410. self.leftView.addSubview(leftSideViewController.view)
  411. }
  412. func initRightSideView() {
  413. self.rightSideViewController = KMRightSideViewController.init()
  414. self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
  415. self.rightSideViewController.view.autoresizingMask = [.height,.width]
  416. self.rightSideViewController.listView = self.listView
  417. // self.rightSideViewController.view.isHidden = true
  418. self.rightSideViewController.isHidden = true
  419. self.rightSideViewController.delegate = self
  420. self.rightView.addSubview(self.rightSideViewController.view)
  421. self.rightSideViewController.propertyDidChange = { [weak self] model in
  422. if let anno = model as? CSelfSignAnnotation {
  423. self?.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: nil)
  424. }
  425. }
  426. }
  427. func addAdsBannerView() {
  428. #if VERSION_FREE
  429. if !IAPProductsManager.default().isAvailableAllFunction(){
  430. guard let document = self.listView.document else {
  431. return
  432. }
  433. if !document.isLocked {
  434. KMAdsManager.defaultManager.beginSheetModalForView(self.readContentView, directions: .down, adPosY: 30, animated: false) { pageIndex in
  435. }
  436. }
  437. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  438. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  439. }
  440. #endif
  441. //加载底部banner
  442. // - (void)loadingAdsManager {
  443. // #if VERSION_FREE
  444. // if(![self.pdfDocument isLocked]) {
  445. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  446. // [[KMAdsManager defaultManager] beginSheetModalForView:self.pdfView
  447. // directions:KMADViewDirectionsDown
  448. // animated:NO
  449. // completionHandler:nil];
  450. // }
  451. // [[NSNotificationCenter defaultCenter] addObserverForName:KMIAPProductPurchasedNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
  452. // if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
  453. // [[KMAdsManager defaultManager] dismissSheetModalForView:self.pdfView];
  454. // }
  455. // }];
  456. // [[NSNotificationCenter defaultCenter] addObserverForName:kDeviceActivateStatusChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
  457. // if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
  458. // [[KMAdsManager defaultManager] dismissSheetModalForView:self.pdfView];
  459. // }
  460. // }];
  461. // }
  462. // #endif
  463. // }
  464. }
  465. // MARK: Private Methods
  466. internal func removeNotifications() {
  467. NotificationCenter.default.removeObserver(self)
  468. self.leftSideViewController.clearAnnotationFilterData()
  469. self.leftSideViewController.clearNotification()
  470. }
  471. func checkShouldAutoOpenLeftVC() {
  472. if KMPreference.shared.showLeftSideBar == false {
  473. return
  474. }
  475. if self.model.leftPanelOpen {
  476. return
  477. }
  478. Task { @MainActor in
  479. self.leftSideViewController.showThumbnail()
  480. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  481. }
  482. }
  483. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  484. mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  485. mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  486. self.model.lastLeftPanWidth = leftSideWidth
  487. self.model.lastRightPanWidth = rightSideWidth
  488. }
  489. internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  490. internal func removeAllAnnotations() {
  491. let alert = NSAlert()
  492. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  493. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  494. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  495. if (alert.runModal() != .alertFirstButtonReturn) {
  496. return
  497. }
  498. DispatchQueue.main.async {
  499. self.removeAllAnnotationsStore.store(t: self.listView)
  500. }
  501. }
  502. // MARK: Set Methods
  503. var setDocument: CPDFDocument? {
  504. get {
  505. return document
  506. }
  507. set {
  508. if document != newValue {
  509. document = newValue
  510. }
  511. listView.document = document
  512. listView.document.delegate = self
  513. self.listView.layoutDocumentView()
  514. self.leftSideViewController.refreshUIForDocumentChanged()
  515. }
  516. }
  517. var setPageNumber: UInt {
  518. get {
  519. return pageNumber!
  520. }
  521. set {
  522. let pageCount = listView.document.pageCount
  523. var value = newValue
  524. if value > pageCount {
  525. value = pageCount
  526. }
  527. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  528. listView.go(to: listView.document.page(at: value-1))
  529. }
  530. if pageNumber != value {
  531. pageNumber = value
  532. }
  533. }
  534. }
  535. // MARK: - 标记密文
  536. func enterRedact() {
  537. if !IAPProductsManager.default().isAvailableAllFunction(){
  538. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  539. return
  540. }
  541. if self.listView.document.allowsPrinting == false || self.listView.document.allowsCopying == false {
  542. Task {
  543. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  544. }
  545. return
  546. }
  547. if self.hasEnterRedact() {
  548. self.exitRedact()
  549. return
  550. }
  551. self.leftSideViewController.thumbnailTableView.isEnabled = false
  552. self.leftSideViewController.tocOutlineView.isEnabled = false
  553. self.leftSideViewController.noteOutlineView.isEnabled = false
  554. self.leftSideViewController.findTableView.isEnabled = false
  555. self.leftSideViewController.groupedFindTableView.isEnabled = false
  556. self.leftSideViewController.snapshotTableView.isEnabled = false
  557. let ttsWindowC = KMTTSWindowController.share
  558. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document.documentURL.path {
  559. if let data = ttsWindowC.window?.isVisible, data {
  560. ttsWindowC.stopSpeaking()
  561. ttsWindowC.close()
  562. }
  563. }
  564. NSColorPanel.shared.showsAlpha = false
  565. redactController = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document.password)
  566. self.addChild(redactController)
  567. self.PDFContendView.addSubview(redactController.view)
  568. redactController.view.frame = self.PDFContendView.bounds
  569. redactController.view.autoresizingMask = [.width, .height]
  570. self.listView.isHidden = true
  571. redactController.scaleFactor = self.listView.scaleFactor
  572. redactController.titleBack = { [weak self] title in
  573. self?.view.window?.title = title
  574. }
  575. redactController.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
  576. self?.listView.go(toPageIndex: self!.redactController.redactPdfView.currentPageIndex, animated: false)
  577. if result == false { // 退出
  578. self?.exitRedact()
  579. return
  580. }
  581. let controller = self?._getPDFRedactController()
  582. controller?.redactPdfView.newAddAnnotation.removeAll()
  583. self?.exitRedact()
  584. if saveResult {
  585. let newDocument = CPDFDocument(url: saveUrl)
  586. if let data = newDocument?.isLocked, data {
  587. newDocument?.unlock(withPassword: self?.listView.document.password ?? "")
  588. }
  589. self?.document = newDocument
  590. self?.listView.document = newDocument
  591. self?.listView.layoutDocumentView()
  592. }
  593. }
  594. redactController.setCurrentPageIndex(self.listView.currentPageIndex)
  595. }
  596. func exitRedact() {
  597. self.leftSideViewController.thumbnailTableView.isEnabled = true
  598. self.leftSideViewController.tocOutlineView.isEnabled = true
  599. self.leftSideViewController.noteOutlineView.isEnabled = true
  600. self.leftSideViewController.findTableView.isEnabled = true
  601. self.leftSideViewController.groupedFindTableView.isEnabled = true
  602. self.leftSideViewController.snapshotTableView.isEnabled = true
  603. let controller = self._getPDFRedactController()
  604. if let data = controller {
  605. if data.redactPdfView.newAddAnnotation.count > 0 {
  606. KMAlertTool.runModel(message: "", informative: KMLocalizedString("There are unapplied redactions in this file. Exit will not save redaction.", nil), buttons: [KMLocalizedString("Exit", nil), KMLocalizedString("Cancel", nil)]) { response in
  607. if response == .alertFirstButtonReturn {
  608. data.redactPdfView.newAddAnnotation.removeAll()
  609. self.exitRedact()
  610. }
  611. }
  612. return
  613. }
  614. }
  615. NSColorPanel.shared.showsAlpha = true
  616. self.toolbarController.findItem(KMDocumentRedactToolbarItemIdentifier)?.isSelected = false
  617. // self.toolbarController.toolbarType = .None
  618. // self.listView.toolMode = .moveToolMode
  619. controller?.redactPdfView.resignMonitor()
  620. controller?.view.removeFromSuperview()
  621. controller?.removeFromParent()
  622. self.listView.isHidden = false
  623. // self.listView.layoutDocumentView()
  624. // self.view.window?.makeFirstResponder(self.listView)
  625. self.listView.annotationType = .unkown
  626. }
  627. func hasEnterRedact() -> Bool {
  628. return self._getPDFRedactController() != nil
  629. }
  630. //MARK: - AI
  631. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  632. if (self.document != nil) {
  633. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  634. } else {
  635. AIChatInfoManager.defaultManager.currentFilePath = ""
  636. }
  637. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  638. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  639. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  640. let documentArray = NSDocumentController.shared.documents
  641. var didFileEdit: Bool = false
  642. var curDoc: KMMainDocument!
  643. for document in documentArray {
  644. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  645. didFileEdit = document.isDocumentEdited
  646. curDoc = document as! KMMainDocument
  647. break
  648. }
  649. }
  650. if didFileEdit {
  651. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  652. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  653. do {
  654. try FileManager.default.removeItem(at: tempFileURL)
  655. } catch {
  656. }
  657. }
  658. if curDoc != nil {
  659. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  660. }
  661. }
  662. windowVC.window?.becomeMain()
  663. }
  664. }
  665. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  666. } else {
  667. var windowRect = windowVC.window?.frame
  668. windowRect!.origin.x = CGRectGetMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  669. windowRect!.origin.y = CGRectGetMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  670. windowVC.window?.setFrame(windowRect!, display: true)
  671. windowVC.didSetOriginFrame = true
  672. }
  673. windowVC.eventLabel = "AITools_Tbr"
  674. windowVC.showWindow(nil)
  675. if (aiConfigType != .none) {
  676. windowVC.eventLabel = "AITools_Start"
  677. if self.listView.currentSelection?.string()?.isEmpty == false {
  678. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  679. }
  680. windowVC.chooseAIFunctionWithType(aiConfigType)
  681. }
  682. }
  683. @objc func aiTipIconViewShowStateChangeNoti() {
  684. }
  685. //MARK: - 引导
  686. func loadFunctionGuide() -> Void {
  687. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  688. if self.view.window != nil {
  689. self.loadOpenFileFunctionGuide(.openFileNormal)
  690. }
  691. }
  692. }
  693. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  694. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  695. let leftPanelItem:KMToolbarItemView = self.toolbarController.findItem("KMLeftControlToolbarItemIdentifier")!
  696. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  697. guard let guideWC = self.guideInfoWindowController else { return }
  698. guideWC.type = .openFileNormal
  699. guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? CGRectZero
  700. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  701. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  702. let rightPanelItem = self?.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  703. let digitalPanelItem = self?.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)
  704. windowVC.rightPanelRect = (self!.view.window?.contentView?.convert(rightPanelItem?.frame ?? .zero, from: rightPanelItem?.superview)) ?? .zero
  705. guideWC.digitalBoxRect = (self!.view.window?.contentView?.convert(digitalPanelItem?.frame ?? .zero, from: digitalPanelItem?.superview)) ?? .zero
  706. }
  707. guideWC.finishHandle = { [weak self] windowVC, type in
  708. if type == .windowNewFinish ||
  709. type == . windowDigitalFinish {
  710. self?.checkFirstTrialController()
  711. }
  712. }
  713. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  714. self?.checkFirstTrialController()
  715. }
  716. var rect = self.view.window!.frame
  717. rect.size.height -= 20
  718. guideWC.window?.setFrame(rect, display: false)
  719. guideWC.window?.minSize = rect.size
  720. guideWC.window?.maxSize = rect.size
  721. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  722. guideWC.show()
  723. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  724. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  725. guard let guideWC = self.guideInfoWindowController else { return }
  726. guideWC.type = .digitalSignGuide
  727. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  728. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  729. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  730. guideWC.finishHandle = { [weak self] windowVC, type in
  731. self?.checkFirstTrialController()
  732. }
  733. var rect = self.view.window!.frame
  734. rect.size.height -= 20
  735. guideWC.window?.setFrame(rect, display: false)
  736. guideWC.window?.minSize = rect.size
  737. guideWC.window?.maxSize = rect.size
  738. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  739. guideWC.show()
  740. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  741. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  742. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  743. guard let guideWC = self.guideInfoWindowController else { return }
  744. guideWC.type = .pdfCompareGuide
  745. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  746. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  747. let compareItem:KMToolbarItemView = self.toolbarController.findItem(KMToolbarComparisonItemIdentifier)!
  748. guideWC.compareItemRect = (self.view.window?.contentView?.convert(compareItem.frame, from: compareItem.superview))!
  749. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  750. var rect = self.view.window!.frame
  751. rect.size.height -= 20
  752. guideWC.window?.setFrame(rect, display: false)
  753. guideWC.window?.minSize = rect.size
  754. guideWC.window?.maxSize = rect.size
  755. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  756. guideWC.show()
  757. }
  758. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  759. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  760. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  761. guard let guideWC = self.guideInfoWindowController else { return }
  762. guideWC.type = .convertGuide
  763. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  764. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  765. guideWC.purchaseHandle = { [weak self] windowVC in
  766. #if VERSION_DMG
  767. if IAPProductsManager.default().isAvailableAllFunction() {
  768. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  769. //Convert:
  770. self?.showAllConvertWindow(convertT: .Word)
  771. } else {
  772. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  773. limitWC.continueBlock = { windowController in
  774. }
  775. limitWC.window?.center()
  776. limitWC.showWindow(nil)
  777. }
  778. } else {
  779. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  780. }
  781. #else
  782. if IAPProductsManager.default().isAvailableAllFunction() {
  783. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  784. //Convert:
  785. } else {
  786. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  787. vc.showWindow(nil)
  788. }
  789. } else {
  790. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  791. }
  792. #endif
  793. }
  794. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  795. var rect = self.view.window!.frame
  796. rect.size.height -= 20
  797. guideWC.window?.setFrame(rect, display: false)
  798. guideWC.window?.minSize = rect.size
  799. guideWC.window?.maxSize = rect.size
  800. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  801. guideWC.show()
  802. }
  803. } else {
  804. }
  805. }
  806. func checkFirstTrialController() -> Void {
  807. #if VERSION_DMG
  808. //打开文档后引导相关
  809. if VerificationManager.default().status == .none {
  810. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  811. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  812. if lastVersion.isEmpty || lastVersion != appVersion {
  813. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  814. UserDefaults.standard.synchronize()
  815. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  816. }
  817. }
  818. #endif
  819. }
  820. // MARK: - 页面编辑
  821. open func enterPageEdit(_ pages: [Int] = []) {
  822. if let doc = self.listView?.document {
  823. if doc.allowsCopying == false || doc.allowsPrinting == false {
  824. KMBaseWindowController.checkPassword(url: doc.documentURL, type: .owner) { result, pwd in
  825. if result && pwd.isEmpty == false {
  826. self.listView?.document?.unlock(withPassword: pwd)
  827. Task { @MainActor in
  828. self.enterPageEdit(pages)
  829. }
  830. } else {
  831. self.exitPageEdit()
  832. }
  833. }
  834. return
  835. }
  836. }
  837. //选中page
  838. var tPages = pages
  839. if tPages.count == 0 {
  840. if self.leftSideViewController.type.methodType == .Thumbnail {
  841. tPages = self.leftSideViewController.thumb_fetchSelectedRows() ?? [self.listView.currentPageIndex]
  842. }
  843. }
  844. if (hasEnterPageEdit()) {
  845. exitPageEdit()
  846. return
  847. }
  848. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  849. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  850. for (key, value) in toolBarView.toolbarItems {
  851. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  852. (value as! KMToolbarItemView).unEnabled = true
  853. }
  854. }
  855. }
  856. let controller = KMPDFEditViewController(self.listView.document)
  857. controller.selectedPages = tPages
  858. controller.listView = self.listView
  859. self.addChild(controller)
  860. self.PDFContendView.addSubview(controller.view)
  861. controller.view.frame = self.PDFContendView.bounds
  862. controller.view.autoresizingMask = [.width,.height]
  863. self.listView.isHidden = true
  864. controller.itemClick = { [weak self] index, params in
  865. if (index == 1) { /// 双击退出
  866. self?.enterEditMode(self!.leftSideViewController, [])
  867. DispatchQueue.main.async {
  868. let pageIndex: Int = params.first as! Int
  869. self?.listView.go(toPageIndex: pageIndex, animated: true)
  870. }
  871. } else if (index == 2) { // 打印
  872. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  873. }
  874. }
  875. controller.documentEditedCallback = { [weak self] params in
  876. self?.recordIsPDFDocumentEdited()
  877. }
  878. controller.selectionDidChange = { selectedIndexs in
  879. var indexSet = IndexSet()
  880. for indexPath in selectedIndexs {
  881. indexSet.insert(indexPath.item)
  882. }
  883. if indexSet.count != 0 {
  884. // self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
  885. // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
  886. }
  887. }
  888. }
  889. open func exitPageEdit() {
  890. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  891. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  892. for (key, value) in toolBarView.toolbarItems {
  893. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  894. (value as! KMToolbarItemView).unEnabled = false
  895. }
  896. }
  897. }
  898. self.toolbarController.findItem(KMDocumentPageToolbarItemIdentifier)?.isSelected = false
  899. let editController = getPDFEditController()
  900. if (editController == nil) {
  901. return
  902. }
  903. self.listView.annotationType = .highlight
  904. editController?.view.removeFromSuperview()
  905. editController?.removeFromParent()
  906. self.listView.isHidden = false
  907. self.listView.layoutDocumentView()
  908. self.view.window?.makeFirstResponder(self.listView)
  909. self.listView.annotationType = .unkown
  910. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  911. if let data = editController?.isEdited, data {
  912. self.leftSideViewController.reloadThumbnailDataIfNeed()
  913. self.leftSideViewController.note_reloadDataIfNeed()
  914. self.leftSideViewController.refreshUIOfOutlineIfNeed()
  915. self.leftSideViewController.refreshUIOfSeachListIfNeed()
  916. }
  917. }
  918. open func hasEnterPageEdit() -> Bool {
  919. return self.getPDFEditController() != nil
  920. }
  921. // MARK: - Edit PDF
  922. func enterEditPDF() {
  923. self.listView.updateActiveAnnotations([])
  924. self.listView.setNeedsDisplayForVisiblePages()
  925. self.listView.commitEditFormText()
  926. self.listView.annotationType = .editTextImage
  927. }
  928. // MARK: - 数字签名
  929. func hasShowDigitalSign() -> Bool {
  930. return self.digitalSignController?.view.superview != nil
  931. }
  932. func canEnterDigitalSign() -> Bool {
  933. guard let doc = self.listView?.document else {
  934. return false
  935. }
  936. return doc.allowsPrinting && doc.allowsCopying
  937. }
  938. func enterDigitalSign() {
  939. self.listView.toolMode = .textToolMode
  940. if self.hasShowDigitalSign() {
  941. self.exitDigitalSign()
  942. } else {
  943. if self.needSaveDocument() {
  944. self.saveDocumentWithProgressAlert { [unowned self] params in
  945. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  946. }
  947. return
  948. }
  949. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  950. }
  951. }
  952. func exitDigitalSign() {
  953. self.digitalSignController?.view.removeFromSuperview()
  954. // self.digitalSignController = nil
  955. self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)?.isSelected = false
  956. }
  957. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  958. if !IAPProductsManager.default().isAvailableAllFunction(){
  959. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  960. return
  961. }
  962. if hasShowDigitalSign() {
  963. self.exitDigitalSign()
  964. }
  965. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  966. var password: String = ""
  967. self.toolbarController.toolbarType = .None
  968. if digitalSignController == nil {
  969. password = listView.document?.password ?? ""
  970. digitalSignController = KMPDFDigitalSignViewController()
  971. }
  972. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  973. digitalSignController?.url = listView.document.documentURL
  974. digitalSignController?.password = password
  975. digitalSignController?.scaleFactor = listView.scaleFactor
  976. digitalSignController?.titleChangeBlock = { title, index in
  977. currentPageIndex = UInt(index)
  978. }
  979. digitalSignController?.buttonActionBlock = { [weak self] type, isChanged in
  980. if type == .cancel {
  981. if let page = self?.listView?.document?.page(at: currentPageIndex) {
  982. self?.listView.go(to: page)
  983. }
  984. self?.exitDigitalSign()
  985. }
  986. }
  987. if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
  988. digitalSignView.frame = splitViewSuperview.bounds
  989. digitalSignView.autoresizingMask = [.width, .height]
  990. splitViewSuperview.addSubview(digitalSignView)
  991. digitalSignController?.setCurrentPageIndex(Int(currentPageIndex))
  992. }
  993. }
  994. // MARK: - Toolbar
  995. func toolbarItemClickForExitMode(_ toolbarItem: KMToolbarItemView) {
  996. if(toolbarItem.itemIdentifier != KMDocumentPageToolbarItemIdentifier) {
  997. if (hasEnterPageEdit()) {
  998. self.exitPageEdit()
  999. }
  1000. }
  1001. if toolbarItem.itemIdentifier != KMDocumentRedactToolbarItemIdentifier {
  1002. if self.hasEnterRedact() {
  1003. self.exitRedact()
  1004. }
  1005. }
  1006. if toolbarItem.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  1007. if self.hasShowDigitalSign() {
  1008. self.exitDigitalSign()
  1009. }
  1010. }
  1011. }
  1012. // MARK: - Private Methods
  1013. private func getPDFEditController() -> KMPDFEditViewController? {
  1014. var editController: KMPDFEditViewController?
  1015. for controller in self.children {
  1016. if (controller.isKind(of: KMPDFEditViewController.self)) {
  1017. editController = (controller as! KMPDFEditViewController)
  1018. break
  1019. }
  1020. }
  1021. return editController
  1022. }
  1023. private func _getPDFRedactController() -> KMPDFRedactViewController? {
  1024. var controller: KMPDFRedactViewController?
  1025. for childC in self.children {
  1026. if (childC.isKind(of: KMPDFRedactViewController.self)) {
  1027. controller = (childC as! KMPDFRedactViewController)
  1028. break
  1029. }
  1030. }
  1031. return controller
  1032. }
  1033. private func addBackgroundMaskView() {
  1034. self.removeBackgroundMaskView()
  1035. if let superview = self.mianSplitView.superview {
  1036. let view = NSView()
  1037. superview.addSubview(view)
  1038. view.frame = superview.bounds
  1039. view.autoresizingMask = [.width, .height]
  1040. view.wantsLayer = true
  1041. view.layer?.backgroundColor = .white
  1042. self.background_mask = view
  1043. }
  1044. }
  1045. private func removeBackgroundMaskView() {
  1046. self.background_mask?.removeFromSuperview()
  1047. self.background_mask = nil
  1048. }
  1049. private func _goToFirstPageForFristAppear() {
  1050. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  1051. self.listView.go(toPageIndex: 0, animated: false)
  1052. }
  1053. }
  1054. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  1055. let url = URL(fileURLWithPath: filePath)
  1056. guard let document = PDFDocument(url: url) else {
  1057. return false
  1058. }
  1059. let pageCount = document.pageCount
  1060. return pageCount > 30
  1061. }
  1062. // MARK: - Redact 【标记密文】
  1063. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  1064. let windowController = KMRedactConfirmWindowController(type)
  1065. self.currentWindowController = windowController
  1066. self.view.window?.beginSheet(windowController.window!)
  1067. windowController.itemClick = { [weak self] index in
  1068. if (index == 2) { /// 取消
  1069. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1070. self?.currentWindowController = nil
  1071. callback()
  1072. return
  1073. }
  1074. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1075. self?.currentWindowController = nil
  1076. let panel = NSSavePanel()
  1077. panel.nameFieldStringValue = "[新文件]"+(self?.listView.document.documentURL.lastPathComponent)!
  1078. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  1079. button.state = .on
  1080. panel.accessoryView = button
  1081. panel.isExtensionHidden = true
  1082. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  1083. if response != .OK {
  1084. callback()
  1085. return
  1086. }
  1087. if (type == .redactOne) {
  1088. let anno = self!.listView.activeAnnotation
  1089. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1090. callback()
  1091. return
  1092. }
  1093. (anno as! CPDFRedactAnnotation).applyRedaction()
  1094. } else if (type == .redactAll) {
  1095. self?.listView.document.applyRedactions()
  1096. } else if (type == .eraserOne) {
  1097. let anno = self!.listView.activeAnnotation
  1098. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1099. callback()
  1100. return
  1101. }
  1102. anno?.page.erasureRedact(from: anno!.bounds)
  1103. } else if (type == .eraserAll) {
  1104. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  1105. if (result == false) {
  1106. callback()
  1107. return
  1108. }
  1109. }
  1110. }
  1111. self!.listView.document.write(to: panel.url)
  1112. if (button.state == .on) {
  1113. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  1114. }
  1115. } else {
  1116. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  1117. }
  1118. callback()
  1119. }
  1120. }
  1121. }
  1122. // MARK: - Secure 【安全】
  1123. public func showSecureLimitTip() {
  1124. self.hiddenSecureLimitTip()
  1125. if self.secureAlertView == nil {
  1126. self.secureAlertView = KMSecureAlertView()
  1127. self.secureAlertView?.show(in: self.listView)
  1128. self.secureAlertView?.closeAction = { [unowned self] view in
  1129. self.hiddenSecureLimitTip()
  1130. self.removeFromAlertView()
  1131. self.showFormAlertView()
  1132. }
  1133. self.secureAlertView?.passwordAction = { [unowned self] view in
  1134. self.removeOwnerPassword()
  1135. self.removeFromAlertView()
  1136. self.showFormAlertView()
  1137. }
  1138. }
  1139. }
  1140. func removeOwnerPassword() {
  1141. guard let doc = self.listView?.document else {
  1142. NSSound.beep()
  1143. return
  1144. }
  1145. if doc.allowsCopying && doc.allowsPrinting {
  1146. NSSound.beep()
  1147. return
  1148. }
  1149. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1150. if result == .cancel { /// 关闭
  1151. return
  1152. }
  1153. /// 解密成功
  1154. self?.hiddenSecureLimitTip()
  1155. self?.model.isSaveKeyChain = false
  1156. self?.listView.document.unlock(withPassword: password)
  1157. }
  1158. }
  1159. public func hiddenSecureLimitTip() {
  1160. self.secureAlertView?.removeFromSuperview()
  1161. self.secureAlertView = nil
  1162. }
  1163. //MARK: - Form
  1164. func showFormAlertView() {
  1165. if (formAlertView == nil) {
  1166. formAlertView = KMFormAlertView()
  1167. formAlertView?.isCloseSecureView = self.secureAlertView != nil ? false : true
  1168. formAlertView?.showInView(self.listView)
  1169. } else {
  1170. self.removeFromAlertView()
  1171. }
  1172. }
  1173. func removeFromAlertView() {
  1174. formAlertView?.removeFromSuperview()
  1175. formAlertView = nil
  1176. }
  1177. override func mouseMoved(with event: NSEvent) {
  1178. self.view.window?.mouseMoved(with: event)
  1179. }
  1180. func savePageNumberIfNeed() {
  1181. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1182. let scaleFactor = self.listView?.scaleFactor ?? 0
  1183. if scaleFactor <= 0 {
  1184. return
  1185. }
  1186. if self.listView.document != nil {
  1187. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1188. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  1189. }
  1190. }
  1191. }
  1192. // MARK: - 显示合并窗口
  1193. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  1194. DispatchQueue.main.async {
  1195. var documentURL = url
  1196. if documentURL == nil {
  1197. documentURL = self.listView.document.documentURL
  1198. }
  1199. guard let _url = documentURL else { return }
  1200. guard let document = PDFDocument(url: _url) else { return }
  1201. self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
  1202. self.mergeWindowController!.oriDucumentUrl = self.listView.document.documentURL
  1203. self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  1204. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  1205. self.view.window?.endSheet(mergeWindowController!.window!)
  1206. }
  1207. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  1208. self.view.window?.endSheet(mergeWindowController!.window!)
  1209. }
  1210. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  1211. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  1212. }
  1213. }
  1214. // MARK: - 显示加密弹窗
  1215. public func showSecureWindow(_ url: URL) {
  1216. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1217. guard let securityWindowController = securityWindowController else { return }
  1218. securityWindowController.documentURL = self.listView.document.documentURL
  1219. securityWindowController.batchAction = { [unowned self] controller, files in
  1220. self.view.window?.endSheet((securityWindowController.window)!)
  1221. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1222. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1223. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  1224. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  1225. batchWindowController.window?.makeKeyAndOrderFront("")
  1226. }
  1227. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  1228. let openPanel = NSOpenPanel()
  1229. openPanel.canChooseFiles = false
  1230. openPanel.canChooseDirectories = true
  1231. openPanel.canCreateDirectories = true
  1232. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1233. if result == NSApplication.ModalResponse.OK {
  1234. for fileURL in openPanel.urls {
  1235. let document = CPDFDocument(url: self.document?.documentURL)
  1236. if document != nil {
  1237. document!.setDocumentAttributes(attribute)
  1238. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1239. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1240. if success {
  1241. self.view.window?.endSheet((securityWindowController.window)!)
  1242. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1243. }
  1244. }
  1245. }
  1246. }
  1247. }
  1248. }
  1249. securityWindowController.cancelAction = { [unowned self] controller in
  1250. self.view.window?.endSheet((securityWindowController.window)!)
  1251. }
  1252. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  1253. }
  1254. // MARK: - 保存文档
  1255. internal func needSaveDocument() -> Bool {
  1256. if (self.isPDFDocumentEdited) {
  1257. return self.isPDFDocumentEdited
  1258. }
  1259. if (self.needSave) {
  1260. return self.needSave
  1261. }
  1262. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1263. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1264. return false
  1265. }
  1266. return true
  1267. }
  1268. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  1269. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1270. if (overlook) {
  1271. document?.save(nil)
  1272. return
  1273. }
  1274. if (self.isPDFDocumentEdited) {
  1275. self.clearIsPDFDocumentEdited()
  1276. self.needSave = false
  1277. document?.save(nil)
  1278. return
  1279. }
  1280. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1281. return
  1282. }
  1283. document?.save(nil)
  1284. }
  1285. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  1286. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1287. if (overlook) {
  1288. DispatchQueue.main.async {
  1289. document?.save(nil)
  1290. callback()
  1291. }
  1292. return
  1293. }
  1294. if (self.isPDFDocumentEdited) {
  1295. self.clearIsPDFDocumentEdited()
  1296. self.needSave = false
  1297. DispatchQueue.main.async {
  1298. document?.save(nil)
  1299. callback()
  1300. }
  1301. return
  1302. }
  1303. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1304. callback()
  1305. return
  1306. }
  1307. DispatchQueue.main.async {
  1308. document?.save(nil)
  1309. callback()
  1310. }
  1311. }
  1312. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  1313. // 显示进度
  1314. AutoSaveManager.manager.isSaving = true
  1315. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  1316. self.progressC?.maxValue = 3.0
  1317. self.progressC?.increment(by: 1.0)
  1318. // 保存文档
  1319. self.asyncSaveDocument { [unowned self] params in
  1320. // 执行进度 [假进度]
  1321. self.progressC?.increment(by: 1.0)
  1322. self.progressC?.increment(by: 1.0)
  1323. // DispatchQueue.main.async {
  1324. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  1325. // 隐藏进度
  1326. self.hiddenProgressWindow()
  1327. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  1328. AutoSaveManager.manager.isSaving = false
  1329. }
  1330. // 回调
  1331. callback()
  1332. }
  1333. }
  1334. }
  1335. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  1336. self.document?.write(toFile: tempPath)
  1337. }
  1338. // MARK: - 定时保存
  1339. func addAutoSaveEvent() {
  1340. if (self.autoSaveTimer != nil) {
  1341. self.autoSaveTimer?.invalidate()
  1342. self.autoSaveTimer = nil
  1343. }
  1344. if self.document != nil {
  1345. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  1346. self?.autoSaveTimerAction(timer)
  1347. })
  1348. }
  1349. self.checkAutoSaveInfo()
  1350. }
  1351. func checkAutoSaveInfo() {
  1352. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  1353. return
  1354. }
  1355. if AutoSaveManager.manager.autoSaveAlertShow {
  1356. return
  1357. }
  1358. AutoSaveManager.manager.autoSaveDidEndAction = false
  1359. AutoSaveManager.manager.autoSaveAlertShow = true
  1360. let blockSaveWindow = AutoSavePopController()
  1361. blockSaveWindow.cancelHandle = { [weak self] windowController in
  1362. AutoSaveManager.manager.autoSaveDidEndAction = true
  1363. AutoSaveManager.manager.clearCache()
  1364. self?.km_quick_endSheet()
  1365. }
  1366. blockSaveWindow.confirmHandle = { [weak self] windowController in
  1367. self?.km_quick_endSheet()
  1368. self?.saveAutoSaveInfo()
  1369. }
  1370. self.km_beginSheet(windowC: blockSaveWindow)
  1371. }
  1372. func saveAutoSaveInfo() {
  1373. let openPanel = NSOpenPanel()
  1374. openPanel.canChooseDirectories = true
  1375. openPanel.canChooseFiles = false
  1376. openPanel.allowsMultipleSelection = false
  1377. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  1378. openPanel.beginSheetModal(for: win!) { result in
  1379. if (result == .OK) {
  1380. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  1381. for path in AutoSaveManager.manager.opendPaths ?? [] {
  1382. let _path = path as? String
  1383. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  1384. newPath = self.getValidFilePath(newPath)
  1385. do {
  1386. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  1387. } catch {
  1388. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  1389. }
  1390. }
  1391. AutoSaveManager.manager.clearCache()
  1392. }
  1393. AutoSaveManager.manager.autoSaveDidEndAction = true
  1394. }
  1395. }
  1396. func autoSaveTimerAction(_ timer: Timer) {
  1397. if (self.document == nil || self.listView?.document?.documentURL.path == nil) {
  1398. return
  1399. }
  1400. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1401. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1402. return
  1403. }
  1404. if let data = self.document?.isLocked, data {
  1405. return
  1406. }
  1407. if AutoSaveManager.manager.autoSaveEnabled == false {
  1408. return
  1409. }
  1410. let documentArray = NSDocumentController.shared.documents
  1411. var didFileEdit = false
  1412. for doc in documentArray {
  1413. if doc.fileURL?.path == self.document?.documentURL.path {
  1414. didFileEdit = doc.isDocumentEdited
  1415. break
  1416. }
  1417. }
  1418. if (didFileEdit == false) {
  1419. return
  1420. }
  1421. AutoSaveManager.manager.isSaving = true
  1422. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView?.document?.documentURL.path ?? "")
  1423. if (!self.document!.isLocked) {
  1424. self.document?.write(to: URL(fileURLWithPath: savePath))
  1425. }
  1426. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  1427. AutoSaveManager.manager.isSaving = false
  1428. }
  1429. }
  1430. func removeAutoSaveInfo() {
  1431. if self.autoSaveTimer != nil {
  1432. self.autoSaveTimer?.invalidate()
  1433. self.autoSaveTimer = nil
  1434. }
  1435. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1436. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1437. return
  1438. }
  1439. if AutoSaveManager.manager.autoSaveEnabled == false {
  1440. return
  1441. }
  1442. if self.document == nil || self.listView?.document?.documentURL.path == nil {
  1443. return
  1444. }
  1445. AutoSaveManager.manager.removeAutoSavePath(self.listView?.document?.documentURL.path ?? "")
  1446. }
  1447. // MARK: - 选择 PDFDisplay 模式
  1448. @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
  1449. let toolModel = self.listView.toolMode
  1450. self.isReadMode = false
  1451. switch display {
  1452. case .singlePage:
  1453. self.listView.setDisplay(.singlePage)
  1454. break
  1455. case .singlePageContinuous:
  1456. self.listView.setDisplay(.singlePageContinuous)
  1457. break
  1458. case .twoUp:
  1459. self.listView.setDisplay(.twoUp)
  1460. break
  1461. case .twoUpContinuous:
  1462. self.listView.setDisplay(.twoUpContinuous)
  1463. break
  1464. case .bookMode:
  1465. self.listView.displaysAsBook = true
  1466. self.listView.displayTwoUp = true
  1467. self.listView.displayDirection = .horizontal
  1468. break
  1469. case .bookContinuous:
  1470. self.listView.displaysAsBook = true
  1471. self.listView.displayTwoUp = true
  1472. self.listView.displayDirection = .vertical
  1473. break
  1474. case .readModel:
  1475. self.openReadModel()
  1476. break
  1477. case .readContinuous:
  1478. self.openReadModel()
  1479. break
  1480. }
  1481. self.listView.layoutDocumentView()
  1482. // if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
  1483. // self.leftSideViewController.panelSetViewController.reloadListViewModel()
  1484. // }
  1485. if (toolModel == .editPDFToolMode) {
  1486. if self.rightSideViewController.eidtPDFImageProperty != nil {
  1487. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  1488. self.rightSideViewController.isHidden = true
  1489. self.closeRightPane()
  1490. }
  1491. }
  1492. }
  1493. // MARK: - 选择缩放模式
  1494. @objc public func selectZoom(_ type: KMPDFZoomType) {
  1495. switch type {
  1496. case .width:
  1497. self.listView.autoScales = true
  1498. // self.listView.autoScales = false
  1499. break
  1500. case .fit:
  1501. // self.listView.autoScales = !self.listView.autoScales
  1502. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  1503. let pdfviewHeight = self.listView.bounds.size.height
  1504. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1505. self.listView.autoScales = false
  1506. }
  1507. break
  1508. case .actualSize:
  1509. if self.listView.scaleFactor != 1.0 {
  1510. self.listView.scaleFactor = 1.0
  1511. self.listView.autoScales = false
  1512. }
  1513. break
  1514. }
  1515. }
  1516. internal func createPdf(index:Int) {
  1517. if index == 1 {
  1518. self.homeVC?.openBlankPage()
  1519. } else if index == 4 {
  1520. self.homeVC?.importFromCamera()
  1521. } else if index == 5 {
  1522. self.homeVC?.importFromScanner()
  1523. } else if index == 3 {
  1524. self.homeVC?.importFromWebPage()
  1525. } else if index == 2 {
  1526. self.homeVC?.newFromImages()
  1527. }
  1528. }
  1529. // MARK - Event 监听
  1530. private func addEventMonitor() {
  1531. if (self.eventMonitor != nil) {
  1532. self.removeEventMonitor()
  1533. }
  1534. KMPrint("已添加事件监听")
  1535. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
  1536. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  1537. self?.listView.magnifyWheel(event)
  1538. return nil
  1539. }
  1540. return event
  1541. }
  1542. }
  1543. func addKeyEventMonitor() {
  1544. if (self.keyEventMonitor != nil) {
  1545. self.removeKeyEventMonitor()
  1546. }
  1547. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  1548. // print(event.keyCode)
  1549. if event.keyCode == 53 {
  1550. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1551. if let data = self?.canExitPresentation(), data {
  1552. self?.browserWindowController?.exitFullscreen()
  1553. }
  1554. return nil
  1555. }
  1556. if self?.listView.toolMode == .editPDFToolMode {
  1557. if self != nil {
  1558. //使用editingSelectionString获取内容文字
  1559. if self!.listView.editingAreas() != nil {
  1560. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  1561. self!.listView.clearEditingSelectCharItem()
  1562. } else if self!.listView.editingAreas().count > 0 {
  1563. if self?.listView.annotationType == .addImage ||
  1564. self?.listView.annotationType == .addText {
  1565. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1566. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1567. textItem?.isSelected = false
  1568. imageItem?.isSelected = false
  1569. }
  1570. self?.rightSideViewController.isHidden = true
  1571. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  1572. self?.listView.updateEditing([])
  1573. self?.listView.isEditImage = false
  1574. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  1575. if self?.listView.annotationType == .addImage {
  1576. self?.listView.change([.text, .image])
  1577. }
  1578. self?.listView.annotationType = .editTextImage
  1579. self?.closeRightPane()
  1580. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1581. if self?.listView.annotationType == .addImage ||
  1582. self?.listView.annotationType == .addText {
  1583. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1584. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1585. textItem?.isSelected = false
  1586. imageItem?.isSelected = false
  1587. }
  1588. self?.rightSideViewController.isHidden = true
  1589. self?.listView.setShouAddEdit([])
  1590. self?.listView.change([.text, .image])
  1591. self?.listView.annotationType = .editTextImage
  1592. self?.closeRightPane()
  1593. }
  1594. } else {
  1595. if self?.listView.annotationType == .addImage ||
  1596. self?.listView.annotationType == .addText {
  1597. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1598. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1599. textItem?.isSelected = false
  1600. imageItem?.isSelected = false
  1601. }
  1602. }
  1603. }
  1604. }
  1605. } else {
  1606. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1607. self?.listView.keyDown(with: event)
  1608. return nil
  1609. }
  1610. }
  1611. return event
  1612. }
  1613. }
  1614. func removeKeyEventMonitor() {
  1615. if (self.keyEventMonitor != nil) {
  1616. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1617. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1618. self.keyEventMonitor = nil
  1619. }
  1620. }
  1621. private func removeEventMonitor() {
  1622. if (self.eventMonitor != nil) {
  1623. KMPrint("已移除事件监听")
  1624. NSEvent.removeMonitor(self.eventMonitor as Any)
  1625. self.eventMonitor = nil
  1626. }
  1627. }
  1628. // MARK: - Tools
  1629. func pdfViewCanHorizontalScroll() -> Bool {
  1630. let scroll = self.listView.scroll()
  1631. if (scroll == nil) {
  1632. return false
  1633. }
  1634. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1635. }
  1636. func pdfViewCanVerticalScroll() -> Bool {
  1637. let scroll = self.listView.scroll()
  1638. if (scroll == nil) {
  1639. return false
  1640. }
  1641. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1642. }
  1643. // MARK: - Public Methods
  1644. // 清理数据 [eg. 通知]
  1645. public func clearData() {
  1646. self.removeNotifications()
  1647. if (self.listView.spellingTag() > 0) {
  1648. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1649. }
  1650. self.removeAutoSaveInfo()
  1651. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1652. // self.myDocument = nil
  1653. }
  1654. public func clearSecureOptions() {
  1655. self._secureOptions = nil
  1656. self.documentAttribute = nil
  1657. }
  1658. public func recordRemoveSecureFlag() {
  1659. self._removeSecureFlag = true
  1660. self.clearSecureOptions()
  1661. self.recordIsPDFDocumentEdited(type: .removePassword)
  1662. self._needSave = true
  1663. }
  1664. public func clearRemoveSecureFlag() {
  1665. self._removeSecureFlag = false
  1666. }
  1667. public func clearSaveWatermarkFlag() {
  1668. km_synchronized(self) {
  1669. self._saveWatermarkFlag = false
  1670. }
  1671. }
  1672. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1673. km_synchronized(self) {
  1674. self.model.isPDFDocumentEdited = true
  1675. if let _document = self.myDocument {
  1676. KMTools.setDocumentEditedState(document: _document)
  1677. }
  1678. }
  1679. }
  1680. public func clearIsPDFDocumentEdited() {
  1681. km_synchronized(self) {
  1682. self.model.isPDFDocumentEdited = false
  1683. }
  1684. }
  1685. func showSnapshots(setups: NSArray?) {
  1686. for setup in setups ?? [] {
  1687. let swc = KMSnapshotWindowController()
  1688. swc.delegate = self
  1689. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  1690. swc.setForceOnTop(self.interactionMode != .normal)
  1691. self.myDocument?.addWindowController(swc)
  1692. }
  1693. }
  1694. func dealDocumentDidLoaded() {
  1695. self.removeBackgroundMaskView()
  1696. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1697. self.showSecureLimitTip()
  1698. }
  1699. if self.model.needConvertNotes {
  1700. self.showConvertNotesProgress()
  1701. }
  1702. if (self._documentFirstLoad) {
  1703. self.checkShouldAutoOpenLeftVC()
  1704. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1705. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1706. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1707. if (pageScale != nil) {
  1708. self.listView.scaleFactor = CGFloat(pageScale!)
  1709. }
  1710. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1711. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1712. } else {
  1713. self._goToFirstPageForFristAppear()
  1714. }
  1715. } else {
  1716. self._goToFirstPageForFristAppear()
  1717. }
  1718. self._documentFirstLoad = false
  1719. }
  1720. }
  1721. func tabViewIsDragging() -> Bool {
  1722. let level = self.view.window?.level ?? .normal
  1723. return level == .floating
  1724. }
  1725. // MARK: - Noti Actions
  1726. internal func documentDidUnlockNotification(_ sender: Notification) {
  1727. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1728. if (self.myDocument == nil) {
  1729. return
  1730. }
  1731. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1732. self.hiddenSecureLimitTip()
  1733. }
  1734. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  1735. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  1736. return
  1737. }
  1738. let type = KMPreferenceManager.shared.savePasswordType
  1739. if (type == .never) {
  1740. return
  1741. }
  1742. if (type == .always) {
  1743. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1744. return
  1745. }
  1746. // 保存到钥匙串
  1747. let alert = NSAlert()
  1748. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1749. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1750. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1751. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1752. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1753. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1754. return
  1755. }
  1756. }
  1757. }
  1758. func annotationsAttributeHasChange(_ sender: Notification) {
  1759. guard let dict = sender.object as? [String : Any] else {
  1760. return
  1761. }
  1762. if let anno = dict["object"] as? CPDFAnnotation {
  1763. let value = dict["keyPath"] as? String ?? ""
  1764. let didEnd = dict["didEnd"] as? Bool ?? false
  1765. if didEnd {
  1766. if value == CPDFAnnotationBoundsKey {
  1767. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  1768. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  1769. }
  1770. }
  1771. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1772. } else {
  1773. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  1774. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1775. }
  1776. }
  1777. }
  1778. }
  1779. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1780. self.savePageNumberIfNeed()
  1781. self.saveDocument()
  1782. }
  1783. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1784. if self.isReadMode {
  1785. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1786. }
  1787. //刷新前一页后一页按钮
  1788. self.updateNextAndPreViousButtonState()
  1789. }
  1790. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1791. if self.isReadMode {
  1792. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1793. }
  1794. //刷新前一页后一页按钮
  1795. self.updateNextAndPreViousButtonState()
  1796. }
  1797. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1798. var editSelectd = false
  1799. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1800. editSelectd = true
  1801. }
  1802. if self.listView.toolMode == .editPDFToolMode {
  1803. if editSelectd {
  1804. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1805. }
  1806. }
  1807. }
  1808. @objc func handlePageChangedNotification(_ sender: Notification) {
  1809. // When the PDFView is changing scale, or when view settings change when switching fullscreen modes,
  1810. // a lot of wrong page change notifications may be send, which we better ignore.
  1811. // Full screen switching and zooming should not change the current page anyway.
  1812. if self.mwcFlags.isSwitchingFullScreen > 0 {
  1813. // if ([pdfView isZooming] || mwcFlags.isSwitchingFullScreen) {
  1814. // [self updatePageNumber];
  1815. // [self updateLeftStatus];
  1816. return
  1817. }
  1818. //
  1819. let page = self.listView.currentPage()
  1820. let pageIndex = page?.pageIndex() ?? 0
  1821. //
  1822. // if ([lastViewedPages count] == 0) {
  1823. // [lastViewedPages addPointer:(void *)pageIndex];
  1824. // } else if ((NSUInteger)[lastViewedPages pointerAtIndex:0] != pageIndex) {
  1825. // [lastViewedPages insertPointer:(void *)pageIndex atIndex:0];
  1826. // if ([lastViewedPages count] > 5)
  1827. // [lastViewedPages setCount:5];
  1828. // }
  1829. self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
  1830. self.leftSideViewController.thumbnailTableView.needsDisplay = true
  1831. self.leftSideViewController.tocOutlineView.needsDisplay = true
  1832. //
  1833. // [self updatePageNumber];
  1834. // [self updatePageLabel];
  1835. //
  1836. // [self updateOutlineSelection];
  1837. // [self updateNoteSelection];
  1838. // [self updateThumbnailSelection];
  1839. //
  1840. // if (beforeMarkedPageIndex != NSNotFound && [[pdfView currentPage] pageIndex] != markedPageIndex)
  1841. // beforeMarkedPageIndex = NSNotFound;
  1842. //
  1843. // [self synchronizeWindowTitleWithDocumentName];
  1844. // [self updateLeftStatus];
  1845. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  1846. // [self updateRightStatus];
  1847. // if ([self interactionMode] == SKPresentationMode)
  1848. // [[self presentationNotesDocument] setCurrentPage:[[[self presentationNotesDocument] pdfDocument] pageAtIndex:[page pageIndex]]];
  1849. }
  1850. @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
  1851. self.leftSideViewController.reloadThumbnailDataIfNeed()
  1852. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  1853. // [self updateRightStatus];
  1854. }
  1855. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  1856. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1857. return
  1858. }
  1859. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  1860. if interactionMode == .presentation {
  1861. let backgroundColor = NSColor.black
  1862. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  1863. let wasInteractionMode = self.interactionMode
  1864. if wasInteractionMode == .normal {
  1865. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  1866. }
  1867. // if findController.view().window() != nil {
  1868. // findController.toggleAboveView(nil, animate: false)
  1869. // }
  1870. if wasInteractionMode == .legacyFullScreen {
  1871. self.enterPresentationMode()
  1872. // updatePresentationOptions(for: self.view.window!)
  1873. self.pdfSplitView.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(centerContentView.bounds), height: CGRectGetHeight(centerContentView.bounds)-1)
  1874. self.centerContentView.addSubview(pdfSplitView)
  1875. self.listView.frame = (self.view.window?.contentView?.bounds)!
  1876. self.view.window?.contentView?.addSubview(listView)
  1877. self.view.window?.backgroundColor = backgroundColor
  1878. self.view.window?.level = level
  1879. self.listView.layoutDocumentView()
  1880. self.listView.requiresDisplay()
  1881. self.forceSubwindowsOnTop(false)
  1882. self.hideLeftSideWindow()
  1883. self.hideRightSideWindow()
  1884. self.removeBlankingWindows()
  1885. }
  1886. } else {
  1887. KMPrint("2")
  1888. }
  1889. }
  1890. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  1891. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1892. return
  1893. }
  1894. if self.interactionMode == .presentation {
  1895. // if self.pdfView().currentPage()?.isEqual(page) == false {
  1896. // self.pdfView().go(to: page)
  1897. // }
  1898. // pdfView().setInteractionMode(SKPresentationMode)
  1899. self.listView?.layoutDocumentView()
  1900. self.listView?.requiresDisplay()
  1901. }
  1902. }
  1903. @objc func willShowFullScreenNotification(_ sender: Notification) {
  1904. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1905. return
  1906. }
  1907. if self.interactionMode == .presentation {
  1908. let view = self.view.window?.firstResponder as? NSView
  1909. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  1910. self.view.window?.makeFirstResponder(nil)
  1911. }
  1912. }
  1913. }
  1914. @objc func didShowFullScreenNotification(_ sender: Notification) {
  1915. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1916. return
  1917. }
  1918. if self.interactionMode == .presentation {
  1919. self.enterPresentationMode()
  1920. }
  1921. }
  1922. @objc func didAddContentViewNotification(_ sender: Notification) {
  1923. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1924. return
  1925. }
  1926. if self.interactionMode == .presentation {
  1927. }
  1928. }
  1929. @objc func purchaseStateUpdateNoti() {
  1930. if IAPProductsManager.default().isAvailableAllFunction() {
  1931. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1932. }
  1933. }
  1934. // MARK: Split View
  1935. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  1936. let openPanel = NSOpenPanel()
  1937. openPanel.allowedFileTypes = ["pdf", "PDF"]
  1938. openPanel.allowsMultipleSelection = false
  1939. guard let mainWindow = NSApp.mainWindow else {
  1940. return
  1941. }
  1942. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  1943. if response == NSApplication.ModalResponse.OK {
  1944. guard let url = openPanel.url else {
  1945. return
  1946. }
  1947. if let document = CPDFDocument(url: url) {
  1948. self?.secondaryPdfView?.document = nil
  1949. self?.secondaryPdfView?.document = document
  1950. if isChange {
  1951. self!.openSecondaryPdfView!.view.removeFromSuperview()
  1952. }
  1953. replaceBlock(document.documentURL?.path ?? "")
  1954. } else {
  1955. let alert = NSAlert()
  1956. alert.alertStyle = .critical
  1957. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1958. alert.runModal()
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. extension KMMainViewController {
  1965. func currentSetup() -> [String: Any] {
  1966. var setup: [String: Any] = [:]
  1967. var point = NSZeroPoint
  1968. // var rotated = listView.currentPage().rotation
  1969. if listView == nil {
  1970. return setup
  1971. }
  1972. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  1973. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  1974. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  1975. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  1976. setup[KMMainModel.Key.pageIndex] = pageIndex
  1977. // if rotated != 0 {
  1978. // setup[SCROLLPOINT_KEY] = NSStringFromPoint(point)
  1979. // }
  1980. // if !snapshots.isEmpty {
  1981. // setup[SNAPSHOTS_KEY] = snapshots.map { $0[SKSnapshotCurrentSetupKey] }
  1982. // }
  1983. // if interactionMode == SKNormalMode {
  1984. // setup.merge(currentPDFSettings(), uniquingKeysWith: { $1 })
  1985. // } else {
  1986. // setup.merge(savedNormalSetup, uniquingKeysWith: { $1 })
  1987. // ["HASHORIZONTALSCROLLER_KEY", "HASVERTICALSCROLLER_KEY", "AUTOHIDESSCROLLERS_KEY", "LOCKED_KEY"].forEach { setup.removeValue(forKey: $0) }
  1988. // }
  1989. return setup
  1990. }
  1991. // MARK: - Recommond活动
  1992. func loadRecommondPopWindow() {
  1993. if IAPProductsManager.default().isAvailableAllFunction() {
  1994. return
  1995. }
  1996. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  1997. if recommondPopWindowVC == nil {
  1998. recommondPopWindowVC = KMRecommondPopWindow()
  1999. }
  2000. recommondPopWindowVC?.recommondInfo = info
  2001. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  2002. return
  2003. }
  2004. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  2005. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  2006. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  2007. recommondPopWindowVC?.window?.orderFront((Any).self)
  2008. recommondPopWindowVC?.window?.becomeMain()
  2009. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  2010. UserDefaults.standard.synchronize()
  2011. }
  2012. }
  2013. }