KMMainViewController.swift 98 KB

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