KMMainViewController.swift 91 KB

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