KMMainViewController.swift 98 KB

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