123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208 |
- //
- // 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?
-
- //AI相关
- var aiTipView: AITipIconView!
- var aiTypeChooseView: AITypeChooseView!
-
- //Search
- var searchIndex: Int = 0
-
- //Form
- var formAlertView: KMFormAlertView?
- //Secure
- var secureAlertView: KMSecureAlertView?
-
- //对比
- var isCompareModel: Bool = false {
- didSet {
- self.toolbarController.updataItemVisible()
- }
- }
- //密码弹窗
- var passwordWindow: KMPasswordInputWindow?
-
- //春季活动
- var recommondPopWindowVC: KMRecommondPopWindow?
-
- 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?
-
- let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
- let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
-
- 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.removeEventMonitor()
- self.removeKeyEventMonitor()
- }
- override func awakeFromNib() {
- super.awakeFromNib()
- self.addBackgroundMaskView()
-
- self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
- listView.delegate = self
- listView.pdfListViewDelegate = self
- // listView.editingConfig().isSupportMultipleSelectEditingArea = true
- if (document != nil) {
- // if (self.document!.isLocked) {
- //
- // } else {
- 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()
-
- //春季活动
- if ((KMAdvertisementManager.manager.info.popWindowContent) != nil) {
- if KMAdvertisementManager.manager.info.popWindowContent!.content!.count > 0 {
- let info = KMAdvertisementManager.manager.info.popWindowContent!.content?.first
- if KMAdvertisementManager.checkAdvertisementValid(info!) {
- self.loadRecommondPopWindow()
- }
- }
- }
-
- //刷新前一页后一页按钮
- self.updateNextAndPreViousButtonState()
-
- KMLightMemberManager.manager.canShowAdvancedView = false
- // Task { @MainActor in
- // await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
- // }
- // 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()
- // self.loadAIIconView()
- }
-
- if (self.document?.isLocked == false) {
- 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
- return
- }
- }
-
- DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
- if self.passwordWindow == nil && self.view.window != nil {
- self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [unowned self] result , password in
- self.passwordWindow = nil
- if (result == .cancel) {
- self.browserWindowController?.browser.closeTab()
- return
- }
- self.model.isSaveKeyChain = true
- self.listView.document = self.document
- self.document?.unlock(withPassword: password)
- }
- } else {
- self.passwordWindow = nil
- }
- }
- }
-
- override func viewWillDisappear() {
- super.viewWillDisappear()
-
- 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
- }
- }
-
- 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 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()
-
- self.addAdsBannerView()
-
- //检测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()
- }
- // [self applyPDFSettings:hasWindowSetup ? savedNormalSetup : [sud dictionaryForKey:SKDefaultPDFDisplaySettingsKey]];
- // self.applyPDFSettings((KMDataManager.ud_dictionary(forKey: SKDefaultPDFDisplaySettingsKey) as? NSDictionary) ?? [:])
- // self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
- }
-
- //MARK: - PDFListView
-
- func initPDFLeftViewVC() {
- var frame = self.leftView.frame
- frame.size.width += 44
- self.leftView.frame = frame
-
- leftSideViewController.listView = self.listView ?? CPDFListView()
- 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.propertyDidChange = { [weak self] model in
- if let anno = model as? CSelfSignAnnotation {
- self?.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: nil)
- }
- }
- }
-
- func addAdsBannerView() {
- #if VERSION_FREE
- if !IAPProductsManager.default().isAvailableAllFunction(){
- guard let document = self.listView.document else {
- return
- }
- if !document.isLocked {
- KMAdsManager.defaultManager.beginSheetModalForView(self.readContentView, directions: .down, adPosY: 30, animated: false) { pageIndex in
-
- }
- }
- NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
- NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
-
- }
- #endif
- //加载底部banner
- // - (void)loadingAdsManager {
- // #if VERSION_FREE
- // if(![self.pdfDocument isLocked]) {
- // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
- // [[KMAdsManager defaultManager] beginSheetModalForView:self.pdfView
- // directions:KMADViewDirectionsDown
- // animated:NO
- // completionHandler:nil];
- // }
- // [[NSNotificationCenter defaultCenter] addObserverForName:KMIAPProductPurchasedNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
- // if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
- // [[KMAdsManager defaultManager] dismissSheetModalForView:self.pdfView];
- // }
- // }];
- // [[NSNotificationCenter defaultCenter] addObserverForName:kDeviceActivateStatusChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
- // if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
- // [[KMAdsManager defaultManager] dismissSheetModalForView:self.pdfView];
- // }
- // }];
- // }
- // #endif
- // }
- }
-
- // 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()
- }
- }
-
- 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
- }
-
- 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
-
- let controller = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document.password)
- self.addChild(controller)
- self.PDFContendView.addSubview(controller.view)
- controller.view.frame = self.PDFContendView.bounds
- controller.view.autoresizingMask = [.width, .height]
- self.listView.isHidden = true
-
- controller.scaleFactor = self.listView.scaleFactor
- controller.titleBack = { [weak self] title in
- self?.view.window?.title = title
- }
- controller.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
- self?.listView.go(toPageIndex: controller.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()
- }
- }
- controller.setCurrentPageIndex(self.listView.currentPageIndex)
- }
-
- func exitRedact() {
- 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 loadAIIconView() -> Void {
- NotificationCenter.default.addObserver(self, selector: #selector(aiTipIconViewShowStateChangeNoti), name: NSNotification.Name(rawValue: "kAIIconShowStateChangeNotification"), object: nil)
- if self.aiTipView == nil {
- self.aiTipView = AITipIconView.createFromNib()
- self.aiTipView.clickHandle = { [weak self] view in
- // self?.showAITypeChooseView()
- }
- self.aiTipView.rightClickHandle = {[unowned self] view in
- AIInfoManager.default().showAIIcon = false
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kAIIconShowStateChangeNotification"), object: nil)
- }
- }
-
- self.aiTipView.frame = CGRectMake(CGRectGetWidth(self.readContentView.frame)-84, CGRectGetHeight(self.readContentView.frame)-64-40, 72, 72)
- self.aiTipView.autoresizingMask = [.minXMargin, .minYMargin]
- self.readContentView.addSubview(self.aiTipView)
- self.updateAITipViewShowState()
- }
-
- func updateAITipViewShowState() {
- if AIInfoManager.default().showAIIcon {
- if self.view.window != nil {
- if self.isReadMode || KMTools.isFullScreen(self.view.window!) {
- self.aiTipView.isHidden = true
- } else {
- self.aiTipView.isHidden = false
- }
- } else {
- self.aiTipView.isHidden = false
- }
-
- } else {
- self.aiTipView.isHidden = true
- }
- }
-
- 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()
- }
- }
- windowVC.window?.center()
- 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() {
- self.updateAITipViewShowState()
- }
-
- //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")!
-
- let guideWC = KMGuideInfoWindowController.currentWC()
- 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) {
- let guideWC = KMGuideInfoWindowController.currentWC()
- 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) {
- let guideWC = KMGuideInfoWindowController.currentWC()
- 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) {
- let guideWC = KMGuideInfoWindowController.currentWC()
- 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 {
- 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
-
- 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()
- }
- }
-
- open func hasEnterPageEdit() -> Bool {
- return self.getPDFEditController() != nil
- }
-
- // 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 }
-
- let windowController = KMMergeWindowController(document: document, password: password ?? "")
- windowController.oriDucumentUrl = self.listView.document.documentURL
- windowController.pageIndex = self.listView.currentPageIndex
- self.currentWindowController = windowController
-
- windowController.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
- }
-
- windowController.mergeAction = { [unowned self] controller, filePath in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
-
- // let newDocument = CPDFDocument(url: NSURL(fileURLWithPath: filePath) as URL)
- // if let data = newDocument?.isLocked, data {
- // newDocument?.unlock(withPassword: self.listView.document.password ?? "")
- // }
- //
- // self.setDocument = newDocument
- // self.leftSideViewController.refreshUIForDocumentChanged()
- }
- self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
-
- self.view.window?.beginSheet(windowController.window!)
- }
- }
-
- // MARK: - 显示加密弹窗
-
- public func showSecureWindow(_ url: URL) {
- let controller = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
- controller.documentURL = self.listView.document.documentURL
- self.currentWindowController = controller
- controller.batchAction = { [unowned self] controller, files in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
- self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
- let batchWindowController = KMBatchOperateWindowController.sharedWindowController
- // batchWindowController.window?.makeKeyAndOrderFront("")
- let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
- batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
- batchWindowController.window?.makeKeyAndOrderFront("")
- }
- controller.doneAction = { [unowned self] controller, options, attribute in
- // let windowController_secure = self.currentWindowController as! KMSecureEncryptWindowController
- 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((self.currentWindowController.window)!)
- self.currentWindowController = nil
-
-
- NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
- }
- }
- }
- }
- }
- }
- controller.cancelAction = { [unowned self] controller in
- self.view.window?.endSheet((self.currentWindowController.window)!)
- self.currentWindowController = nil
- }
- NSWindow.currentWindow().beginSheet(controller.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) {
- // 显示进度
- 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.async {
- DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
- // 隐藏进度
- self.hiddenProgressWindow()
-
- // 回调
- 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
- // self.listView.autoScales = false
- break
- case .fit:
- // self.listView.autoScales = !self.listView.autoScales
- 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) { [weak self] event in
- if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
- self?.listView.magnifyWheel(event)
- 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()
- KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
- }
-
- 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.document != nil {
- self.convertNotesUsingPDFDocument(self.document!)
- }
- 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
- }
- }
-
- // MARK: - Noti Actions
-
- internal func documentDidUnlockNotification(_ sender: Notification) {
- if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
-
- // self.loadAIIconView()
-
- if (self.myDocument == nil) {
- return
- }
- if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
- self.hiddenSecureLimitTip()
- }
-
- if ((self.myDocument as! KMMainDocument).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 {
- // if ([pdfView isZooming] || mwcFlags.isSwitchingFullScreen) {
- // [self updatePageNumber];
- // [self updateLeftStatus];
- return
- }
- //
- let page = self.listView.currentPage()
- let pageIndex = page?.pageIndex() ?? 0
- //
- // if ([lastViewedPages count] == 0) {
- // [lastViewedPages addPointer:(void *)pageIndex];
- // } else if ((NSUInteger)[lastViewedPages pointerAtIndex:0] != pageIndex) {
- // [lastViewedPages insertPointer:(void *)pageIndex atIndex:0];
- // if ([lastViewedPages count] > 5)
- // [lastViewedPages setCount:5];
- // }
- self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
- self.leftSideViewController.thumbnailTableView.needsDisplay = true
- self.leftSideViewController.tocOutlineView.needsDisplay = true
- //
- // [self updatePageNumber];
- // [self updatePageLabel];
- //
- // [self updateOutlineSelection];
- // [self updateNoteSelection];
- // [self updateThumbnailSelection];
- //
- // if (beforeMarkedPageIndex != NSNotFound && [[pdfView currentPage] pageIndex] != markedPageIndex)
- // beforeMarkedPageIndex = NSNotFound;
- //
- // [self synchronizeWindowTitleWithDocumentName];
- // [self updateLeftStatus];
- // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
- // [self updateRightStatus];
- // if ([self interactionMode] == SKPresentationMode)
- // [[self presentationNotesDocument] setCurrentPage:[[[self presentationNotesDocument] pdfDocument] pageAtIndex:[page pageIndex]]];
- }
-
- @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
- self.leftSideViewController.reloadThumbnailDataIfNeed()
- // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
- // [self updateRightStatus];
- }
-
- @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 findController.view().window() != nil {
- // findController.toggleAboveView(nil, animate: false)
- // }
-
- if wasInteractionMode == .legacyFullScreen {
- self.enterPresentationMode()
- // updatePresentationOptions(for: self.view.window!)
- 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 {
- // if self.pdfView().currentPage()?.isEqual(page) == false {
- // self.pdfView().go(to: page)
- // }
-
- // pdfView().setInteractionMode(SKPresentationMode)
-
- 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 {
-
- }
- }
-
- @objc func purchaseStateUpdateNoti() {
- if IAPProductsManager.default().isAvailableAllFunction() {
- KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
- }
- }
-
- // 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
- 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
- }
-
- if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
- if recommondPopWindowVC == nil {
- recommondPopWindowVC = KMRecommondPopWindow()
- }
- recommondPopWindowVC?.recommondInfo = info
-
- guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
- return
- }
-
- let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
- let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
- recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
-
- recommondPopWindowVC?.window?.orderFront((Any).self)
- recommondPopWindowVC?.window?.becomeMain()
-
- UserDefaults.standard.set("Show", forKey: info.version ?? "")
- UserDefaults.standard.synchronize()
- }
- }
- }
|