12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243 |
- //
- // KMMainViewController.swift
- // PDF Reader Pro
- //
- // Created by wanjun on 2022/12/15.
- //
- import Cocoa
- @objcMembers class KMMainViewController: KMBaseViewController, NSTextFieldDelegate {
- @IBOutlet var PDFContendView: NSView!
- @IBOutlet var centerContentView: NSView!
- @IBOutlet var listView: CPDFListView!
- @IBOutlet var secondaryPdfView: KMSecondaryPDFView?
-
- @IBOutlet weak var readContentView: NSView!
- @IBOutlet weak var tipCurrentPageBox: KMBox!
- @IBOutlet weak var rightView: NSView!
- @IBOutlet weak var leftView: NSView!
- @IBOutlet weak var mianSplitView: KMSplitView!
- @IBOutlet weak var pdfSplitView: KMSplitView!
- @IBOutlet weak var newPDFSplitView: KMSplitView!
- @IBOutlet weak var pdfContentView: NSView!
- @IBOutlet weak var pdfSplitSecondView: NSBox!
-
- @IBOutlet weak var locationPageView: NSView!
- @IBOutlet weak var tipLabel: NSTextField!
-
- @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
- @IBOutlet var childToolbarController: KMToolbarViewController!
- @IBOutlet var toolbarController: KMToolbarController!
- @IBOutlet weak var toolbarBox: NSBox!
- @IBOutlet weak var heightOffset: NSLayoutConstraint!
-
- //阅读模式界面
- @IBOutlet weak var readModelView: KMReadModelView!
- @IBOutlet weak var bottomAreaView: KMBox!
- @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
-
- //页码显示器
- @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
- @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
-
- @IBOutlet weak var topTipBox: NSBox!
- @IBOutlet weak var exitFullButton: NSButton!
-
- var model = KMMainModel()
-
- var isReadMode: Bool = false
- var readAlertView: CustomAlertView?
-
- var readLeftMethodType: BotaType = .None
- var readLeftPanelOpen = false
- var readLastLeftPanWidth = 0.0
- var readLeftViewShowPanel = false
- var readRightPanelOpen = false
- var readToolbarType: KMToolbarViewType = .None
- var readToolbarItemIdentifier: String = ""
- var readToolMode: CToolMode = .textToolMode
- var readAnnotationType: CAnnotationType = .unkown
- var readSubViewType: RightSubViewType = .None
- //自动滚动
- var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
-
- //Search
- var searchIndex: Int = 0
-
- //Form
- var formAlertView: KMFormAlertView?
- //Secure
- var secureAlertView: KMSecureAlertView?
-
- //对比
- var isCompareModel: Bool = false {
- didSet {
- self.toolbarController.updataItemVisible()
- }
- }
- //合并
- var mergeWindowController: KMMergeWindowController?
- //水印
- var watermarkWindowController: KMWatermarkWindowController?
- //密码弹窗
- var passwordWindow: KMPasswordInputWindow?
- //对比
- var compressWIndowControllerNew: KMCompressWIndowControllerNew?
- //
- var securityWindowController: KMSecurityWindowController?
-
- //引导
- var guideInfoWindowController: KMGuideInfoWindowController?
-
- private var _needSave = false
- var needSave: Bool {
- set {
- _needSave = newValue
-
- if (_needSave == false) {
- self.clearIsPDFDocumentEdited()
- }
- }
- get {
- return _needSave
- }
- }
- var isPDFDocumentEdited: Bool {
- get {
- return self.model.isPDFDocumentEdited
- }
- }
-
- var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
- var rightSideViewController: KMRightSideViewController!
- var searchResults: [KMSearchMode] = []
- var mwcFlags: MwcFlags = MwcFlags()
- var document: CPDFDocument?
- var myDocument: NSDocument?
- weak var browserWindowController: KMBrowserWindowController?
-
- var cropSettingWindowController: KMCropSettingWindowController!
- var currentWindowController: NSWindowController!
- var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
-
- //数字签名
- var digitalSignController: KMPDFDigitalSignViewController?
-
- var redactController: KMPDFRedactViewController!
-
- let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
- let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
-
- var extract: KMExtractImageWindowController?
-
- var functionWidth: Double {
- get {
- if self.isReadMode {
- if !self.model.isShowBOTA {
- return 0
- }
- }
- return 48-4
- }
- }
- var pageNumber: UInt?
-
- var openSecondaryPdfView: KMSecondaryViewController?
- var secondaryPdfContentView: NSView?
- var lastSplitPDFHeight: Float = 0.0
- var pdfEditController: KMPDFEditViewController? {
- get {
- return self.getPDFEditController()
- }
- }
-
- var autoSaveTimer: Timer?
- private var _documentFirstLoad: Bool = true
-
- var eventMonitor: Any?
- var keyEventMonitor: Any?
- var mouseRightMenuEvent: NSEvent?
- var aiTranslationWindow: KMAITranslationWindowController?
- var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
-
- lazy private var homeVC: KMHomeViewController? = {
- let vc = KMHomeViewController()
- return vc
- }()
- private var background_mask: NSView?
-
- fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
- var secureOptions: [CPDFDocumentWriteOption : Any]? {
- get {
- return self._secureOptions
- }
- }
- var documentAttribute: [CPDFDocumentAttribute : Any]?
-
- fileprivate var _removeSecureFlag = false
- var removeSecureFlag: Bool {
- get {
- return self._removeSecureFlag
- }
- }
- fileprivate var _saveWatermarkFlag = false
- var saveWatermarkFlag: Bool {
- get {
- return self._saveWatermarkFlag
- }
- }
-
- private var mainWindow_: NSWindow?
- var mainWindow: NSWindow? {
- get {
- return self.mainWindow_
- }
- set {
- self.mainWindow_ = newValue
- }
- }
-
- deinit {
- NotificationCenter.default.removeObserver(self)
-
- self.listView.delegate = nil
- self.listView.document.delegate = nil
-
- self.removeEventMonitor()
- self.removeKeyEventMonitor()
- }
- override func awakeFromNib() {
- super.awakeFromNib()
- self.addBackgroundMaskView()
-
- self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
- listView.delegate = self
- listView.pdfListViewDelegate = self
- if (document != nil) {
- listView.document = document
- listView.document.delegate = self
- let autoScale = listView.autoScales
- if !autoScale {
- listView.scaleFactor = 1.0
- }
- }
-
-
- self.initPDFLeftViewVC()
- self.initRightSideView()
- self.toolbarController.listView = self.listView
- self.toolbarController.mainViewController = self
- self.leftSideViewController.mainViewController = self
-
- self.newPDFSplitView.delegate = self
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
-
- //刷新前一页后一页按钮
- self.updateNextAndPreViousButtonState()
-
- self.addEventMonitor()
-
- self.view.window?.makeFirstResponder(self.listView)
- // 更新属性页面的信息
- NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
- self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
-
- if (self.document == nil) {
- return
- }
-
- if (self.document == nil || self.document!.isLocked == false) {
- self.loadFunctionGuide()
- }
-
- if (self.document?.isLocked == false) {
- if self.model.needConvertNotes && self.tabViewIsDragging() == false {
- self.showConvertNotesProgress()
- }
- return
- }
- if (self.view.window == nil) {
- return
- }
- if (self.model.password != nil) {
- if self.listView.document.unlock(withPassword: self.model.password) {
- self.model.isSaveKeyChain = false
- if self.model.needConvertNotes && self.tabViewIsDragging() == false {
- self.showConvertNotesProgress()
- }
- return
- }
- }
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
- if self.view.window != nil && self.tabViewIsDragging() == false {
- self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [unowned self] result , password in
- if (result == .cancel) {
- // self.browserWindowController?.browser?.closeTab()
- (self.myDocument as? KMMainDocument)?.browser.closeTab()
- return
- }
- self.model.isSaveKeyChain = true
- self.listView.document = self.document
- self.document?.unlock(withPassword: password)
- }
- } else {
- if self.model.needConvertNotes && self.tabViewIsDragging() == false {
- self.showConvertNotesProgress()
- }
- }
- }
- }
-
- override func viewWillDisappear() {
- super.viewWillDisappear()
-
- if self.interactionMode != .presentation {
- self.removeEventMonitor()
- }
- }
-
- override func viewWillLayout() {
- super.viewWillLayout()
-
- if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
- self.exitFullButton.isHidden = false
- self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
- } else {
- self.exitFullButton.isHidden = true
- self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
- }
- if let guideWC = self.guideInfoWindowController{
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- guideWC.show()
- }
- }
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- mwcFlags.settingUpWindow = 1
- toolbarController.delegate = self
-
- //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
- toolbarBox.contentView = toolbarController.view
- if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
- UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
- UserDefaults.standard.synchronize()
- }
- if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
- UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
- UserDefaults.standard.synchronize()
- }
- let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
- mianSplitView.setPosition(position, ofDividerAt: 0)
- mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0)
-
- pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0)
-
- self.locationPageView.wantsLayer = true;
- self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
- 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: "")
-
- if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
- if (self.listView.document != nil) {
- let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
- let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
- if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
- if (pageScale != nil) {
- self.listView.scaleFactor = CGFloat(pageScale!)
- }
- self.listView.go(toPageIndex: pageNumber!, animated: false)
- }
- } else {
- self._goToFirstPageForFristAppear()
- }
- }
- } else {
- self._goToFirstPageForFristAppear()
- }
-
- //阅读页面
- readModelView.delegate = self
- pageNumberDisplayView.delegate = self
-
- tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
- if !isReadMode {
- if mouseEntered {
- self.pageNumberDisplayView.hover = true
- } else {
- self.pageNumberDisplayView.hover = false
- }
- }
- }
- NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
- NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
-
- NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.listView)
- NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayBoxChangedNotification), name: NSNotification.Name.CPDFViewDisplayBoxChanged, object: self.listView)
- // 互动模式
- NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(didAddContentViewNotification), name: NSWindow.didAddContentViewNotification, object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(addAutoSaveEvent), name: AutoSaveManager.kTimeValueChangedNotificationName, object: nil)
-
- Task {
- self.addAutoSaveEvent()
- }
-
- self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
- self.closeRightPane()
-
- self.addKeyEventMonitor()
-
- //检测OCR包是否需要更新
- #if VERSION_DMG
- // KMResourceDownloadManager.manager.checkDocumentAIVersion()
- #endif
-
- // Open snapshots?
- var snapshotSetups: NSArray?
- // if (hasWindowSetup)
- // snapshotSetups = [savedNormalSetup objectForKey:SNAPSHOTS_KEY];
- // else if ([sud boolForKey:SKRememberSnapshotsKey])
- if KMPreferenceManager.shared.rememberSnapshot {
- // snapshotSetups = [[SKBookmarkController sharedBookmarkController] snapshotsForRecentDocumentAtURL:[(NSDocument *)[self document] fileURL]];
- if let fileUrl = (self.myDocument as? KMMainDocument)?.fileURL {
- snapshotSetups = SKBookmarkController.shared().snapshotsForRecentDocument(at: fileUrl) as NSArray?
- }
- }
- if let cnt = snapshotSetups?.count, cnt > 0 {
- if let data = self.listView?.document?.isLocked, data {
- self.savedNormalSetup.setObject(snapshotSetups as Any, forKey: "snapshots" as NSCopying)
- } else {
- self.showSnapshots(setups: snapshotSetups)
- }
- }
-
- let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
- if readModel == true {
- self.openReadModel()
- }
- let hasWindowSetup = savedNormalSetup.count > 0
- if UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey) != nil {
- let pdfSettings: NSDictionary = hasWindowSetup ? savedNormalSetup : UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey)! as NSDictionary
- self.applyPDFSettings(pdfSettings)
- } else {
- self.applyPDFSettings(savedNormalSetup)
- }
-
- //文字
- let fontManager = NSFontManager.shared
- fontManager.target = self
- fontManager.action = #selector(changeFont(_:))
- }
-
- //MARK: - PDFListView
-
- func initPDFLeftViewVC() {
- var frame = self.leftView.frame
- frame.size.width += 44
- self.leftView.frame = frame
- leftSideViewController.isFirst = true
- leftSideViewController.listView = self.listView
- leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
- leftSideViewController.view.autoresizingMask = [.height,.width]
- leftSideViewController.delegate = self
- self.leftView.addSubview(leftSideViewController.view)
- }
-
- func initRightSideView() {
- self.rightSideViewController = KMRightSideViewController.init()
- self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
- self.rightSideViewController.view.autoresizingMask = [.height,.width]
- self.rightSideViewController.listView = self.listView
- // self.rightSideViewController.view.isHidden = true
- self.rightSideViewController.isHidden = true
- self.rightSideViewController.delegate = self
- self.rightView.addSubview(self.rightSideViewController.view)
- self.rightSideViewController.mainController = self
- self.rightSideViewController.propertyDidChange = { [weak self] model in
- if let anno = model as? CSelfSignAnnotation {
- self?.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: nil)
- }
- }
- }
-
- // MARK: Private Methods
-
- internal func removeNotifications() {
- NotificationCenter.default.removeObserver(self)
- self.leftSideViewController.clearAnnotationFilterData()
- self.leftSideViewController.clearNotification()
- }
-
- func checkShouldAutoOpenLeftVC() {
- if KMPreference.shared.showLeftSideBar == false {
- return
- }
- if self.model.leftPanelOpen {
- return
- }
- Task { @MainActor in
- self.leftSideViewController.showThumbnail()
- self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
- }
- }
-
- func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
- mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
- mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
- self.model.lastLeftPanWidth = leftSideWidth
- self.model.lastRightPanWidth = rightSideWidth
- }
-
- internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
- internal func removeAllAnnotations() {
- let alert = NSAlert()
- alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
- alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
- alert.addButton(withTitle: NSLocalizedString("No", comment:""))
- if (alert.runModal() != .alertFirstButtonReturn) {
- return
- }
-
- DispatchQueue.main.async {
- self.removeAllAnnotationsStore.store(t: self.listView)
- }
- }
-
- // MARK: Set Methods
-
- var setDocument: CPDFDocument? {
- get {
- return document
- }
- set {
- if document != newValue {
- document = newValue
- }
- listView.document = document
- listView.document?.delegate = self
- self.listView.layoutDocumentView()
-
- self.leftSideViewController.refreshUIForDocumentChanged()
- }
- }
-
- var setPageNumber: UInt {
- get {
- return pageNumber!
- }
- set {
- let pageCount = listView.document.pageCount
- var value = newValue
- if value > pageCount {
- value = pageCount
- }
- if value > 0 && listView.currentPage().pageIndex() != value-1 {
- listView.go(to: listView.document.page(at: value-1))
- }
- if pageNumber != value {
- pageNumber = value
- }
- }
- }
-
- // MARK: - 标记密文
-
- func enterRedact() {
- if !IAPProductsManager.default().isAvailableAllFunction(){
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
-
- if self.listView.document.allowsPrinting == false || self.listView.document.allowsCopying == false {
- Task {
- _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
- }
- return
- }
-
- if self.hasEnterRedact() {
- self.exitRedact()
- return
- }
-
- self.leftSideViewController.thumbnailTableView.isEnabled = false
- self.leftSideViewController.tocOutlineView.isEnabled = false
- self.leftSideViewController.noteOutlineView.isEnabled = false
- self.leftSideViewController.findTableView.isEnabled = false
- self.leftSideViewController.groupedFindTableView.isEnabled = false
- self.leftSideViewController.snapshotTableView.isEnabled = false
-
-
- let ttsWindowC = KMTTSWindowController.share
- if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document.documentURL.path {
- if let data = ttsWindowC.window?.isVisible, data {
- ttsWindowC.stopSpeaking()
- ttsWindowC.close()
- }
- }
- NSColorPanel.shared.showsAlpha = false
-
- redactController = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document.password)
- self.addChild(redactController)
- self.PDFContendView.addSubview(redactController.view)
- redactController.view.frame = self.PDFContendView.bounds
- redactController.view.autoresizingMask = [.width, .height]
- self.listView.isHidden = true
-
- redactController.scaleFactor = self.listView.scaleFactor
- redactController.titleBack = { [weak self] title in
- self?.view.window?.title = title
- }
- redactController.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
- self?.listView.go(toPageIndex: self!.redactController.redactPdfView.currentPageIndex, animated: false)
-
- if result == false { // 退出
- self?.exitRedact()
- return
- }
- let controller = self?._getPDFRedactController()
- controller?.redactPdfView.newAddAnnotation.removeAll()
- self?.exitRedact()
- if saveResult {
- let newDocument = CPDFDocument(url: saveUrl)
- if let data = newDocument?.isLocked, data {
- newDocument?.unlock(withPassword: self?.listView.document.password ?? "")
- }
- self?.document = newDocument
- self?.listView.document = newDocument
- self?.listView.layoutDocumentView()
- }
- }
- redactController.setCurrentPageIndex(self.listView.currentPageIndex)
- }
-
- func exitRedact() {
- self.leftSideViewController.thumbnailTableView.isEnabled = true
- self.leftSideViewController.tocOutlineView.isEnabled = true
- self.leftSideViewController.noteOutlineView.isEnabled = true
- self.leftSideViewController.findTableView.isEnabled = true
- self.leftSideViewController.groupedFindTableView.isEnabled = true
- self.leftSideViewController.snapshotTableView.isEnabled = true
-
- let controller = self._getPDFRedactController()
- if let data = controller {
- if data.redactPdfView.newAddAnnotation.count > 0 {
- 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
- if response == .alertFirstButtonReturn {
- data.redactPdfView.newAddAnnotation.removeAll()
- self.exitRedact()
- }
- }
- return
- }
- }
- NSColorPanel.shared.showsAlpha = true
- self.toolbarController.findItem(KMDocumentRedactToolbarItemIdentifier)?.isSelected = false
- // self.toolbarController.toolbarType = .None
- // self.listView.toolMode = .moveToolMode
- controller?.redactPdfView.resignMonitor()
-
- controller?.view.removeFromSuperview()
- controller?.removeFromParent()
-
- self.listView.isHidden = false
- // self.listView.layoutDocumentView()
- // self.view.window?.makeFirstResponder(self.listView)
-
- self.listView.annotationType = .unkown
- }
-
- func hasEnterRedact() -> Bool {
- return self._getPDFRedactController() != nil
- }
-
- //MARK: - AI
-
- func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
-
- if (self.document != nil) {
- AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
- } else {
- AIChatInfoManager.defaultManager.currentFilePath = ""
- }
-
- let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
- windowVC.chooseCurFileHandle = {[unowned self] windowVC in
- if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
- let documentArray = NSDocumentController.shared.documents
- var didFileEdit: Bool = false
- var curDoc: KMMainDocument!
- for document in documentArray {
- if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
- didFileEdit = document.isDocumentEdited
- curDoc = document as! KMMainDocument
- break
- }
- }
- if didFileEdit {
- let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
- if FileManager.default.fileExists(atPath: tempFileURL.path) {
- do {
- try FileManager.default.removeItem(at: tempFileURL)
-
- } catch {
-
- }
- }
- if curDoc != nil {
- curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
- }
- }
- windowVC.window?.becomeMain()
- }
- }
- if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
-
- } else {
- var windowRect = windowVC.window?.frame
- windowRect!.origin.x = CGRectGetMaxX(self.view.window!.frame) - (windowRect?.size.width)!
- windowRect!.origin.y = CGRectGetMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
- windowVC.window?.setFrame(windowRect!, display: true)
-
- windowVC.didSetOriginFrame = true
- }
- windowVC.eventLabel = "AITools_Tbr"
- windowVC.showWindow(nil)
- if (aiConfigType != .none) {
- windowVC.eventLabel = "AITools_Start"
- if self.listView.currentSelection?.string()?.isEmpty == false {
- windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
- }
- windowVC.chooseAIFunctionWithType(aiConfigType)
- }
- }
-
- @objc func aiTipIconViewShowStateChangeNoti() {
- }
-
- //MARK: - 引导
-
- func loadFunctionGuide() -> Void {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
- if self.view.window != nil {
- self.loadOpenFileFunctionGuide(.openFileNormal)
- }
- }
- }
-
-
- func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
- if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
- let leftPanelItem:KMToolbarItemView = self.toolbarController.findItem("KMLeftControlToolbarItemIdentifier")!
-
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .openFileNormal
- guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? CGRectZero
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- guideWC.normalGuideFinishHandle = { [weak self] windowVC in
- let rightPanelItem = self?.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
- let digitalPanelItem = self?.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)
-
- windowVC.rightPanelRect = (self!.view.window?.contentView?.convert(rightPanelItem?.frame ?? .zero, from: rightPanelItem?.superview)) ?? .zero
- guideWC.digitalBoxRect = (self!.view.window?.contentView?.convert(digitalPanelItem?.frame ?? .zero, from: digitalPanelItem?.superview)) ?? .zero
-
- }
- guideWC.finishHandle = { [weak self] windowVC, type in
- if type == .windowNewFinish ||
- type == . windowDigitalFinish {
- self?.checkFirstTrialController()
- }
- }
- guideWC.openFileToggleHandle = { [weak self] windowVC, type in
- self?.checkFirstTrialController()
- }
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .digitalSignGuide
- let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
- guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- guideWC.finishHandle = { [weak self] windowVC, type in
- self?.checkFirstTrialController()
- }
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
-
- } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .pdfCompareGuide
-
- let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
- guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
-
- let compareItem:KMToolbarItemView = self.toolbarController.findItem(KMToolbarComparisonItemIdentifier)!
- guideWC.compareItemRect = (self.view.window?.contentView?.convert(compareItem.frame, from: compareItem.superview))!
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
- self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
- guard let guideWC = self.guideInfoWindowController else { return }
-
- guideWC.type = .convertGuide
- let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
- guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
- guideWC.purchaseHandle = { [weak self] windowVC in
- #if VERSION_DMG
- if IAPProductsManager.default().isAvailableAllFunction() {
- if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
- //Convert:
- self?.showAllConvertWindow(convertT: .Word)
- } else {
- let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
- limitWC.continueBlock = { windowController in
-
- }
- limitWC.window?.center()
- limitWC.showWindow(nil)
- }
- } else {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- }
- #else
- if IAPProductsManager.default().isAvailableAllFunction() {
- if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
- //Convert:
- } else {
- var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
- vc.showWindow(nil)
- }
- } else {
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- }
- #endif
- }
-
- guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
- var rect = self.view.window!.frame
- rect.size.height -= 20
- guideWC.window?.setFrame(rect, display: false)
- guideWC.window?.minSize = rect.size
- guideWC.window?.maxSize = rect.size
- self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
- guideWC.show()
- }
- } else {
-
- }
- }
-
- func checkFirstTrialController() -> Void {
- #if VERSION_DMG
- //打开文档后引导相关
- if VerificationManager.default().status == .none {
- let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
- let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
- if lastVersion.isEmpty || lastVersion != appVersion {
- UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
- UserDefaults.standard.synchronize()
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- }
- }
- #endif
- }
-
- // MARK: - 页面编辑
-
- open func enterPageEdit(_ pages: [Int] = []) {
- if let doc = self.listView?.document {
- if doc.allowsCopying == false || doc.allowsPrinting == false {
- KMBaseWindowController.checkPassword(url: doc.documentURL, type: .owner) { result, pwd in
- if result && pwd.isEmpty == false {
- self.listView?.document?.unlock(withPassword: pwd)
-
- Task { @MainActor in
- self.enterPageEdit(pages)
- }
- } else {
- self.exitPageEdit()
- }
- }
- return
- }
- }
- //选中page
- var tPages = pages
- if tPages.count == 0 {
- if self.leftSideViewController.type.methodType == .Thumbnail {
- tPages = self.leftSideViewController.thumb_fetchSelectedRows() ?? [self.listView.currentPageIndex]
- }
- }
-
- if (hasEnterPageEdit()) {
- exitPageEdit()
- return
- }
-
- if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
- let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
- for (key, value) in toolBarView.toolbarItems {
- if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
- (value as! KMToolbarItemView).unEnabled = true
- }
- }
- }
-
- let controller = KMPDFEditViewController(self.listView.document)
-
- controller.selectedPages = tPages
- controller.listView = self.listView
- self.addChild(controller)
- self.PDFContendView.addSubview(controller.view)
- controller.view.frame = self.PDFContendView.bounds
- controller.view.autoresizingMask = [.width,.height]
- self.listView.isHidden = true
-
- controller.itemClick = { [weak self] index, params in
- if (index == 1) { /// 双击退出
- self?.enterEditMode(self!.leftSideViewController, [])
- DispatchQueue.main.async {
- let pageIndex: Int = params.first as! Int
- self?.listView.go(toPageIndex: pageIndex, animated: true)
- }
- } else if (index == 2) { // 打印
- self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
- }
- }
- controller.documentEditedCallback = { [weak self] params in
- self?.recordIsPDFDocumentEdited()
- }
-
- controller.selectionDidChange = { selectedIndexs in
- var indexSet = IndexSet()
- for indexPath in selectedIndexs {
- indexSet.insert(indexPath.item)
- }
- if indexSet.count != 0 {
- // self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
- // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
- }
- }
- }
-
- open func exitPageEdit() {
- if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
- let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
- for (key, value) in toolBarView.toolbarItems {
- if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
- (value as! KMToolbarItemView).unEnabled = false
- }
- }
- }
-
- self.toolbarController.findItem(KMDocumentPageToolbarItemIdentifier)?.isSelected = false
- let editController = getPDFEditController()
- if (editController == nil) {
- return
- }
- self.listView.annotationType = .highlight
-
- // FIXME: - sdk修复插入特定文档crash后,这行代码可以去掉
- self.leftSideViewController.model.insertedDocumentSet.formUnion(editController?.model.insertedDocumentSet ?? [])
-
- editController?.view.removeFromSuperview()
- editController?.removeFromParent()
-
- self.listView.isHidden = false
- self.listView.layoutDocumentView()
- self.view.window?.makeFirstResponder(self.listView)
-
- self.listView.annotationType = .unkown
-
- self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
-
- if let data = editController?.isEdited, data {
- self.leftSideViewController.reloadThumbnailDataIfNeed()
- self.leftSideViewController.note_reloadDataIfNeed()
- self.leftSideViewController.refreshUIOfOutlineIfNeed()
- self.leftSideViewController.refreshUIOfSeachListIfNeed()
- }
- }
-
- open func hasEnterPageEdit() -> Bool {
- return self.getPDFEditController() != nil
- }
-
- // MARK: - Edit PDF
-
- func enterEditPDF() {
- self.listView.updateActiveAnnotations([])
- self.listView.setNeedsDisplayForVisiblePages()
- self.listView.commitEditFormText()
- self.listView.annotationType = .editTextImage
- }
-
- // MARK: - 数字签名
-
- func hasShowDigitalSign() -> Bool {
- return self.digitalSignController?.view.superview != nil
- }
-
- func canEnterDigitalSign() -> Bool {
- guard let doc = self.listView?.document else {
- return false
- }
- return doc.allowsPrinting && doc.allowsCopying
- }
-
- func enterDigitalSign() {
- self.listView.toolMode = .textToolMode
- if self.hasShowDigitalSign() {
- self.exitDigitalSign()
- } else {
- if self.needSaveDocument() {
- self.saveDocumentWithProgressAlert { [unowned self] params in
- self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
- }
- return
- }
- self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
- }
- }
-
- func exitDigitalSign() {
- self.digitalSignController?.view.removeFromSuperview()
- self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)?.isSelected = false
- }
-
- func showDigitalSignWindow(withFilePathURL fileURL: URL) {
- if !IAPProductsManager.default().isAvailableAllFunction(){
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
-
- if hasShowDigitalSign() {
- self.exitDigitalSign()
- }
-
- var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
- var password: String = ""
-
- self.toolbarController.toolbarType = .None
- if digitalSignController == nil {
- password = listView.document?.password ?? ""
-
- digitalSignController = KMPDFDigitalSignViewController()
- }
-
- digitalSignController?.currentPageIndex = Int(currentPageIndex)
- digitalSignController?.url = listView.document.documentURL
- digitalSignController?.password = password
- digitalSignController?.scaleFactor = listView.scaleFactor
-
- digitalSignController?.titleChangeBlock = { title, index in
- currentPageIndex = UInt(index)
- }
-
- digitalSignController?.buttonActionBlock = { [weak self] type, isChanged in
- if type == .cancel {
- if let page = self?.listView?.document?.page(at: currentPageIndex) {
- self?.listView.go(to: page)
- }
- self?.exitDigitalSign()
- }
- }
-
- if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
- digitalSignView.frame = splitViewSuperview.bounds
- digitalSignView.autoresizingMask = [.width, .height]
- splitViewSuperview.addSubview(digitalSignView)
-
- digitalSignController?.setCurrentPageIndex(Int(currentPageIndex))
- }
- }
-
- // MARK: - Toolbar
-
- func toolbarItemClickForExitMode(_ toolbarItem: KMToolbarItemView) {
- if(toolbarItem.itemIdentifier != KMDocumentPageToolbarItemIdentifier) {
- if (hasEnterPageEdit()) {
- self.exitPageEdit()
- }
- }
- if toolbarItem.itemIdentifier != KMDocumentRedactToolbarItemIdentifier {
- if self.hasEnterRedact() {
- self.exitRedact()
- }
- }
- if toolbarItem.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
- if self.hasShowDigitalSign() {
- self.exitDigitalSign()
- }
- }
- }
-
- // MARK: - Private Methods
-
- private func getPDFEditController() -> KMPDFEditViewController? {
- var editController: KMPDFEditViewController?
- for controller in self.children {
- if (controller.isKind(of: KMPDFEditViewController.self)) {
- editController = (controller as! KMPDFEditViewController)
- break
- }
- }
- return editController
- }
-
- private func _getPDFRedactController() -> KMPDFRedactViewController? {
- var controller: KMPDFRedactViewController?
- for childC in self.children {
- if (childC.isKind(of: KMPDFRedactViewController.self)) {
- controller = (childC as! KMPDFRedactViewController)
- break
- }
- }
- return controller
- }
-
- private func addBackgroundMaskView() {
- self.removeBackgroundMaskView()
-
- if let superview = self.mianSplitView.superview {
- let view = NSView()
- superview.addSubview(view)
- view.frame = superview.bounds
- view.autoresizingMask = [.width, .height]
- view.wantsLayer = true
- view.layer?.backgroundColor = .white
- self.background_mask = view
- }
- }
-
- private func removeBackgroundMaskView() {
- self.background_mask?.removeFromSuperview()
- self.background_mask = nil
- }
-
- private func _goToFirstPageForFristAppear() {
- DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
- self.listView.go(toPageIndex: 0, animated: false)
- }
- }
-
- func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
- let url = URL(fileURLWithPath: filePath)
- guard let document = PDFDocument(url: url) else {
- return false
- }
-
- let pageCount = document.pageCount
- return pageCount > 30
- }
-
- // MARK: - Redact 【标记密文】
-
- func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
- let windowController = KMRedactConfirmWindowController(type)
- self.currentWindowController = windowController
- self.view.window?.beginSheet(windowController.window!)
- windowController.itemClick = { [weak self] index in
- if (index == 2) { /// 取消
- self?.view.window?.endSheet((self?.currentWindowController.window)!)
- self?.currentWindowController = nil
- callback()
- return
- }
-
- self?.view.window?.endSheet((self?.currentWindowController.window)!)
- self?.currentWindowController = nil
-
- let panel = NSSavePanel()
- panel.nameFieldStringValue = "[新文件]"+(self?.listView.document.documentURL.lastPathComponent)!
- let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
- button.state = .on
- panel.accessoryView = button
- panel.isExtensionHidden = true
- panel.beginSheetModal(for: (self?.view.window!)!) { response in
- if response != .OK {
- callback()
- return
- }
-
- if (type == .redactOne) {
- let anno = self!.listView.activeAnnotation
- if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
- callback()
- return
- }
-
- (anno as! CPDFRedactAnnotation).applyRedaction()
- } else if (type == .redactAll) {
- self?.listView.document.applyRedactions()
- } else if (type == .eraserOne) {
- let anno = self!.listView.activeAnnotation
- if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
- callback()
- return
- }
-
- anno?.page.erasureRedact(from: anno!.bounds)
- } else if (type == .eraserAll) {
- KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
- if (result == false) {
- callback()
- return
- }
- }
- }
-
- self!.listView.document.write(to: panel.url)
- if (button.state == .on) {
- NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
-
- }
- } else {
- NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
- }
- callback()
- }
- }
- }
-
- // MARK: - Secure 【安全】
-
- public func showSecureLimitTip() {
- self.hiddenSecureLimitTip()
-
- if self.secureAlertView == nil {
- self.secureAlertView = KMSecureAlertView()
- self.secureAlertView?.show(in: self.listView)
- self.secureAlertView?.closeAction = { [unowned self] view in
- self.hiddenSecureLimitTip()
-
- self.removeFromAlertView()
- self.showFormAlertView()
- }
-
- self.secureAlertView?.passwordAction = { [unowned self] view in
- self.removeOwnerPassword()
-
- self.removeFromAlertView()
- self.showFormAlertView()
- }
- }
- }
-
- func removeOwnerPassword() {
- guard let doc = self.listView?.document else {
- NSSound.beep()
- return
- }
- if doc.allowsCopying && doc.allowsPrinting {
- NSSound.beep()
- return
- }
- _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
- if result == .cancel { /// 关闭
- return
- }
- /// 解密成功
- self?.hiddenSecureLimitTip()
- self?.model.isSaveKeyChain = false
- self?.listView.document.unlock(withPassword: password)
- }
- }
-
- public func hiddenSecureLimitTip() {
- self.secureAlertView?.removeFromSuperview()
- self.secureAlertView = nil
- }
-
- //MARK: - Form
-
- func showFormAlertView() {
- if (formAlertView == nil) {
- formAlertView = KMFormAlertView()
- formAlertView?.isCloseSecureView = self.secureAlertView != nil ? false : true
- formAlertView?.showInView(self.listView)
- } else {
- self.removeFromAlertView()
- }
- }
-
- func removeFromAlertView() {
- formAlertView?.removeFromSuperview()
- formAlertView = nil
- }
-
- override func mouseMoved(with event: NSEvent) {
- self.view.window?.mouseMoved(with: event)
- }
-
- func savePageNumberIfNeed() {
- if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
- let scaleFactor = self.listView?.scaleFactor ?? 0
- if scaleFactor <= 0 {
- return
- }
- if self.listView.document != nil {
- KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
- KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
- }
- }
- }
-
- // MARK: - 显示合并窗口
-
- public func showMergeWindow(url: URL? = nil, _ password: String?) {
- DispatchQueue.main.async {
- var documentURL = url
- if documentURL == nil {
- documentURL = self.listView.document.documentURL
- }
-
- guard let _url = documentURL else { return }
- guard let document = PDFDocument(url: _url) else { return }
-
- self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
- self.mergeWindowController!.oriDucumentUrl = self.listView.document.documentURL
- self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
-
- self.mergeWindowController!.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet(mergeWindowController!.window!)
- }
-
- self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
- self.view.window?.endSheet(mergeWindowController!.window!)
- }
- self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
-
- self.view.window?.beginSheet(self.mergeWindowController!.window!)
- }
- }
-
- // MARK: - 显示加密弹窗
-
- public func showSecureWindow(_ url: URL) {
- self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
- guard let securityWindowController = securityWindowController else { return }
-
- securityWindowController.documentURL = self.listView.document.documentURL
- securityWindowController.batchAction = { [unowned self] controller, files in
- self.view.window?.endSheet((securityWindowController.window)!)
- self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
- let batchWindowController = KMBatchOperateWindowController.sharedWindowController
- let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
- batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
- batchWindowController.window?.makeKeyAndOrderFront("")
- }
- securityWindowController.doneAction = { [unowned self] controller, options, attribute in
- let openPanel = NSOpenPanel()
- openPanel.canChooseFiles = false
- openPanel.canChooseDirectories = true
- openPanel.canCreateDirectories = true
- openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
- if result == NSApplication.ModalResponse.OK {
- for fileURL in openPanel.urls {
- let document = CPDFDocument(url: self.document?.documentURL)
- if document != nil {
- document!.setDocumentAttributes(attribute)
-
- let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
- let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
- if success {
- self.view.window?.endSheet((securityWindowController.window)!)
-
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
- }
- }
- }
- }
- }
- }
- securityWindowController.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet((securityWindowController.window)!)
- }
- NSWindow.currentWindow().beginSheet(securityWindowController.window!)
- }
-
- // MARK: - 保存文档
-
- internal func needSaveDocument() -> Bool {
- if (self.isPDFDocumentEdited) {
- return self.isPDFDocumentEdited
- }
- if (self.needSave) {
- return self.needSave
- }
-
- let document: KMMainDocument? = self.myDocument as? KMMainDocument
- if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
- return false
- }
- return true
- }
-
- internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
- let document: KMMainDocument? = self.myDocument as? KMMainDocument
- if (overlook) {
- document?.save(nil)
- return
- }
- if (self.isPDFDocumentEdited) {
- self.clearIsPDFDocumentEdited()
- self.needSave = false
- document?.save(nil)
- return
- }
- if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
- return
- }
-
- document?.save(nil)
- }
-
- internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
- let document: KMMainDocument? = self.myDocument as? KMMainDocument
- if (overlook) {
- DispatchQueue.main.async {
- document?.save(nil)
- callback()
- }
- return
- }
- if (self.isPDFDocumentEdited) {
- self.clearIsPDFDocumentEdited()
- self.needSave = false
- DispatchQueue.main.async {
- document?.save(nil)
- callback()
- }
- return
- }
- if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
- callback()
- return
- }
-
- DispatchQueue.main.async {
- document?.save(nil)
- callback()
- }
- }
-
- internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
- // 显示进度
- AutoSaveManager.manager.isSaving = true
- self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
- self.progressC?.maxValue = 3.0
- self.progressC?.increment(by: 1.0)
- // 保存文档
- self.asyncSaveDocument { [unowned self] params in
- // 执行进度 [假进度]
- self.progressC?.increment(by: 1.0)
- self.progressC?.increment(by: 1.0)
-
- DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
- // 隐藏进度
- self.hiddenProgressWindow()
- DispatchQueue.main.asyncAfter(deadline: .now()+1) {
- AutoSaveManager.manager.isSaving = false
- }
- // 回调
- callback()
- }
- }
- }
- func SaveTempPDFDocumentToURLPath(tempPath: String) {
- self.document?.write(toFile: tempPath)
- }
-
- // MARK: - 定时保存
-
- func addAutoSaveEvent() {
- if (self.autoSaveTimer != nil) {
- self.autoSaveTimer?.invalidate()
- self.autoSaveTimer = nil
- }
-
- if self.document != nil {
- self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
- self?.autoSaveTimerAction(timer)
- })
- }
- self.checkAutoSaveInfo()
- }
-
- func checkAutoSaveInfo() {
- guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
- return
- }
- if AutoSaveManager.manager.autoSaveAlertShow {
- return
- }
-
- AutoSaveManager.manager.autoSaveDidEndAction = false
- AutoSaveManager.manager.autoSaveAlertShow = true
-
- let blockSaveWindow = AutoSavePopController()
- blockSaveWindow.cancelHandle = { [weak self] windowController in
- AutoSaveManager.manager.autoSaveDidEndAction = true
- AutoSaveManager.manager.clearCache()
- self?.km_quick_endSheet()
- }
-
- blockSaveWindow.confirmHandle = { [weak self] windowController in
- self?.km_quick_endSheet()
- self?.saveAutoSaveInfo()
- }
- self.km_beginSheet(windowC: blockSaveWindow)
- }
-
- func saveAutoSaveInfo() {
- let openPanel = NSOpenPanel()
- openPanel.canChooseDirectories = true
- openPanel.canChooseFiles = false
- openPanel.allowsMultipleSelection = false
- let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
- openPanel.beginSheetModal(for: win!) { result in
- if (result == .OK) {
- let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
- for path in AutoSaveManager.manager.opendPaths ?? [] {
- let _path = path as? String
- var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
- newPath = self.getValidFilePath(newPath)
- do {
- try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
- } catch {
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
- }
- }
- AutoSaveManager.manager.clearCache()
- }
- AutoSaveManager.manager.autoSaveDidEndAction = true
- }
- }
-
- func autoSaveTimerAction(_ timer: Timer) {
- if (self.document == nil || self.listView?.document?.documentURL.path == nil) {
- return
- }
- if AutoSaveManager.manager.autoSaveDidEndAction == false {
- //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
- return
- }
-
- if let data = self.document?.isLocked, data {
- return
- }
-
- if AutoSaveManager.manager.autoSaveEnabled == false {
- return
- }
-
- let documentArray = NSDocumentController.shared.documents
- var didFileEdit = false
- for doc in documentArray {
- if doc.fileURL?.path == self.document?.documentURL.path {
- didFileEdit = doc.isDocumentEdited
- break
- }
- }
- if (didFileEdit == false) {
- return
- }
-
- AutoSaveManager.manager.isSaving = true
- let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView?.document?.documentURL.path ?? "")
- if (!self.document!.isLocked) {
- self.document?.write(to: URL(fileURLWithPath: savePath))
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
- AutoSaveManager.manager.isSaving = false
- }
- }
-
- func removeAutoSaveInfo() {
- if self.autoSaveTimer != nil {
- self.autoSaveTimer?.invalidate()
- self.autoSaveTimer = nil
- }
-
- if AutoSaveManager.manager.autoSaveDidEndAction == false {
- //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
- return
- }
- if AutoSaveManager.manager.autoSaveEnabled == false {
- return
- }
-
- if self.document == nil || self.listView?.document?.documentURL.path == nil {
- return
- }
- AutoSaveManager.manager.removeAutoSavePath(self.listView?.document?.documentURL.path ?? "")
- }
-
- // MARK: - 选择 PDFDisplay 模式
-
- @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
- let toolModel = self.listView.toolMode
- self.isReadMode = false
- switch display {
- case .singlePage:
- self.listView.setDisplay(.singlePage)
- break
- case .singlePageContinuous:
- self.listView.setDisplay(.singlePageContinuous)
- break
- case .twoUp:
- self.listView.setDisplay(.twoUp)
- break
- case .twoUpContinuous:
- self.listView.setDisplay(.twoUpContinuous)
- break
- case .bookMode:
- self.listView.displaysAsBook = true
- self.listView.displayTwoUp = true
- self.listView.displayDirection = .horizontal
- break
- case .bookContinuous:
- self.listView.displaysAsBook = true
- self.listView.displayTwoUp = true
- self.listView.displayDirection = .vertical
- break
- case .readModel:
- self.openReadModel()
- break
- case .readContinuous:
- self.openReadModel()
- break
- }
-
- self.listView.layoutDocumentView()
- // if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
- // self.leftSideViewController.panelSetViewController.reloadListViewModel()
- // }
-
- if (toolModel == .editPDFToolMode) {
- if self.rightSideViewController.eidtPDFImageProperty != nil {
- self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
- self.rightSideViewController.isHidden = true
- self.closeRightPane()
- }
- }
- }
-
- // MARK: - 选择缩放模式
-
- @objc public func selectZoom(_ type: KMPDFZoomType) {
- switch type {
- case .width:
- self.listView.autoScales = true
- break
- case .fit:
- if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
- let pdfviewHeight = self.listView.bounds.size.height
- self.listView.scaleFactor = pdfviewHeight/pageHeight
- self.listView.autoScales = false
- }
- break
- case .actualSize:
- if self.listView.scaleFactor != 1.0 {
- self.listView.scaleFactor = 1.0
- self.listView.autoScales = false
- }
- break
- }
- }
-
- internal func createPdf(index:Int) {
- if index == 1 {
- self.homeVC?.openBlankPage()
- } else if index == 4 {
- self.homeVC?.importFromCamera()
- } else if index == 5 {
- self.homeVC?.importFromScanner()
- } else if index == 3 {
- self.homeVC?.importFromWebPage()
- } else if index == 2 {
- self.homeVC?.newFromImages()
- }
- }
-
- // MARK - Event 监听
-
- private func addEventMonitor() {
- if (self.eventMonitor != nil) {
- self.removeEventMonitor()
- }
-
- // KMPrint("已添加事件监听")
- self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown]) { [weak self] event in
- if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
- if CustomStampManager.manager.isWindowShow {
- return event
- }
- self?.listView.magnifyWheel(event)
- return nil
- } else if event.type == .leftMouseDown {
- if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
- let can = self?.listView?.canGoToNextPage() ?? false
- if can {
- self?.listView.goToNextPage(nil)
- }
- return nil
- }
- }
- return event
- }
- }
-
- func addKeyEventMonitor() {
- if (self.keyEventMonitor != nil) {
- self.removeKeyEventMonitor()
- }
- keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
- // print(event.keyCode)
- if event.keyCode == 53 {
- if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
- if let data = self?.canExitPresentation(), data {
- self?.browserWindowController?.exitFullscreen()
- }
- return nil
- }
- if self?.listView.toolMode == .editPDFToolMode {
- if self != nil {
- //使用editingSelectionString获取内容文字
- if self!.listView.editingAreas() != nil {
- if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
- self!.listView.clearEditingSelectCharItem()
- } else if self!.listView.editingAreas().count > 0 {
- if self?.listView.annotationType == .addImage ||
- self?.listView.annotationType == .addText {
- let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
- let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
- textItem?.isSelected = false
- imageItem?.isSelected = false
- }
- self?.rightSideViewController.isHidden = true
- self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
- self?.listView.updateEditing([])
- self?.listView.isEditImage = false
- self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
- if self?.listView.annotationType == .addImage {
- self?.listView.change([.text, .image])
- }
- self?.listView.annotationType = .editTextImage
- self?.closeRightPane()
- } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
- if self?.listView.annotationType == .addImage ||
- self?.listView.annotationType == .addText {
- let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
- let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
- textItem?.isSelected = false
- imageItem?.isSelected = false
- }
- self?.rightSideViewController.isHidden = true
- self?.listView.setShouAddEdit([])
- self?.listView.change([.text, .image])
- self?.listView.annotationType = .editTextImage
- self?.closeRightPane()
- }
- } else {
- if self?.listView.annotationType == .addImage ||
- self?.listView.annotationType == .addText {
- let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
- let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
- textItem?.isSelected = false
- imageItem?.isSelected = false
- }
- }
- }
- }
- } else {
- if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
- self?.listView.keyDown(with: event)
- return nil
- }
- }
- return event
- }
- }
-
- func removeKeyEventMonitor() {
- if (self.keyEventMonitor != nil) {
- KMPrint("removeKeyEventMonitor 已移除事件监听")
-
- NSEvent.removeMonitor(self.keyEventMonitor as Any)
- self.keyEventMonitor = nil
- }
- }
-
- private func removeEventMonitor() {
- if (self.eventMonitor != nil) {
- KMPrint("已移除事件监听")
-
- NSEvent.removeMonitor(self.eventMonitor as Any)
- self.eventMonitor = nil
- }
- }
-
- // MARK: - Tools
-
- func pdfViewCanHorizontalScroll() -> Bool {
- let scroll = self.listView.scroll()
- if (scroll == nil) {
- return false
- }
-
- return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
- }
-
- func pdfViewCanVerticalScroll() -> Bool {
- let scroll = self.listView.scroll()
- if (scroll == nil) {
- return false
- }
-
- return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
- }
-
- // MARK: - Public Methods
- // 清理数据 [eg. 通知]
- public func clearData() {
- self.removeNotifications()
- if (self.listView.spellingTag() > 0) {
- NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
- }
- self.removeAutoSaveInfo()
- // self.myDocument = nil
- self.myDocument = nil
-
- }
-
- public func clearSecureOptions() {
- self._secureOptions = nil
- self.documentAttribute = nil
- }
-
- public func recordRemoveSecureFlag() {
- self._removeSecureFlag = true
- self.clearSecureOptions()
- self.recordIsPDFDocumentEdited(type: .removePassword)
- self._needSave = true
- }
-
- public func clearRemoveSecureFlag() {
- self._removeSecureFlag = false
- }
-
- public func clearSaveWatermarkFlag() {
- km_synchronized(self) {
- self._saveWatermarkFlag = false
- }
- }
-
- public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
- km_synchronized(self) {
- self.model.isPDFDocumentEdited = true
-
- if let _document = self.myDocument {
- KMTools.setDocumentEditedState(document: _document)
- }
- }
- }
-
- public func clearIsPDFDocumentEdited() {
- km_synchronized(self) {
- self.model.isPDFDocumentEdited = false
- }
- }
-
- func showSnapshots(setups: NSArray?) {
- for setup in setups ?? [] {
- let swc = KMSnapshotWindowController()
- swc.delegate = self
- swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
- swc.setForceOnTop(self.interactionMode != .normal)
- self.myDocument?.addWindowController(swc)
- }
- }
-
- func dealDocumentDidLoaded() {
- self.removeBackgroundMaskView()
- if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
- self.showSecureLimitTip()
- }
-
- if self.model.needConvertNotes {
- self.showConvertNotesProgress()
- }
- if (self._documentFirstLoad) {
- self.checkShouldAutoOpenLeftVC()
- if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
- let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
- let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
- if (pageScale != nil) {
- self.listView.scaleFactor = CGFloat(pageScale!)
- }
- if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
- self.listView.go(toPageIndex: pageNumber!, animated: false)
- } else {
- self._goToFirstPageForFristAppear()
- }
- } else {
- self._goToFirstPageForFristAppear()
- }
- self._documentFirstLoad = false
- }
- }
-
- func tabViewIsDragging() -> Bool {
- let level = self.view.window?.level ?? .normal
- return level == .floating
- }
-
- // MARK: - Noti Actions
-
- internal func documentDidUnlockNotification(_ sender: Notification) {
- if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
-
- if (self.myDocument == nil) {
- return
- }
- if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
- self.hiddenSecureLimitTip()
- }
-
- let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
- if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
- return
- }
-
- let type = KMPreferenceManager.shared.savePasswordType
- if (type == .never) {
- return
- }
- if (type == .always) {
- self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
- return
- }
-
- // 保存到钥匙串
- let alert = NSAlert()
- alert.messageText = NSLocalizedString("Remember Password?", comment: "")
- alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
- alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
- alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
- if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
- self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
- return
- }
- }
- }
-
- func annotationsAttributeHasChange(_ sender: Notification) {
- guard let dict = sender.object as? [String : Any] else {
- return
- }
- if let anno = dict["object"] as? CPDFAnnotation {
- let value = dict["keyPath"] as? String ?? ""
- let didEnd = dict["didEnd"] as? Bool ?? false
- if didEnd {
- if value == CPDFAnnotationBoundsKey {
- if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
- anno.contents = anno.page?.string(for: anno.bounds) ?? ""
- }
- }
- self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
- } else {
- if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
- self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
- }
- }
- }
- }
-
- internal func applicationWillTerminateNotification(_ sender: Notification) {
- self.savePageNumberIfNeed()
- self.saveDocument()
- }
-
- func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
- if self.isReadMode {
- self.readModelView.currentPageIndex = self.listView.currentPageIndex
- }
- //刷新前一页后一页按钮
- self.updateNextAndPreViousButtonState()
- }
-
- func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
- if self.isReadMode {
- self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
- }
- //刷新前一页后一页按钮
- self.updateNextAndPreViousButtonState()
- }
-
- func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
- var editSelectd = false
- if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
- editSelectd = true
- }
- if self.listView.toolMode == .editPDFToolMode {
- if editSelectd {
- self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
- }
- }
- }
-
- @objc func handlePageChangedNotification(_ sender: Notification) {
- // When the PDFView is changing scale, or when view settings change when switching fullscreen modes,
- // a lot of wrong page change notifications may be send, which we better ignore.
- // Full screen switching and zooming should not change the current page anyway.
- if self.mwcFlags.isSwitchingFullScreen > 0 {
- return
- }
- //
- let page = self.listView.currentPage()
- let pageIndex = page?.pageIndex() ?? 0
- self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
- self.leftSideViewController.thumbnailTableView.needsDisplay = true
- self.leftSideViewController.tocOutlineView.needsDisplay = true
- }
-
- @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
- self.leftSideViewController.reloadThumbnailDataIfNeed()
- }
-
- @objc func willEnterInteractionModeNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
- if interactionMode == .presentation {
- let backgroundColor = NSColor.black
- let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
-
- let wasInteractionMode = self.interactionMode
- if wasInteractionMode == .normal {
- self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
- }
-
- if wasInteractionMode == .legacyFullScreen {
- self.enterPresentationMode()
- self.pdfSplitView.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(centerContentView.bounds), height: CGRectGetHeight(centerContentView.bounds)-1)
- self.centerContentView.addSubview(pdfSplitView)
- self.listView.frame = (self.view.window?.contentView?.bounds)!
- self.view.window?.contentView?.addSubview(listView)
-
- self.view.window?.backgroundColor = backgroundColor
- self.view.window?.level = level
- self.listView.layoutDocumentView()
- self.listView.requiresDisplay()
-
- self.forceSubwindowsOnTop(false)
-
- self.hideLeftSideWindow()
- self.hideRightSideWindow()
- self.removeBlankingWindows()
- }
- } else {
- KMPrint("2")
- }
- }
-
- @objc func didEnterInteractionModeNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
- self.listView?.layoutDocumentView()
- self.listView?.requiresDisplay()
- }
- }
-
- @objc func willShowFullScreenNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
- let view = self.view.window?.firstResponder as? NSView
- if let data = view?.isDescendant(of: self.pdfSplitView), data {
- self.view.window?.makeFirstResponder(nil)
- }
- }
- }
-
- @objc func didShowFullScreenNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
- self.enterPresentationMode()
- }
- }
-
- @objc func didAddContentViewNotification(_ sender: Notification) {
- guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
- return
- }
- if self.interactionMode == .presentation {
-
- }
- }
-
- // MARK: Split View
-
- func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
- let openPanel = NSOpenPanel()
- openPanel.allowedFileTypes = ["pdf", "PDF"]
- openPanel.allowsMultipleSelection = false
-
- guard let mainWindow = NSApp.mainWindow else {
- return
- }
-
- openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
- if response == NSApplication.ModalResponse.OK {
- guard let url = openPanel.url else {
- return
- }
-
- if let document = CPDFDocument(url: url) {
- self?.secondaryPdfView?.document = nil
- self?.secondaryPdfView?.document = document
-
- if isChange {
- self!.openSecondaryPdfView!.view.removeFromSuperview()
- }
-
- replaceBlock(document.documentURL?.path ?? "")
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
- alert.runModal()
- }
- }
- }
- }
- }
- extension KMMainViewController {
- func currentSetup() -> [String: Any] {
- var setup: [String: Any] = [:]
- var point = NSZeroPoint
- // var rotated = listView.currentPage().rotation
- if listView == nil {
- return setup
- }
- let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
-
- setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
- setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
- setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
- setup[KMMainModel.Key.pageIndex] = pageIndex
- // if rotated != 0 {
- // setup[SCROLLPOINT_KEY] = NSStringFromPoint(point)
- // }
- // if !snapshots.isEmpty {
- // setup[SNAPSHOTS_KEY] = snapshots.map { $0[SKSnapshotCurrentSetupKey] }
- // }
- // if interactionMode == SKNormalMode {
- // setup.merge(currentPDFSettings(), uniquingKeysWith: { $1 })
- // } else {
- // setup.merge(savedNormalSetup, uniquingKeysWith: { $1 })
- // ["HASHORIZONTALSCROLLER_KEY", "HASVERTICALSCROLLER_KEY", "AUTOHIDESSCROLLERS_KEY", "LOCKED_KEY"].forEach { setup.removeValue(forKey: $0) }
- // }
-
- return setup
- }
-
- // MARK: - Recommond活动
-
- func loadRecommondPopWindow() {
- if IAPProductsManager.default().isAvailableAllFunction() {
- return
- }
- }
- }
- extension KMMainViewController {
- func changeFont(_ sender: NSFontManager) {
- KMPrint("changeFont ...")
- if ((self.listView.activeAnnotation?.isKind(of: CPDFFreeTextAnnotation.self)) != nil) {
- let annotation: CPDFFreeTextAnnotation = self.listView.activeAnnotation as! CPDFFreeTextAnnotation
- var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
- font = sender.convert(font!)
-
- annotation.setFontSize(font!.pointSize)
-
- self.listView.commitEditAnnotationFreeText(annotation)
- self.listView.setNeedsDisplay(annotation)
- }
- }
- }
|