KMMainViewController.swift 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  1. //
  2. // KMMainViewController.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. @objcMembers class KMMainViewController: NSViewController,CPDFViewDelegate,CPDFListViewDelegate,NSTextFieldDelegate {
  9. @IBOutlet var PDFContendView: NSView!
  10. @IBOutlet var centerContentView: NSView!
  11. @IBOutlet var listView: CPDFListView!
  12. @IBOutlet var secondaryPdfView: CPDFView!
  13. @IBOutlet weak var readContentView: NSView!
  14. @IBOutlet weak var tipCurrentPageBox: KMBox!
  15. @IBOutlet weak var rightView: NSView!
  16. @IBOutlet weak var leftView: NSView!
  17. @IBOutlet weak var mianSplitView: KMSplitView!
  18. @IBOutlet weak var pdfSplitView: KMSplitView!
  19. @IBOutlet weak var pdfContentView: NSView!
  20. @IBOutlet weak var pdfSplitSecondView: NSBox!
  21. @IBOutlet weak var locationPageView: NSView!
  22. @IBOutlet weak var tipLabel: NSTextField!
  23. @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
  24. @IBOutlet var childToolbarController: KMToolbarViewController!
  25. @IBOutlet var toolbarController: KMToolbarController!
  26. @IBOutlet weak var toolbarBox: NSBox!
  27. @IBOutlet weak var heightOffset: NSLayoutConstraint!
  28. //阅读模式界面
  29. @IBOutlet weak var readModelView: KMReadModelView!
  30. @IBOutlet weak var bottomAreaView: KMBox!
  31. @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
  32. var isReadMode: Bool = false
  33. var readLeftMethodType: BotaType = .None
  34. var readLeftPanelOpen = false
  35. var readLastLeftPanWidth = 0.0
  36. var readLeftViewShowPanel = false
  37. var readRightPanelOpen = false
  38. var readToolbarType: KMToolbarViewType = .None
  39. var readToolbarItemIdentifier: String = ""
  40. var readToolMode: CToolMode = .textToolMode
  41. var readAnnotationType: CAnnotationType = .unkown
  42. var readSubViewType: RightSubViewType = .None
  43. //页码显示器
  44. @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
  45. @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
  46. private var _needSave = false
  47. var needSave: Bool {
  48. set {
  49. _needSave = newValue
  50. if (_needSave == false) {
  51. self.clearIsPDFDocumentEdited()
  52. self.hiddenSecureSuccessTip()
  53. }
  54. }
  55. get {
  56. return _needSave
  57. }
  58. }
  59. // 标识 pdf 已编辑
  60. fileprivate var _isPDFDocumentEdited = false
  61. // 标识 pdf文字图片已编辑
  62. internal var isPDFTextImageEdited = false
  63. var isPDFDocumentEdited: Bool {
  64. get {
  65. return _isPDFDocumentEdited
  66. }
  67. }
  68. var password: String?
  69. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  70. var rightSideViewController: KMRightSideViewController!
  71. var searchResults: [KMSearchMode] = []
  72. var mwcFlags: MwcFlags = MwcFlags()
  73. var isShowQuickTour: Bool = false
  74. var document: CPDFDocument?
  75. var myDocument: NSDocument?
  76. var browserWindowController: KMBrowserWindowController?
  77. var documentAIViewController: KMDocumentAIViewController?
  78. var cropSettingWindowController: KMCropSettingWindowController!
  79. var currentWindowController: NSWindowController!
  80. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  81. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  82. @IBOutlet weak var topTipBox: NSBox!
  83. @IBOutlet weak var exitFullButton: NSButton!
  84. var hasAddRedact: Bool = false
  85. var functionWidth: Double {
  86. get {
  87. if self.isReadMode {
  88. if !self.isShowBOTA {
  89. return 0
  90. }
  91. }
  92. return 48
  93. }
  94. }
  95. var isShowBOTA: Bool = false
  96. let panelWidth = 212.0
  97. let defaultRightWidth = 260.0
  98. var lastLeftPanWidth = 0.0
  99. var lastRightPanWidth = 0.0
  100. var leftPanelOpen: Bool = false
  101. var rightPanelIsOpen = false
  102. var pageNumber: UInt?
  103. var openSecondaryPdfView: KMSecondaryViewController?
  104. var secondaryPdfContentView: NSView?
  105. var lastSplitPDFHeight: Float?
  106. internal var isSaveKeyChain = true
  107. var rightMouseEventing = false
  108. var pdfEditController: KMPDFEditViewController? {
  109. get {
  110. return self.getPDFEditController()
  111. }
  112. }
  113. var autoSaveTimer: Timer?
  114. var progressController: SKProgressController?
  115. private var _documentFirstLoad: Bool = true
  116. var eventMonitor: Any?
  117. var keyEventMonitor: Any?
  118. var mouseRightMenuEvent: NSEvent?
  119. var aiTranslationWindow: KMAITranslationWindowController?
  120. var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
  121. private var background_mask: NSView?
  122. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  123. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  124. get {
  125. return self._secureOptions
  126. }
  127. }
  128. fileprivate var _removeSecureFlag = false
  129. var removeSecureFlag: Bool {
  130. get {
  131. return self._removeSecureFlag
  132. }
  133. }
  134. fileprivate var _saveWatermarkFlag = false
  135. var saveWatermarkFlag: Bool {
  136. get {
  137. return self._saveWatermarkFlag
  138. }
  139. }
  140. deinit {
  141. NotificationCenter.default.removeObserver(self)
  142. self.stopAutoSaveTimer()
  143. self.removeEventMonitor()
  144. self.removeKeyEventMonitor()
  145. }
  146. override func awakeFromNib() {
  147. super.awakeFromNib()
  148. self.addBackgroundMaskView()
  149. // pdfSplitView.frame = NSMakeRect(0, 0, NSWidth(centerContentView.bounds), NSHeight(centerContentView.bounds)-1)
  150. // centerContentView.addSubview(pdfSplitView)
  151. self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
  152. listView.delegate = self
  153. listView.pdfListViewDelegate = self
  154. // listView.editingConfig().isSupportMultipleSelectEditingArea = true
  155. if (document != nil) {
  156. // if (self.document!.isLocked) {
  157. //
  158. // } else {
  159. listView.document = document
  160. // }
  161. // listView.document.delegate = self
  162. let autoScale = listView.autoScales
  163. if !autoScale {
  164. listView.scaleFactor = 1.0
  165. }
  166. }
  167. self.initPDFLeftViewVC()
  168. self.initRightSideView()
  169. self.toolbarController.listView = self.listView
  170. }
  171. override func viewDidAppear() {
  172. super.viewDidAppear()
  173. //刷新向前向后按钮
  174. self.updateBackAndForwardButtonState()
  175. KMLightMemberManager.manager.canShowAdvancedView = false
  176. Task { @MainActor in
  177. await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
  178. }
  179. // self.addEventMonitor()
  180. self.view.window?.makeFirstResponder(self.listView)
  181. // 更新属性页面的信息
  182. NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
  183. if (self.document == nil) {
  184. return
  185. }
  186. if (self.document!.isLocked == false) {
  187. return
  188. }
  189. if (self.view.window == nil) {
  190. return
  191. }
  192. if (self.password != nil) {
  193. self.isSaveKeyChain = false
  194. self.listView.document.unlock(withPassword: self.password)
  195. return
  196. }
  197. KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { result , password in
  198. if (result == .cancel) {
  199. self.browserWindowController?.browser.closeTab()
  200. return
  201. }
  202. self.isSaveKeyChain = true
  203. self.listView.document = self.document
  204. self.document?.unlock(withPassword: password)
  205. }
  206. }
  207. override func viewWillAppear() {
  208. super.viewWillAppear()
  209. self.reStartAutoSaveTimer()
  210. //是否弹出登录窗口
  211. // self.needShowRegisterView()
  212. }
  213. override func viewWillDisappear() {
  214. super.viewWillDisappear()
  215. // KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  216. self.pauseAutoSaveTimer()
  217. self.removeEventMonitor()
  218. }
  219. override func viewWillLayout() {
  220. super.viewWillLayout()
  221. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  222. self.exitFullButton.isHidden = false
  223. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  224. } else {
  225. self.exitFullButton.isHidden = true
  226. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  227. }
  228. }
  229. override func viewDidLoad() {
  230. super.viewDidLoad()
  231. leftSideViewController.mainVC = self
  232. mwcFlags.settingUpWindow = 1
  233. toolbarController.delegate = self
  234. //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
  235. toolbarBox.contentView = toolbarController.view
  236. // self.childToolbarController.updateType(newType: .Annatiton)
  237. // self.showChildToolbar(showToolbar: true)
  238. // self.toolbarController.editPDFButtonAction(item: NSMenuItem())
  239. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  240. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  241. UserDefaults.standard.synchronize()
  242. }
  243. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  244. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  245. UserDefaults.standard.synchronize()
  246. }
  247. let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
  248. mianSplitView.setPosition(position, ofDividerAt: 0)
  249. mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0)
  250. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0)
  251. self.locationPageView.wantsLayer = true;
  252. self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
  253. 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: "")
  254. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  255. if (self.listView.document != nil) {
  256. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  257. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  258. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  259. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  260. if (pageScale != nil) {
  261. self.listView.scaleFactor = CGFloat(pageScale!)
  262. }
  263. self.listView.go(toPageIndex: pageNumber!, animated: false)
  264. }
  265. } else {
  266. self._goToFirstPageForFristAppear()
  267. }
  268. }
  269. } else {
  270. self._goToFirstPageForFristAppear()
  271. }
  272. //阅读页面
  273. readModelView.delegate = self
  274. pageNumberDisplayView.delegate = self
  275. tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
  276. if mouseEntered {
  277. self.pageNumberDisplayView.hover = true
  278. // self.updatePageIndicatoreType()
  279. } else {
  280. self.pageNumberDisplayView.hover = false
  281. // self.updatePageIndicatoreType()
  282. }
  283. }
  284. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  285. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  286. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  287. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  288. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  289. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  290. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  291. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  292. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  293. self.autoSaveTimeStartOrStopIfNeed()
  294. self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
  295. self.closeRightPane()
  296. self.addKeyEventMonitor()
  297. //检测OCR包是否需要更新
  298. #if VERSION_DMG
  299. KMResourceDownloadManager.manager.checkDocumentAIVersion()
  300. #endif
  301. }
  302. //MARK: - PDFListView
  303. func initPDFLeftViewVC() {
  304. leftSideViewController.listView = self.listView ?? CPDFListView()
  305. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  306. leftSideViewController.view.autoresizingMask = [.height,.width]
  307. leftSideViewController.delegate = self
  308. self.leftView.addSubview(leftSideViewController.view)
  309. }
  310. func initRightSideView() {
  311. self.rightSideViewController = KMRightSideViewController.init()
  312. self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
  313. self.rightSideViewController.view.autoresizingMask = [.height,.width]
  314. self.rightSideViewController.listView = self.listView
  315. // self.rightSideViewController.view.isHidden = true
  316. self.rightSideViewController.isHidden = true
  317. self.rightSideViewController.delegate = self
  318. self.rightView.addSubview(self.rightSideViewController.view)
  319. self.rightSideViewController.propertyDidChange = {
  320. [weak self] (model: AnyObject?) in
  321. let topBarView = self?.toolbarController.fetchTopBarView()
  322. if (topBarView == nil || ((topBarView?.isKind(of: KMWatermarkAdjectiveTopBarView.self)) == false)) {
  323. return
  324. }
  325. /// Bates码、页眉页脚、背景、水印
  326. if (model == nil) {
  327. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
  328. } else {
  329. if ((model?.isKind(of: KMBatesModel.self))!) {
  330. if ((model as! KMBatesModel).hasVaild) {
  331. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  332. } else {
  333. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
  334. }
  335. } else if ((model?.isKind(of: KMHeaderFooterModel.self))!) {
  336. if ((model as! KMHeaderFooterModel).hasVaild) {
  337. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  338. } else {
  339. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
  340. }
  341. } else if ((model?.isKind(of: KMBackgroundModel.self))!) {
  342. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  343. } else if ((model?.isKind(of: KMWatermarkModel.self))!) {
  344. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  345. }
  346. }
  347. }
  348. }
  349. // MARK: Private Methods
  350. internal func removeNotifications() {
  351. NotificationCenter.default.removeObserver(self)
  352. self.leftSideViewController.clearAnnotationFilterData()
  353. self.leftSideViewController.clearNotification()
  354. }
  355. func checkShouldAutoOpenLeftVC() {
  356. if (KMPreferenceManager.shared.leftSideNeedCloseWhenOpenFile()) {
  357. return
  358. }
  359. if (KMPreferenceManager.shared.leftSideDisplayType == .showOutlineIfHas) {
  360. let outlineRoot = self.listView.document.outlineRoot()
  361. let hasOutline = (outlineRoot != nil && outlineRoot!.numberOfChildren > 0)
  362. if (hasOutline == false) {
  363. return
  364. }
  365. DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
  366. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  367. }
  368. return
  369. }
  370. DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
  371. let selectedIndex = UserDefaults.standard.integer(forKey: "KMBOTASelectedIndexKey")
  372. let thumai = KMLeftMethodMode()
  373. if selectedIndex == 0 {
  374. thumai.methodType = .Thumbnail
  375. } else if selectedIndex == 1 {
  376. thumai.methodType = .Outline
  377. } else if selectedIndex == 2 {
  378. thumai.methodType = .BookMark
  379. } else if selectedIndex == 3 {
  380. thumai.methodType = .Annotation
  381. } else if selectedIndex == 4 {
  382. thumai.methodType = .Search
  383. }
  384. self.leftSideViewController.refreshMethodType(methodType: thumai.methodType)
  385. }
  386. }
  387. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  388. mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  389. mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  390. lastLeftPanWidth = leftSideWidth
  391. lastRightPanWidth = rightSideWidth
  392. }
  393. //MARK: 动画 暂未接入
  394. func animateSplitView(to position: CGFloat) {
  395. let frame1 = NSRect(x: 0, y: 0, width: position, height: mianSplitView.frame.height)
  396. let frame2 = NSRect(x: position, y: 0, width: mianSplitView.frame.width - position, height: mianSplitView.frame.height)
  397. // 创建一个新的动画上下文
  398. let animationContext = NSAnimationContext.current
  399. animationContext.duration = 0.5
  400. animationContext.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  401. // 启用隐式动画
  402. NSAnimationContext.current.allowsImplicitAnimation = true
  403. // 移动分隔条
  404. mianSplitView.setPosition(position, ofDividerAt: 0)
  405. mianSplitView.subviews[0].frame = frame1
  406. mianSplitView.subviews[1].frame = frame2
  407. }
  408. internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  409. internal func removeAllAnnotations() {
  410. let alert = NSAlert()
  411. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  412. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  413. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  414. if (alert.runModal() != .alertFirstButtonReturn) {
  415. return
  416. }
  417. DispatchQueue.main.async {
  418. self.removeAllAnnotationsStore.store(t: self.listView)
  419. }
  420. }
  421. // MARK: Set Methods
  422. var setDocument: CPDFDocument? {
  423. get {
  424. return document
  425. }
  426. set {
  427. if document != newValue {
  428. document = newValue
  429. }
  430. listView.document = document
  431. // listView.document.delegate = self
  432. self.listView.layoutDocumentView()
  433. }
  434. }
  435. var setPageNumber: UInt {
  436. get {
  437. return pageNumber!
  438. }
  439. set {
  440. let pageCount = listView.document.pageCount
  441. var value = newValue
  442. if value > pageCount {
  443. value = pageCount
  444. }
  445. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  446. listView.go(to: listView.document.page(at: value-1))
  447. }
  448. if pageNumber != value {
  449. pageNumber = value
  450. }
  451. }
  452. }
  453. // MARK: - 页面编辑
  454. open func enterPageEdit(_ pages: [Int] = []) {
  455. //选中page
  456. var tPages = pages
  457. if tPages.count == 0 {
  458. tPages = self.leftSideViewController.selectPages ?? [self.listView.currentPageIndex]
  459. }
  460. if (hasEnterPageEdit()) {
  461. exitPageEdit()
  462. return
  463. }
  464. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  465. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  466. for (key, value) in toolBarView.toolbarItems {
  467. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  468. (value as! KMToolBoxItem).unEnabled = true
  469. }
  470. }
  471. }
  472. #if VERSION_DMG
  473. let controller = KMPDFEditViewController_dmg(self.listView.document)
  474. #else
  475. let controller = KMPDFEditViewController(self.listView.document)
  476. #endif
  477. controller.selectedPages = tPages
  478. controller.listView = self.listView
  479. self.addChild(controller)
  480. self.PDFContendView.addSubview(controller.view)
  481. controller.view.frame = self.PDFContendView.bounds
  482. controller.view.autoresizingMask = [.width,.height]
  483. self.listView.isHidden = true
  484. controller.itemClick = { [weak self] index, params in
  485. if (index == 1) { /// 双击退出
  486. self?.enterEditMode(self!.leftSideViewController, [])
  487. DispatchQueue.main.async {
  488. let pageIndex: Int = params.first as! Int
  489. self?.listView.go(toPageIndex: pageIndex, animated: true)
  490. }
  491. } else if (index == 2) { // 打印
  492. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  493. }
  494. }
  495. controller.documentEditedCallback = { [weak self] params in
  496. self?.recordIsPDFDocumentEdited()
  497. // self?.needSave = true
  498. if let data = params.first as? KMPageEditType {
  499. self?.recordSaveWatermarkFlag(type: data.toSubscribeWaterMarkType())
  500. } else {
  501. self?.recordSaveWatermarkFlag()
  502. }
  503. }
  504. controller.selectionDidChange = { [weak self] selectedIndexs in
  505. var indexSet = IndexSet()
  506. for indexPath in selectedIndexs {
  507. indexSet.insert(indexPath.item)
  508. }
  509. if indexSet.count != 0 {
  510. self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
  511. // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
  512. }
  513. }
  514. }
  515. open func exitPageEdit() {
  516. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  517. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  518. for (key, value) in toolBarView.toolbarItems {
  519. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  520. (value as! KMToolBoxItem).unEnabled = false
  521. }
  522. }
  523. }
  524. let editController = getPDFEditController()
  525. if (editController == nil) {
  526. return
  527. }
  528. self.listView.annotationType = .highlight
  529. editController?.view.removeFromSuperview()
  530. editController?.removeFromParent()
  531. self.listView.isHidden = false
  532. self.listView.layoutDocumentView()
  533. self.view.window?.makeFirstResponder(self.listView)
  534. self.listView.annotationType = .unkown
  535. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  536. }
  537. open func hasEnterPageEdit() -> Bool {
  538. return self.getPDFEditController() != nil
  539. }
  540. // MARK: - Private Methods
  541. private func getPDFEditController() -> KMPDFEditViewController? {
  542. var editController: KMPDFEditViewController?
  543. for controller in self.children {
  544. if (controller.isKind(of: KMPDFEditViewController.self)) {
  545. editController = (controller as! KMPDFEditViewController)
  546. break
  547. }
  548. }
  549. return editController
  550. }
  551. private func addBackgroundMaskView() {
  552. self.removeBackgroundMaskView()
  553. if let superview = self.mianSplitView.superview {
  554. let view = NSView()
  555. superview.addSubview(view)
  556. view.frame = superview.bounds
  557. view.autoresizingMask = [.width, .height]
  558. view.wantsLayer = true
  559. view.layer?.backgroundColor = .white
  560. self.background_mask = view
  561. }
  562. }
  563. private func removeBackgroundMaskView() {
  564. self.background_mask?.removeFromSuperview()
  565. self.background_mask = nil
  566. }
  567. private func _goToFirstPageForFristAppear() {
  568. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  569. self.listView.go(toPageIndex: 0, animated: false)
  570. }
  571. }
  572. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  573. let fileManager = FileManager.default
  574. do {
  575. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  576. if let fileSize = fileAttributes[.size] as? UInt64 {
  577. let megabyteSize = fileSize / (1024 * 1024)
  578. return megabyteSize >= 10
  579. }
  580. } catch {
  581. KMPrint("Error: \(error)")
  582. }
  583. return false
  584. }
  585. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  586. let url = URL(fileURLWithPath: filePath)
  587. guard let document = PDFDocument(url: url) else {
  588. return false
  589. }
  590. let pageCount = document.pageCount
  591. return pageCount > 30
  592. }
  593. // MARK: Redact 【标记密文】
  594. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  595. let windowController = KMRedactConfirmWindowController(type)
  596. self.currentWindowController = windowController
  597. self.view.window?.beginSheet(windowController.window!)
  598. windowController.itemClick = { [weak self] index in
  599. if (index == 2) { /// 取消
  600. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  601. self?.currentWindowController = nil
  602. callback()
  603. return
  604. }
  605. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  606. self?.currentWindowController = nil
  607. let panel = NSSavePanel()
  608. panel.nameFieldStringValue = "[新文件]"+(self?.listView.document.documentURL.lastPathComponent)!
  609. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  610. button.state = .on
  611. panel.accessoryView = button
  612. panel.isExtensionHidden = true
  613. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  614. if response != .OK {
  615. callback()
  616. return
  617. }
  618. if (type == .redactOne) {
  619. let anno = self!.listView.activeAnnotation
  620. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  621. callback()
  622. return
  623. }
  624. (anno as! CPDFRedactAnnotation).applyRedaction()
  625. } else if (type == .redactAll) {
  626. self?.listView.document.applyRedactions()
  627. } else if (type == .eraserOne) {
  628. let anno = self!.listView.activeAnnotation
  629. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  630. callback()
  631. return
  632. }
  633. anno?.page.erasureRedact(from: anno!.bounds)
  634. } else if (type == .eraserAll) {
  635. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  636. if (result == false) {
  637. callback()
  638. return
  639. }
  640. }
  641. }
  642. self!.listView.document.write(to: panel.url)
  643. if (button.state == .on) {
  644. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  645. }
  646. } else {
  647. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  648. }
  649. callback()
  650. }
  651. }
  652. }
  653. // MARK: Secure 【安全】
  654. public func showSecureSuccessTip() {
  655. let view: NSView = self.view
  656. let tip = KMSecureEncryptSuccessTipView()
  657. let size = NSSize(width: 379, height: 176)
  658. tip.frame = NSMakeRect(view.frame.size.width-size.width-16, view.frame.size.height-size.height-88, size.width, size.height)
  659. tip.autoresizingMask = [.minXMargin, .minYMargin]
  660. view.addSubview(tip)
  661. tip.itemClick = { [weak self] in
  662. self!.hiddenSecureSuccessTip()
  663. }
  664. }
  665. public func hiddenSecureSuccessTip() {
  666. let view: NSView = self.view
  667. var tip: KMSecureEncryptSuccessTipView?
  668. for subview in view.subviews {
  669. if (subview.isKind(of: KMSecureEncryptSuccessTipView.self)) {
  670. tip = (subview as! KMSecureEncryptSuccessTipView)
  671. break
  672. }
  673. }
  674. if (tip == nil) {
  675. return
  676. }
  677. tip?.removeFromSuperview()
  678. }
  679. public func showSecureLimitTip() {
  680. self.hiddenSecureLimitTip()
  681. let view: NSView = self.view
  682. let tip = KMSecureLimitAlertView()
  683. let size = NSSize(width: 379, height: 154)
  684. tip.frame = NSMakeRect(view.frame.size.width-size.width-16, view.frame.size.height-size.height-50, size.width, size.height)
  685. tip.autoresizingMask = [.minXMargin, .minYMargin]
  686. view.addSubview(tip)
  687. tip.itemClick = { [unowned self] index in
  688. if (index == 1) {
  689. self.hiddenSecureLimitTip()
  690. return
  691. }
  692. if (self.listView.document.allowsPrinting == false || self.listView.document.allowsCopying == false) {
  693. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  694. if result == .cancel { /// 关闭
  695. return
  696. }
  697. /// 解密成功
  698. self?.hiddenSecureLimitTip()
  699. self?.isSaveKeyChain = false
  700. self?.listView.document.unlock(withPassword: password)
  701. }
  702. return
  703. }
  704. }
  705. }
  706. public func hiddenSecureLimitTip() {
  707. let view: NSView = self.view
  708. var tip: KMSecureLimitAlertView?
  709. for subview in view.subviews {
  710. if (subview.isKind(of: KMSecureLimitAlertView.self)) {
  711. tip = (subview as! KMSecureLimitAlertView)
  712. break
  713. }
  714. }
  715. if (tip == nil) {
  716. return
  717. }
  718. tip?.removeFromSuperview()
  719. }
  720. override func mouseMoved(with event: NSEvent) {
  721. }
  722. func savePageNumberIfNeed() {
  723. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  724. if self.listView.document != nil {
  725. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  726. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  727. }
  728. }
  729. }
  730. // MARK: -
  731. // MARK: 退出全屏
  732. @IBAction func exitFullScreen(_ sender: Any) {
  733. if (self.view.window == nil) {
  734. return
  735. }
  736. if (KMTools.isFullScreen(self.view.window!)) {
  737. self.view.window?.toggleFullScreen(nil)
  738. }
  739. }
  740. // MARK: -
  741. // MARK: 显示合并窗口
  742. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  743. DispatchQueue.main.async {
  744. if let _url = url {
  745. let document = PDFDocument(url: _url)
  746. let windowController = KMPDFEditAppendWindow(pdfDocument: document, password: password)
  747. windowController?.oriDucumentUrl = self.listView.document.documentURL
  748. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  749. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, selectedIndexSet in
  750. })
  751. } else {
  752. let document = PDFDocument(url: self.listView.document.documentURL)
  753. let windowController = KMPDFEditAppendWindow(pdfDocument: document, password: password)
  754. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  755. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, selectedIndexSet in
  756. })
  757. }
  758. }
  759. }
  760. // MARK: -
  761. // MARR: 显示加密弹窗
  762. public func showSecureWindow(_ url: URL) {
  763. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  764. windowController.documentURL = url
  765. windowController.myDocument = self.listView.document
  766. self.currentWindowController = windowController
  767. windowController.itemClick = { [weak self] index in
  768. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  769. self?.currentWindowController = nil
  770. }
  771. windowController.resultCallback = { [weak self] result in
  772. let windowController_secure = self?.currentWindowController as! KMSecureEncryptWindowController
  773. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  774. self?.currentWindowController = nil
  775. self?._secureOptions = windowController_secure.options
  776. self?.needSave = true
  777. self?.recordIsPDFDocumentEdited(type: .setPassword)
  778. if (result) {
  779. self?.showSecureSuccessTip()
  780. self?.recordSaveWatermarkFlag(type: .setPassword)
  781. } else {
  782. let alert = NSAlert()
  783. alert.messageText = NSLocalizedString("Failure", comment: "")
  784. alert.runModal()
  785. }
  786. }
  787. self.view.window?.beginSheet(windowController.window!)
  788. }
  789. // MARK: -
  790. // MARK: 保存文档
  791. internal func needSaveDocument() -> Bool {
  792. if (self.isPDFDocumentEdited) {
  793. return self.isPDFDocumentEdited
  794. }
  795. if (self.needSave) {
  796. return self.needSave
  797. }
  798. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  799. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  800. return false
  801. }
  802. return true
  803. }
  804. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  805. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  806. if (overlook) {
  807. document?.save(nil)
  808. return
  809. }
  810. if (self.isPDFDocumentEdited) {
  811. self.clearIsPDFDocumentEdited()
  812. self.needSave = false
  813. document?.save(nil)
  814. return
  815. }
  816. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  817. return
  818. }
  819. document?.save(nil)
  820. }
  821. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  822. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  823. if (overlook) {
  824. DispatchQueue.main.async {
  825. document?.save(nil)
  826. callback()
  827. }
  828. return
  829. }
  830. if (self.isPDFDocumentEdited) {
  831. self.clearIsPDFDocumentEdited()
  832. self.needSave = false
  833. DispatchQueue.main.async {
  834. document?.save(nil)
  835. callback()
  836. }
  837. return
  838. }
  839. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  840. callback()
  841. return
  842. }
  843. DispatchQueue.main.async {
  844. document?.save(nil)
  845. callback()
  846. }
  847. }
  848. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  849. // 显示进度
  850. self.showProgressWindow(message: NSLocalizedString("Save PDF", comment: ""))
  851. self.progressController?.maxValue = 3.0
  852. self.progressController?.increment(by: 1.0)
  853. // 保存文档
  854. self.asyncSaveDocument { [unowned self] params in
  855. // 执行进度 [假进度]
  856. self.progressController?.increment(by: 1.0)
  857. self.progressController?.increment(by: 1.0)
  858. // DispatchQueue.main.async {
  859. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  860. // 隐藏进度
  861. self.hiddenProgressWindow()
  862. // 回调
  863. callback()
  864. }
  865. }
  866. }
  867. // MARK: -
  868. // MARK: 选择 PDFDisplay 模式
  869. @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
  870. let toolModel = self.listView.toolMode
  871. self.isReadMode = false
  872. switch display {
  873. case .singlePage:
  874. self.listView.setDisplay(.singlePage)
  875. break
  876. case .singlePageContinuous:
  877. self.listView.setDisplay(.singlePageContinuous)
  878. break
  879. case .twoUp:
  880. self.listView.setDisplay(.twoUp)
  881. break
  882. case .twoUpContinuous:
  883. self.listView.setDisplay(.twoUpContinuous)
  884. break
  885. case .bookMode:
  886. self.listView.displaysAsBook = true
  887. self.listView.displayTwoUp = true
  888. self.listView.displayDirection = .horizontal
  889. break
  890. case .bookContinuous:
  891. self.listView.displaysAsBook = true
  892. self.listView.displayTwoUp = true
  893. self.listView.displayDirection = .vertical
  894. break
  895. case .readModel:
  896. self.openReadModel()
  897. break
  898. case .readContinuous:
  899. self.openReadModel()
  900. break
  901. }
  902. self.listView.layoutDocumentView()
  903. if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
  904. self.leftSideViewController.panelSetViewController.reloadListViewModel()
  905. }
  906. if (toolModel == .editPDFToolMode) {
  907. if self.rightSideViewController.eidtPDFImageProperty != nil {
  908. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  909. self.rightSideViewController.isHidden = true
  910. self.closeRightPane()
  911. }
  912. }
  913. }
  914. // Mark: -
  915. // MARK: - 选择缩放模式
  916. @objc public func selectZoom(_ type: KMPDFZoomType) {
  917. switch type {
  918. case .width:
  919. self.listView.autoScales = true
  920. // self.listView.autoScales = false
  921. break
  922. case .fit:
  923. // self.listView.autoScales = !self.listView.autoScales
  924. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  925. let pdfviewHeight = self.listView.bounds.size.height
  926. self.listView.scaleFactor = pdfviewHeight/pageHeight
  927. self.listView.autoScales = false
  928. }
  929. break
  930. case .actualSize:
  931. if self.listView.scaleFactor != 1.0 {
  932. self.listView.scaleFactor = 1.0
  933. self.listView.autoScales = false
  934. }
  935. break
  936. }
  937. }
  938. // MARK: - 自动保存
  939. internal func autoSaveTimeStartOrStopIfNeed() {
  940. if (KMPreferenceManager.shared.autoSave == false) {
  941. self.stopAutoSaveTimer()
  942. return
  943. }
  944. self.startAutoSaveTimer(KMPreferenceManager.shared.autoSaveTimeInterval)
  945. if (self.myDocument == nil) {
  946. self.stopAutoSaveTimer()
  947. return
  948. }
  949. let browser = self.browserWindowController?.browser
  950. guard let activeDocument = browser?.activeTabContents() else {
  951. return
  952. }
  953. if (self.myDocument!.isEqual(to: activeDocument) == false) {
  954. self.pauseAutoSaveTimer()
  955. return
  956. }
  957. }
  958. private func startAutoSaveTimer(_ interval: TimeInterval) {
  959. if (self.autoSaveTimer != nil) {
  960. self.autoSaveTimer?.invalidate()
  961. self.autoSaveTimer = nil
  962. }
  963. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] timer in
  964. DispatchQueue.main.async {
  965. #if DEBUG
  966. Swift.debugPrint("文档已自动保存")
  967. if let _document = self?.myDocument {
  968. Swift.debugPrint(_document.fileURL as Any)
  969. }
  970. #endif
  971. self?.saveDocument()
  972. }
  973. }
  974. RunLoop.current.add(self.autoSaveTimer!, forMode: .common)
  975. }
  976. private func pauseAutoSaveTimer() {
  977. self.autoSaveTimer?.fireDate = Date.distantFuture
  978. }
  979. private func reStartAutoSaveTimer() {
  980. self.autoSaveTimer?.fireDate = Date()+KMPreferenceManager.shared.autoSaveTimeInterval
  981. }
  982. private func needShowRegisterView() {
  983. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  984. if KMLightMemberManager.manager.checkPopupRegister() {
  985. // Login & Logout
  986. let window = NSApp.mainWindow ?? self.view.window
  987. if KMLightMemberManager.manager.isLogin() {
  988. } else if window != nil {
  989. var email: String = UserDefaults.standard.value(forKey: "kLoginEmail") as? String ?? ""
  990. if email.count == 0 {
  991. KMLoginWindowController.show(window: window!, .Batch, .register)
  992. } else {
  993. KMLoginWindowController.show(window: window!, .Batch, .login)
  994. }
  995. }
  996. }
  997. }
  998. }
  999. private func stopAutoSaveTimer() {
  1000. self.autoSaveTimer?.invalidate()
  1001. self.autoSaveTimer = nil
  1002. }
  1003. // MARK: -
  1004. // MARK: Progress
  1005. func showProgressWindow(message: String = "") {
  1006. if (self.progressController != nil) {
  1007. self.hiddenProgressWindow()
  1008. }
  1009. let progress = SKProgressController()
  1010. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  1011. progress.window?.contentView?.wantsLayer = true
  1012. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1013. progress.progressField.textColor = NSColor.white
  1014. progress.showClose = false
  1015. progress.message = message
  1016. self.progressController = progress
  1017. self.view.window?.beginSheet(progress.window!)
  1018. }
  1019. func hiddenProgressWindow() {
  1020. if (self.progressController != nil) {
  1021. self.view.window?.endSheet((self.progressController?.window)!)
  1022. self.progressController = nil
  1023. }
  1024. }
  1025. // MARK -
  1026. // MARK - Event 监听
  1027. private func addEventMonitor() {
  1028. if (self.eventMonitor != nil) {
  1029. self.removeEventMonitor()
  1030. }
  1031. KMPrint("已添加事件监听")
  1032. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
  1033. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  1034. self?.listView.magnifyWheel(event)
  1035. return nil
  1036. }
  1037. return event
  1038. }
  1039. }
  1040. func addKeyEventMonitor() {
  1041. if (self.keyEventMonitor != nil) {
  1042. self.removeKeyEventMonitor()
  1043. }
  1044. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  1045. // print(event.keyCode)
  1046. if event.keyCode == 53 {
  1047. if self?.listView.toolMode == .editPDFToolMode {
  1048. if self != nil {
  1049. //使用editingSelectionString获取内容文字
  1050. if self!.listView.editingAreas() != nil {
  1051. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  1052. self!.listView.clearEditingSelectCharItem()
  1053. } else if self!.listView.editingAreas().count > 0 {
  1054. if self?.listView.annotationType == .addImage ||
  1055. self?.listView.annotationType == .addText {
  1056. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1057. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1058. textItem?.isSelected = false
  1059. imageItem?.isSelected = false
  1060. }
  1061. self?.rightSideViewController.isHidden = true
  1062. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  1063. self?.listView.updateEditing([])
  1064. self?.listView.isEditImage = false
  1065. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  1066. self?.closeRightPane()
  1067. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1068. if self?.listView.annotationType == .addImage ||
  1069. self?.listView.annotationType == .addText {
  1070. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1071. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1072. textItem?.isSelected = false
  1073. imageItem?.isSelected = false
  1074. }
  1075. self?.rightSideViewController.isHidden = true
  1076. self?.listView.setShouAddEdit([])
  1077. self?.listView.change([.text, .image])
  1078. self?.listView.annotationType = .editTextImage
  1079. self?.closeRightPane()
  1080. }
  1081. } else {
  1082. if self?.listView.annotationType == .addImage ||
  1083. self?.listView.annotationType == .addText {
  1084. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1085. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1086. textItem?.isSelected = false
  1087. imageItem?.isSelected = false
  1088. }
  1089. }
  1090. }
  1091. }
  1092. }
  1093. return event
  1094. }
  1095. }
  1096. func removeKeyEventMonitor() {
  1097. if (self.keyEventMonitor != nil) {
  1098. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1099. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1100. self.keyEventMonitor = nil
  1101. }
  1102. }
  1103. private func removeEventMonitor() {
  1104. if (self.eventMonitor != nil) {
  1105. KMPrint("已移除事件监听")
  1106. NSEvent.removeMonitor(self.eventMonitor as Any)
  1107. self.eventMonitor = nil
  1108. }
  1109. }
  1110. // MARK: -
  1111. // MARK: Tools
  1112. func pdfViewCanHorizontalScroll() -> Bool {
  1113. let scroll = self.listView.scroll()
  1114. if (scroll == nil) {
  1115. return false
  1116. }
  1117. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1118. }
  1119. func pdfViewCanVerticalScroll() -> Bool {
  1120. let scroll = self.listView.scroll()
  1121. if (scroll == nil) {
  1122. return false
  1123. }
  1124. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1125. }
  1126. // MARK: - Public Methods
  1127. // 清理数据 [eg. 通知]
  1128. public func clearData() {
  1129. self.removeNotifications()
  1130. if (self.listView.spellingTag() > 0) {
  1131. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1132. }
  1133. }
  1134. public func clearSecureOptions() {
  1135. self._secureOptions = nil
  1136. }
  1137. public func recordRemoveSecureFlag() {
  1138. self._removeSecureFlag = true
  1139. self.clearSecureOptions()
  1140. self.recordIsPDFDocumentEdited(type: .removePassword)
  1141. self._needSave = true
  1142. }
  1143. public func clearRemoveSecureFlag() {
  1144. self._removeSecureFlag = false
  1145. }
  1146. public func recordSaveWatermarkFlag(type: KMSubscribeWaterMarkType = .none) {
  1147. km_synchronized(self) {
  1148. self._saveWatermarkFlag = true
  1149. }
  1150. if let _document = self.myDocument as? KMMainDocument {
  1151. _document.recordTrackEvent(type: type)
  1152. }
  1153. }
  1154. public func clearSaveWatermarkFlag() {
  1155. km_synchronized(self) {
  1156. self._saveWatermarkFlag = false
  1157. }
  1158. }
  1159. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1160. km_synchronized(self) {
  1161. self._isPDFDocumentEdited = true
  1162. if let _document = self.myDocument {
  1163. KMTools.setDocumentEditedState(document: _document)
  1164. }
  1165. }
  1166. }
  1167. public func clearIsPDFDocumentEdited() {
  1168. km_synchronized(self) {
  1169. self._isPDFDocumentEdited = false
  1170. }
  1171. }
  1172. // MARK: - Noti Actions
  1173. internal func documentDidUnlockNotification(_ sender: Notification) {
  1174. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1175. if (self.myDocument == nil) {
  1176. return
  1177. }
  1178. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1179. self.hiddenSecureLimitTip()
  1180. }
  1181. if ((self.myDocument as! KMMainDocument).isUnlockFromKeychain || self.isSaveKeyChain == false) {
  1182. return
  1183. }
  1184. let type = KMPreferenceManager.shared.savePasswordType
  1185. if (type == .never) {
  1186. return
  1187. }
  1188. if (type == .always) {
  1189. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1190. return
  1191. }
  1192. // 保存到钥匙串
  1193. let alert = NSAlert()
  1194. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1195. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1196. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1197. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1198. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1199. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1200. return
  1201. }
  1202. }
  1203. }
  1204. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1205. self.savePageNumberIfNeed()
  1206. self.saveDocument()
  1207. }
  1208. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1209. if self.isReadMode {
  1210. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1211. }
  1212. //刷新向前向后按钮
  1213. self.updateBackAndForwardButtonState()
  1214. }
  1215. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1216. if self.isReadMode {
  1217. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1218. }
  1219. //刷新向前向后按钮
  1220. self.updateBackAndForwardButtonState()
  1221. }
  1222. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1223. var editSelectd = false
  1224. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1225. editSelectd = true
  1226. }
  1227. if self.listView.toolMode == .editPDFToolMode {
  1228. if editSelectd {
  1229. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1230. }
  1231. }
  1232. }
  1233. //MARK: - PDFListViewDelegate
  1234. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  1235. // KMPrint("pdfViewDocumentDidLoaded")
  1236. self.removeBackgroundMaskView()
  1237. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1238. self.showSecureLimitTip()
  1239. }
  1240. if (self._documentFirstLoad) {
  1241. self.checkShouldAutoOpenLeftVC()
  1242. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1243. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1244. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1245. if (pageScale != nil) {
  1246. self.listView.scaleFactor = CGFloat(pageScale!)
  1247. }
  1248. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1249. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1250. } else {
  1251. self._goToFirstPageForFristAppear()
  1252. }
  1253. } else {
  1254. self._goToFirstPageForFristAppear()
  1255. }
  1256. self._documentFirstLoad = false
  1257. }
  1258. let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
  1259. self.preferenceDidChangeNotification(notification:notification)
  1260. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: panelWidth + functionWidth)
  1261. let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: defaultRightWidth)
  1262. applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
  1263. self.updatePageIndicatoreType()
  1264. }
  1265. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  1266. self.updatePageIndicatoreType()
  1267. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
  1268. // KMPrint("KMPDFViewCurrentPageDidChanged")
  1269. }
  1270. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  1271. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
  1272. self.updateZoomInOutButtonState()
  1273. // KMPrint("pdfViewScaleDidChanged")
  1274. }
  1275. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  1276. if let urlString = url, urlString == kKMPurchaseProductURLString {
  1277. //跳转订阅比较表
  1278. let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
  1279. return
  1280. }
  1281. KMTools.openURL(urlString: url)
  1282. }
  1283. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  1284. KMPrint("pdfViewPerformURL")
  1285. }
  1286. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  1287. KMPrint("pdfViewPerformPrint")
  1288. }
  1289. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  1290. KMPrint("pdfViewPerformGo")
  1291. }
  1292. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  1293. KMPrint("pdfViewOpenPDF")
  1294. }
  1295. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  1296. KMPrint("pdfViewPerformReset")
  1297. }
  1298. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  1299. KMPrint("pdfViewEditingBlockDidChanged")
  1300. }
  1301. func pdfViewAsBookBookmark() -> NSImage! {
  1302. return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
  1303. }
  1304. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  1305. self.recordSaveWatermarkFlag()
  1306. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
  1307. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1308. self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1309. }
  1310. }
  1311. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  1312. let areas = self.listView.editingAreas()
  1313. if areas == nil || areas?.count ?? 0 == 0 {
  1314. if self.listView.toolMode == .editPDFToolMode {
  1315. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1316. if self.listView.isEditImage {
  1317. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1318. } else {
  1319. // if self.listView.annotationType == .addImage {
  1320. // self.closeRightPane()
  1321. // }
  1322. // if self.rightSideViewController.eidtPDFImageProperty != nil {
  1323. // self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1324. // }
  1325. // self.openRightPane()
  1326. }
  1327. } else {
  1328. self.closeRightPane()
  1329. }
  1330. } else {
  1331. self.rightSideViewController.isHidden = true
  1332. self.closeRightPane()
  1333. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1334. self.rightSideViewController.eidtPDFTextProperty.initData()
  1335. }
  1336. }
  1337. if self.listView.isEdited() {
  1338. self.recordIsPDFDocumentEdited(type: .editText)
  1339. }
  1340. if self.listView.annotationType != .addText {
  1341. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1342. }
  1343. return
  1344. }
  1345. self.isPDFTextImageEdited = true
  1346. if (self.listView.annotationType == .addImage) && areas!.count > 0 {
  1347. var isImageArea = false
  1348. for i in 0 ... areas!.count-1 {
  1349. if areas![i] is CPDFEditImageArea {
  1350. isImageArea = true
  1351. }
  1352. }
  1353. if isImageArea {
  1354. // self.rightSideViewController.view.isHidden = false
  1355. self.rightSideViewController.isHidden = false
  1356. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
  1357. self.rightSideViewController.subViewType = .EditPDFAddImage
  1358. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1359. }
  1360. self.openRightPane()
  1361. } else {
  1362. // self.rightSideViewController.view.isHidden = true
  1363. self.rightSideViewController.isHidden = true
  1364. self.closeRightPane()
  1365. }
  1366. } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1367. // self.rightSideViewController.view.isHidden = false
  1368. self.rightSideViewController.isHidden = false
  1369. if self.listView.editingSelectionString().count != 0 {
  1370. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1371. } else {
  1372. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1373. }
  1374. self.openRightPane()
  1375. } else {
  1376. var textsAreas : [CPDFEditTextArea] = []
  1377. var imagesAreas : [CPDFEditImageArea] = []
  1378. if self.listView.editingAreas()?.count ?? 0 < 1 {
  1379. return
  1380. }
  1381. for i in 0 ... areas!.count-1 {
  1382. if areas![i] is CPDFEditTextArea {
  1383. textsAreas.append(areas![i] as! CPDFEditTextArea)
  1384. }
  1385. if areas![i] is CPDFEditImageArea {
  1386. imagesAreas.append(areas![i] as! CPDFEditImageArea)
  1387. }
  1388. }
  1389. if textsAreas.count > 0 && textsAreas.count == areas!.count {
  1390. // self.rightSideViewController.view.isHidden = false
  1391. self.rightSideViewController.isHidden = false
  1392. self.rightSideViewController.subViewType = .EditPDFAddText
  1393. self.rightSideViewController.eidtPDFTextProperty?.reloadData()
  1394. self.openRightPane()
  1395. } else if imagesAreas.count > 0 {
  1396. // self.rightSideViewController.view.isHidden = false
  1397. self.rightSideViewController.isHidden = false
  1398. self.rightSideViewController.subViewType = .EditPDFAddImage
  1399. self.rightSideViewController.eidtPDFImageProperty?.reloadData()
  1400. self.openRightPane()
  1401. }
  1402. }
  1403. if self.listView.isEdited() {
  1404. self.recordIsPDFDocumentEdited(type: .editText)
  1405. if self.listView.annotationType != .addText {
  1406. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1407. }
  1408. }
  1409. }
  1410. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1411. self.recordSaveWatermarkFlag()
  1412. if editArea != nil && (editArea is CPDFEditImageArea){
  1413. self.listView.cropAreas = editArea as? CPDFEditImageArea
  1414. }
  1415. }
  1416. //编辑PDF 创建图片区域回调
  1417. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1418. self.recordSaveWatermarkFlag(type: .editImage)
  1419. if self.listView.isEditImage {
  1420. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1421. } else {
  1422. let panel = NSOpenPanel()
  1423. panel.allowsMultipleSelection = false
  1424. panel.allowedFileTypes = ["png","jpg"]
  1425. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1426. if response == .OK {
  1427. var filePath = panel.url?.path
  1428. var image = NSImage.init(contentsOf: panel.url!)
  1429. //图片自适应范围
  1430. if image != nil {
  1431. var imageRect = rect
  1432. let imageSize = image!.size
  1433. var previewSize = rect.size
  1434. var isChangeSize = false
  1435. if previewSize.width == 0 && previewSize.height == 0 {
  1436. previewSize = CGSize(width: 500, height: 500)
  1437. isChangeSize = true
  1438. }
  1439. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1440. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1441. if isChangeSize {
  1442. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1443. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1444. } else {
  1445. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1446. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1447. }
  1448. imageRect.size = newSize
  1449. let limitWidth = 1920.0
  1450. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1451. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1452. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1453. maxSizeInBytes: 1024 * 1024 * 5,
  1454. targetCompression: 1.0)
  1455. }
  1456. //自适应page
  1457. let pageRect = self.listView.currentPage().bounds
  1458. if imageRect.width > pageRect.width ||
  1459. imageRect.height > pageRect.height {
  1460. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1461. imageRect = CGRect(x: imageRect.origin.x,
  1462. y: imageRect.origin.y,
  1463. width: imageRect.width * pageScale,
  1464. height: imageRect.height * pageScale)
  1465. }
  1466. if imageRect.origin.x < 0 {
  1467. imageRect.origin.x = 5
  1468. }
  1469. if imageRect.origin.y < 0 {
  1470. imageRect.origin.y = 5
  1471. }
  1472. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1473. imageRect.origin.y + imageRect.height > pageRect.height {
  1474. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1475. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1476. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1477. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1478. }
  1479. DispatchQueue.main.async {
  1480. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1481. self.isPDFTextImageEdited = true
  1482. self.recordIsPDFDocumentEdited(type: .editImage)
  1483. // self.asyncSaveDocument { params in
  1484. //
  1485. // }
  1486. }
  1487. }
  1488. }
  1489. }
  1490. }
  1491. }
  1492. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1493. // print(rect)
  1494. var newrect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
  1495. if __CGSizeEqualToSize(rect.size, CGSize.zero) {
  1496. newrect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1497. } else {
  1498. newrect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1499. }
  1500. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1501. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1502. let fontSize = model.fontSize
  1503. let fontColor = model.color
  1504. let fontAlign = model.alignment
  1505. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1506. NSColorPanel.shared.color = fontColor
  1507. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1508. let style = NSMutableParagraphStyle()
  1509. style.alignment = fontAlign
  1510. let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
  1511. self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: pdfView.currentPage())
  1512. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1513. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1514. }
  1515. // self.asyncSaveDocument { params in
  1516. //
  1517. // }
  1518. self.recordSaveWatermarkFlag(type: .editText)
  1519. }
  1520. // func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  1521. // debugPrint("pdfViewEditingDoubleClick")
  1522. // }
  1523. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  1524. debugPrint("pdfViewEditingOperationDidChanged")
  1525. if self.listView.isEdited() {
  1526. self.recordSaveWatermarkFlag()
  1527. }
  1528. }
  1529. // func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  1530. // debugPrint("pdfListViewEditAnnotation")
  1531. // }
  1532. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  1533. let command = theEvent.modifierFlags.contains(.command)
  1534. let control = theEvent.modifierFlags.contains(.control)
  1535. KMPrint(theEvent.keyCode)
  1536. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  1537. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  1538. return false
  1539. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  1540. return false
  1541. } else if (theEvent.keyCode == 123) { // 向左
  1542. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1543. return false
  1544. } else {
  1545. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  1546. self.listView.goToPreviousPage(nil)
  1547. return false
  1548. }
  1549. }
  1550. } else if (theEvent.keyCode == 126) { // 向上
  1551. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1552. return false
  1553. } else {
  1554. if (self.listView.isContinousScroll()) {
  1555. return true
  1556. }
  1557. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  1558. self.listView.goToPreviousPage(nil)
  1559. return false
  1560. }
  1561. }
  1562. } else if (theEvent.keyCode == 124) { // 向右
  1563. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1564. return false
  1565. } else {
  1566. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  1567. self.listView.goToNextPage(nil)
  1568. return false
  1569. }
  1570. }
  1571. } else if (theEvent.keyCode == 125) { // 向下
  1572. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1573. return false
  1574. } else {
  1575. if (self.listView.isContinousScroll()) {
  1576. return true
  1577. }
  1578. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  1579. self.listView.goToNextPage(nil)
  1580. return false
  1581. }
  1582. }
  1583. } else if (theEvent.keyCode == 36) {
  1584. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1585. if self.listView.isEditImage {
  1586. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1587. }
  1588. }
  1589. }
  1590. if theEvent.keyCode == 53 {
  1591. if self.isReadMode {
  1592. self.closeReadModel()
  1593. }
  1594. self.leftSideViewCancelSelect()
  1595. if (self.toolbarController.toolbarType.isToolMode()) {
  1596. self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
  1597. }
  1598. }
  1599. return true
  1600. }
  1601. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  1602. guard let action = menuItem.action else {
  1603. isTakesEffect.pointee = false
  1604. return false
  1605. }
  1606. if (KMSystemMenu.isEditSelector(sel: action)) {
  1607. if (KMSystemMenu.Edit.deleteSelector == action) {
  1608. isTakesEffect.pointee = true
  1609. return self.listView.activeAnnotations.count > 0
  1610. } else if (KMSystemMenu.Edit.copySelector == action) {
  1611. isTakesEffect.pointee = true
  1612. return true//self.listView.canCopy()
  1613. } else if (KMSystemMenu.Edit.cutSelector == action) {
  1614. isTakesEffect.pointee = true
  1615. return self.listView.canCopy()
  1616. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  1617. isTakesEffect.pointee = true
  1618. return self.listView.canPaste()
  1619. }
  1620. }
  1621. isTakesEffect.pointee = false
  1622. return false
  1623. }
  1624. //MARK: -CPDFListViewDelegate
  1625. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  1626. }
  1627. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  1628. self.view.window?.makeFirstResponder(self.listView)
  1629. if isRightMenu {
  1630. } else if annotations.count > 0 {
  1631. if annotations.count > 1 {
  1632. let fristAnnotation = annotations.first
  1633. var isSameAnnotation = true
  1634. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1635. for annotation in annotations {
  1636. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  1637. if (className == "CPDFSquareAnnotation") ||
  1638. (className == "CPDFCircleAnnotation") ||
  1639. (className == "CPDFLineAnnotation") {
  1640. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  1641. (cunrrentClassName != "CPDFCircleAnnotation") &&
  1642. (cunrrentClassName != "CPDFLineAnnotation") {
  1643. isSameAnnotation = false
  1644. }
  1645. } else {
  1646. if className != cunrrentClassName {
  1647. isSameAnnotation = false
  1648. }
  1649. }
  1650. }
  1651. if isSameAnnotation == false {
  1652. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1653. // self.closeRightPane()
  1654. } else {
  1655. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1656. self.openRightPane()
  1657. }
  1658. } else {
  1659. let fristAnnotation = annotations.first
  1660. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1661. if self.isReadMode {
  1662. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1663. self.closeRightPane()
  1664. } else {
  1665. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1666. if className != "CPDFStampAnnotation" &&
  1667. className != "CPDFSignatureAnnotation" &&
  1668. className != "CPDFListStampAnnotation" {
  1669. self.openRightPane()
  1670. }
  1671. }
  1672. }
  1673. } else if (annotations.count == 0){
  1674. if pdfListView.annotationType == .unkown {
  1675. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1676. self.closeRightPane()
  1677. } else {
  1678. if self.isReadMode {
  1679. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1680. self.closeRightPane()
  1681. } else {
  1682. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1683. self.openRightPane()
  1684. }
  1685. }
  1686. }
  1687. }
  1688. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  1689. if(annotationType == .unkown) {
  1690. // self.rightSideViewController.view.isHidden = true
  1691. self.rightSideViewController.isHidden = true
  1692. self.closeRightPane()
  1693. }
  1694. }
  1695. ///开始定位链接注释
  1696. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1697. if self.locationPageView.superview == nil {
  1698. self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
  1699. pdfListView.addSubview(self.locationPageView)
  1700. }
  1701. }
  1702. ///刷新链接注释
  1703. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1704. if self.locationPageView.superview != nil {
  1705. self.locationPageView.removeFromSuperview()
  1706. }
  1707. if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
  1708. self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1709. }
  1710. }
  1711. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  1712. if (listView.toolMode != CToolMode.editPDFToolMode) {
  1713. return menuItems
  1714. }
  1715. var tMenuItems = menuItems;
  1716. if(listView.isSelectEditCharRange() ||
  1717. listView.isSelecteditArea(with: point)) {
  1718. tMenuItems?.append(NSMenuItem.separator())
  1719. // tMenuItems?.append(self.fontColorMenuItem())
  1720. // tMenuItems?.append(self.fontSizeMenuItem())
  1721. }
  1722. let areas = self.listView.editingAreas() ?? []
  1723. if areas.count == 1 {
  1724. let fristAreas = areas.first
  1725. if fristAreas is CPDFEditImageArea {
  1726. self.listView.selectImageAreas = fristAreas as! CPDFEditImageArea
  1727. if self.listView.isEditImage {
  1728. tMenuItems?.removeAll()
  1729. tMenuItems?.append(self.corpImageMenuItem())
  1730. tMenuItems?.append(self.cancelCorpImageMenuItem())
  1731. tMenuItems?.append(self.restoreCorpImageMenuItem())
  1732. } else {
  1733. tMenuItems?.append(NSMenuItem.separator())
  1734. tMenuItems?.append(self.cutImageArea())
  1735. tMenuItems?.append(self.replaceImageArea())
  1736. tMenuItems?.append(self.exportImageArea())
  1737. }
  1738. } else {
  1739. tMenuItems?.swapAt(0, 1)
  1740. }
  1741. } else if areas.count == 0 {
  1742. tMenuItems?.append(NSMenuItem.separator())
  1743. tMenuItems?.append(self.addText())
  1744. tMenuItems?.append(self.addImage())
  1745. }
  1746. return tMenuItems
  1747. }
  1748. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!) {
  1749. self.mouseRightMenuEvent = theEvent
  1750. let currentMenu : NSMenu = menu.pointee!
  1751. if (listView.toolMode == .redactToolMode) {
  1752. if (listView.activeAnnotation == nil) {
  1753. } else {
  1754. let currentPoint: NSPoint = pdfListView.convert(theEvent.locationInWindow, from: pdfListView.superview)
  1755. let currentPage = pdfListView.page(for: currentPoint, nearest: true)
  1756. // let currentPage = pdfListView.activeAnnotation.page
  1757. let pagePoint = pdfListView.convert(currentPoint, to: currentPage)
  1758. currentMenu.removeAllItems()
  1759. if (pdfListView.activeAnnotation.bounds.contains(pagePoint)) {
  1760. currentMenu.insertItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(redact_menuItemClick_delete), target: self, at: currentMenu.items.count)
  1761. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1762. currentMenu.insertItem(withTitle: NSLocalizedString("Properties...", comment: ""), action: #selector(redact_menuItemClick_setProperty), target: self, at: currentMenu.items.count)
  1763. currentMenu.insertItem(withTitle: NSLocalizedString("Use Current Properties as New Default", comment: ""), action: #selector(redact_menuItemClick_setCurrentPropertyToDefaultValue), target: self, at: currentMenu.items.count)
  1764. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1765. currentMenu.insertItem(withTitle: NSLocalizedString("Repeat mark across pages", comment: ""), action: #selector(redact_menuItemClick_MultiPageFlag), target: self, at: currentMenu.items.count)
  1766. currentMenu.insertItem(withTitle: NSLocalizedString("Apply Redactions", comment: ""), action: #selector(redact_menuItemClick_apply), target: self, at: currentMenu.items.count)
  1767. currentMenu.insertItem(withTitle: NSLocalizedString("Erase Redactions", comment: ""), action: #selector(redact_menuItemClick_clear), target: self, at: currentMenu.items.count)
  1768. } else {
  1769. currentMenu.insertItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(redact_menuItemClick_paste), target: self, at: currentMenu.items.count)
  1770. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1771. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1772. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1773. }
  1774. }
  1775. return
  1776. }
  1777. if(listView.toolMode == .selectToolMode) {
  1778. if currentMenu.items.count > 0 {
  1779. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1780. export.submenu = self.exportMenu()
  1781. currentMenu.insertItem(export, at: currentMenu.items.count)
  1782. let corp = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action:#selector(cropCurrentPage), target: self)
  1783. // corp?.submenu = self.cropMenu()
  1784. currentMenu.insertItem(corp, at: currentMenu.items.count)
  1785. // MARK: 暂时拿掉 2023.04.26
  1786. // currentMenu.insertItem(self.zoomSelectionMenuItem(), at: currentMenu.items.count)
  1787. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1788. }
  1789. } else {
  1790. if listView.currentSelection != nil {
  1791. if (listView.currentSelection.string() != nil || listView.currentSelection.selectionType() == .image) {
  1792. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1793. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1794. } else {
  1795. var isMarkup = false
  1796. for item in self.listView.activeAnnotations {
  1797. if (item is CPDFMarkupAnnotation) {
  1798. isMarkup = true
  1799. break
  1800. }
  1801. }
  1802. if(!isMarkup) {
  1803. self.addAnnotationForStyleMenu(menu: currentMenu)
  1804. }
  1805. }
  1806. }
  1807. } else if (listView.activeAnnotation == nil) {
  1808. if(currentMenu.items.count > 2) {
  1809. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  1810. }
  1811. if(currentMenu.items.count > 3) {
  1812. currentMenu.insertItem(self.addBookmarkMenu(), at: 4)
  1813. }
  1814. if(currentMenu.items.count > 4) {
  1815. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  1816. }
  1817. if(currentMenu.items.count > 5) {
  1818. currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
  1819. }
  1820. if (currentMenu.items.count > 6) {
  1821. currentMenu.insertItem(self.addReadModelStype(), at: 7)
  1822. }
  1823. if (currentMenu.items.count > 7 && self.isReadMode) {
  1824. currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
  1825. }
  1826. // if(currentMenu.items.count > 6) {
  1827. // let menuItem = NSMenuItem(title: NSLocalizedString("Automatic rolling", comment: ""), action:nil, target: self)!
  1828. // currentMenu.insertItem(menuItem, at: 6)
  1829. // }
  1830. // if(currentMenu.items.count > 7) {
  1831. // let menuItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action:nil, target: self)!
  1832. // currentMenu.insertItem(menuItem, at: 7)
  1833. // }
  1834. // if(currentMenu.items.count > 8) {
  1835. // let menuItem = NSMenuItem(title: NSLocalizedString("menuItem", comment: ""), action:nil, target: self)!
  1836. // currentMenu.insertItem(menuItem, at: 8)
  1837. // }
  1838. if !self.isReadMode {
  1839. if (currentMenu.items.count > 10) {
  1840. currentMenu.insertItem(self.addHighlightLinksStype(), at: 11)
  1841. }
  1842. }
  1843. if self.isReadMode {
  1844. } else {
  1845. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1846. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1847. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1848. }
  1849. } else if listView.activeAnnotation != nil {
  1850. var type : CAnnotationType = .unkown
  1851. if listView.activeAnnotation is CPDFMarkupAnnotation {
  1852. if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1853. type = .highlight
  1854. } else if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .underline {
  1855. type = .underline
  1856. } else {
  1857. type = .strikeOut
  1858. }
  1859. } else if listView.activeAnnotation is CPDFInkAnnotation {
  1860. type = .ink
  1861. } else if listView.activeAnnotation is CPDFFreeTextAnnotation {
  1862. type = .freeText
  1863. } else if listView.activeAnnotation is CPDFTextAnnotation {
  1864. type = .anchored
  1865. } else if listView.activeAnnotation is CPDFCircleAnnotation {
  1866. type = .circle
  1867. } else if listView.activeAnnotation is CPDFSquareAnnotation {
  1868. type = .square
  1869. }
  1870. if ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1871. if listView.activeAnnotations.count == 1 {
  1872. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1873. }
  1874. }
  1875. if type != .unkown && listView.activeAnnotations.count == 1{
  1876. currentMenu.insertItem(self.setDefaultAnnotationPorpert(type: type), at: currentMenu.items.count)
  1877. }
  1878. // closeRightPane()
  1879. }
  1880. }
  1881. for item in currentMenu.items {
  1882. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  1883. // 显示与隐藏注释 item action 截取
  1884. item.action = #selector(menuItemClick_HidenorShowNote)
  1885. item.target = self
  1886. break
  1887. }
  1888. }
  1889. }
  1890. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1891. var addRedact = false
  1892. var saveWatermark = false
  1893. var saveWatermarkType: KMSubscribeWaterMarkType = .none
  1894. for anno in annotations {
  1895. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  1896. addRedact = true
  1897. // break
  1898. } else if (anno.isKind(of: CPDFLinkAnnotation.self)) { // link 注释
  1899. saveWatermark = true
  1900. saveWatermarkType = .link
  1901. } else if (anno.isKind(of: CPDFListStampAnnotation.self)) { // 图章注释
  1902. saveWatermark = true
  1903. saveWatermarkType = .stamp
  1904. } else if (anno.isKind(of: CPDFListSignatureAnnotation.self)) { // 签名注释
  1905. saveWatermark = true
  1906. saveWatermarkType = .sign
  1907. }
  1908. }
  1909. if (saveWatermark) {
  1910. self.recordSaveWatermarkFlag(type: saveWatermarkType)
  1911. }
  1912. self.hasAddRedact = addRedact
  1913. if self.isReadMode || self.listView.toolMode == .moveToolMode {
  1914. self.listView.toolMode = .textToolMode
  1915. self.listView.annotationType = .unkown
  1916. self.toolbarController.toolbarType = .Annatiton
  1917. }
  1918. if (self.rightMouseEventing) {
  1919. self.rightMouseEventing = false
  1920. if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
  1921. self.listView.toolMode = .textToolMode
  1922. self.listView.annotationType = .unkown
  1923. }
  1924. }
  1925. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  1926. }
  1927. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  1928. if (!self.listView.isEqual(to: pdfListView)) {
  1929. return
  1930. }
  1931. if (self.listView.toolMode != .selectToolMode) {
  1932. return
  1933. }
  1934. if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
  1935. return
  1936. }
  1937. let tipView = self.topTipBox.contentView?.subviews.first
  1938. if (tipView?.isKind(of: KMCropTipView.self) == false) {
  1939. return
  1940. }
  1941. (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
  1942. }
  1943. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  1944. if(speedy == .right) {
  1945. self.toggleRightPane()
  1946. } else if (speedy == .left) {
  1947. self.menuItemAction_hiddenLeftSide(speedy)
  1948. }
  1949. }
  1950. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  1951. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  1952. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1953. return KMAnnotationPropertiesColorManager.manager.markHighlightColors
  1954. } else {
  1955. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1956. }
  1957. } else {
  1958. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1959. }
  1960. }
  1961. func pdfListViewHaveDocumentAttribute() -> Bool {
  1962. if(!self.listView.document.allowsCopying) {
  1963. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  1964. if (result == .cancel) {
  1965. return
  1966. }
  1967. self?.isSaveKeyChain = false
  1968. self?.listView.document.unlock(withPassword: password)
  1969. self?.hiddenSecureLimitTip()
  1970. }
  1971. return false
  1972. }
  1973. return true
  1974. }
  1975. func addTopTip(_ view: NSView?) {
  1976. if (Thread.isMainThread) {
  1977. if (view == nil) {
  1978. let contentView: NSView = self.topTipBox.contentView!
  1979. for subview in contentView.subviews {
  1980. subview.removeFromSuperview()
  1981. }
  1982. self.topTipBox.isHidden = true
  1983. return
  1984. }
  1985. let contentView: NSView = self.topTipBox.contentView!
  1986. for subview in contentView.subviews {
  1987. subview.removeFromSuperview()
  1988. }
  1989. self.topTipBox.isHidden = false
  1990. self.topTipBox.contentView?.addSubview(view!)
  1991. } else {
  1992. DispatchQueue.main.async {
  1993. if (view == nil) {
  1994. let contentView: NSView = self.topTipBox.contentView!
  1995. for subview in contentView.subviews {
  1996. subview.removeFromSuperview()
  1997. }
  1998. self.topTipBox.isHidden = true
  1999. return
  2000. }
  2001. let contentView: NSView = self.topTipBox.contentView!
  2002. for subview in contentView.subviews {
  2003. subview.removeFromSuperview()
  2004. }
  2005. self.topTipBox.isHidden = false
  2006. self.topTipBox.contentView?.addSubview(view!)
  2007. }
  2008. }
  2009. }
  2010. }
  2011. extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
  2012. func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
  2013. self.isPDFTextImageEdited = true
  2014. }
  2015. }