KMMainViewController.swift 100 KB

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