1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035 |
- //
- // KMMainViewController+UI.swift
- // PDF Reader Pro
- //
- // Created by wanjun on 2022/12/15.
- //
- import Foundation
- extension KMMainViewController {
- // MARK: - 退出全屏
-
- @IBAction func exitFullScreen(_ sender: Any) {
- if (self.view.window == nil) {
- return
- }
-
- if (KMTools.isFullScreen(self.view.window!)) {
- self.view.window?.toggleFullScreen(nil)
- }
- }
-
- @IBAction func startSpeaking(_ sender: Any) {
- self.showTTSWindow()
- let ttsView = KMTTSWindowController.share
- ttsView.buttonItemClick_Play(ttsView.playButton)
- }
-
- @IBAction func stopSpeaking(_ sender: Any) {
- 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()
- }
- }
- }
- }
- extension KMMainViewController {
- //通知
- func preferenceDidChangeNotification(notification:Notification) {
- let info : [AnyHashable : Any] = notification.userInfo ?? [:]
-
- if info.keys.contains(KMPreference.viewZoomScaleTypeKey) {
- self.selectZoom(KMPreferenceManager.shared.viewZoomScaleType)
- }
-
- if notification.name.rawValue == "pdfViewDocumentDidLoaded" || info.keys.contains(KMPreference.viewPageDisplayTypeKey) {
- self.selectDisplay(display: KMPreferenceManager.shared.viewPageDisplayType)
- }
-
- if info.keys.contains(KMPreference.displayBackgroundNormalColorKey) || notification.name.rawValue == "pdfViewDocumentDidLoaded" {
- self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
- self.listView.layoutDocumentView()
- }
-
- self.updatePageIndicatoreType()
- if (info.keys.contains(KMPreference.generalAuthorNameKey)) { // 作者名称
- CPDFKitConfig.sharedInstance().setAnnotationAuthor((info[KMPreference.generalAuthorNameKey] as! String))
- }
- if (info.keys.contains(KMPreference.highlightLinksKey)) {
- let hlLink = info[KMPreference.highlightLinksKey] as? Bool
- CPDFKitConfig.sharedInstance().setEnableLinkFieldHighlight(hlLink == nil ? false : hlLink!)
- self.listView.setNeedsDisplayForVisiblePages()
- }
- if info.keys.contains(KMPreference.thumbPageSizeKey) {
- self.leftSideViewController.refreshUIOfThumbnailIfNeed(preference: true)
- }
- if info.keys.contains(KMPreference.thumbSnapshotSizeKey) {
- self.leftSideViewController.refreshUIOfSnapshotIfNeed(preference: true)
- }
- if info.keys.contains(KMPreference.outlineFontSizeKey) {
- self.leftSideViewController.updateTableFont()
- }
- if info.keys.contains(KMPreference.greekThresholdKey) {
- let value = KMPreference.shared.greekThreshold.cgFloat
- self.listView.setGreekingThreshold(value)
- self.secondaryPdfView?.setGreekingThreshold(value)
- }
- if info.keys.contains(KMPreference.antiAliasTextKey) {
- self.listView.setShouldAntiAlias(KMPreference.shared.antiAliasText)
- self.listView.applyDefaultInterpolationQuality()
- self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
- self.secondaryPdfView?.applyDefaultInterpolationQuality()
- }
- if info.keys.contains(KMPreference.markupColorHighlightKey) {
- if let item = self.toolbarController.findItem(KMToolbarHighlightAnnotationItemIdentifier) {
- if item.isSelected {
- let color = KMPreference.shared.markupHighlightColor
- let imageV = KMNoteTypeImageView()
- item.image = imageV.noteTypeImage(withType: SKNHighlightString, color: color)
- }
- }
- }
- if info.keys.contains(KMPreference.markupColorUnderlineKey) {
- if let item = self.toolbarController.findItem(KMToolbarUnderlineAnnotationItemIdentifier) {
- if item.isSelected {
- let color = KMPreference.shared.markupUnderlineColor
- let imageV = KMNoteTypeImageView()
- item.image = imageV.noteTypeImage(withType: SKNUnderlineString, color: color)
- }
- }
- }
- if info.keys.contains(KMPreference.markupColorStrikthroughKey) {
- if let item = self.toolbarController.findItem(KMToolbarStrikeOutAnnotationItemIdentifier) {
- if item.isSelected {
- let color = KMPreference.shared.markupStrikthroughColor
- let imageV = KMNoteTypeImageView()
- item.image = imageV.noteTypeImage(withType: SKNStrikeOutString, color: color)
- }
- }
- }
- if info.keys.contains(KMPreference.markupColorPenKey) {
- if let item = self.toolbarController.findItem(KMToolbarInkAnnotationItemIdentifier) {
- if item.isSelected {
- let color = KMPreference.shared.markupPenColor
- let imageV = KMNoteTypeImageView()
- item.image = imageV.noteTypeImage(withType: SKNInkString, color: color)
- }
- }
- }
- }
-
- //刷新页面显示器
- func updatePageIndicatoreType () {
- if self.isReadMode {
- self.pageNumberDisplayView.outView()
- } else {
- if self.listView.document != nil {
- self.pageNumberDisplayView.totalPagesCount = Int(self.listView.document.pageCount)
- }
- self.pageNumberDisplayView.currentPageIndex = self.listView.currentPageIndex
- self.pageNumberDisplayView.displayType = KMPreferenceManager.shared.pageIndicatorType
-
- self.readContentView.addSubview(self.tipCurrentPageBox, positioned: .above, relativeTo: self.readContentView)
- }
- }
-
- func showConvertNotesProgress() {
- guard let pdfDocument = self.document else {
- return
- }
- guard let _ = self.listView?.document else {
- return
- }
- guard let _ = self.view.window else {
- return
- }
-
- let isNewCreated = (self.myDocument as? KMMainDocument)?.isNewCreated ?? false
- if isNewCreated {
- return
- }
-
- self.model.needConvertNotes = false
- Task { @MainActor in
- self.convertNotesUsingPDFDocument(pdfDocument)
- }
- }
-
- func convertNotesUsingPDFDocument(_ pdfDocument: CPDFDocument) {
- guard let doc = self.listView?.document else {
- return
- }
- DispatchQueue.main.async {
- self.beginProgressSheet(withMessage: NSLocalizedString("Converting notes", comment: "Message for progress sheet").appending("..."), maxValue: 0)
-
- let count = pdfDocument.pageCount
- DispatchQueue.global().async {
- // var addAnnotations = [CPDFAnnotation]()
- // var removeAnnotations = [CPDFAnnotation]()
- self.model.addAnnotations.removeAll()
- self.model.removeAnnotations.removeAll()
- for i in 0..<count {
- let page = pdfDocument.page(at: i)
-
- // var addAnnotations = [CPDFAnnotation]()
- // var removeAnnotations = [CPDFAnnotation]()
- for annotation in page?.annotations ?? [] {
- var newAnnotation: CPDFAnnotation?
- if let inkAnnotation = annotation as? CPDFInkAnnotation, inkAnnotation.contents.hasPrefix("<?xml version=\"1.0\" encoding=\"utf-8\"?>") {
- let table = KMTableAnnotation(KMNoteBounds: inkAnnotation.bounds, document: doc)
- table.border = inkAnnotation.border
- table.color = inkAnnotation.color
- table.createForm(withList: inkAnnotation.contents, andPaths: inkAnnotation.bezierPaths())
- table.updateAppearanceInk(withIsAdd: false)
- table.contents = annotation.contents
- newAnnotation = table
- }
- if let newAnnotation = newAnnotation {
- self.model.addAnnotations.append(newAnnotation)
- self.model.removeAnnotations.append(annotation)
- }
- }
-
- // for i in 0..<addAnnotations.count {
- // let newAnnotation = addAnnotations[i]
- // let annotation = removeAnnotations[i]
- //
- // // this is only to make sure markup annotations generate the lineRects, for thread safety
- // pdfView?.addAnnotation(with: newAnnotation, to: page)
- // pdfView?.remove(annotation)
- // if newAnnotation.contents != nil {
- // if newAnnotation.contents.count == 0 {
- // newAnnotation.autoUpdateString()
- // }
- // }
- // }
- }
-
- DispatchQueue.main.async {
- for i in 0..<self.model.addAnnotations.count {
- let newAnnotation = self.model.addAnnotations[i]
- let annotation = self.model.removeAnnotations[i]
-
- let page = annotation.page
- // this is only to make sure markup annotations generate the lineRects, for thread safety
- self.listView?.addAnnotation(with: newAnnotation, to: page)
- self.listView?.remove(annotation)
- if newAnnotation.contents != nil {
- if newAnnotation.contents.count == 0 {
- newAnnotation.autoUpdateString()
- }
- }
- }
-
- self.dismissProgressSheet()
-
- self.listView?.undoManager?.removeAllActions()
- self.undoManager?.removeAllActions()
-
- // 清空数据
- self.model.addAnnotations.removeAll()
- self.model.removeAnnotations.removeAll()
- }
- }
- }
- }
-
- // MARK: - KMInterfaceThemeChangedProtocol
-
- override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
- super.interfaceThemeDidChanged(appearance)
-
- self.toolbarController.interfaceThemeDidChanged(appearance)
- self.leftSideViewController.interfaceThemeDidChanged(appearance)
- self.rightSideViewController.interfaceThemeDidChanged(appearance)
-
- self.pdfEditController?.interfaceThemeDidChanged(appearance)
-
- self.mianSplitView.superview?.wantsLayer = true
- // let sView = self.listView.documentView()
- if KMAppearance.isDarkMode() {
- self.mianSplitView.superview?.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
- // sView?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
- } else {
- self.mianSplitView.superview?.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
- // sView?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1)
- }
- }
- }
- // MARK: - KMToolbarControllerDelegate
- extension KMMainViewController: KMToolbarControllerDelegate {
- func toolbarController(_ viewController: KMToolbarController, heightOffsetChange heightOffset: Float, animated: Bool) {
- let heightConst = (animated ? self.heightOffset.animator() : self.heightOffset)
- if self.isReadMode {
- if self.toolbarController.toolbarType == .Annatiton {
- heightConst?.constant = CGFloat(heightOffset)
- } else {
- heightConst?.constant = CGFloat(0)
- }
- } else {
- heightConst?.constant = CGFloat(heightOffset)
- }
- self.refreshListViewToolMode()
- self.trackEvent(toolMode: self.listView.toolMode)
- if self.listView.annotationType == .editTextImage ||
- self.listView.annotationType == .addText ||
- self.listView.annotationType == .addImage {
- self.closeRightPane()
- }
- self.listView.annotationType = .unkown
- }
-
- func changeAnnotationModeAction(item: KMToolbarClickButton) {
- if self.listView.toolMode == .formToolMode {
- if !IAPProductsManager.default().isAvailableAllFunction(){
- KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
- return
- }
- }
-
- if (self.model.rightMouseEventing) {
- self.model.rightMouseEventing = false
- }
- if (self.toolbarController.ignoreCurrentAnnotationTypeChange) {
- self.toolbarController.ignoreCurrentAnnotationTypeChange = false
- }
-
- var currentType = self.listView.annotationType
- if (currentType == .eraser) {
- currentType = .ink
- }
- let isSelected = (currentType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown) && ((self.listView.toolMode == .noteToolMode) || (self.listView.toolMode == .selfSignMode) || (self.listView.toolMode == .formToolMode))
- var editSelectd = false
- if self.listView.annotationType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown && self.listView.toolMode == .editPDFToolMode {
- editSelectd = true
- }
-
- if isSelected {
- if self.listView.toolMode == .formToolMode {
-
- } else {
- self.listView.toolMode = .textToolMode
- }
- self.listView.annotationType = .unkown
- self.closeRightPane()
- } else {
- let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
- self.trackEvent(annotationType: type)
- self.listView.annotationType = type
-
- if self.listView.currentSelection != nil {
- let annotation = self.listView.addAnnotation(with: CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
- if((annotation != nil) &&
- !self.listView.activeAnnotations.contains(annotation ?? self.listView.activeAnnotation)) {
- var newAnnonations : [CPDFAnnotation] = []
- newAnnonations.append(annotation!)
- self.listView.updateActiveAnnotations(newAnnonations)
- self.listView.setNeedsDisplayAnnotationViewFor(annotation?.page)
- }
- }
-
- if self.listView.toolMode == .formToolMode {
-
- } else {
- self.refreshListViewToolMode()
- }
- }
-
- if self.listView.toolMode != .editPDFToolMode && self.listView.annotationType != .unkown {
- self.rightSideViewController.isHidden = false
- self.rightSideViewController.subViewType = .AnnotationProperts
- if !self.isReadMode {
- self.openRightPane()
- }
- } else if self.listView.toolMode == .editPDFToolMode {
- if editSelectd {
- self.rightSideViewController.isHidden = true
- self.listView.setShouAddEdit([])
- self.listView.change([.text, .image])
- self.listView.annotationType = .editTextImage
- self.closeRightPane()
- } else if self.listView.annotationType == .addText {
- self.rightSideViewController.isHidden = false
- if !self.isReadMode {
- self.openRightPane()
- }
- self.rightSideViewController.subViewType = .EditPDFAddText
- FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddText"])
- self.listView.setShouAddEdit(.text)
- self.listView.change(.text)
- } else if self.listView.annotationType == .addImage {
- self.rightSideViewController.isHidden = false
- if !self.isReadMode {
- self.openRightPane()
- }
- FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddImage"])
- // self.closeRightPane()
-
- self.rightSideViewController.subViewType = .EditPDFAddImage
- self.listView.setShouAddEdit(.image)
- self.listView.change(.image)
- self.rightSideViewController.eidtPDFImageProperty.reloadData()
- }
- } else {
- self.rightSideViewController.isHidden = true
- self.closeRightPane()
- }
- }
-
- func refreshListViewToolMode () {
- if self.toolbarController.toolbarType == .Annatiton {
- self.listView.toolMode = .noteToolMode
- } else if self.toolbarController.toolbarType == .Move {
- self.listView.toolMode = .moveToolMode
- } else if self.toolbarController.toolbarType == .Magnify {
- self.listView.toolMode = .magnifyToolMode
- } else if self.toolbarController.toolbarType == .Select {
- self.listView.toolMode = .selectToolMode
- } else if self.toolbarController.toolbarType == .SelectZoom {
- self.listView.toolMode = .selectZoomToolMode
- } else if self.toolbarController.toolbarType == .Page {
-
- } else if self.toolbarController.toolbarType == .Form {
- self.listView.toolMode = .formToolMode
- self.rightSideViewController.subViewType = .AnnotationProperts
- } else if self.toolbarController.toolbarType == .FillSign {
- self.listView.toolMode = .selfSignMode
- self.rightSideViewController.subViewType = .AnnotationProperts
- } else if self.toolbarController.toolbarType == .editPDF {
- self.listView.toolMode = .editPDFToolMode
- // self.listView.editingConfig().isShowEditingAreaHover = true
- // self.listView.editingConfig().editingBorderWidth = 1
- // self.listView.editingConfig().editingCenterRadius = 5
- // self.listView.editingConfig().editAreaMargin = 2
- // self.listView.editingConfig().editingHoverBorderColor = NSColor.init(red: 0, green: 136.0/255.0, blue: 1.0, alpha: 0.5)
- // self.listView.editingConfig().editingBorderColor = NSColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
- // self.listView.editingConfig().addEditAreaColor = NSColor.init(red: 23.0/255.0, green: 112.0/255.0, blue: 244.0/255.0, alpha: 0.5)
- // self.listView.editingConfig().editAreaMoveFillColor = NSColor.init(red: 23.0/255.0, green: 112.0/255.0, blue: 244.0/255.0, alpha: 0.1)
- self.listView.setShouAddEdit([])
- }else if self.toolbarController.toolbarType == .LeftPanel {
- self.toggleLeftPane()
- self.leftSideViewController.showPanelView(show: true)
- }else {
- self.listView.toolMode = .textToolMode
- }
- }
-
- func showPDFLayoutModeAction(show: Bool) {
- self.listView.annotationType = .unkown
- self.showOrHideNotes()
- }
- }
- // MARK: - NSSplitViewDelegate
- extension KMMainViewController : NSSplitViewDelegate {
- func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
- if splitView == self.mianSplitView {
- // return (subview == self.listView) == false
- } else if splitView == self.newPDFSplitView {
- return subview.isEqual(to: self.secondaryPdfContentView)
- }
- return false
- }
-
- func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
- if splitView == self.newPDFSplitView {
- if subview.isEqual(to: self.secondaryPdfContentView) {
- var position = self.newPDFSplitView.maxPossiblePositionOfDivider(at: dividerIndex)
- if self.newPDFSplitView.isSubviewCollapsed(subview) {
- if self.lastSplitPDFHeight <= 0.0 {
- let DEFAULT_SPLIT_PANE_HEIGHT: Float = 200.0
- self.lastSplitPDFHeight = DEFAULT_SPLIT_PANE_HEIGHT
- }
- if self.lastSplitPDFHeight.cgFloat > NSHeight(self.pdfContentView.frame) {
- self.lastSplitPDFHeight = floorf(0.5 * Float(NSHeight(self.pdfContentView.frame)))
- }
- position += self.lastSplitPDFHeight.cgFloat
- } else {
- self.lastSplitPDFHeight = Float(NSHeight(subview.frame))
- }
- self.pdfSplitView.setPosition(position, ofDividerAt: dividerIndex, animate: true)
- }
- return false
- }
- return false
- }
-
- func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
- if splitView == self.mianSplitView {
- return splitView == self.mianSplitView
- } else if splitView == self.newPDFSplitView {
- return false
- }
- return false
- }
-
- func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
- if splitView == mianSplitView {
- let splitViewWidth = splitView.frame.width
- let dividerIndexX0 = self.model.panelWidth + functionWidth
- if dividerIndex == 0 {
- if self.model.leftPanelOpen {
- return CGFloat(dividerIndexX0 * 1.5)
- } else {
- return functionWidth
- }
- } else if dividerIndex == 1 {
- return splitViewWidth
- }
- } else if splitView == self.newPDFSplitView {
- if dividerIndex == 0 {
- let MIN_SIDE_PANE_WIDTH = 270
- return proposedMaximumPosition + MIN_SIDE_PANE_WIDTH.cgFloat
- }
- }
- return proposedMaximumPosition
- }
-
- func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
- if splitView == mianSplitView {
- let splitViewWidth = splitView.frame.width
- let dividerIndexX1 = splitViewWidth - self.model.defaultRightWidth
- if dividerIndex == 0 {
- return functionWidth
- } else if dividerIndex == 1 {
- return dividerIndexX1
- }
- } else if splitView == self.newPDFSplitView {
- }
- return proposedMinimumPosition
- }
-
- func splitView(_ splitView: NSSplitView, resizeSubviewsWithOldSize oldSize: NSSize) {
- if splitView.isEqual(to: mianSplitView) {
- let leftView = splitView.subviews[0]
- let centerView = splitView.subviews[1]
- let rightView = splitView.subviews[2]
- // let centerView = self.pdfSplitView ?? splitView.subviews[1]
- // let rightView = self.rightView ?? splitView.subviews[2]
-
- // 左边是否收起
- let leftCollapsed = splitView.isSubviewCollapsed(leftView)
- // 右边是否收起
- let rightCollapsed = splitView.isSubviewCollapsed(rightView)
- var leftSize = leftView.frame.size
- var mainSize = centerView.frame.size
- var rightSize = rightView.frame.size
- var contentWidth = splitView.frame.width
- if leftCollapsed {
- leftSize.width = 0.0
- } else {
- contentWidth = contentWidth - splitView.dividerThickness
- }
- if rightCollapsed {
- rightSize.width = 0.0
- } else {
- contentWidth = contentWidth - splitView.dividerThickness
- }
- if contentWidth < leftSize.width + rightSize.width {
- var oldContentWidth = oldSize.width
- if leftCollapsed == false {
- oldContentWidth = oldContentWidth - splitView.dividerThickness
- }
- if rightCollapsed == false {
- oldContentWidth = oldContentWidth - splitView.dividerThickness
- }
- let resizeFactor = contentWidth / oldContentWidth
- leftSize.width = floor(resizeFactor*leftSize.width)
- rightSize.width = floor(resizeFactor*rightSize.width)
- }
- mainSize.width = contentWidth - leftSize.width - rightSize.width
- leftSize.height = splitView.frame.height
- rightSize.height = splitView.frame.height
- mainSize.height = splitView.frame.height
- if leftCollapsed == false {
- leftView.setFrameSize(leftSize)
- }
- if rightCollapsed == false {
- rightView.setFrameSize(rightSize)
- }
- centerView.setFrameSize(mainSize)
- } else if splitView == self.newPDFSplitView {
- // let firstV = splitView.subviews.first
- // let lastV = splitView.subviews.last
- // if firstV == lastV{
- // splitView.adjustSubviews()
- // return
- // }
- // if self.newPDFSplitView.isVertical { // 横向
- // // 左边是否收起
- // let leftCollapsed = splitView.isSubviewCollapsed(firstV!)
- // // 右边是否收起
- // let rightCollapsed = splitView.isSubviewCollapsed(lastV!)
- //
- // var contentSize = splitView.frame.size
- // firstV?.setFrameSize(NSMakeSize(contentSize.width * 0.5, contentSize.height))
- // lastV?.setFrameSize(NSMakeSize(contentSize.width * 0.5, contentSize.height))
- // } else { // 纵向
- // // 左边是否收起
- // let leftCollapsed = splitView.isSubviewCollapsed(firstV!)
- // // 右边是否收起
- // let rightCollapsed = splitView.isSubviewCollapsed(lastV!)
- //
- // var contentSize = splitView.frame.size
- // firstV?.setFrameSize(NSMakeSize(contentSize.width, contentSize.height * 0.5))
- // lastV?.setFrameSize(NSMakeSize(contentSize.width, contentSize.height * 0.5))
- // }
- }
- splitView.adjustSubviews()
- }
-
- func splitViewWillResizeSubviews(_ notification: Notification) {
- let defaultView = KMSplitView()
- let sender : NSSplitView = notification.object as? NSSplitView ?? defaultView
- if (sender == self.mianSplitView || sender == defaultView) && self.view.window?.frameAutosaveName != nil{
- // let leftWidth = self.mianSplitView.isSubviewCollapsed(self.leftView) ? 0.0 : leftSideViewController.view.frame.width
- // if leftPanelOpen {
- // if leftWidth < 100 && lastLeftPanWidth > functionWidth{
- // self.closeLeftPane()
- // }
- // }
- } else {
- if sender == self.pdfSplitView {
- KMPrint("")
- }
- }
- }
-
- func splitViewDidResizeSubviews(_ notification: Notification) {
- self.locationPageView.frame = CGRect(x: 0, y: self.listView.frame.maxY-32, width: self.listView.frame.width, height: 32)
- let defaultView = KMSplitView()
- let sender : NSSplitView = notification.object as? NSSplitView ?? defaultView
- if (sender == self.mianSplitView || sender == defaultView) && self.view.window?.frameAutosaveName != nil{
- let leftWidth = self.mianSplitView.isSubviewCollapsed(self.leftView) ? 0.0 : leftSideViewController.view.frame.width
- let rightWidth = self.mianSplitView.isSubviewCollapsed(self.rightView) ? 0.0 : rightSideViewController.view.frame.width
- UserDefaults.standard.set(leftWidth, forKey: CPDFOfficeLeftSidePaneWidthKey)
- UserDefaults.standard.set(rightWidth, forKey: CPDFOfficeRightSidePaneWidthKey)
- } else {
- if sender == self.pdfSplitView {
- KMPrint("")
- }
- }
- }
-
- func splitView(_ splitView: NSSplitView, constrainSplitPosition proposedPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
- if splitView == self.mianSplitView {
- if dividerIndex == 0 {
- if self.model.leftPanelOpen {
- //当左边栏开启式,拖拽时不改变宽度,当宽度达到原宽度的一半时关闭窗口
- //如果 isShowPanel 为 true 那么将不会收缩
- if (proposedPosition < functionWidth + self.model.panelWidth * 0.5) && !self.leftSideViewController.isShowPanel {
- self.closeLeftPane()
- self.leftSideViewController.refreshMethodType(methodType: .None)
- return functionWidth
- } else if proposedPosition > self.model.panelWidth + functionWidth {
- return proposedPosition
- } else {
- return self.model.panelWidth + functionWidth
- }
- } else {
- return functionWidth
- }
- }
- } else if splitView == self.newPDFSplitView {
- }
- return proposedPosition
- }
- }
- // MARK: - KMLeftSideViewControllerDelegate
- extension KMMainViewController: KMLeftSideViewControllerDelegate {
- func controlStateChange(_ obj: KMLeftSideViewController, show: Bool) {
- if show {
- self.openLeftPane()
- } else {
- self.closeLeftPane()
- }
- }
-
- func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int]) {
- let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPageToolbarItemIdentifier))!
- self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode: .Page, toolbar: item, pages)
- }
-
- func searchAction(searchString: String,isCase:Bool) {
- self.search(searchString: searchString,isCase: isCase)
- }
-
- func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType) {
- self.selectDisplay(display: dispay, viewSettingIsReload: false)
- }
-
- func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?) {
- if (itemKey == .print) { // 打印
- if params is NSImage {
- KMPrintWindowController.cpdf_printImage(image: params as! NSImage)
- return
- }
- var pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [], reversePrintOrder: false)
- if (params != nil) {
- pageRange.type = .custom
- pageRange.selectPages = params as! [Int]
- }
-
- self.showPrintWindow(pageRange: pageRange)
- } else if (itemKey == .cut || itemKey == .paste || itemKey == .delete || itemKey == .leftRotate || itemKey == .rightRotate) {
- self.recordIsPDFDocumentEdited(type: itemKey.toSubscribeWaterMarkType())
- } else if itemKey == .pageEdit {
- self.toolbarController.clickItem(KMDocumentPageToolbarItemIdentifier)
- } else if itemKey == .demote { // 大纲降级
- guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
- return
- }
- self.listView?.demote(outline: currentOutline)
- } else if itemKey == .promote { // 大纲升级
- guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
- return
- }
- self.listView?.promote(outline: currentOutline)
- }
- }
-
- func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem]) {
- self.needSave = true
- self.recordIsPDFDocumentEdited()
- }
-
- func controller(controller: KMLeftSideViewController, rotateType: KMRotateType) {
- if rotateType == .clockwise {
- self.menuItemAction_rotateRight((Any).self)
- } else if rotateType == .anticlockwise {
- self.menuItemAction_rotateLeft((Any).self)
- }
- }
-
- func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?) {
- if controller.thumbnailTableView.isEqual(to: object) {
- let row = controller.thumbnailTableView.selectedRow
- let curIndex = self.listView.currentPageIndex
- if (row != -1 && row != curIndex) {
- self.listView?.go(toPageIndex: row, animated: true)
- }
- }
- }
- }
- //MARK: - ReadModel
- extension KMMainViewController {
- @objc func openReadModel() {
- //保存进入阅读模式之前的状态
- readLeftMethodType = self.leftSideViewController.type.methodType
- readLeftPanelOpen = self.model.leftPanelOpen
- readLastLeftPanWidth = self.model.lastLeftPanWidth
- readLeftViewShowPanel = self.leftSideViewController.isShowPanel
- readRightPanelOpen = self.model.rightPanelIsOpen
- readToolbarType = self.toolbarController.toolbarType
- readToolMode = self.listView.toolMode
- readAnnotationType = self.listView.annotationType
- readSubViewType = self.rightSideViewController.subViewType ?? .None
-
- if self.toolbarController.lastItemBox.isSelected {
- readToolbarItemIdentifier = self.toolbarController.lastItemBox.itemIdentifier ?? ""
- } else {
- readToolbarItemIdentifier = ""
- }
- //设置阅读模式
- self.isReadMode = true
- self.readModelView.isHidden = false
- //
- //顶部菜单栏状态清空
- self.toolbarController.toolbarType = .None
- // self.toolbarController.view.isHidden = true
- self.toolbarController.cancelSelected(KMLeftControlToolbarItemIdentifier)
- self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
- self.toolbarController.lastItemBox.isSelected = false
-
- //左侧菜单栏情况
- self.model.leftPanelOpen = false
- self.model.lastLeftPanWidth = 0
- self.leftSideViewController.refreshMethodType(methodType: .None)
- //阅读界面初始化
- self.readModelView.isHidden = false
- self.readModelView.currentPageIndex = self.listView.currentPageIndex
- self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
- self.readModelView.beginTimer()
- // self.listView.autoScales = true
- // self.readModelView.scaleType = .autoSize
- self.readModelView.zoomButton.stringValue = (NSString(format: "%.0f", self.listView.scaleFactor * 100) as String) + "%"
-
- //关闭左侧右侧菜单栏
- self.closeLeftPane()
- self.closeRightPane()
- self.leftSideViewController.showPanelView(show: false)
- self.leftView.isHidden = true
-
- //弹出提示框
- if readAlertView != nil {
- readAlertView?.removeFromSuperview()
- }
- readAlertView = CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: self.view, withStyle: .blue, backgroundColor: NSColor.km_init(hex: "#36383B"))
-
- UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
- UserDefaults.standard.synchronize()
-
- self.updatePageIndicatoreType()
-
- }
-
- @objc func closeReadModel() {
- if self.isReadMode {
- self.model.isShowBOTA = false
- self.readModelView.isHidden = true
- self.isReadMode = false
- self.readModelView.isHidden = true
-
- self.leftSideViewController.refreshMethodType(methodType: readLeftMethodType)
- self.model.leftPanelOpen = readLeftPanelOpen
- self.model.rightPanelIsOpen = readRightPanelOpen
- self.model.lastLeftPanWidth = readLastLeftPanWidth
-
- if self.model.leftPanelOpen {
- self.openLeftPane()
- }
-
- self.closeRightPane()
- self.toolbarController.toolbarType = .None
- self.toolbarController.cancelSelected(KMDocumentViewDisplayToolbarItemIdentifier)
-
- // if self.rightPanelIsOpen {
- // self.rightPanelIsOpen = false
- //// self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
- // self.openRightPane()
- // }
- //
- // if readToolbarItemIdentifier.count == 0 {
- // self.toolbarController.toolbarType = .None
- // } else {
- // self.toolbarController.selectItem(readToolbarItemIdentifier)
- // }
- // self.toolbarController.selectItem(KMDocumentViewDisplayToolbarItemIdentifier)
-
- self.leftSideViewController.showPanelView(show: readLeftViewShowPanel)
- if readLeftViewShowPanel {
- self.toolbarController.selectItem(KMLeftControlToolbarItemIdentifier)
- }
-
- self.toolbarController.view.isHidden = false
- self.listView.toolMode = readToolMode
- self.listView.annotationType = readAnnotationType
- // self.toolbarController.toolbarType = .viewSetting
- } else {
- self.toolbarController.toolbarType = .None
- }
-
- if readAlertView != nil {
- readAlertView?.removeFromSuperview()
- }
- readAlertView = CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: self.view, withStyle: .blue, backgroundColor: NSColor.km_init(hex: "#36383B"))
-
- UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
- UserDefaults.standard.synchronize()
- }
-
- @objc func addOutLineItemAction() {
- let labelString = "\(KMLocalizedString("Page", nil)) \((self.listView?.currentPageIndex ?? 0) + 1)"
- let label = self.listView?.currentSelection?.string() ?? labelString
- let dest = self.listView?.currentDestination
- if let row = self.leftSideViewController.selectedRowIndexes().last {
- if let ol = self.leftSideViewController.tocOutlineView.item(atRow: row) as? CPDFOutline {
- _ = self.listView.addOutline(for: ol.parent, label: label, dest: dest, at: ol.index+1)
- } else {
- let idx = self.listView?.document?.outlineRoot()?.numberOfChildren ?? 0
- _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
- }
- } else {
- let idx = self.listView?.document?.outlineRoot()?.numberOfChildren ?? 0
- _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
- }
- }
-
- @objc func showTTSView() {
- self.showTTSWindow()
- }
- @objc func showShareAction() {
-
- }
- @objc func lookUpAction() {
- let label = self.listView?.currentSelection?.string() ?? ""
- self.toolbarController.showFindBar()
- self.toolbarController.findSearchView.searchString(label)
- // self.toolbarController.findSearchView.find(Any.self)
-
- }
- @objc func searchBaiduAction() {
- let label = self.listView?.currentSelection?.string() ?? ""
- let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
- if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
- NSWorkspace.shared.open(url)
- }
- }
- @objc func showInfoInFinder() {
-
- }
- @objc func NextPageAction() {
-
- }
- @objc func PreviousPageAction() {
-
- }
- @objc func TranslateItemAction() {
- // 获取选中的文本
- if let selection = self.listView?.currentSelection?.string() {
- // 进行翻译
- let escapedText = selection.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
- let urlStr = "https://translate.google.com/?sl=auto&tl=zh-CN&text=\(escapedText)"
- if let url = URL(string: urlStr) {
- NSWorkspace.shared.open(url)
- }
- } else {
- print("No text selected.")
- }
- }
- @objc func AutoScrollItemAction() {
- //增加判断,如果是正在滚动,就停止,否则就开始滚动
- self.listView.autoFlow()
- }
- @objc func shareFromService(sender: NSMenuItem) {
- if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
- return
- }
-
- var string = ""
- if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
- string = freeTextAnnotation.contents ?? ""
- } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
- if let page = markupAnnotation.page {
- if let selection = page.selection(for: markupAnnotation.bounds) {
- string = selection.string() ?? ""
- }
- }
- } else {
- string = listView.currentSelection?.string() ?? ""
- }
-
- let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
- let model = windowControler.browser?.tabStripModel
- if let cnt = model?.count(), cnt <= 0 {
- return
- }
-
- if let data = model?.activeTabContents().isHome, data {
- return
- }
-
- let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
- if string.count > 0 {
- let represent : NSSharingService = sender.representedObject as! NSSharingService
- represent.perform(withItems: [string])
- return
- }
- let represent = sender.representedObject as? NSSharingService
- represent?.perform(withItems: [string])
- }
-
- @objc func cutAction(sender: NSMenuItem) {
-
- }
- @objc func deleteAction(sender: NSMenuItem) {
-
- }
- @objc func ColorsItemAction(sender: NSMenuItem) {
-
- }
- @objc func LinesItemAction(sender: NSMenuItem) {
-
- }
- @objc func EditNoteItemAction(sender: NSMenuItem) {
-
- }
- @objc func AITranslateItemAction(sender: NSMenuItem) {
- self.showAITypeChooseView(aiConfigType: .translate)
- }
- @objc func AIProofreadItemAction(sender: NSMenuItem) {
- self.showAITypeChooseView(aiConfigType: .proofreading)
- }
- @objc func AIRewriteItemAction(sender: NSMenuItem) {
- self.showAITypeChooseView(aiConfigType: .reWriting)
- }
-
- // @objc func highlightLinks() {
- // let highlightLinks = KMPreferenceManager.shared.highlightLinks
- // KMPreferenceManager.shared.highlightLinks = !highlightLinks
- // }
- }
- // MARK: - KMEditImagePropertyViewControllerDelegate
- extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
- func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
- self.model.isPDFTextImageEdited = true
- }
- }
- // MARK: - KMSnapshotWindowControllerDelegate
- extension KMMainViewController: KMSnapshotWindowControllerDelegate {
- func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
- self.leftSideViewController.snapshotControllerWillClose(controller)
- }
-
- func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
- if isMiniaturize && self.interactionMode != .presentation {
- if self.interactionMode != .legacyFullScreen && self.model.leftPanelOpen == false {
- self.toggleLeftPane()
- } else if self.interactionMode == .legacyFullScreen {
- // else if ([self interactionMode] == SKLegacyFullScreenMode && ([rightSideWindow state] == NSDrawerClosedState || [rightSideWindow state] == NSDrawerClosingState)) {
- // [rightSideWindow expand];
- // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hideRightSideWindow:) userInfo:NULL repeats:NO];
- }
- var row = NSNotFound
- for (i,sp) in self.leftSideViewController.snapshots.enumerated() {
- if controller.isEqual(sp.windowC) {
- row = i
- }
- }
- if (row != NSNotFound) {
- if self.leftSideViewController.type.methodType != .snapshot {
- self.leftSideViewController.leftView.segmentedControl.selectedSegment = 3
- } else {
- self.leftSideViewController.refreshUIOfSnapshotIfNeed()
- }
- self.leftSideViewController.snapshotTableView.scrollRowToVisible(row)
- }
- }
-
- return self.leftSideViewController.snapshotController(controller, miniaturizedRect: isMiniaturize)
- }
-
- func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
- self.leftSideViewController.snapshotControllerDidFinishSetup(controller)
- }
- }
- // MARK: - CPDFDocumentDelegate
- extension KMMainViewController: CPDFDocumentDelegate {
- func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
- self.leftSideViewController.documentDidBeginFind()
- // [statusBar setProgressIndicatorStyle:SKProgressIndicatorBarStyle];
- // [[statusBar progressIndicator] setMaxValue:[[note object] pageCount]];
- // [[statusBar progressIndicator] setDoubleValue:0.0];
- // [statusBar startAnimation:self];
- // [self willChangeValueForKey:SEARCHRESULTS_KEY];
- // [self willChangeValueForKey:GROUPEDSEARCHRESULTS_KEY];
- }
-
- func documentDidEndDocumentFind(_ document: CPDFDocument!) {
- self.leftSideViewController.documentDidEndFind()
- // [self didChangeValueForKey:GROUPEDSEARCHRESULTS_KEY];
- // [self didChangeValueForKey:SEARCHRESULTS_KEY];
- // [statusBar stopAnimation:self];
- // [statusBar setProgressIndicatorStyle:SKProgressIndicatorNone];
- // NSArray *highlights = [[NSArray alloc] initWithArray:searchResults copyItems:YES];
- // [highlights setValue:[NSColor yellowColor] forKey:@"color"];
- // [self.pdfView setHighlightedSelections:highlights];
- // [highlights release];
- }
- }
- // MAKR: - CPDFViewDelegate,CPDFListViewDelegate
- extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
- func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
- self.dealDocumentDidLoaded()
-
- let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
- self.preferenceDidChangeNotification(notification:notification)
- let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: self.model.panelWidth + functionWidth)
- let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: self.model.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)
- // KMPrint("KMPDFViewCurrentPageDidChanged")
- }
-
- func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
- self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
- }
-
- func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
- if let urlString = url, urlString == kKMPurchaseProductURLString {
- //跳转订阅比较表
- let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
- return
- }
-
- KMTools.openURL(urlString: url)
- }
-
- func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
- KMPrint("pdfViewPerformURL")
- if content != nil {
- NSWorkspace.shared.open(URL(string: content)!)
- } else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.informativeText = NSLocalizedString("The hyperlink is invalid.", comment: "")
- alert.messageText = ""
- alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
- alert.runModal()
- return
- }
- }
-
- func pdfViewPerformPrint(_ pdfView: CPDFView!) {
- KMPrint("pdfViewPerformPrint")
- self.showPrintWindow()
- }
-
- func pdfViewPerformGo(toPage pdfView: CPDFView!) {
- KMPrint("pdfViewPerformGo")
- }
-
- func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
- KMPrint("pdfViewOpenPDF")
- }
-
- func pdfViewPerformReset(_ pdfView: CPDFView!) {
- KMPrint("pdfViewPerformReset")
- // self.listView.resetFormAnnotation()
- pdfView.document.resetForm()
- }
-
- func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
- KMPrint("pdfViewEditingBlockDidChanged")
- }
-
- func pdfViewAsBookBookmark() -> NSImage! {
- return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
- }
-
- func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
- if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
- self.rightSideViewController.eidtPDFTextProperty.reloadData()
- self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
- }
- }
-
- func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
- let areas = self.listView.editingAreas()
- if areas == nil || areas?.count ?? 0 == 0 {
- if self.listView.toolMode == .editPDFToolMode {
- if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
- if self.listView.isEditImage {
- self.menuItemEditingClick_CropImage(sender: NSMenuItem())
- } else {
- // if self.listView.annotationType == .addImage {
- // self.closeRightPane()
- // }
- if self.listView.annotationType == .addImage {
- if self.rightSideViewController.eidtPDFImageProperty != nil {
- self.rightSideViewController.eidtPDFImageProperty.reloadData()
- }
- }
- // self.openRightPane()
- }
- } else {
- self.closeRightPane()
- }
- } else {
- self.rightSideViewController.isHidden = true
- self.closeRightPane()
- if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
- self.rightSideViewController.eidtPDFTextProperty.initData()
- }
- }
- if self.listView.isEdited() {
- self.recordIsPDFDocumentEdited(type: .editText)
- }
- if self.listView.annotationType != .addText {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
- }
- return
- }
-
- self.model.isPDFTextImageEdited = true
- 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.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
- if self.listView.editingSelectionString().count != 0 {
- self.rightSideViewController.eidtPDFTextProperty.reloadData()
- } else {
- self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
- }
- 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()
- }
- }
-
- if self.listView.isEdited() {
- self.recordIsPDFDocumentEdited(type: .editText)
-
- if self.listView.annotationType != .addText {
- NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
- }
- }
- }
-
- 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 page: CPDFPage!, add rect: CGRect) {
- if self.listView.isEditImage {
- self.menuItemEditingClick_CropImage(sender: NSMenuItem())
- } else {
- let panel = NSOpenPanel()
- panel.allowsMultipleSelection = false
- panel.allowedFileTypes = ["png","jpg"]
- panel.beginSheetModal(for: NSApp.mainWindow!) { response in
- if response == .OK {
- var filePath = panel.url?.path
- var image = NSImage.init(contentsOf: panel.url!)
- //图片自适应范围
- if image != nil {
- var imageRect = rect
- let imageSize = image!.size
- var previewSize = rect.size
- var isChangeSize = false
- if previewSize.width == 0 && previewSize.height == 0 {
- previewSize = CGSize(width: 500, height: 500)
- isChangeSize = true
- }
-
- let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
- let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
-
- if isChangeSize {
- imageRect.origin.x = imageRect.origin.x - newSize.width / 2
- imageRect.origin.y = imageRect.origin.y - newSize.height / 2
- } else {
- imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
- imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
- }
-
- imageRect.size = newSize
- let limitWidth = 1920.0
- if imageSize.width > limitWidth || imageSize.height > limitWidth {
- filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
- targetSize: CGSize(width: limitWidth, height: limitWidth),
- maxSizeInBytes: 1024 * 1024 * 5,
- targetCompression: 1.0)
- }
-
- //自适应page
- let pageRect = self.listView.currentPage().bounds
- if imageRect.width > pageRect.width ||
- imageRect.height > pageRect.height {
- let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
- imageRect = CGRect(x: imageRect.origin.x,
- y: imageRect.origin.y,
- width: imageRect.width * pageScale,
- height: imageRect.height * pageScale)
- }
-
- if imageRect.origin.x < 0 {
- imageRect.origin.x = 5
- }
-
- if imageRect.origin.y < 0 {
- imageRect.origin.y = 5
- }
-
- if imageRect.origin.x + imageRect.width > pageRect.width ||
- imageRect.origin.y + imageRect.height > pageRect.height {
- let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
- let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
-
- imageRect.origin.x = imageRect.origin.x - offsetX - 5
- imageRect.origin.y = imageRect.origin.y - offsetY - 5
- }
-
-
- DispatchQueue.main.async {
- self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
- self.model.isPDFTextImageEdited = true
- self.recordIsPDFDocumentEdited(type: .editImage)
- // self.asyncSaveDocument { params in
- //
- // }
- }
- }
- }
- }
- }
-
- }
-
- func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
- // print(rect)
- 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 model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
- let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
- let fontSize = model.fontSize
- let fontColor = model.color
- let fontAlign = model.alignment
- let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
- NSColorPanel.shared.color = fontColor
- let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
- let style = NSMutableParagraphStyle()
- style.alignment = fontAlign
- let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
- self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: page)
-
- if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
- self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
- }
-
- // self.asyncSaveDocument { params in
- //
- // }
- }
-
- 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.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
- self.listView.goToPreviousPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 126) { // 向上
- if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- 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.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
- self.listView.goToNextPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 125) { // 向下
- if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
- return false
- } else {
- if (self.listView.isContinousScroll()) {
- return true
- }
- if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
- self.listView.goToNextPage(nil)
- return false
- }
- }
- } else if (theEvent.keyCode == 36) {
- if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
- if self.listView.isEditImage {
- self.menuItemEditingClick_CropImage(sender: NSMenuItem())
- }
- }
- }
-
- if theEvent.keyCode == 53 {
- self.exitFullScreen(Any.self)
-
- if self.isReadMode {
- self.closeReadModel()
- }
-
- self.leftSideViewCancelSelect()
- if (self.toolbarController.toolbarType.isToolMode()) {
- self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
- }
- }
- return true
- }
-
- func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
- guard let action = menuItem.action else {
- isTakesEffect.pointee = false
- return false
- }
-
- if (KMSystemMenu.isEditSelector(sel: action)) {
- if (KMSystemMenu.Edit.deleteSelector == action) {
- isTakesEffect.pointee = true
- return self.listView.activeAnnotations.count > 0
- } else if (KMSystemMenu.Edit.copySelector == action) {
- isTakesEffect.pointee = true
- return true//self.listView.canCopy()
- } else if (KMSystemMenu.Edit.cutSelector == action) {
- isTakesEffect.pointee = true
- return self.listView.canCopy()
- } else if (KMSystemMenu.Edit.pasteSelector == action) {
- isTakesEffect.pointee = true
- return self.listView.canPaste()
- }
- }
-
- isTakesEffect.pointee = false
- return false
- }
-
- //MARK: -CPDFListViewDelegate
- func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
- self.leftSideViewController.updateThumbnail(at: Int(pdfPage.pageIndex()))
- }
-
- 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()
- }
- let aType = annotationType
- if aType.isMarkup() || aType == .anchored || aType == .freeText || aType.isSquare() || aType == .link {
- KMDataManager.ud_set(annotationType.rawValue, forKey: SKLastAnnotationModeKey)
- }
- }
-
- ///开始定位链接注释
- 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())
- tMenuItems?.append(self.restoreCorpImageMenuItem())
- } else {
- tMenuItems?.append(NSMenuItem.separator())
- tMenuItems?.append(self.cutImageArea())
- tMenuItems?.append(self.replaceImageArea())
- tMenuItems?.append(self.exportImageArea())
- }
- } else {
- if tMenuItems?.count != 1 {
- tMenuItems?.swapAt(0, 1)
- }
- }
- } else if areas.count == 0 {
- tMenuItems?.append(NSMenuItem.separator())
- tMenuItems?.append(self.addText())
- tMenuItems?.append(self.addImage())
- }
-
- return tMenuItems
- }
-
- func tableMenu(_ menu: NSMenu, withTable table: KMTableAnnotation, point: CGPoint) -> NSMenu {
- if table.currentCell.row >= 0 && table.currentCell.column >= 0 {
- let itemTitles = ["Edit", "", "Add Row Above", "Add Row Below", "", "Add Column Before", "Add Column After", "", "Delete Row", "Delete Column", "Delete Table", "Cut", "Copy", "Paste", "Paste and Match Style", "Delete Cell Contents", "Clear All"]
- let actions = ["formAnnotTextEdit:", "", "addRowAbove:", "addRowBelow:", "", "addColumnBefore:", "addColumnAfter:", "", "deleteRow:", "deleteColumn:", "deleteTabel", "cutCell:", "copyCell:", "pasteCell:", "pasteAndMatchStyle:", "deleteCellContents:", "clearAll:"]
- for i in 0..<itemTitles.count {
- var item: NSMenuItem? = nil
- if itemTitles[i] == "" {
- item = NSMenuItem.separator()
- menu.insertItem(item!, at: i)
- } else {
- item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
- item!.target = self
- item!.action = NSSelectorFromString(actions[i])
- if itemTitles[i] == "Paste" /*&& !_copyCellData*/ {
- item!.action = nil
- } else if itemTitles[i] == "Paste and Match Style" /*&& !_copyCellData */{
- item!.action = nil
- } else if itemTitles[i] == "Add Row Above" {
- let path1 = table.crossLines[table.rowNumber - table.currentCell.row]
- let path2 = table.crossLines[table.rowNumber - table.currentCell.row - 1]
- if (path1 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.round && table.headerCount() >= 5 {
- item!.action = nil
- } else if (path2 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.bevel && table.footerCount() >= 5 {
- item!.action = nil
- }
- }
- item!.title = NSLocalizedString(item!.title, comment: "")
- item!.representedObject = NSValue(point: point)
- menu.insertItem(item!, at: i)
- }
- }
- } else {
- let itemTitles = ["Cut", "Copy", "Paste", "Delete"]
- let actions = ["cut:", "copy:", "paste:", "delete:"]
- for i in 0..<itemTitles.count {
- let item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
- item.target = self
- item.action = NSSelectorFromString(actions[i])
- item.title = NSLocalizedString(item.title, comment: "")
- menu.insertItem(item, at: i)
- item.representedObject = NSValue(point: point)
- }
- }
- return menu
- }
-
- func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
- self.mouseRightMenuEvent = theEvent
- var currentMenu : NSMenu = menu.pointee!
-
- if let activeAnno = listView.activeAnnotation as? KMTableAnnotation {//Table
- var pagePoint = NSPoint()
- _ = self.listView.pageAndPoint(&pagePoint, for: theEvent, nearest: true)
- currentMenu.removeAllItems()
- let annotation = activeAnno
- annotation.completeEditCellText()
- if !(NSIsEmptyRect(annotation.drawRect)) {
- annotation.drawLine(pagePoint)
- NotificationCenter.default.post(name: NSNotification.Name.KMPDFViewTableAnnotationDidChange, object: self, userInfo: ["point": NSValue(point: pagePoint)])
- }
- if (annotation.rowNumber - annotation.currentCell.row - 1) < 0 {
- return
- }
- currentMenu = tableMenu(currentMenu, withTable: listView.activeAnnotation as! KMTableAnnotation, point: pagePoint)
- listView.needsDisplay = true
- return
- }
-
- if (listView.toolMode == .selectToolMode){
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- currentMenu.insertItem(self.printingMenu(), at: 3)
- currentMenu.insertItem(self.setTTSStype(), at: 3)
- currentMenu.insertItem(self.setCropStype(), at: 3)
- currentMenu.insertItem(self.setSnapshotStype(), at: 3)
- let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
- export.submenu = self.exportMenu()
- currentMenu.insertItem(export, at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- if listView.activeAnnotation == nil{
- currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- }
-
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
- currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
- //
- // currentMenu.insertItem(NSMenuItem.separator(), at: 0)
- // currentMenu.insertItem(self.setAITranslateStype(), at: 0)
- // currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
- // currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
- return
- }
- if (listView.toolMode == .moveToolMode || listView.toolMode == .magnifyToolMode){
- currentMenu.insertItem(NSMenuItem.separator(), at: 0)
- currentMenu.insertItem(self.setTTSStype(), at: 0)
- currentMenu.insertItem(self.setCropStype(), at: 0)
- currentMenu.insertItem(self.setSnapshotStype(), at: 0)
- currentMenu.insertItem(NSMenuItem.separator(), at: 0)
-
- currentMenu.insertItem(self.addOutlineStype(), at: 0)
- currentMenu.insertItem(self.addBookmarkMenu(), at: 0)
- if listView.activeAnnotation == nil{
- currentMenu.insertItem(NSMenuItem.separator(), at: 0)
- currentMenu.insertItem(self.setAnnotationToolStype(), at: 0)
- }
- //
- // currentMenu.insertItem(NSMenuItem.separator(), at: 0)
- // currentMenu.insertItem(self.setAITranslateStype(), at: 0)
- // currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
- // currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
- return
- }
-
- if currentMenu.items.count > 3 {
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
- currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
- }
- if listView.currentSelection != nil && listView.activeAnnotations.count < 1{
- if listView.currentSelection.selectionType() == .text {
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- currentMenu.insertItem(self.setSearchBaiduStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- currentMenu.insertItem(self.setLookUpStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- currentMenu.insertItem(self.addOutlineStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- // if listView.activeAnnotation == nil{
- currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
- // }
- currentMenu.insertItem(self.setTTSStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- currentMenu.insertItem(self.setShareStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- }
- currentMenu.insertItem(self.enterAnnotationStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 3)
- if listView.currentSelection.selectionType() == .image{
- //
- // currentMenu.insertItem(self.setCutStype(), at: 1)
- // }
- // if listView.activeAnnotations.count > 0 {
- // currentMenu.insertItem(self.setDeleteStype(), at: 3)
- currentMenu.insertItem(NSMenuItem.separator(), at: 6)
- currentMenu.insertItem(self.addOutlineStype(), at: 6)
- currentMenu.insertItem(NSMenuItem.separator(), at: 6)
- currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
-
- // currentMenu.insertItem(self.setEditNoteStype(), at: 6)
- // currentMenu.insertItem(self.setRotateStype(), at: 6)
- // currentMenu.insertItem(self.setLinesStype(), at: 6)
- // currentMenu.insertItem(self.setColorsStype(), at: 6)
- // }
- }
- if listView.currentSelection.selectionType() == .text {
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
- currentMenu.insertItem(self.setTranslateStype(), at: currentMenu.items.count)
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
- // currentMenu.insertItem(self.setServicesStype(), at: currentMenu.items.count)
- }
- }
- if listView.activeAnnotation != nil || isMoveSelectAnno {
- if let data = self.listView?.activeAnnotation?.type?.lowercased(), data == "stamp"{
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- }else{
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(self.setAnnotationToolStype(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(self.addBookmarkMenu(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(self.addOutlineStype(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(self.setSnapshotStype(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(self.setCropStype(), at: currentMenu.items.count - 15)
- // currentMenu.insertItem(self.setTTSStype(), at: currentMenu.items.count - 15)
- if let anno = self.listView.activeAnnotation, anno.isKind(of: CPDFStampAnnotation.self) {
- // currentMenu.insertItem(self.setRotateStype(), at: currentMenu.items.count - 15)
- } else {
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- currentMenu.insertItem(self.setShareStype(), at: currentMenu.items.count - 15)
- }
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
- }
- }
-
- if listView.activeAnnotation == nil && listView.currentSelection == nil{
- currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
- if(listView.toolMode == .selectToolMode) {
- if NSIsEmptyRect(listView.currentSelectionRect()) {
- currentMenu.insertItem(self.zoomSelectionMenuItem(), at: 0)
- currentMenu.insertItem(NSMenuItem.separator(), at: 0)
- }
- currentMenu.insertItem(self.printingMenu(), at: 0)
- currentMenu.insertItem(self.setTTSStype(), at: 0)
- currentMenu.insertItem(self.setCropStype(), at: 0)
- currentMenu.insertItem(self.setSnapshotStype(), at: 0)
- let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
- export.submenu = self.exportMenu()
- currentMenu.insertItem(export, at: currentMenu.items.count)
-
- }else{
- currentMenu.insertItem(NSMenuItem.separator(), at: 2)
- currentMenu.insertItem(self.setTTSStype(), at: 2)
- currentMenu.insertItem(self.setCropStype(), at: 2)
- currentMenu.insertItem(self.setSnapshotStype(), at: 2)
- currentMenu.insertItem(NSMenuItem.separator(), at: 2)
-
- currentMenu.insertItem(self.addOutlineStype(), at: 2)
- currentMenu.insertItem(NSMenuItem.separator(), at: 2)
- currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
- currentMenu.insertItem(NSMenuItem.separator(), at: 2)
-
- if(currentMenu.items.count > 4) {
- currentMenu.insertItem(NSMenuItem.separator(), at: 5)
- }
- if(currentMenu.items.count > 5) {
- currentMenu.insertItem(self.addBookmarkMenu(), at: 6)
- }
-
- // if (currentMenu.items.count > 6 && self.isReadMode) {
- // currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
- // }
- // currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
-
- currentMenu.insertItem(self.setAutoScrollStype(), at: currentMenu.items.count)
- }
- currentMenu.insertItem(self.setAnnotationToolStype(), at: 5)
- }
- //
- // currentMenu.insertItem(NSMenuItem.separator(), at: 0)
- // currentMenu.insertItem(self.setAITranslateStype(), at: 0)
- // currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
- // currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
-
- 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 = false
- for anno in annotations {
- if (anno.isKind(of: CPDFRedactAnnotation.self)) {
- addRedact = true
- } else if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
- anno.contents = pdfPage?.string(for: anno.bounds) ?? ""
- }
- }
- self.model.hasAddRedact = addRedact
- if /*self.isReadMode || */self.listView.toolMode == .moveToolMode {
- self.listView.toolMode = .textToolMode
- self.listView.annotationType = .unkown
- self.toolbarController.toolbarType = .Annatiton
- }
- if (self.model.rightMouseEventing) {
- self.model.rightMouseEventing = false
-
- if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
- self.listView.toolMode = .textToolMode
- self.listView.annotationType = .unkown
- }
- }
- self.toolbarController.ignoreCurrentAnnotationTypeChange = false
- self.leftSideViewController.refreshUIForAddAnnotation(annos: annotations, page: pdfPage)
- }
-
- func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
- self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: annotations, page: pdfPage)
- }
-
- 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.manager.markHighlightColors
- } else {
- return KMAnnotationPropertiesColorManager.manager.markOtherColors
- }
- } else {
- return KMAnnotationPropertiesColorManager.manager.markOtherColors
- }
- }
-
- func pdfListViewHaveDocumentAttribute() -> Bool {
- if(!self.listView.document.allowsCopying) {
- self.removeOwnerPassword()
- return false
- }
- return true
- }
-
- func pdfListView(_ sender: CPDFListView!, showSnapshotAtPageNumber pageNum: Int, for rect: NSRect, scaleFactor: CGFloat, autoFits: Bool) {
- let swc = KMSnapshotWindowController(windowNibName: "SnapshotWindow")
- swc.delegate = self
- swc.setPdfDocument(self.listView.document, goToPageNumber: pageNum, rect: rect, scaleFactor: scaleFactor, autoFits: autoFits)
- swc.forceOnTop = self.interactionMode != .normal
- self.myDocument?.addWindowController(swc)
- }
-
- func pdfListView(_ pdfView: CPDFListView!, documentDataDidChanged docData: Any!, withInfo info: [AnyHashable : Any]!) {
- if let data = info?[CPDFListView.outlineKey] as? Bool, data { // 大纲改变
- guard let ol = docData as? CPDFOutline else {
- return
- }
- let add = info?[CPDFListView.outlineAddKey] as? Bool ?? false
- let remove = info?[CPDFListView.outlineRemoveKey] as? Bool ?? false
- if add {
- self.leftSideViewController.addOutlineAfter(ol)
- }
- if remove {
- self.leftSideViewController.removeOutlineAfter(ol)
- }
-
- let demote = info?[CPDFListView.outlineDemoteKey] as? Bool ?? false
- let promote = info?[CPDFListView.outlinePromoteKey] as? Bool ?? false
- if demote {
- self.leftSideViewController.demoteOutlineAfter(ol)
- }
- if promote {
- self.leftSideViewController.promoteOutlineAfter(ol)
- }
- }
- }
-
- func pdfListViewDidApplyStamp(toAllPages pdfView: CPDFListView!) {
-
- let pagesWindowController = KMRedactSelectPagesWindowController(document: self.listView.document)
- self.km_beginSheet(windowC: pagesWindowController)
- pagesWindowController.callback = { [unowned self] pages in
- if pages.count > 0 {
- DispatchQueue.main.async {
- self.listView.apply(annotation: self.listView.activeAnnotation, toPages: pages)
- }
- }
- }
- }
-
- func pdfListViewDidAddLink(toSelectedImage pdfView: CPDFListView!) {
- if self.listView.currentSelection != nil {
- let annotation = self.listView.addAnnotation(with: CAnnotationType(rawValue: 2) ?? CAnnotationType.unkown, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
- if((annotation != nil) &&
- !self.listView.activeAnnotations.contains(annotation ?? self.listView.activeAnnotation)) {
- var newAnnonations : [CPDFAnnotation] = []
- newAnnonations.append(annotation!)
- self.listView.updateActiveAnnotations(newAnnonations)
- self.listView.setNeedsDisplayAnnotationViewFor(annotation?.page)
- }
- }
- self.refreshListViewToolMode()
- let type = CAnnotationType(rawValue: 2) ?? CAnnotationType.unkown
- var annotations: [CPDFAnnotation] = []
- if (type == .link) {
- for annotation in self.listView.activeAnnotations {
- if ((annotation is CPDFLinkAnnotation) == false) {
- continue
- }
- annotations.append(annotation as! CPDFAnnotation)
- }
- }
- self.listView.annotationType = type
- if (type == .link && annotations.count > 0) {
- self.listView.updateActiveAnnotations(annotations)
- }
-
- // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.15) {
- DispatchQueue.main.async {
- self.listView.changeAnnotationTypeWithoutAction(.unkown)
- self.toolbarController.cancelSelected(KMToolbarLinkAnnotationItemIdentifier)
- }
- }
-
- //TextEdit
- func pdfListViewDidTextFontChanged(_ pdfListView: CPDFListView!) {
- self.rightSideViewController.eidtPDFTextProperty.reloadData()
- }
-
- func pdfListViewDidTextColorChanged(_ pdfListView: CPDFListView!, with color: NSColor!) {
- self.rightSideViewController.eidtPDFTextProperty.fontColorChangeAction()
- }
-
- func pdfListViewIsPDFReadMode() -> Bool {
- return self.isReadMode
- }
- }
|