KMMainViewController.swift 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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 = { 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 = {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 {
  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. }
  661. windowVC.eventLabel = "AITools_Tbr"
  662. windowVC.showWindow(nil)
  663. if (aiConfigType != .none) {
  664. windowVC.eventLabel = "AITools_Start"
  665. if self.listView.currentSelection.string().isEmpty == false {
  666. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  667. }
  668. windowVC.chooseAIFunctionWithType(aiConfigType)
  669. }
  670. }
  671. @objc func aiTipIconViewShowStateChangeNoti() {
  672. self.updateAITipViewShowState()
  673. }
  674. //MARK: - 引导
  675. func loadFunctionGuide() -> Void {
  676. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  677. if self.view.window != nil {
  678. self.loadOpenFileFunctionGuide(.openFileNormal)
  679. }
  680. }
  681. }
  682. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  683. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  684. let leftPanelItem:KMToolbarItemView = self.toolbarController.findItem("KMLeftControlToolbarItemIdentifier")!
  685. let guideWC = KMGuideInfoWindowController.currentWC()
  686. guideWC.type = .openFileNormal
  687. guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? CGRectZero
  688. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  689. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  690. let rightPanelItem = self?.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  691. let digitalPanelItem = self?.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)
  692. windowVC.rightPanelRect = (self!.view.window?.contentView?.convert(rightPanelItem?.frame ?? .zero, from: rightPanelItem?.superview)) ?? .zero
  693. guideWC.digitalBoxRect = (self!.view.window?.contentView?.convert(digitalPanelItem?.frame ?? .zero, from: digitalPanelItem?.superview)) ?? .zero
  694. }
  695. guideWC.finishHandle = { [weak self] windowVC, type in
  696. if type == .windowNewFinish ||
  697. type == . windowDigitalFinish {
  698. self?.checkFirstTrialController()
  699. }
  700. }
  701. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  702. self?.checkFirstTrialController()
  703. }
  704. var rect = self.view.window!.frame
  705. rect.size.height -= 20
  706. guideWC.window?.setFrame(rect, display: false)
  707. guideWC.window?.minSize = rect.size
  708. guideWC.window?.maxSize = rect.size
  709. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  710. guideWC.show()
  711. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  712. let guideWC = KMGuideInfoWindowController.currentWC()
  713. guideWC.type = .digitalSignGuide
  714. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  715. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  716. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  717. guideWC.finishHandle = { [weak self] windowVC, type in
  718. self?.checkFirstTrialController()
  719. }
  720. var rect = self.view.window!.frame
  721. rect.size.height -= 20
  722. guideWC.window?.setFrame(rect, display: false)
  723. guideWC.window?.minSize = rect.size
  724. guideWC.window?.maxSize = rect.size
  725. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  726. guideWC.show()
  727. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  728. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  729. let guideWC = KMGuideInfoWindowController.currentWC()
  730. guideWC.type = .pdfCompareGuide
  731. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  732. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  733. let compareItem:KMToolbarItemView = self.toolbarController.findItem(KMToolbarComparisonItemIdentifier)!
  734. guideWC.compareItemRect = (self.view.window?.contentView?.convert(compareItem.frame, from: compareItem.superview))!
  735. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  736. var rect = self.view.window!.frame
  737. rect.size.height -= 20
  738. guideWC.window?.setFrame(rect, display: false)
  739. guideWC.window?.minSize = rect.size
  740. guideWC.window?.maxSize = rect.size
  741. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  742. guideWC.show()
  743. }
  744. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  745. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  746. let guideWC = KMGuideInfoWindowController.currentWC()
  747. guideWC.type = .convertGuide
  748. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  749. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  750. guideWC.purchaseHandle = { [weak self] windowVC in
  751. #if VERSION_DMG
  752. if IAPProductsManager.default().isAvailableAllFunction() {
  753. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  754. //Convert:
  755. self?.showAllConvertWindow(convertT: .Word)
  756. } else {
  757. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  758. limitWC.continueBlock = { windowController in
  759. }
  760. limitWC.window?.center()
  761. limitWC.showWindow(nil)
  762. }
  763. } else {
  764. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  765. }
  766. #else
  767. if IAPProductsManager.default().isAvailableAllFunction() {
  768. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  769. //Convert:
  770. } else {
  771. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  772. vc.showWindow(nil)
  773. }
  774. } else {
  775. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  776. }
  777. #endif
  778. }
  779. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  780. var rect = self.view.window!.frame
  781. rect.size.height -= 20
  782. guideWC.window?.setFrame(rect, display: false)
  783. guideWC.window?.minSize = rect.size
  784. guideWC.window?.maxSize = rect.size
  785. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  786. guideWC.show()
  787. }
  788. } else {
  789. }
  790. }
  791. func checkFirstTrialController() -> Void {
  792. #if VERSION_DMG
  793. //打开文档后引导相关
  794. if VerificationManager.default().status == .none {
  795. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  796. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  797. if lastVersion.isEmpty || lastVersion != appVersion {
  798. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  799. UserDefaults.standard.synchronize()
  800. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  801. }
  802. }
  803. #endif
  804. }
  805. // MARK: - 页面编辑
  806. open func enterPageEdit(_ pages: [Int] = []) {
  807. if let doc = self.listView?.document {
  808. if doc.allowsCopying == false || doc.allowsPrinting == false {
  809. KMBaseWindowController.checkPassword(url: doc.documentURL, type: .owner) { result, pwd in
  810. if result && pwd.isEmpty == false {
  811. self.listView?.document?.unlock(withPassword: pwd)
  812. Task { @MainActor in
  813. self.enterPageEdit(pages)
  814. }
  815. } else {
  816. self.exitPageEdit()
  817. }
  818. }
  819. return
  820. }
  821. }
  822. //选中page
  823. var tPages = pages
  824. if tPages.count == 0 {
  825. tPages = self.leftSideViewController.thumb_fetchSelectedRows() ?? [self.listView.currentPageIndex]
  826. }
  827. if (hasEnterPageEdit()) {
  828. exitPageEdit()
  829. return
  830. }
  831. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  832. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  833. for (key, value) in toolBarView.toolbarItems {
  834. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  835. (value as! KMToolbarItemView).unEnabled = true
  836. }
  837. }
  838. }
  839. let controller = KMPDFEditViewController(self.listView.document)
  840. controller.selectedPages = tPages
  841. controller.listView = self.listView
  842. self.addChild(controller)
  843. self.PDFContendView.addSubview(controller.view)
  844. controller.view.frame = self.PDFContendView.bounds
  845. controller.view.autoresizingMask = [.width,.height]
  846. self.listView.isHidden = true
  847. controller.itemClick = { [weak self] index, params in
  848. if (index == 1) { /// 双击退出
  849. self?.enterEditMode(self!.leftSideViewController, [])
  850. DispatchQueue.main.async {
  851. let pageIndex: Int = params.first as! Int
  852. self?.listView.go(toPageIndex: pageIndex, animated: true)
  853. }
  854. } else if (index == 2) { // 打印
  855. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  856. }
  857. }
  858. controller.documentEditedCallback = { [weak self] params in
  859. self?.recordIsPDFDocumentEdited()
  860. }
  861. controller.selectionDidChange = { selectedIndexs in
  862. var indexSet = IndexSet()
  863. for indexPath in selectedIndexs {
  864. indexSet.insert(indexPath.item)
  865. }
  866. if indexSet.count != 0 {
  867. // self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
  868. // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
  869. }
  870. }
  871. }
  872. open func exitPageEdit() {
  873. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  874. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  875. for (key, value) in toolBarView.toolbarItems {
  876. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  877. (value as! KMToolbarItemView).unEnabled = false
  878. }
  879. }
  880. }
  881. self.toolbarController.findItem(KMDocumentPageToolbarItemIdentifier)?.isSelected = false
  882. let editController = getPDFEditController()
  883. if (editController == nil) {
  884. return
  885. }
  886. self.listView.annotationType = .highlight
  887. editController?.view.removeFromSuperview()
  888. editController?.removeFromParent()
  889. self.listView.isHidden = false
  890. self.listView.layoutDocumentView()
  891. self.view.window?.makeFirstResponder(self.listView)
  892. self.listView.annotationType = .unkown
  893. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  894. if let data = editController?.isEdited, data {
  895. self.leftSideViewController.reloadThumbnailDataIfNeed()
  896. }
  897. }
  898. open func hasEnterPageEdit() -> Bool {
  899. return self.getPDFEditController() != nil
  900. }
  901. // MARK: - Private Methods
  902. private func getPDFEditController() -> KMPDFEditViewController? {
  903. var editController: KMPDFEditViewController?
  904. for controller in self.children {
  905. if (controller.isKind(of: KMPDFEditViewController.self)) {
  906. editController = (controller as! KMPDFEditViewController)
  907. break
  908. }
  909. }
  910. return editController
  911. }
  912. private func _getPDFRedactController() -> KMPDFRedactViewController? {
  913. var controller: KMPDFRedactViewController?
  914. for childC in self.children {
  915. if (childC.isKind(of: KMPDFRedactViewController.self)) {
  916. controller = (childC as! KMPDFRedactViewController)
  917. break
  918. }
  919. }
  920. return controller
  921. }
  922. private func addBackgroundMaskView() {
  923. self.removeBackgroundMaskView()
  924. if let superview = self.mianSplitView.superview {
  925. let view = NSView()
  926. superview.addSubview(view)
  927. view.frame = superview.bounds
  928. view.autoresizingMask = [.width, .height]
  929. view.wantsLayer = true
  930. view.layer?.backgroundColor = .white
  931. self.background_mask = view
  932. }
  933. }
  934. private func removeBackgroundMaskView() {
  935. self.background_mask?.removeFromSuperview()
  936. self.background_mask = nil
  937. }
  938. private func _goToFirstPageForFristAppear() {
  939. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  940. self.listView.go(toPageIndex: 0, animated: false)
  941. }
  942. }
  943. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  944. let url = URL(fileURLWithPath: filePath)
  945. guard let document = PDFDocument(url: url) else {
  946. return false
  947. }
  948. let pageCount = document.pageCount
  949. return pageCount > 30
  950. }
  951. // MARK: - Redact 【标记密文】
  952. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  953. let windowController = KMRedactConfirmWindowController(type)
  954. self.currentWindowController = windowController
  955. self.view.window?.beginSheet(windowController.window!)
  956. windowController.itemClick = { [weak self] index in
  957. if (index == 2) { /// 取消
  958. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  959. self?.currentWindowController = nil
  960. callback()
  961. return
  962. }
  963. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  964. self?.currentWindowController = nil
  965. let panel = NSSavePanel()
  966. panel.nameFieldStringValue = "[新文件]"+(self?.listView.document.documentURL.lastPathComponent)!
  967. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  968. button.state = .on
  969. panel.accessoryView = button
  970. panel.isExtensionHidden = true
  971. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  972. if response != .OK {
  973. callback()
  974. return
  975. }
  976. if (type == .redactOne) {
  977. let anno = self!.listView.activeAnnotation
  978. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  979. callback()
  980. return
  981. }
  982. (anno as! CPDFRedactAnnotation).applyRedaction()
  983. } else if (type == .redactAll) {
  984. self?.listView.document.applyRedactions()
  985. } else if (type == .eraserOne) {
  986. let anno = self!.listView.activeAnnotation
  987. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  988. callback()
  989. return
  990. }
  991. anno?.page.erasureRedact(from: anno!.bounds)
  992. } else if (type == .eraserAll) {
  993. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  994. if (result == false) {
  995. callback()
  996. return
  997. }
  998. }
  999. }
  1000. self!.listView.document.write(to: panel.url)
  1001. if (button.state == .on) {
  1002. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  1003. }
  1004. } else {
  1005. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  1006. }
  1007. callback()
  1008. }
  1009. }
  1010. }
  1011. // MARK: - Secure 【安全】
  1012. public func showSecureLimitTip() {
  1013. self.hiddenSecureLimitTip()
  1014. if self.secureAlertView == nil {
  1015. self.secureAlertView = KMSecureAlertView()
  1016. self.secureAlertView?.show(in: self.listView)
  1017. self.secureAlertView?.closeAction = { [unowned self] view in
  1018. self.hiddenSecureLimitTip()
  1019. self.removeFromAlertView()
  1020. self.showFormAlertView()
  1021. }
  1022. self.secureAlertView?.passwordAction = { [unowned self] view in
  1023. self.removeOwnerPassword()
  1024. self.removeFromAlertView()
  1025. self.showFormAlertView()
  1026. }
  1027. }
  1028. }
  1029. func removeOwnerPassword() {
  1030. guard let doc = self.listView?.document else {
  1031. NSSound.beep()
  1032. return
  1033. }
  1034. if doc.allowsCopying && doc.allowsPrinting {
  1035. NSSound.beep()
  1036. return
  1037. }
  1038. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1039. if result == .cancel { /// 关闭
  1040. return
  1041. }
  1042. /// 解密成功
  1043. self?.hiddenSecureLimitTip()
  1044. self?.model.isSaveKeyChain = false
  1045. self?.listView.document.unlock(withPassword: password)
  1046. }
  1047. }
  1048. public func hiddenSecureLimitTip() {
  1049. self.secureAlertView?.removeFromSuperview()
  1050. self.secureAlertView = nil
  1051. }
  1052. //MARK: - Form
  1053. func showFormAlertView() {
  1054. if (formAlertView == nil) {
  1055. formAlertView = KMFormAlertView()
  1056. formAlertView?.isCloseSecureView = self.secureAlertView != nil ? false : true
  1057. formAlertView?.showInView(self.listView)
  1058. } else {
  1059. self.removeFromAlertView()
  1060. }
  1061. }
  1062. func removeFromAlertView() {
  1063. formAlertView?.removeFromSuperview()
  1064. formAlertView = nil
  1065. }
  1066. override func mouseMoved(with event: NSEvent) {
  1067. self.view.window?.mouseMoved(with: event)
  1068. }
  1069. func savePageNumberIfNeed() {
  1070. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1071. let scaleFactor = self.listView?.scaleFactor ?? 0
  1072. if scaleFactor <= 0 {
  1073. return
  1074. }
  1075. if self.listView.document != nil {
  1076. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1077. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  1078. }
  1079. }
  1080. }
  1081. // MARK: - 显示合并窗口
  1082. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  1083. DispatchQueue.main.async {
  1084. var documentURL = url
  1085. if documentURL == nil {
  1086. documentURL = self.listView.document.documentURL
  1087. }
  1088. guard let _url = documentURL else { return }
  1089. guard let document = PDFDocument(url: _url) else { return }
  1090. let windowController = KMMergeWindowController(document: document, password: password ?? "")
  1091. windowController.oriDucumentUrl = self.listView.document.documentURL
  1092. windowController.pageIndex = self.listView.currentPageIndex
  1093. self.currentWindowController = windowController
  1094. windowController.cancelAction = { [unowned self] controller in
  1095. self.view.window?.endSheet((self.currentWindowController.window)!)
  1096. self.currentWindowController = nil
  1097. }
  1098. windowController.mergeAction = { [unowned self] controller, filePath in
  1099. self.view.window?.endSheet((self.currentWindowController.window)!)
  1100. self.currentWindowController = nil
  1101. // let newDocument = CPDFDocument(url: NSURL(fileURLWithPath: filePath) as URL)
  1102. // if let data = newDocument?.isLocked, data {
  1103. // newDocument?.unlock(withPassword: self.listView.document.password ?? "")
  1104. // }
  1105. //
  1106. // self.setDocument = newDocument
  1107. // self.leftSideViewController.refreshUIForDocumentChanged()
  1108. }
  1109. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  1110. self.view.window?.beginSheet(windowController.window!)
  1111. }
  1112. }
  1113. // MARK: - 显示加密弹窗
  1114. public func showSecureWindow(_ url: URL) {
  1115. let controller = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1116. controller.documentURL = self.listView.document.documentURL
  1117. self.currentWindowController = controller
  1118. controller.batchAction = { [unowned self] controller, files in
  1119. self.view.window?.endSheet((self.currentWindowController.window)!)
  1120. self.currentWindowController = nil
  1121. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1122. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1123. // batchWindowController.window?.makeKeyAndOrderFront("")
  1124. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  1125. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  1126. batchWindowController.window?.makeKeyAndOrderFront("")
  1127. }
  1128. controller.doneAction = { [unowned self] controller, options, attribute in
  1129. // let windowController_secure = self.currentWindowController as! KMSecureEncryptWindowController
  1130. let openPanel = NSOpenPanel()
  1131. openPanel.canChooseFiles = false
  1132. openPanel.canChooseDirectories = true
  1133. openPanel.canCreateDirectories = true
  1134. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1135. if result == NSApplication.ModalResponse.OK {
  1136. for fileURL in openPanel.urls {
  1137. let document = CPDFDocument(url: self.document?.documentURL)
  1138. if document != nil {
  1139. document!.setDocumentAttributes(attribute)
  1140. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1141. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1142. if success {
  1143. self.view.window?.endSheet((self.currentWindowController.window)!)
  1144. self.currentWindowController = nil
  1145. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1146. }
  1147. }
  1148. }
  1149. }
  1150. }
  1151. }
  1152. controller.cancelAction = { [unowned self] controller in
  1153. self.view.window?.endSheet((self.currentWindowController.window)!)
  1154. self.currentWindowController = nil
  1155. }
  1156. NSWindow.currentWindow().beginSheet(controller.window!)
  1157. }
  1158. // MARK: - 保存文档
  1159. internal func needSaveDocument() -> Bool {
  1160. if (self.isPDFDocumentEdited) {
  1161. return self.isPDFDocumentEdited
  1162. }
  1163. if (self.needSave) {
  1164. return self.needSave
  1165. }
  1166. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1167. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1168. return false
  1169. }
  1170. return true
  1171. }
  1172. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  1173. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1174. if (overlook) {
  1175. document?.save(nil)
  1176. return
  1177. }
  1178. if (self.isPDFDocumentEdited) {
  1179. self.clearIsPDFDocumentEdited()
  1180. self.needSave = false
  1181. document?.save(nil)
  1182. return
  1183. }
  1184. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1185. return
  1186. }
  1187. document?.save(nil)
  1188. }
  1189. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  1190. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1191. if (overlook) {
  1192. DispatchQueue.main.async {
  1193. document?.save(nil)
  1194. callback()
  1195. }
  1196. return
  1197. }
  1198. if (self.isPDFDocumentEdited) {
  1199. self.clearIsPDFDocumentEdited()
  1200. self.needSave = false
  1201. DispatchQueue.main.async {
  1202. document?.save(nil)
  1203. callback()
  1204. }
  1205. return
  1206. }
  1207. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1208. callback()
  1209. return
  1210. }
  1211. DispatchQueue.main.async {
  1212. document?.save(nil)
  1213. callback()
  1214. }
  1215. }
  1216. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  1217. // 显示进度
  1218. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  1219. self.progressC?.maxValue = 3.0
  1220. self.progressC?.increment(by: 1.0)
  1221. // 保存文档
  1222. self.asyncSaveDocument { [unowned self] params in
  1223. // 执行进度 [假进度]
  1224. self.progressC?.increment(by: 1.0)
  1225. self.progressC?.increment(by: 1.0)
  1226. // DispatchQueue.main.async {
  1227. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  1228. // 隐藏进度
  1229. self.hiddenProgressWindow()
  1230. // 回调
  1231. callback()
  1232. }
  1233. }
  1234. }
  1235. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  1236. self.document?.write(toFile: tempPath)
  1237. }
  1238. // MARK: - 定时保存
  1239. func addAutoSaveEvent() {
  1240. if (self.autoSaveTimer != nil) {
  1241. self.autoSaveTimer?.invalidate()
  1242. self.autoSaveTimer = nil
  1243. }
  1244. if self.document != nil {
  1245. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  1246. self?.autoSaveTimerAction(timer)
  1247. })
  1248. }
  1249. self.checkAutoSaveInfo()
  1250. }
  1251. func checkAutoSaveInfo() {
  1252. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  1253. return
  1254. }
  1255. if AutoSaveManager.manager.autoSaveAlertShow {
  1256. return
  1257. }
  1258. AutoSaveManager.manager.autoSaveDidEndAction = false
  1259. AutoSaveManager.manager.autoSaveAlertShow = true
  1260. let blockSaveWindow = AutoSavePopController()
  1261. blockSaveWindow.cancelHandle = { [weak self] windowController in
  1262. AutoSaveManager.manager.autoSaveDidEndAction = true
  1263. AutoSaveManager.manager.clearCache()
  1264. self?.km_quick_endSheet()
  1265. }
  1266. blockSaveWindow.confirmHandle = { [weak self] windowController in
  1267. self?.km_quick_endSheet()
  1268. self?.saveAutoSaveInfo()
  1269. }
  1270. self.km_beginSheet(windowC: blockSaveWindow)
  1271. }
  1272. func saveAutoSaveInfo() {
  1273. let openPanel = NSOpenPanel()
  1274. openPanel.canChooseDirectories = true
  1275. openPanel.canChooseFiles = false
  1276. openPanel.allowsMultipleSelection = false
  1277. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  1278. openPanel.beginSheetModal(for: win!) { result in
  1279. if (result == .OK) {
  1280. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  1281. for path in AutoSaveManager.manager.opendPaths ?? [] {
  1282. let _path = path as? String
  1283. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  1284. newPath = self.getValidFilePath(newPath)
  1285. do {
  1286. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  1287. } catch {
  1288. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  1289. }
  1290. }
  1291. AutoSaveManager.manager.clearCache()
  1292. }
  1293. AutoSaveManager.manager.autoSaveDidEndAction = true
  1294. }
  1295. }
  1296. func autoSaveTimerAction(_ timer: Timer) {
  1297. if (self.document == nil || self.listView?.document?.documentURL.path == nil) {
  1298. return
  1299. }
  1300. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1301. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1302. return
  1303. }
  1304. if let data = self.document?.isLocked, data {
  1305. return
  1306. }
  1307. if AutoSaveManager.manager.autoSaveEnabled == false {
  1308. return
  1309. }
  1310. let documentArray = NSDocumentController.shared.documents
  1311. var didFileEdit = false
  1312. for doc in documentArray {
  1313. if doc.fileURL?.path == self.document?.documentURL.path {
  1314. didFileEdit = doc.isDocumentEdited
  1315. break
  1316. }
  1317. }
  1318. if (didFileEdit == false) {
  1319. return
  1320. }
  1321. AutoSaveManager.manager.isSaving = true
  1322. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView?.document?.documentURL.path ?? "")
  1323. if (!self.document!.isLocked) {
  1324. self.document?.write(to: URL(fileURLWithPath: savePath))
  1325. }
  1326. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  1327. AutoSaveManager.manager.isSaving = false
  1328. }
  1329. }
  1330. func removeAutoSaveInfo() {
  1331. if self.autoSaveTimer != nil {
  1332. self.autoSaveTimer?.invalidate()
  1333. self.autoSaveTimer = nil
  1334. }
  1335. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1336. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1337. return
  1338. }
  1339. if AutoSaveManager.manager.autoSaveEnabled == false {
  1340. return
  1341. }
  1342. if self.document == nil || self.listView?.document?.documentURL.path == nil {
  1343. return
  1344. }
  1345. AutoSaveManager.manager.removeAutoSavePath(self.listView?.document?.documentURL.path ?? "")
  1346. }
  1347. // MARK: - 选择 PDFDisplay 模式
  1348. @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
  1349. let toolModel = self.listView.toolMode
  1350. self.isReadMode = false
  1351. switch display {
  1352. case .singlePage:
  1353. self.listView.setDisplay(.singlePage)
  1354. break
  1355. case .singlePageContinuous:
  1356. self.listView.setDisplay(.singlePageContinuous)
  1357. break
  1358. case .twoUp:
  1359. self.listView.setDisplay(.twoUp)
  1360. break
  1361. case .twoUpContinuous:
  1362. self.listView.setDisplay(.twoUpContinuous)
  1363. break
  1364. case .bookMode:
  1365. self.listView.displaysAsBook = true
  1366. self.listView.displayTwoUp = true
  1367. self.listView.displayDirection = .horizontal
  1368. break
  1369. case .bookContinuous:
  1370. self.listView.displaysAsBook = true
  1371. self.listView.displayTwoUp = true
  1372. self.listView.displayDirection = .vertical
  1373. break
  1374. case .readModel:
  1375. self.openReadModel()
  1376. break
  1377. case .readContinuous:
  1378. self.openReadModel()
  1379. break
  1380. }
  1381. self.listView.layoutDocumentView()
  1382. // if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
  1383. // self.leftSideViewController.panelSetViewController.reloadListViewModel()
  1384. // }
  1385. if (toolModel == .editPDFToolMode) {
  1386. if self.rightSideViewController.eidtPDFImageProperty != nil {
  1387. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  1388. self.rightSideViewController.isHidden = true
  1389. self.closeRightPane()
  1390. }
  1391. }
  1392. }
  1393. // MARK: - 选择缩放模式
  1394. @objc public func selectZoom(_ type: KMPDFZoomType) {
  1395. switch type {
  1396. case .width:
  1397. self.listView.autoScales = true
  1398. // self.listView.autoScales = false
  1399. break
  1400. case .fit:
  1401. // self.listView.autoScales = !self.listView.autoScales
  1402. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  1403. let pdfviewHeight = self.listView.bounds.size.height
  1404. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1405. self.listView.autoScales = false
  1406. }
  1407. break
  1408. case .actualSize:
  1409. if self.listView.scaleFactor != 1.0 {
  1410. self.listView.scaleFactor = 1.0
  1411. self.listView.autoScales = false
  1412. }
  1413. break
  1414. }
  1415. }
  1416. internal func createPdf(index:Int) {
  1417. if index == 1 {
  1418. self.homeVC?.openBlankPage()
  1419. } else if index == 4 {
  1420. self.homeVC?.importFromCamera()
  1421. } else if index == 5 {
  1422. self.homeVC?.importFromScanner()
  1423. } else if index == 3 {
  1424. self.homeVC?.importFromWebPage()
  1425. } else if index == 2 {
  1426. self.homeVC?.newFromImages()
  1427. }
  1428. }
  1429. // MARK - Event 监听
  1430. private func addEventMonitor() {
  1431. if (self.eventMonitor != nil) {
  1432. self.removeEventMonitor()
  1433. }
  1434. KMPrint("已添加事件监听")
  1435. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
  1436. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  1437. self?.listView.magnifyWheel(event)
  1438. return nil
  1439. }
  1440. return event
  1441. }
  1442. }
  1443. func addKeyEventMonitor() {
  1444. if (self.keyEventMonitor != nil) {
  1445. self.removeKeyEventMonitor()
  1446. }
  1447. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  1448. // print(event.keyCode)
  1449. if event.keyCode == 53 {
  1450. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1451. if let data = self?.canExitPresentation(), data {
  1452. self?.browserWindowController?.exitFullscreen()
  1453. }
  1454. return nil
  1455. }
  1456. if self?.listView.toolMode == .editPDFToolMode {
  1457. if self != nil {
  1458. //使用editingSelectionString获取内容文字
  1459. if self!.listView.editingAreas() != nil {
  1460. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  1461. self!.listView.clearEditingSelectCharItem()
  1462. } else if self!.listView.editingAreas().count > 0 {
  1463. if self?.listView.annotationType == .addImage ||
  1464. self?.listView.annotationType == .addText {
  1465. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1466. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1467. textItem?.isSelected = false
  1468. imageItem?.isSelected = false
  1469. }
  1470. self?.rightSideViewController.isHidden = true
  1471. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  1472. self?.listView.updateEditing([])
  1473. self?.listView.isEditImage = false
  1474. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  1475. if self?.listView.annotationType == .addImage {
  1476. self?.listView.change([.text, .image])
  1477. }
  1478. self?.listView.annotationType = .editTextImage
  1479. self?.closeRightPane()
  1480. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1481. if self?.listView.annotationType == .addImage ||
  1482. self?.listView.annotationType == .addText {
  1483. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1484. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1485. textItem?.isSelected = false
  1486. imageItem?.isSelected = false
  1487. }
  1488. self?.rightSideViewController.isHidden = true
  1489. self?.listView.setShouAddEdit([])
  1490. self?.listView.change([.text, .image])
  1491. self?.listView.annotationType = .editTextImage
  1492. self?.closeRightPane()
  1493. }
  1494. } else {
  1495. if self?.listView.annotationType == .addImage ||
  1496. self?.listView.annotationType == .addText {
  1497. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1498. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1499. textItem?.isSelected = false
  1500. imageItem?.isSelected = false
  1501. }
  1502. }
  1503. }
  1504. }
  1505. } else {
  1506. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1507. self?.listView.keyDown(with: event)
  1508. return nil
  1509. }
  1510. }
  1511. return event
  1512. }
  1513. }
  1514. func removeKeyEventMonitor() {
  1515. if (self.keyEventMonitor != nil) {
  1516. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1517. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1518. self.keyEventMonitor = nil
  1519. }
  1520. }
  1521. private func removeEventMonitor() {
  1522. if (self.eventMonitor != nil) {
  1523. KMPrint("已移除事件监听")
  1524. NSEvent.removeMonitor(self.eventMonitor as Any)
  1525. self.eventMonitor = nil
  1526. }
  1527. }
  1528. // MARK: - Tools
  1529. func pdfViewCanHorizontalScroll() -> Bool {
  1530. let scroll = self.listView.scroll()
  1531. if (scroll == nil) {
  1532. return false
  1533. }
  1534. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1535. }
  1536. func pdfViewCanVerticalScroll() -> Bool {
  1537. let scroll = self.listView.scroll()
  1538. if (scroll == nil) {
  1539. return false
  1540. }
  1541. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1542. }
  1543. // MARK: - Public Methods
  1544. // 清理数据 [eg. 通知]
  1545. public func clearData() {
  1546. self.removeNotifications()
  1547. if (self.listView.spellingTag() > 0) {
  1548. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1549. }
  1550. self.removeAutoSaveInfo()
  1551. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1552. }
  1553. public func clearSecureOptions() {
  1554. self._secureOptions = nil
  1555. self.documentAttribute = nil
  1556. }
  1557. public func recordRemoveSecureFlag() {
  1558. self._removeSecureFlag = true
  1559. self.clearSecureOptions()
  1560. self.recordIsPDFDocumentEdited(type: .removePassword)
  1561. self._needSave = true
  1562. }
  1563. public func clearRemoveSecureFlag() {
  1564. self._removeSecureFlag = false
  1565. }
  1566. public func clearSaveWatermarkFlag() {
  1567. km_synchronized(self) {
  1568. self._saveWatermarkFlag = false
  1569. }
  1570. }
  1571. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1572. km_synchronized(self) {
  1573. self.model.isPDFDocumentEdited = true
  1574. if let _document = self.myDocument {
  1575. KMTools.setDocumentEditedState(document: _document)
  1576. }
  1577. }
  1578. }
  1579. public func clearIsPDFDocumentEdited() {
  1580. km_synchronized(self) {
  1581. self.model.isPDFDocumentEdited = false
  1582. }
  1583. }
  1584. func showSnapshots(setups: NSArray?) {
  1585. for setup in setups ?? [] {
  1586. let swc = KMSnapshotWindowController()
  1587. swc.delegate = self
  1588. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  1589. swc.setForceOnTop(self.interactionMode != .normal)
  1590. self.myDocument?.addWindowController(swc)
  1591. }
  1592. }
  1593. func dealDocumentDidLoaded() {
  1594. self.removeBackgroundMaskView()
  1595. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1596. self.showSecureLimitTip()
  1597. }
  1598. if self.document != nil {
  1599. self.convertNotesUsingPDFDocument(self.document!)
  1600. }
  1601. if (self._documentFirstLoad) {
  1602. self.checkShouldAutoOpenLeftVC()
  1603. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1604. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1605. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1606. if (pageScale != nil) {
  1607. self.listView.scaleFactor = CGFloat(pageScale!)
  1608. }
  1609. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1610. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1611. } else {
  1612. self._goToFirstPageForFristAppear()
  1613. }
  1614. } else {
  1615. self._goToFirstPageForFristAppear()
  1616. }
  1617. self._documentFirstLoad = false
  1618. }
  1619. }
  1620. // MARK: - Noti Actions
  1621. internal func documentDidUnlockNotification(_ sender: Notification) {
  1622. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1623. // self.loadAIIconView()
  1624. if (self.myDocument == nil) {
  1625. return
  1626. }
  1627. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1628. self.hiddenSecureLimitTip()
  1629. }
  1630. if ((self.myDocument as! KMMainDocument).isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  1631. return
  1632. }
  1633. let type = KMPreferenceManager.shared.savePasswordType
  1634. if (type == .never) {
  1635. return
  1636. }
  1637. if (type == .always) {
  1638. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1639. return
  1640. }
  1641. // 保存到钥匙串
  1642. let alert = NSAlert()
  1643. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1644. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1645. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1646. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1647. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1648. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1649. return
  1650. }
  1651. }
  1652. }
  1653. func annotationsAttributeHasChange(_ sender: Notification) {
  1654. guard let dict = sender.object as? [String : Any] else {
  1655. return
  1656. }
  1657. if let anno = dict["object"] as? CPDFAnnotation {
  1658. let value = dict["keyPath"] as? String ?? ""
  1659. let didEnd = dict["didEnd"] as? Bool ?? false
  1660. if didEnd {
  1661. if value == CPDFAnnotationBoundsKey {
  1662. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  1663. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  1664. }
  1665. }
  1666. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1667. } else {
  1668. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  1669. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1670. }
  1671. }
  1672. }
  1673. }
  1674. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1675. self.savePageNumberIfNeed()
  1676. self.saveDocument()
  1677. }
  1678. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1679. if self.isReadMode {
  1680. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1681. }
  1682. //刷新前一页后一页按钮
  1683. self.updateNextAndPreViousButtonState()
  1684. }
  1685. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1686. if self.isReadMode {
  1687. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1688. }
  1689. //刷新前一页后一页按钮
  1690. self.updateNextAndPreViousButtonState()
  1691. }
  1692. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1693. var editSelectd = false
  1694. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1695. editSelectd = true
  1696. }
  1697. if self.listView.toolMode == .editPDFToolMode {
  1698. if editSelectd {
  1699. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1700. }
  1701. }
  1702. }
  1703. @objc func handlePageChangedNotification(_ sender: Notification) {
  1704. // When the PDFView is changing scale, or when view settings change when switching fullscreen modes,
  1705. // a lot of wrong page change notifications may be send, which we better ignore.
  1706. // Full screen switching and zooming should not change the current page anyway.
  1707. if self.mwcFlags.isSwitchingFullScreen > 0 {
  1708. // if ([pdfView isZooming] || mwcFlags.isSwitchingFullScreen) {
  1709. // [self updatePageNumber];
  1710. // [self updateLeftStatus];
  1711. return
  1712. }
  1713. //
  1714. let page = self.listView.currentPage()
  1715. let pageIndex = page?.pageIndex() ?? 0
  1716. //
  1717. // if ([lastViewedPages count] == 0) {
  1718. // [lastViewedPages addPointer:(void *)pageIndex];
  1719. // } else if ((NSUInteger)[lastViewedPages pointerAtIndex:0] != pageIndex) {
  1720. // [lastViewedPages insertPointer:(void *)pageIndex atIndex:0];
  1721. // if ([lastViewedPages count] > 5)
  1722. // [lastViewedPages setCount:5];
  1723. // }
  1724. self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
  1725. self.leftSideViewController.thumbnailTableView.needsDisplay = true
  1726. self.leftSideViewController.tocOutlineView.needsDisplay = true
  1727. //
  1728. // [self updatePageNumber];
  1729. // [self updatePageLabel];
  1730. //
  1731. // [self updateOutlineSelection];
  1732. // [self updateNoteSelection];
  1733. // [self updateThumbnailSelection];
  1734. //
  1735. // if (beforeMarkedPageIndex != NSNotFound && [[pdfView currentPage] pageIndex] != markedPageIndex)
  1736. // beforeMarkedPageIndex = NSNotFound;
  1737. //
  1738. // [self synchronizeWindowTitleWithDocumentName];
  1739. // [self updateLeftStatus];
  1740. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  1741. // [self updateRightStatus];
  1742. // if ([self interactionMode] == SKPresentationMode)
  1743. // [[self presentationNotesDocument] setCurrentPage:[[[self presentationNotesDocument] pdfDocument] pageAtIndex:[page pageIndex]]];
  1744. }
  1745. @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
  1746. self.leftSideViewController.reloadThumbnailDataIfNeed()
  1747. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  1748. // [self updateRightStatus];
  1749. }
  1750. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  1751. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1752. return
  1753. }
  1754. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  1755. if interactionMode == .presentation {
  1756. let backgroundColor = NSColor.black
  1757. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  1758. let wasInteractionMode = self.interactionMode
  1759. if wasInteractionMode == .normal {
  1760. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  1761. }
  1762. // if findController.view().window() != nil {
  1763. // findController.toggleAboveView(nil, animate: false)
  1764. // }
  1765. if wasInteractionMode == .legacyFullScreen {
  1766. self.enterPresentationMode()
  1767. // updatePresentationOptions(for: self.view.window!)
  1768. self.pdfSplitView.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(centerContentView.bounds), height: CGRectGetHeight(centerContentView.bounds)-1)
  1769. self.centerContentView.addSubview(pdfSplitView)
  1770. self.listView.frame = (self.view.window?.contentView?.bounds)!
  1771. self.view.window?.contentView?.addSubview(listView)
  1772. self.view.window?.backgroundColor = backgroundColor
  1773. self.view.window?.level = level
  1774. self.listView.layoutDocumentView()
  1775. self.listView.requiresDisplay()
  1776. self.forceSubwindowsOnTop(false)
  1777. self.hideLeftSideWindow()
  1778. self.hideRightSideWindow()
  1779. self.removeBlankingWindows()
  1780. }
  1781. } else {
  1782. KMPrint("2")
  1783. }
  1784. }
  1785. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  1786. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1787. return
  1788. }
  1789. if self.interactionMode == .presentation {
  1790. // if self.pdfView().currentPage()?.isEqual(page) == false {
  1791. // self.pdfView().go(to: page)
  1792. // }
  1793. // pdfView().setInteractionMode(SKPresentationMode)
  1794. self.listView?.layoutDocumentView()
  1795. self.listView?.requiresDisplay()
  1796. }
  1797. }
  1798. @objc func willShowFullScreenNotification(_ sender: Notification) {
  1799. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1800. return
  1801. }
  1802. if self.interactionMode == .presentation {
  1803. let view = self.view.window?.firstResponder as? NSView
  1804. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  1805. self.view.window?.makeFirstResponder(nil)
  1806. }
  1807. }
  1808. }
  1809. @objc func didShowFullScreenNotification(_ sender: Notification) {
  1810. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1811. return
  1812. }
  1813. if self.interactionMode == .presentation {
  1814. self.enterPresentationMode()
  1815. }
  1816. }
  1817. @objc func didAddContentViewNotification(_ sender: Notification) {
  1818. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1819. return
  1820. }
  1821. if self.interactionMode == .presentation {
  1822. }
  1823. }
  1824. @objc func purchaseStateUpdateNoti() {
  1825. if IAPProductsManager.default().isAvailableAllFunction() {
  1826. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1827. }
  1828. }
  1829. // MARK: Split View
  1830. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  1831. let openPanel = NSOpenPanel()
  1832. openPanel.allowedFileTypes = ["pdf", "PDF"]
  1833. openPanel.allowsMultipleSelection = false
  1834. guard let mainWindow = NSApp.mainWindow else {
  1835. return
  1836. }
  1837. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  1838. if response == NSApplication.ModalResponse.OK {
  1839. guard let url = openPanel.url else {
  1840. return
  1841. }
  1842. if let document = CPDFDocument(url: url) {
  1843. self?.secondaryPdfView?.document = nil
  1844. self?.secondaryPdfView?.document = document
  1845. if isChange {
  1846. self!.openSecondaryPdfView!.view.removeFromSuperview()
  1847. }
  1848. replaceBlock(document.documentURL?.path ?? "")
  1849. } else {
  1850. let alert = NSAlert()
  1851. alert.alertStyle = .critical
  1852. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1853. alert.runModal()
  1854. }
  1855. }
  1856. }
  1857. }
  1858. }
  1859. extension KMMainViewController {
  1860. func currentSetup() -> [String: Any] {
  1861. var setup: [String: Any] = [:]
  1862. var point = NSZeroPoint
  1863. // var rotated = listView.currentPage().rotation
  1864. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  1865. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  1866. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  1867. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  1868. setup[KMMainModel.Key.pageIndex] = pageIndex
  1869. // if rotated != 0 {
  1870. // setup[SCROLLPOINT_KEY] = NSStringFromPoint(point)
  1871. // }
  1872. // if !snapshots.isEmpty {
  1873. // setup[SNAPSHOTS_KEY] = snapshots.map { $0[SKSnapshotCurrentSetupKey] }
  1874. // }
  1875. // if interactionMode == SKNormalMode {
  1876. // setup.merge(currentPDFSettings(), uniquingKeysWith: { $1 })
  1877. // } else {
  1878. // setup.merge(savedNormalSetup, uniquingKeysWith: { $1 })
  1879. // ["HASHORIZONTALSCROLLER_KEY", "HASVERTICALSCROLLER_KEY", "AUTOHIDESSCROLLERS_KEY", "LOCKED_KEY"].forEach { setup.removeValue(forKey: $0) }
  1880. // }
  1881. return setup
  1882. }
  1883. // MARK: - Recommond活动
  1884. func loadRecommondPopWindow() {
  1885. if IAPProductsManager.default().isAvailableAllFunction() {
  1886. return
  1887. }
  1888. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  1889. if recommondPopWindowVC == nil {
  1890. recommondPopWindowVC = KMRecommondPopWindow()
  1891. }
  1892. recommondPopWindowVC?.recommondInfo = info
  1893. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  1894. return
  1895. }
  1896. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  1897. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  1898. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  1899. recommondPopWindowVC?.window?.orderFront((Any).self)
  1900. recommondPopWindowVC?.window?.becomeMain()
  1901. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  1902. UserDefaults.standard.synchronize()
  1903. }
  1904. }
  1905. }