1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792 |
- //
- // KMMainViewController.swift
- // PDF Master
- //
- // Created by wanjun on 2022/12/15.
- //
- import Cocoa
- @objcMembers class KMMainViewController: NSViewController,CPDFViewDelegate,CPDFListViewDelegate,NSTextFieldDelegate {
-
- @IBOutlet var PDFContendView: NSView!
- @IBOutlet var centerContentView: NSView!
- @IBOutlet var listView: CPDFListView!
- @IBOutlet var secondaryPdfView: CPDFView!
-
- @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 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!
- var isReadMode: Bool = false
- @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
-
- //页码显示器
- @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
- @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
-
- private var _needSave = false
- var needSave: Bool {
- set {
- _needSave = newValue
-
- if (_needSave == false) {
- self._isPDFDocumentEdited = false
- self.hiddenSecureSuccessTip()
- }
- }
- get {
- return _needSave
- }
- }
- // 标识 pdf 已编辑
- internal var _isPDFDocumentEdited = false
- var isPDFDocumentEdited: Bool {
- get {
- return _isPDFDocumentEdited
- }
- }
- var password: String?
-
- var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
- var rightSideViewController: KMRightSideViewController!
- var searchResults: [KMSearchMode] = []
- var mwcFlags: MwcFlags = MwcFlags()
- var isShowQuickTour: Bool = false
- var document: CPDFDocument?
- var myDocument: NSDocument?
- var browserWindowController: KMBrowserWindowController?
-
- var documentAIViewController: KMDocumentAIViewController?
-
- var cropSettingWindowController: KMCropSettingWindowController!
- var currentWindowController: NSWindowController!
-
- let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
- let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
-
- @IBOutlet weak var topTipBox: NSBox!
- @IBOutlet weak var exitFullButton: NSButton!
-
- var hasAddRedact: Bool = false
-
- var functionWidth: Double {
- get {
- if self.isReadMode {
- if !self.isShowBOTA {
- return 0
- }
- }
- return 48
- }
- }
- var isShowBOTA: Bool = false
-
- let panelWidth = 212.0
- let defaultRightWidth = 260.0
- var lastLeftPanWidth = 0.0
- var lastRightPanWidth = 0.0
- var leftPanelOpen: Bool = false
- var rightPanelIsOpen = false
- var pageNumber: UInt?
-
- var openSecondaryPdfView: KMSecondaryViewController?
- var secondaryPdfContentView: NSView?
- var lastSplitPDFHeight: Float?
- internal var isSaveKeyChain = true
-
- var pdfEditController: KMPDFEditViewController? {
- get {
- return self.getPDFEditController()
- }
- }
-
- var autoSaveTimer: Timer?
- var progressController: SKProgressController?
- private var _documentFirstLoad: Bool = true
-
- var eventMonitor: Any?
- var mouseRightMenuEvent: NSEvent?
- var aiTranslationWindow: KMAITranslationWindowController?
- var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
-
- deinit {
- NotificationCenter.default.removeObserver(self)
- self.stopAutoSaveTimer()
- self.removeEventMonitor()
- }
- override func awakeFromNib() {
- super.awakeFromNib()
-
- // pdfSplitView.frame = NSMakeRect(0, 0, NSWidth(centerContentView.bounds), NSHeight(centerContentView.bounds)-1)
- // centerContentView.addSubview(pdfSplitView)
- self.PDFContendView.backgroundColor(NSColor(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
- }
-
- override func viewDidAppear() {
- super.viewDidAppear()
- 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: NSNotification.Name(rawValue: kKMWindowDidBecomeMainNotificationName), object: self.myDocument)
-
- if (self.document == nil) {
- return
- }
- if (self.document!.isLocked == false) {
- return
- }
- if (self.view.window == nil) {
- return
- }
- if (self.password != nil) {
- self.isSaveKeyChain = false
- self.listView.document.unlock(withPassword: self.password)
- return
- }
-
- KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { result , password in
- if (result == .cancel) {
- self.browserWindowController?.browser.closeTab()
- return
- }
- self.isSaveKeyChain = true
- self.listView.document = self.document
- self.document?.unlock(withPassword: password)
- }
- }
-
- override func viewWillAppear() {
- super.viewWillAppear()
-
- self.reStartAutoSaveTimer()
- }
- override func viewWillDisappear() {
- super.viewWillDisappear()
-
- // KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
- self.pauseAutoSaveTimer()
- self.removeEventMonitor()
- }
-
- override func viewWillLayout() {
- super.viewWillLayout()
-
- if (KMTools.isFullScreen(self.view.window!)) { // 全屏
- 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()
- leftSideViewController.mainVC = self
-
- mwcFlags.settingUpWindow = 1
- toolbarController.delegate = self
-
- //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
- toolbarBox.contentView = toolbarController.view
-
- // self.childToolbarController.updateType(newType: .Annatiton)
- // self.showChildToolbar(showToolbar: true)
- // self.toolbarController.editPDFButtonAction(item: NSMenuItem())
-
- 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, animate: false)
- mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: false)
-
- pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
-
- 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)
- }
- }
- }
- }
-
- //阅读页面
- readModelView.delegate = self
- pageNumberDisplayView.delegate = self
-
- tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
- if mouseEntered {
- self.pageNumberDisplayView.hover = true
- // self.updatePageIndicatoreType()
- } else {
- self.pageNumberDisplayView.hover = false
- // self.updatePageIndicatoreType()
- }
- }
- 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(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)
-
- self.autoSaveTimeStartOrStopIfNeed()
-
- self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
- }
-
- //MARK: - PDFListView
- func initPDFLeftViewVC() {
- 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.rightView.addSubview(self.rightSideViewController.view)
- self.rightSideViewController.propertyDidChange = {
- [weak self] (model: AnyObject?) in
- let topBarView = self?.toolbarController.fetchTopBarView()
- if (topBarView == nil || ((topBarView?.isKind(of: KMWatermarkAdjectiveTopBarView.self)) == false)) {
- return
- }
-
- /// Bates码、页眉页脚、背景、水印
- if (model == nil) {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
- } else {
- if ((model?.isKind(of: KMBatesModel.self))!) {
- if ((model as! KMBatesModel).hasVaild) {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
- } else {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
- }
- } else if ((model?.isKind(of: KMHeaderFooterModel.self))!) {
- if ((model as! KMHeaderFooterModel).hasVaild) {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
- } else {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
- }
- } else if ((model?.isKind(of: KMBackgroundModel.self))!) {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
- } else if ((model?.isKind(of: KMWatermarkModel.self))!) {
- (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
- }
- }
- }
- }
-
- // MARK: Private Methods
-
- internal func removeNotifications() {
- NotificationCenter.default.removeObserver(self)
- self.leftSideViewController.clearAnnotationFilterData()
- self.leftSideViewController.clearNotification()
- }
-
- func checkShouldAutoOpenLeftVC() {
- if (KMPreferenceManager.shared.leftSideNeedCloseWhenOpenFile()) {
- return
- }
- if (KMPreferenceManager.shared.leftSideDisplayType == .showOutlineIfHas) {
- let outlineRoot = self.listView.document.outlineRoot()
- let hasOutline = (outlineRoot != nil && outlineRoot!.numberOfChildren > 0)
- if (hasOutline == false) {
- return
- }
-
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
- self.leftSideViewController.refreshMethodType(methodType: .Outline)
- }
- return
- }
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
- let selectedIndex = UserDefaults.standard.integer(forKey: "KMBOTASelectedIndexKey")
- let thumai = KMLeftMethodMode()
- if selectedIndex == 0 {
- thumai.methodType = .Thumbnail
- } else if selectedIndex == 1 {
- thumai.methodType = .Outline
- } else if selectedIndex == 2 {
- thumai.methodType = .BookMark
- } else if selectedIndex == 3 {
- thumai.methodType = .Annotation
- } else if selectedIndex == 4 {
- thumai.methodType = .Search
- }
-
- self.leftSideViewController.refreshMethodType(methodType: thumai.methodType)
- }
- }
-
- func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
- mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
- mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
- lastLeftPanWidth = leftSideWidth
- lastRightPanWidth = rightSideWidth
- }
-
- //MARK: 动画 暂未接入
- func animateSplitView(to position: CGFloat) {
- let frame1 = NSRect(x: 0, y: 0, width: position, height: mianSplitView.frame.height)
- let frame2 = NSRect(x: position, y: 0, width: mianSplitView.frame.width - position, height: mianSplitView.frame.height)
-
- // 创建一个新的动画上下文
- let animationContext = NSAnimationContext.current
- animationContext.duration = 0.5
- animationContext.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
-
- // 启用隐式动画
- NSAnimationContext.current.allowsImplicitAnimation = true
-
- // 移动分隔条
- mianSplitView.setPosition(position, ofDividerAt: 0)
- mianSplitView.subviews[0].frame = frame1
- mianSplitView.subviews[1].frame = frame2
- }
-
- 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: - 页面编辑
-
- open func enterPageEdit(_ pages: [Int] = []) {
- //选中page
- var tPages = pages
- if tPages.count == 0 {
- tPages = self.leftSideViewController.selectPages ?? [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! KMToolBoxItem).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]
-
- 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] _ in
- self?._isPDFDocumentEdited = true
- // self?.needSave = true
- }
- }
-
- 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! KMToolBoxItem).unEnabled = false
- }
- }
- }
-
- let editController = getPDFEditController()
- if (editController == nil) {
- return
- }
-
- editController?.view.removeFromSuperview()
- editController?.removeFromParent()
-
- self.view.window?.makeFirstResponder(self.listView)
- }
-
- 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
- }
-
- func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
- let fileManager = FileManager.default
- do {
- let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
- if let fileSize = fileAttributes[.size] as? UInt64 {
- let megabyteSize = fileSize / (1024 * 1024)
- return megabyteSize > 10
- }
- } catch {
- print("Error: \(error)")
- }
- return 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 showSecureSuccessTip() {
- let view: NSView = self.view
- let tip = KMSecureEncryptSuccessTipView()
- let size = NSSize(width: 379, height: 176)
- tip.frame = NSMakeRect(view.frame.size.width-size.width-16, view.frame.size.height-size.height-88, size.width, size.height)
- tip.autoresizingMask = [.minXMargin, .minYMargin]
- view.addSubview(tip)
-
- tip.itemClick = { [weak self] in
- self!.hiddenSecureSuccessTip()
- }
- }
-
- public func hiddenSecureSuccessTip() {
- let view: NSView = self.view
- var tip: KMSecureEncryptSuccessTipView?
- for subview in view.subviews {
- if (subview.isKind(of: KMSecureEncryptSuccessTipView.self)) {
- tip = (subview as! KMSecureEncryptSuccessTipView)
- break
- }
- }
-
- if (tip == nil) {
- return
- }
-
- tip?.removeFromSuperview()
- }
-
- public func showSecureLimitTip() {
- self.hiddenSecureLimitTip()
-
- let view: NSView = self.view
- let tip = KMSecureLimitAlertView()
- let size = NSSize(width: 379, height: 154)
- tip.frame = NSMakeRect(view.frame.size.width-size.width-16, view.frame.size.height-size.height-50, size.width, size.height)
- tip.autoresizingMask = [.minXMargin, .minYMargin]
- view.addSubview(tip)
-
- tip.itemClick = { [unowned self] index in
- if (index == 1) {
- self.hiddenSecureLimitTip()
- return
- }
-
- if (self.listView.document.allowsPrinting == false || self.listView.document.allowsCopying == false) {
- KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
- if result == .cancel { /// 关闭
- return
- }
- /// 解密成功
- self?.hiddenSecureLimitTip()
- self?.isSaveKeyChain = false
- self?.listView.document.unlock(withPassword: password)
- }
- return
- }
- }
- }
-
- public func hiddenSecureLimitTip() {
- let view: NSView = self.view
- var tip: KMSecureLimitAlertView?
- for subview in view.subviews {
- if (subview.isKind(of: KMSecureLimitAlertView.self)) {
- tip = (subview as! KMSecureLimitAlertView)
- break
- }
- }
-
- if (tip == nil) {
- return
- }
-
- tip?.removeFromSuperview()
- }
-
- override func mouseMoved(with event: NSEvent) {
-
- }
-
- func savePageNumberIfNeed() {
- if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
- 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: -
- // MARK: 退出全屏
- @IBAction func exitFullScreen(_ sender: Any) {
- if (self.view.window == nil) {
- return
- }
-
- if (KMTools.isFullScreen(self.view.window!)) {
- self.view.window?.toggleFullScreen(nil)
- }
- }
-
- // MARK: -
- // MARK: 显示合并窗口
-
- public func showMergeWindow(_ password: String?) {
- let document = PDFDocument(url: self.listView.document.documentURL)
- let windowController = KMPDFEditAppendWindow(pdfDocument: document, password: password)
-
- self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
-
- windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, selectedIndexSet in
- })
- }
-
- // MARK: -
- // MARR: 显示加密弹窗
-
- public func showSecureWindow(_ url: URL) {
- let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
- windowController.documentURL = url
- windowController.myDocument = self.listView.document
- self.currentWindowController = windowController
- windowController.itemClick = { [weak self] index in
- self?.view.window?.endSheet((self?.currentWindowController.window)!)
- self?.currentWindowController = nil
- }
-
- windowController.resultCallback = { [weak self] result in
- let windowController_secure = self?.currentWindowController as! KMSecureEncryptWindowController
- self?.view.window?.endSheet((self?.currentWindowController.window)!)
- self?.currentWindowController = nil
-
- self?.listView.document.setPasswordOptions(windowController_secure.options)
- self?.needSave = true
- self?._isPDFDocumentEdited = true
-
- if (result) {
- self?.showSecureSuccessTip()
- } else {
- let alert = NSAlert()
- alert.messageText = NSLocalizedString("Failure", comment: "")
- alert.runModal()
- }
- }
-
- self.view.window?.beginSheet(windowController.window!)
- }
-
- // MARK: -
- // 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._isPDFDocumentEdited = false
- 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._isPDFDocumentEdited = false
- 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 PDF", comment: ""))
- self.progressController?.maxValue = 3.0
- self.progressController?.increment(by: 1.0)
- // 保存文档
- self.asyncSaveDocument { [unowned self] params in
- // 执行进度 [假进度]
- self.progressController?.increment(by: 1.0)
- self.progressController?.increment(by: 1.0)
-
- // DispatchQueue.main.async {
- DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
- // 隐藏进度
- self.hiddenProgressWindow()
-
- // 回调
- callback()
- }
- }
- }
-
- // MARK: -
- // MARK: 选择 PDFDisplay 模式
- @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
- 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()
- }
- }
-
- // Mark: -
- // 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
- self.listView.autoScales = true
- break
- case .actualSize:
- if self.listView.scaleFactor != 1.0 {
- self.listView.scaleFactor = 1.0
- self.listView.autoScales = false
- }
- break
- }
- }
-
- // MARK: -
- // MARK: - 自动保存
-
- internal func autoSaveTimeStartOrStopIfNeed() {
- if (KMPreferenceManager.shared.autoSave == false) {
- self.stopAutoSaveTimer()
- return
- }
-
- self.startAutoSaveTimer(KMPreferenceManager.shared.autoSaveTimeInterval)
- if (self.myDocument == nil) {
- self.stopAutoSaveTimer()
- return
- }
-
- let browser = self.browserWindowController?.browser
- guard let activeDocument = browser?.activeTabContents() else {
- return
- }
-
- if (self.myDocument!.isEqual(to: activeDocument) == false) {
- self.pauseAutoSaveTimer()
- return
- }
- }
-
- private func startAutoSaveTimer(_ interval: TimeInterval) {
- if (self.autoSaveTimer != nil) {
- self.autoSaveTimer?.invalidate()
- self.autoSaveTimer = nil
- }
-
- self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] timer in
- DispatchQueue.main.async {
- #if DEBUG
- print("文档已自动保存")
- guard let document = self?.myDocument else {
- return
- }
- print(document.fileURL as Any)
- #endif
- self?.saveDocument()
- }
- }
- RunLoop.current.add(self.autoSaveTimer!, forMode: .common)
- }
-
- private func pauseAutoSaveTimer() {
- self.autoSaveTimer?.fireDate = Date.distantFuture
- }
-
- private func reStartAutoSaveTimer() {
- self.autoSaveTimer?.fireDate = Date()+KMPreferenceManager.shared.autoSaveTimeInterval
-
- }
-
- private func stopAutoSaveTimer() {
- self.autoSaveTimer?.invalidate()
- self.autoSaveTimer = nil
- }
-
- // MARK: -
- // MARK: Progress
-
- func showProgressWindow(message: String = "") {
- if (self.progressController != nil) {
- self.hiddenProgressWindow()
- }
-
- let progress = SKProgressController()
- progress.showClose = false
- progress.message = message
- progress.window?.backgroundColor = NSColor(hex: "#36383B")
- progress.window?.contentView?.wantsLayer = true
- progress.window?.contentView?.layer?.backgroundColor = NSColor(hex: "#36383B").cgColor
- progress.progressField.textColor = NSColor.white
-
- self.progressController = progress
- self.view.window?.beginSheet(progress.window!)
- }
-
- func hiddenProgressWindow() {
- if (self.progressController != nil) {
- self.view.window?.endSheet((self.progressController?.window)!)
- self.progressController = nil
- }
- }
-
- // MARK -
- // 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
- }
- }
-
- private func removeEventMonitor() {
- if (self.eventMonitor != nil) {
- KMPrint("已移除事件监听")
-
- NSEvent.removeMonitor(self.eventMonitor as Any)
- self.eventMonitor = nil
- }
- }
-
- // MARK: -
- // 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()
- }
-
- // MARK: -
- // 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()
- }
-
- if ((self.myDocument as! KMMainDocument).isUnlockFromKeychain || self.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
- }
- }
- }
-
- internal func applicationWillTerminateNotification(_ sender: Notification) {
- self.savePageNumberIfNeed()
- self.saveDocument()
- }
-
- func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
- if self.isReadMode {
- self.readModelView.currentPageIndex = self.listView.currentPageIndex
- }
- }
-
- func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
- if self.isReadMode {
- self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
- }
- }
-
- //MARK: - PDFListViewDelegate
- func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
- #if DEBUG
- print("pdfViewDocumentDidLoaded")
- #endif
-
- if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
- self.showSecureLimitTip()
- }
-
- 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)
- }
- }
- self._documentFirstLoad = false
- }
-
- let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
- self.preferenceDidChangeNotification(notification:notification)
- let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: panelWidth + functionWidth)
- let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: defaultRightWidth)
-
- applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
-
- self.updatePageIndicatoreType()
- }
-
- func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
- self.updatePageIndicatoreType()
- NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
- print("KMPDFViewCurrentPageDidChanged")
- }
-
- func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
- self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
- print("pdfViewScaleDidChanged")
- }
-
- func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
- print("pdfViewDidClick")
- }
-
- func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
- print("pdfViewPerformURL")
- }
-
- func pdfViewPerformPrint(_ pdfView: CPDFView!) {
- print("pdfViewPerformPrint")
- }
-
- func pdfViewPerformGo(toPage pdfView: CPDFView!) {
- print("pdfViewPerformGo")
- }
-
- func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
- print("pdfViewOpenPDF")
- }
-
- func pdfViewPerformReset(_ pdfView: CPDFView!) {
- print("pdfViewPerformReset")
- }
-
- func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
- print("pdfViewEditingBlockDidChanged")
- }
-
- func pdfViewAsBookBookmark() -> NSImage! {
- return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
- }
-
- func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
- if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
- self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty()
- }
- }
-
- func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
- let areas = self.listView.editingAreas()
- if areas == nil || areas?.count ?? 0 == 0{
- // self.rightSideViewController.view.isHidden = true
- self.rightSideViewController.isHidden = true
- self.closeRightPane()
- if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
- self.rightSideViewController.eidtPDFTextProperty.setDefaultProperty()
- self.rightSideViewController.eidtPDFTextProperty.formAearsAlignIcon()
- }
- return
- }
- if (self.listView.annotationType == .addImage) && areas!.count > 0 {
- var isImageArea = false
- for i in 0 ... areas!.count-1 {
- if areas![i] is CPDFEditImageArea {
- isImageArea = true
- }
- }
- if isImageArea {
- // self.rightSideViewController.view.isHidden = false
- self.rightSideViewController.isHidden = false
- if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
- self.rightSideViewController.eidtPDFImageProperty.reloadData()
- }
- self.openRightPane()
- } else {
- // self.rightSideViewController.view.isHidden = true
- self.rightSideViewController.isHidden = true
- self.closeRightPane()
- }
- } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText{
- // self.rightSideViewController.view.isHidden = false
- self.rightSideViewController.isHidden = false
- self.rightSideViewController.eidtPDFTextProperty.reloadData()
- self.openRightPane()
- } else {
- var textsAreas : [CPDFEditTextArea] = []
- var imagesAreas : [CPDFEditImageArea] = []
- if self.listView.editingAreas()?.count ?? 0 < 1 {
- return
- }
- for i in 0 ... areas!.count-1 {
- if areas![i] is CPDFEditTextArea {
- textsAreas.append(areas![i] as! CPDFEditTextArea)
- }
- if areas![i] is CPDFEditImageArea {
- imagesAreas.append(areas![i] as! CPDFEditImageArea)
- }
- }
- if textsAreas.count > 0 && textsAreas.count == areas!.count {
- // self.rightSideViewController.view.isHidden = false
- self.rightSideViewController.isHidden = false
- self.rightSideViewController.subViewType = .EditPDFAddText
- self.rightSideViewController.eidtPDFTextProperty?.reloadData()
- self.openRightPane()
- } else if imagesAreas.count > 0 {
- // self.rightSideViewController.view.isHidden = false
- self.rightSideViewController.isHidden = false
- self.rightSideViewController.subViewType = .EditPDFAddImage
- self.rightSideViewController.eidtPDFImageProperty?.reloadData()
- self.openRightPane()
- }
- }
- }
-
- func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
- if editArea != nil && (editArea is CPDFEditImageArea){
- self.listView.cropAreas = editArea as! CPDFEditImageArea
- }
- }
-
- //编辑PDF 创建图片区域回调
- func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add rect: CGRect) {
- let panel = NSOpenPanel()
- panel.allowsMultipleSelection = false
- panel.allowedFileTypes = ["png","jpg"]
- panel.beginSheetModal(for: NSApp.mainWindow!) { response in
- if response == .OK {
- let openPath = panel.url?.path
- self.listView.createImagePath(openPath!, rect: rect, page: pdfView.currentPage())
- }
- }
- }
-
- func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add rect: CGRect) {
- var newrect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
- if __CGSizeEqualToSize(rect.size, CGSize.zero) {
- newrect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
- } else {
- newrect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
- }
-
- let fontName : String = UserDefaults.standard.object(forKey: CEditPDFTextDefaultFontName) as? String ?? "Helvetica"
- let fontStyle : String = UserDefaults.standard.object(forKey: CEditPDFTextDefaultFontStyle) as? String ?? "Bold"
- let fontSize : String = UserDefaults.standard.object(forKey: CEditPDFTextDefaultFontSize) as? String ?? "12"
- let fontColor : NSColor = UserDefaults.standard.pdfListViewColor(forKey: CEditPDFTextDefaultFontColor) ?? NSColor.black
- let fontAlign : String = UserDefaults.standard.object(forKey: CEditPDFTextDefaultFontAlign) as? String ?? "2"
- let attributeFontDescriptor = NSFontDescriptor.init(fontAttributes: [NSFontDescriptor.AttributeName.family : fontName,NSFontDescriptor.AttributeName.face : fontStyle])
- let font = NSFont.init(descriptor: attributeFontDescriptor, size: CGFloat(Float(fontSize)!))
- let style = NSMutableParagraphStyle()
- style.alignment = NSTextAlignment.init(rawValue: Int(fontAlign)!)!
- let attributes = [NSAttributedString.Key.font:font,NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style]
- self.listView.createEmptyStringBounds(newrect,withAttributes: attributes, page: pdfView.currentPage())
- }
-
- func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
- let command = theEvent.modifierFlags.contains(.command)
- let control = theEvent.modifierFlags.contains(.control)
- KMPrint(theEvent.keyCode)
- if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
- self.menuItemBookMarkClick_add(sender: NSMenuItem())
- return false
- } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
- return false
- } else if (theEvent.keyCode == 123) { // 向左
- if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
- self.listView.goToPreviousPage(nil)
- return false
- }
- } else if (theEvent.keyCode == 126) { // 向上
- if (self.listView.isContinousScroll()) {
- return true
- }
- if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
- self.listView.goToPreviousPage(nil)
- return false
- }
- } else if (theEvent.keyCode == 124) { // 向右
- if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
- self.listView.goToNextPage(nil)
- return false
- }
- } else if (theEvent.keyCode == 125) { // 向下
- if (self.listView.isContinousScroll()) {
- return true
- }
- if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
- self.listView.goToNextPage(nil)
- return false
- }
- }
-
- if theEvent.keyCode == 53 {
- if self.isReadMode {
- self.closeReadModel()
- }
-
- self.leftSideViewCancelSelect()
- if (self.toolbarController.toolbarType.isToolMode()) {
- self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
- }
- }
- return true
- }
-
- //MARK: -CPDFListViewDelegate
- func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
-
- }
-
- func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
- self.view.window?.makeFirstResponder(self.listView)
-
- if isRightMenu {
-
- } else if annotations.count > 0 {
- if annotations.count > 1 {
- let fristAnnotation = annotations.first
- var isSameAnnotation = true
- let className = NSStringFromClass(fristAnnotation!.classForCoder)
- for annotation in annotations {
- let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
- if (className == "CPDFSquareAnnotation") ||
- (className == "CPDFCircleAnnotation") ||
- (className == "CPDFLineAnnotation") {
- if (cunrrentClassName != "CPDFSquareAnnotation") &&
- (cunrrentClassName != "CPDFCircleAnnotation") &&
- (cunrrentClassName != "CPDFLineAnnotation") {
- isSameAnnotation = false
- }
- } else {
- if className != cunrrentClassName {
- isSameAnnotation = false
- }
- }
- }
- if isSameAnnotation == false {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
- // self.closeRightPane()
- } else {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
- self.openRightPane()
- }
- } else {
- let fristAnnotation = annotations.first
- let className = NSStringFromClass(fristAnnotation!.classForCoder)
- if self.isReadMode {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
- self.closeRightPane()
- } else {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
- if className != "CPDFStampAnnotation" &&
- className != "CPDFSignatureAnnotation" &&
- className != "CPDFListStampAnnotation" {
- self.openRightPane()
- }
- }
- }
- } else if (annotations.count == 0){
- if pdfListView.annotationType == .unkown {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
- self.closeRightPane()
- } else {
- if self.isReadMode {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
- self.closeRightPane()
- } else {
- self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
- self.openRightPane()
- }
- }
- }
- }
-
- func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
- if(annotationType == .unkown) {
- // self.rightSideViewController.view.isHidden = true
- self.rightSideViewController.isHidden = true
- self.closeRightPane()
- }
- }
-
- ///开始定位链接注释
- func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
- if self.locationPageView.superview == nil {
- self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
- pdfListView.addSubview(self.locationPageView)
- }
- }
-
- ///刷新链接注释
- func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
- if self.locationPageView.superview != nil {
- self.locationPageView.removeFromSuperview()
- }
- if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
- self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
- }
- }
-
- func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
- if (listView.toolMode != CToolMode.editPDFToolMode) {
- return menuItems
- }
- var tMenuItems = menuItems;
-
- if(listView.isSelectEditCharRange() ||
- listView.isSelecteditArea(with: point)) {
- tMenuItems?.append(NSMenuItem.separator())
- tMenuItems?.append(self.fontColorMenuItem())
- tMenuItems?.append(self.fontSizeMenuItem())
- }
- let areas = self.listView.editingAreas() ?? []
- if areas.count == 1 {
- let fristAreas = areas.first
- if fristAreas is CPDFEditImageArea {
- self.listView.selectImageAreas = fristAreas as! CPDFEditImageArea
- if self.listView.isEditImage {
- tMenuItems?.removeAll()
- tMenuItems?.append(self.corpImageMenuItem())
- tMenuItems?.append(self.cancelCorpImageMenuItem())
- } else {
- tMenuItems?.append(self.cutImageArea())
- tMenuItems?.append(self.replaceImageArea())
- tMenuItems?.append(self.exportImageArea())
- }
- }
- } else if areas.count == 0 {
-
-
- }
-
- return tMenuItems
- }
-
- func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!) {
- self.mouseRightMenuEvent = theEvent
- let currentMenu : NSMenu = menu.pointee!
- if (listView.toolMode == .redactToolMode) {
- if (listView.activeAnnotation == nil) {
- } else {
- let currentPoint: NSPoint = pdfListView.convert(theEvent.locationInWindow, from: pdfListView.superview)
- let currentPage = pdfListView.page(for: currentPoint, nearest: true)
- // let currentPage = pdfListView.activeAnnotation.page
- let pagePoint = pdfListView.convert(currentPoint, to: currentPage)
-
- currentMenu.removeAllItems()
- if (pdfListView.activeAnnotation.bounds.contains(pagePoint)) {
- currentMenu.insertItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(redact_menuItemClick_delete), target: self, at: currentMenu.items.count)
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
-
- currentMenu.insertItem(withTitle: NSLocalizedString("Properties...", comment: ""), action: #selector(redact_menuItemClick_setProperty), target: self, at: currentMenu.items.count)
- currentMenu.insertItem(withTitle: NSLocalizedString("Use Current Properties as New Default", comment: ""), action: #selector(redact_menuItemClick_setCurrentPropertyToDefaultValue), target: self, at: currentMenu.items.count)
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
-
- currentMenu.insertItem(withTitle: NSLocalizedString("Repeat mark across pages", comment: ""), action: #selector(redact_menuItemClick_MultiPageFlag), target: self, at: currentMenu.items.count)
- currentMenu.insertItem(withTitle: NSLocalizedString("Apply Redactions", comment: ""), action: #selector(redact_menuItemClick_apply), target: self, at: currentMenu.items.count)
- currentMenu.insertItem(withTitle: NSLocalizedString("Erase Redactions", comment: ""), action: #selector(redact_menuItemClick_clear), target: self, at: currentMenu.items.count)
- } else {
- currentMenu.insertItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(redact_menuItemClick_paste), target: self, at: currentMenu.items.count)
-
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
- currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
- currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
- }
- }
- return
- }
-
- if(listView.toolMode == .selectToolMode) {
- if currentMenu.items.count > 0 {
- let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
- export?.submenu = self.exportMenu()
- currentMenu.insertItem(export!, at: currentMenu.items.count)
- let corp = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action:#selector(cropCurrentPage), target: self)
- // corp?.submenu = self.cropMenu()
- currentMenu.insertItem(corp!, at: currentMenu.items.count)
- // MARK: 暂时拿掉 2023.04.26
- // currentMenu.insertItem(self.zoomSelectionMenuItem(), at: currentMenu.items.count)
- currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
- }
- } else {
- if listView.currentSelection != nil {
- if (listView.currentSelection.string() != nil || listView.currentSelection.selectionType() == .image) {
- if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
- currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
- } else {
- var isMarkup = false
- for item in self.listView.activeAnnotations {
- if (item is CPDFMarkupAnnotation) {
- isMarkup = true
- break
- }
- }
- if(!isMarkup) {
- self.addAnnotationForStyleMenu(menu: currentMenu)
- }
- }
- }
- } else if (listView.activeAnnotation == nil) {
- if(currentMenu.items.count > 2) {
- currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
- }
- if(currentMenu.items.count > 3) {
- currentMenu.insertItem(self.addBookmarkMenu(), at: 4)
- }
- if(currentMenu.items.count > 4) {
- currentMenu.insertItem(NSMenuItem.separator(), at: 5)
- }
- if(currentMenu.items.count > 5) {
- currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
- }
-
- if (currentMenu.items.count > 6) {
- currentMenu.insertItem(self.addReadModelStype(), at: 7)
- }
-
- if (currentMenu.items.count > 7 && self.isReadMode) {
- currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
- }
- // if(currentMenu.items.count > 6) {
- // let menuItem = NSMenuItem(title: NSLocalizedString("Automatic rolling", comment: ""), action:nil, target: self)!
- // currentMenu.insertItem(menuItem, at: 6)
- // }
- // if(currentMenu.items.count > 7) {
- // let menuItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action:nil, target: self)!
- // currentMenu.insertItem(menuItem, at: 7)
- // }
- // if(currentMenu.items.count > 8) {
- // let menuItem = NSMenuItem(title: NSLocalizedString("menuItem", comment: ""), action:nil, target: self)!
- // currentMenu.insertItem(menuItem, at: 8)
- // }
- if !self.isReadMode {
- if (currentMenu.items.count > 10) {
- currentMenu.insertItem(self.addHighlightLinksStype(), at: 11)
- }
- }
- if self.isReadMode {
-
- } else {
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
- currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
- currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
- }
- } else if listView.activeAnnotation != nil {
- var type : CAnnotationType = .unkown
- if listView.activeAnnotation is CPDFMarkupAnnotation {
- if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .highlight {
- type = .highlight
- } else if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .underline {
- type = .underline
- } else {
- type = .strikeOut
- }
- } else if listView.activeAnnotation is CPDFInkAnnotation {
- type = .ink
- } else if listView.activeAnnotation is CPDFFreeTextAnnotation {
- type = .freeText
- } else if listView.activeAnnotation is CPDFTextAnnotation {
- type = .anchored
- } else if listView.activeAnnotation is CPDFCircleAnnotation {
- type = .circle
- } else if listView.activeAnnotation is CPDFSquareAnnotation {
- type = .square
- }
- if ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
- if listView.activeAnnotations.count == 1 {
- currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
- }
- }
- if type != .unkown && listView.activeAnnotations.count == 1{
- currentMenu.insertItem(self.setDefaultAnnotationPorpert(type: type), at: currentMenu.items.count)
- }
- // closeRightPane()
- }
- }
-
- for item in currentMenu.items {
- if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
- // 显示与隐藏注释 item action 截取
- item.action = #selector(menuItemClick_HidenorShowNote)
- item.target = self
- break
- }
- }
- }
-
- func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
-
- var addRedact: Bool = false
- for anno in annotations {
- if (anno.isKind(of: CPDFRedactAnnotation.self)) {
- addRedact = true
- break
- }
- }
- self.hasAddRedact = addRedact
- if self.isReadMode || self.listView.toolMode == .moveToolMode {
- self.listView.toolMode = .textToolMode
- self.listView.annotationType = .unkown
- self.toolbarController.toolbarType = .Annatiton
- }
- }
-
- func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
- if (!self.listView.isEqual(to: pdfListView)) {
- return
-
- }
-
- if (self.listView.toolMode != .selectToolMode) {
- return
- }
-
- if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
- return
- }
-
- let tipView = self.topTipBox.contentView?.subviews.first
- if (tipView?.isKind(of: KMCropTipView.self) == false) {
- return
- }
-
- (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
- }
-
- func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
- if(speedy == .right) {
- self.toggleRightPane()
- } else if (speedy == .left) {
- self.menuItemAction_hiddenLeftSide(speedy)
- }
- }
-
- func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
- if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
- if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
- return KMAnnotationPropertiesColorManager.default().markHighlightColors
- } else {
- return KMAnnotationPropertiesColorManager.default().markOtherColors
- }
- } else {
- return KMAnnotationPropertiesColorManager.default().markOtherColors
- }
- }
-
- func pdfListViewHaveDocumentAttribute() -> Bool {
- if(!self.listView.document.allowsCopying) {
- KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
- if (result == .cancel) {
- return
- }
-
- self?.isSaveKeyChain = false
- self?.listView.document.unlock(withPassword: password)
- self?.hiddenSecureLimitTip()
- }
- return false
- }
- return true
- }
-
- func addTopTip(_ view: NSView?) {
- if (Thread.isMainThread) {
- if (view == nil) {
- let contentView: NSView = self.topTipBox.contentView!
- for subview in contentView.subviews {
- subview.removeFromSuperview()
- }
- self.topTipBox.isHidden = true
- return
- }
-
- let contentView: NSView = self.topTipBox.contentView!
- for subview in contentView.subviews {
- subview.removeFromSuperview()
- }
- self.topTipBox.isHidden = false
- self.topTipBox.contentView?.addSubview(view!)
- } else {
- DispatchQueue.main.async {
- if (view == nil) {
- let contentView: NSView = self.topTipBox.contentView!
- for subview in contentView.subviews {
- subview.removeFromSuperview()
- }
- self.topTipBox.isHidden = true
- return
- }
-
- let contentView: NSView = self.topTipBox.contentView!
- for subview in contentView.subviews {
- subview.removeFromSuperview()
- }
- self.topTipBox.isHidden = false
- self.topTipBox.contentView?.addSubview(view!)
- }
- }
- }
- }
|