KMMainViewController.swift 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326
  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. if self?.listView.annotationType == .addImage {
  1067. self?.listView.change([.text, .image])
  1068. }
  1069. self?.listView.annotationType = .editTextImage
  1070. self?.closeRightPane()
  1071. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1072. if self?.listView.annotationType == .addImage ||
  1073. self?.listView.annotationType == .addText {
  1074. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1075. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1076. textItem?.isSelected = false
  1077. imageItem?.isSelected = false
  1078. }
  1079. self?.rightSideViewController.isHidden = true
  1080. self?.listView.setShouAddEdit([])
  1081. self?.listView.change([.text, .image])
  1082. self?.listView.annotationType = .editTextImage
  1083. self?.closeRightPane()
  1084. }
  1085. } else {
  1086. if self?.listView.annotationType == .addImage ||
  1087. self?.listView.annotationType == .addText {
  1088. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1089. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1090. textItem?.isSelected = false
  1091. imageItem?.isSelected = false
  1092. }
  1093. }
  1094. }
  1095. }
  1096. }
  1097. return event
  1098. }
  1099. }
  1100. func removeKeyEventMonitor() {
  1101. if (self.keyEventMonitor != nil) {
  1102. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1103. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1104. self.keyEventMonitor = nil
  1105. }
  1106. }
  1107. private func removeEventMonitor() {
  1108. if (self.eventMonitor != nil) {
  1109. KMPrint("已移除事件监听")
  1110. NSEvent.removeMonitor(self.eventMonitor as Any)
  1111. self.eventMonitor = nil
  1112. }
  1113. }
  1114. // MARK: -
  1115. // MARK: Tools
  1116. func pdfViewCanHorizontalScroll() -> Bool {
  1117. let scroll = self.listView.scroll()
  1118. if (scroll == nil) {
  1119. return false
  1120. }
  1121. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1122. }
  1123. func pdfViewCanVerticalScroll() -> Bool {
  1124. let scroll = self.listView.scroll()
  1125. if (scroll == nil) {
  1126. return false
  1127. }
  1128. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1129. }
  1130. // MARK: - Public Methods
  1131. // 清理数据 [eg. 通知]
  1132. public func clearData() {
  1133. self.removeNotifications()
  1134. if (self.listView.spellingTag() > 0) {
  1135. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1136. }
  1137. }
  1138. public func clearSecureOptions() {
  1139. self._secureOptions = nil
  1140. }
  1141. public func recordRemoveSecureFlag() {
  1142. self._removeSecureFlag = true
  1143. self.clearSecureOptions()
  1144. self.recordIsPDFDocumentEdited(type: .removePassword)
  1145. self._needSave = true
  1146. }
  1147. public func clearRemoveSecureFlag() {
  1148. self._removeSecureFlag = false
  1149. }
  1150. public func recordSaveWatermarkFlag(type: KMSubscribeWaterMarkType = .none) {
  1151. km_synchronized(self) {
  1152. self._saveWatermarkFlag = true
  1153. }
  1154. if let _document = self.myDocument as? KMMainDocument {
  1155. _document.recordTrackEvent(type: type)
  1156. }
  1157. }
  1158. public func clearSaveWatermarkFlag() {
  1159. km_synchronized(self) {
  1160. self._saveWatermarkFlag = false
  1161. }
  1162. }
  1163. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1164. km_synchronized(self) {
  1165. self._isPDFDocumentEdited = true
  1166. if let _document = self.myDocument {
  1167. KMTools.setDocumentEditedState(document: _document)
  1168. }
  1169. }
  1170. }
  1171. public func clearIsPDFDocumentEdited() {
  1172. km_synchronized(self) {
  1173. self._isPDFDocumentEdited = false
  1174. }
  1175. }
  1176. // MARK: - Noti Actions
  1177. internal func documentDidUnlockNotification(_ sender: Notification) {
  1178. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1179. if (self.myDocument == nil) {
  1180. return
  1181. }
  1182. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1183. self.hiddenSecureLimitTip()
  1184. }
  1185. if ((self.myDocument as! KMMainDocument).isUnlockFromKeychain || self.isSaveKeyChain == false) {
  1186. return
  1187. }
  1188. let type = KMPreferenceManager.shared.savePasswordType
  1189. if (type == .never) {
  1190. return
  1191. }
  1192. if (type == .always) {
  1193. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1194. return
  1195. }
  1196. // 保存到钥匙串
  1197. let alert = NSAlert()
  1198. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1199. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1200. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1201. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1202. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1203. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1204. return
  1205. }
  1206. }
  1207. }
  1208. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1209. self.savePageNumberIfNeed()
  1210. self.saveDocument()
  1211. }
  1212. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1213. if self.isReadMode {
  1214. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1215. }
  1216. //刷新向前向后按钮
  1217. self.updateBackAndForwardButtonState()
  1218. }
  1219. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1220. if self.isReadMode {
  1221. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1222. }
  1223. //刷新向前向后按钮
  1224. self.updateBackAndForwardButtonState()
  1225. }
  1226. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1227. var editSelectd = false
  1228. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1229. editSelectd = true
  1230. }
  1231. if self.listView.toolMode == .editPDFToolMode {
  1232. if editSelectd {
  1233. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1234. }
  1235. }
  1236. }
  1237. //MARK: - PDFListViewDelegate
  1238. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  1239. // KMPrint("pdfViewDocumentDidLoaded")
  1240. self.removeBackgroundMaskView()
  1241. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1242. self.showSecureLimitTip()
  1243. }
  1244. if (self._documentFirstLoad) {
  1245. self.checkShouldAutoOpenLeftVC()
  1246. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1247. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1248. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1249. if (pageScale != nil) {
  1250. self.listView.scaleFactor = CGFloat(pageScale!)
  1251. }
  1252. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1253. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1254. } else {
  1255. self._goToFirstPageForFristAppear()
  1256. }
  1257. } else {
  1258. self._goToFirstPageForFristAppear()
  1259. }
  1260. self._documentFirstLoad = false
  1261. }
  1262. let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
  1263. self.preferenceDidChangeNotification(notification:notification)
  1264. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: panelWidth + functionWidth)
  1265. let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: defaultRightWidth)
  1266. applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
  1267. self.updatePageIndicatoreType()
  1268. }
  1269. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  1270. self.updatePageIndicatoreType()
  1271. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
  1272. // KMPrint("KMPDFViewCurrentPageDidChanged")
  1273. }
  1274. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  1275. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
  1276. self.updateZoomInOutButtonState()
  1277. // KMPrint("pdfViewScaleDidChanged")
  1278. }
  1279. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  1280. if let urlString = url, urlString == kKMPurchaseProductURLString {
  1281. //跳转订阅比较表
  1282. let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
  1283. return
  1284. }
  1285. KMTools.openURL(urlString: url)
  1286. }
  1287. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  1288. KMPrint("pdfViewPerformURL")
  1289. }
  1290. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  1291. KMPrint("pdfViewPerformPrint")
  1292. }
  1293. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  1294. KMPrint("pdfViewPerformGo")
  1295. }
  1296. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  1297. KMPrint("pdfViewOpenPDF")
  1298. }
  1299. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  1300. KMPrint("pdfViewPerformReset")
  1301. }
  1302. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  1303. KMPrint("pdfViewEditingBlockDidChanged")
  1304. }
  1305. func pdfViewAsBookBookmark() -> NSImage! {
  1306. return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
  1307. }
  1308. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  1309. self.recordSaveWatermarkFlag()
  1310. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
  1311. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1312. self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1313. }
  1314. }
  1315. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  1316. let areas = self.listView.editingAreas()
  1317. if areas == nil || areas?.count ?? 0 == 0 {
  1318. if self.listView.toolMode == .editPDFToolMode {
  1319. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1320. if self.listView.isEditImage {
  1321. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1322. } else {
  1323. // if self.listView.annotationType == .addImage {
  1324. // self.closeRightPane()
  1325. // }
  1326. if self.listView.annotationType == .addImage {
  1327. if self.rightSideViewController.eidtPDFImageProperty != nil {
  1328. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1329. }
  1330. }
  1331. // self.openRightPane()
  1332. }
  1333. } else {
  1334. self.closeRightPane()
  1335. }
  1336. } else {
  1337. self.rightSideViewController.isHidden = true
  1338. self.closeRightPane()
  1339. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1340. self.rightSideViewController.eidtPDFTextProperty.initData()
  1341. }
  1342. }
  1343. if self.listView.isEdited() {
  1344. self.recordIsPDFDocumentEdited(type: .editText)
  1345. }
  1346. if self.listView.annotationType != .addText {
  1347. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1348. }
  1349. return
  1350. }
  1351. self.isPDFTextImageEdited = true
  1352. if (self.listView.annotationType == .addImage) && areas!.count > 0 {
  1353. var isImageArea = false
  1354. for i in 0 ... areas!.count-1 {
  1355. if areas![i] is CPDFEditImageArea {
  1356. isImageArea = true
  1357. }
  1358. }
  1359. if isImageArea {
  1360. // self.rightSideViewController.view.isHidden = false
  1361. self.rightSideViewController.isHidden = false
  1362. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
  1363. self.rightSideViewController.subViewType = .EditPDFAddImage
  1364. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1365. }
  1366. self.openRightPane()
  1367. } else {
  1368. // self.rightSideViewController.view.isHidden = true
  1369. self.rightSideViewController.isHidden = true
  1370. self.closeRightPane()
  1371. }
  1372. } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1373. // self.rightSideViewController.view.isHidden = false
  1374. self.rightSideViewController.isHidden = false
  1375. if self.listView.editingSelectionString().count != 0 {
  1376. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1377. } else {
  1378. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1379. }
  1380. self.openRightPane()
  1381. } else {
  1382. var textsAreas : [CPDFEditTextArea] = []
  1383. var imagesAreas : [CPDFEditImageArea] = []
  1384. if self.listView.editingAreas()?.count ?? 0 < 1 {
  1385. return
  1386. }
  1387. for i in 0 ... areas!.count-1 {
  1388. if areas![i] is CPDFEditTextArea {
  1389. textsAreas.append(areas![i] as! CPDFEditTextArea)
  1390. }
  1391. if areas![i] is CPDFEditImageArea {
  1392. imagesAreas.append(areas![i] as! CPDFEditImageArea)
  1393. }
  1394. }
  1395. if textsAreas.count > 0 && textsAreas.count == areas!.count {
  1396. // self.rightSideViewController.view.isHidden = false
  1397. self.rightSideViewController.isHidden = false
  1398. self.rightSideViewController.subViewType = .EditPDFAddText
  1399. self.rightSideViewController.eidtPDFTextProperty?.reloadData()
  1400. self.openRightPane()
  1401. } else if imagesAreas.count > 0 {
  1402. // self.rightSideViewController.view.isHidden = false
  1403. self.rightSideViewController.isHidden = false
  1404. self.rightSideViewController.subViewType = .EditPDFAddImage
  1405. self.rightSideViewController.eidtPDFImageProperty?.reloadData()
  1406. self.openRightPane()
  1407. }
  1408. }
  1409. if self.listView.isEdited() {
  1410. self.recordIsPDFDocumentEdited(type: .editText)
  1411. if self.listView.annotationType != .addText {
  1412. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1413. }
  1414. }
  1415. }
  1416. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1417. self.recordSaveWatermarkFlag()
  1418. if editArea != nil && (editArea is CPDFEditImageArea){
  1419. self.listView.cropAreas = editArea as? CPDFEditImageArea
  1420. }
  1421. }
  1422. //编辑PDF 创建图片区域回调
  1423. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1424. self.recordSaveWatermarkFlag(type: .editImage)
  1425. if self.listView.isEditImage {
  1426. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1427. } else {
  1428. let panel = NSOpenPanel()
  1429. panel.allowsMultipleSelection = false
  1430. panel.allowedFileTypes = ["png","jpg"]
  1431. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1432. if response == .OK {
  1433. var filePath = panel.url?.path
  1434. var image = NSImage.init(contentsOf: panel.url!)
  1435. //图片自适应范围
  1436. if image != nil {
  1437. var imageRect = rect
  1438. let imageSize = image!.size
  1439. var previewSize = rect.size
  1440. var isChangeSize = false
  1441. if previewSize.width == 0 && previewSize.height == 0 {
  1442. previewSize = CGSize(width: 500, height: 500)
  1443. isChangeSize = true
  1444. }
  1445. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1446. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1447. if isChangeSize {
  1448. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1449. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1450. } else {
  1451. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1452. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1453. }
  1454. imageRect.size = newSize
  1455. let limitWidth = 1920.0
  1456. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1457. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1458. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1459. maxSizeInBytes: 1024 * 1024 * 5,
  1460. targetCompression: 1.0)
  1461. }
  1462. //自适应page
  1463. let pageRect = self.listView.currentPage().bounds
  1464. if imageRect.width > pageRect.width ||
  1465. imageRect.height > pageRect.height {
  1466. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1467. imageRect = CGRect(x: imageRect.origin.x,
  1468. y: imageRect.origin.y,
  1469. width: imageRect.width * pageScale,
  1470. height: imageRect.height * pageScale)
  1471. }
  1472. if imageRect.origin.x < 0 {
  1473. imageRect.origin.x = 5
  1474. }
  1475. if imageRect.origin.y < 0 {
  1476. imageRect.origin.y = 5
  1477. }
  1478. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1479. imageRect.origin.y + imageRect.height > pageRect.height {
  1480. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1481. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1482. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1483. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1484. }
  1485. DispatchQueue.main.async {
  1486. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1487. self.isPDFTextImageEdited = true
  1488. self.recordIsPDFDocumentEdited(type: .editImage)
  1489. // self.asyncSaveDocument { params in
  1490. //
  1491. // }
  1492. }
  1493. }
  1494. }
  1495. }
  1496. }
  1497. }
  1498. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1499. // print(rect)
  1500. var newrect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
  1501. if __CGSizeEqualToSize(rect.size, CGSize.zero) {
  1502. newrect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1503. } else {
  1504. newrect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1505. }
  1506. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1507. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1508. let fontSize = model.fontSize
  1509. let fontColor = model.color
  1510. let fontAlign = model.alignment
  1511. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1512. NSColorPanel.shared.color = fontColor
  1513. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1514. let style = NSMutableParagraphStyle()
  1515. style.alignment = fontAlign
  1516. let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
  1517. self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: pdfView.currentPage())
  1518. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1519. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1520. }
  1521. // self.asyncSaveDocument { params in
  1522. //
  1523. // }
  1524. self.recordSaveWatermarkFlag(type: .editText)
  1525. }
  1526. // func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  1527. // debugPrint("pdfViewEditingDoubleClick")
  1528. // }
  1529. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  1530. debugPrint("pdfViewEditingOperationDidChanged")
  1531. if self.listView.isEdited() {
  1532. self.recordSaveWatermarkFlag()
  1533. }
  1534. }
  1535. // func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  1536. // debugPrint("pdfListViewEditAnnotation")
  1537. // }
  1538. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  1539. let command = theEvent.modifierFlags.contains(.command)
  1540. let control = theEvent.modifierFlags.contains(.control)
  1541. KMPrint(theEvent.keyCode)
  1542. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  1543. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  1544. return false
  1545. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  1546. return false
  1547. } else if (theEvent.keyCode == 123) { // 向左
  1548. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1549. return false
  1550. } else {
  1551. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  1552. self.listView.goToPreviousPage(nil)
  1553. return false
  1554. }
  1555. }
  1556. } else if (theEvent.keyCode == 126) { // 向上
  1557. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1558. return false
  1559. } else {
  1560. if (self.listView.isContinousScroll()) {
  1561. return true
  1562. }
  1563. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  1564. self.listView.goToPreviousPage(nil)
  1565. return false
  1566. }
  1567. }
  1568. } else if (theEvent.keyCode == 124) { // 向右
  1569. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1570. return false
  1571. } else {
  1572. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  1573. self.listView.goToNextPage(nil)
  1574. return false
  1575. }
  1576. }
  1577. } else if (theEvent.keyCode == 125) { // 向下
  1578. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1579. return false
  1580. } else {
  1581. if (self.listView.isContinousScroll()) {
  1582. return true
  1583. }
  1584. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  1585. self.listView.goToNextPage(nil)
  1586. return false
  1587. }
  1588. }
  1589. } else if (theEvent.keyCode == 36) {
  1590. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1591. if self.listView.isEditImage {
  1592. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1593. }
  1594. }
  1595. }
  1596. if theEvent.keyCode == 53 {
  1597. if self.isReadMode {
  1598. self.closeReadModel()
  1599. }
  1600. self.leftSideViewCancelSelect()
  1601. if (self.toolbarController.toolbarType.isToolMode()) {
  1602. self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
  1603. }
  1604. }
  1605. return true
  1606. }
  1607. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  1608. guard let action = menuItem.action else {
  1609. isTakesEffect.pointee = false
  1610. return false
  1611. }
  1612. if (KMSystemMenu.isEditSelector(sel: action)) {
  1613. if (KMSystemMenu.Edit.deleteSelector == action) {
  1614. isTakesEffect.pointee = true
  1615. return self.listView.activeAnnotations.count > 0
  1616. } else if (KMSystemMenu.Edit.copySelector == action) {
  1617. isTakesEffect.pointee = true
  1618. return true//self.listView.canCopy()
  1619. } else if (KMSystemMenu.Edit.cutSelector == action) {
  1620. isTakesEffect.pointee = true
  1621. return self.listView.canCopy()
  1622. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  1623. isTakesEffect.pointee = true
  1624. return self.listView.canPaste()
  1625. }
  1626. }
  1627. isTakesEffect.pointee = false
  1628. return false
  1629. }
  1630. //MARK: -CPDFListViewDelegate
  1631. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  1632. }
  1633. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  1634. self.view.window?.makeFirstResponder(self.listView)
  1635. if isRightMenu {
  1636. } else if annotations.count > 0 {
  1637. if annotations.count > 1 {
  1638. let fristAnnotation = annotations.first
  1639. var isSameAnnotation = true
  1640. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1641. for annotation in annotations {
  1642. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  1643. if (className == "CPDFSquareAnnotation") ||
  1644. (className == "CPDFCircleAnnotation") ||
  1645. (className == "CPDFLineAnnotation") {
  1646. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  1647. (cunrrentClassName != "CPDFCircleAnnotation") &&
  1648. (cunrrentClassName != "CPDFLineAnnotation") {
  1649. isSameAnnotation = false
  1650. }
  1651. } else {
  1652. if className != cunrrentClassName {
  1653. isSameAnnotation = false
  1654. }
  1655. }
  1656. }
  1657. if isSameAnnotation == false {
  1658. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1659. // self.closeRightPane()
  1660. } else {
  1661. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1662. self.openRightPane()
  1663. }
  1664. } else {
  1665. let fristAnnotation = annotations.first
  1666. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1667. if self.isReadMode {
  1668. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1669. self.closeRightPane()
  1670. } else {
  1671. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1672. if className != "CPDFStampAnnotation" &&
  1673. className != "CPDFSignatureAnnotation" &&
  1674. className != "CPDFListStampAnnotation" {
  1675. self.openRightPane()
  1676. }
  1677. }
  1678. }
  1679. } else if (annotations.count == 0){
  1680. if pdfListView.annotationType == .unkown {
  1681. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1682. self.closeRightPane()
  1683. } else {
  1684. if self.isReadMode {
  1685. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1686. self.closeRightPane()
  1687. } else {
  1688. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1689. self.openRightPane()
  1690. }
  1691. }
  1692. }
  1693. }
  1694. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  1695. if(annotationType == .unkown) {
  1696. // self.rightSideViewController.view.isHidden = true
  1697. self.rightSideViewController.isHidden = true
  1698. self.closeRightPane()
  1699. }
  1700. }
  1701. ///开始定位链接注释
  1702. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1703. if self.locationPageView.superview == nil {
  1704. self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
  1705. pdfListView.addSubview(self.locationPageView)
  1706. }
  1707. }
  1708. ///刷新链接注释
  1709. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1710. if self.locationPageView.superview != nil {
  1711. self.locationPageView.removeFromSuperview()
  1712. }
  1713. if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
  1714. self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1715. }
  1716. }
  1717. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  1718. if (listView.toolMode != CToolMode.editPDFToolMode) {
  1719. return menuItems
  1720. }
  1721. var tMenuItems = menuItems;
  1722. if(listView.isSelectEditCharRange() ||
  1723. listView.isSelecteditArea(with: point)) {
  1724. tMenuItems?.append(NSMenuItem.separator())
  1725. // tMenuItems?.append(self.fontColorMenuItem())
  1726. // tMenuItems?.append(self.fontSizeMenuItem())
  1727. }
  1728. let areas = self.listView.editingAreas() ?? []
  1729. if areas.count == 1 {
  1730. let fristAreas = areas.first
  1731. if fristAreas is CPDFEditImageArea {
  1732. self.listView.selectImageAreas = fristAreas as! CPDFEditImageArea
  1733. if self.listView.isEditImage {
  1734. tMenuItems?.removeAll()
  1735. tMenuItems?.append(self.corpImageMenuItem())
  1736. tMenuItems?.append(self.cancelCorpImageMenuItem())
  1737. tMenuItems?.append(self.restoreCorpImageMenuItem())
  1738. } else {
  1739. tMenuItems?.append(NSMenuItem.separator())
  1740. tMenuItems?.append(self.cutImageArea())
  1741. tMenuItems?.append(self.replaceImageArea())
  1742. tMenuItems?.append(self.exportImageArea())
  1743. }
  1744. } else {
  1745. tMenuItems?.swapAt(0, 1)
  1746. }
  1747. } else if areas.count == 0 {
  1748. tMenuItems?.append(NSMenuItem.separator())
  1749. tMenuItems?.append(self.addText())
  1750. tMenuItems?.append(self.addImage())
  1751. }
  1752. return tMenuItems
  1753. }
  1754. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!) {
  1755. self.mouseRightMenuEvent = theEvent
  1756. let currentMenu : NSMenu = menu.pointee!
  1757. if (listView.toolMode == .redactToolMode) {
  1758. if (listView.activeAnnotation == nil) {
  1759. } else {
  1760. let currentPoint: NSPoint = pdfListView.convert(theEvent.locationInWindow, from: pdfListView.superview)
  1761. let currentPage = pdfListView.page(for: currentPoint, nearest: true)
  1762. // let currentPage = pdfListView.activeAnnotation.page
  1763. let pagePoint = pdfListView.convert(currentPoint, to: currentPage)
  1764. currentMenu.removeAllItems()
  1765. if (pdfListView.activeAnnotation.bounds.contains(pagePoint)) {
  1766. currentMenu.insertItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(redact_menuItemClick_delete), target: self, at: currentMenu.items.count)
  1767. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1768. currentMenu.insertItem(withTitle: NSLocalizedString("Properties...", comment: ""), action: #selector(redact_menuItemClick_setProperty), target: self, at: currentMenu.items.count)
  1769. currentMenu.insertItem(withTitle: NSLocalizedString("Use Current Properties as New Default", comment: ""), action: #selector(redact_menuItemClick_setCurrentPropertyToDefaultValue), target: self, at: currentMenu.items.count)
  1770. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1771. currentMenu.insertItem(withTitle: NSLocalizedString("Repeat mark across pages", comment: ""), action: #selector(redact_menuItemClick_MultiPageFlag), target: self, at: currentMenu.items.count)
  1772. currentMenu.insertItem(withTitle: NSLocalizedString("Apply Redactions", comment: ""), action: #selector(redact_menuItemClick_apply), target: self, at: currentMenu.items.count)
  1773. currentMenu.insertItem(withTitle: NSLocalizedString("Erase Redactions", comment: ""), action: #selector(redact_menuItemClick_clear), target: self, at: currentMenu.items.count)
  1774. } else {
  1775. currentMenu.insertItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(redact_menuItemClick_paste), target: self, at: currentMenu.items.count)
  1776. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1777. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1778. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1779. }
  1780. }
  1781. return
  1782. }
  1783. if(listView.toolMode == .selectToolMode) {
  1784. if currentMenu.items.count > 0 {
  1785. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1786. export.submenu = self.exportMenu()
  1787. currentMenu.insertItem(export, at: currentMenu.items.count)
  1788. let corp = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action:#selector(cropCurrentPage), target: self)
  1789. // corp?.submenu = self.cropMenu()
  1790. currentMenu.insertItem(corp, at: currentMenu.items.count)
  1791. // MARK: 暂时拿掉 2023.04.26
  1792. // currentMenu.insertItem(self.zoomSelectionMenuItem(), at: currentMenu.items.count)
  1793. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1794. }
  1795. } else {
  1796. if listView.currentSelection != nil {
  1797. if (listView.currentSelection.string() != nil || listView.currentSelection.selectionType() == .image) {
  1798. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1799. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1800. } else {
  1801. var isMarkup = false
  1802. for item in self.listView.activeAnnotations {
  1803. if (item is CPDFMarkupAnnotation) {
  1804. isMarkup = true
  1805. break
  1806. }
  1807. }
  1808. if(!isMarkup) {
  1809. self.addAnnotationForStyleMenu(menu: currentMenu)
  1810. }
  1811. }
  1812. }
  1813. } else if (listView.activeAnnotation == nil) {
  1814. if(currentMenu.items.count > 2) {
  1815. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  1816. }
  1817. if(currentMenu.items.count > 3) {
  1818. currentMenu.insertItem(self.addBookmarkMenu(), at: 4)
  1819. }
  1820. if(currentMenu.items.count > 4) {
  1821. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  1822. }
  1823. if(currentMenu.items.count > 5) {
  1824. currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
  1825. }
  1826. if (currentMenu.items.count > 6) {
  1827. currentMenu.insertItem(self.addReadModelStype(), at: 7)
  1828. }
  1829. if (currentMenu.items.count > 7 && self.isReadMode) {
  1830. currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
  1831. }
  1832. // if(currentMenu.items.count > 6) {
  1833. // let menuItem = NSMenuItem(title: NSLocalizedString("Automatic rolling", comment: ""), action:nil, target: self)!
  1834. // currentMenu.insertItem(menuItem, at: 6)
  1835. // }
  1836. // if(currentMenu.items.count > 7) {
  1837. // let menuItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action:nil, target: self)!
  1838. // currentMenu.insertItem(menuItem, at: 7)
  1839. // }
  1840. // if(currentMenu.items.count > 8) {
  1841. // let menuItem = NSMenuItem(title: NSLocalizedString("menuItem", comment: ""), action:nil, target: self)!
  1842. // currentMenu.insertItem(menuItem, at: 8)
  1843. // }
  1844. if !self.isReadMode {
  1845. if (currentMenu.items.count > 10) {
  1846. currentMenu.insertItem(self.addHighlightLinksStype(), at: 11)
  1847. }
  1848. }
  1849. if self.isReadMode {
  1850. } else {
  1851. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1852. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1853. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1854. }
  1855. } else if listView.activeAnnotation != nil {
  1856. var type : CAnnotationType = .unkown
  1857. if listView.activeAnnotation is CPDFMarkupAnnotation {
  1858. if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1859. type = .highlight
  1860. } else if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .underline {
  1861. type = .underline
  1862. } else {
  1863. type = .strikeOut
  1864. }
  1865. } else if listView.activeAnnotation is CPDFInkAnnotation {
  1866. type = .ink
  1867. } else if listView.activeAnnotation is CPDFFreeTextAnnotation {
  1868. type = .freeText
  1869. } else if listView.activeAnnotation is CPDFTextAnnotation {
  1870. type = .anchored
  1871. } else if listView.activeAnnotation is CPDFCircleAnnotation {
  1872. type = .circle
  1873. } else if listView.activeAnnotation is CPDFSquareAnnotation {
  1874. type = .square
  1875. }
  1876. if ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1877. if listView.activeAnnotations.count == 1 {
  1878. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1879. }
  1880. }
  1881. if type != .unkown && listView.activeAnnotations.count == 1{
  1882. currentMenu.insertItem(self.setDefaultAnnotationPorpert(type: type), at: currentMenu.items.count)
  1883. }
  1884. // closeRightPane()
  1885. }
  1886. }
  1887. for item in currentMenu.items {
  1888. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  1889. // 显示与隐藏注释 item action 截取
  1890. item.action = #selector(menuItemClick_HidenorShowNote)
  1891. item.target = self
  1892. break
  1893. }
  1894. }
  1895. }
  1896. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1897. var addRedact = false
  1898. var saveWatermark = false
  1899. var saveWatermarkType: KMSubscribeWaterMarkType = .none
  1900. for anno in annotations {
  1901. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  1902. addRedact = true
  1903. // break
  1904. } else if (anno.isKind(of: CPDFLinkAnnotation.self)) { // link 注释
  1905. saveWatermark = true
  1906. saveWatermarkType = .link
  1907. } else if (anno.isKind(of: CPDFListStampAnnotation.self)) { // 图章注释
  1908. saveWatermark = true
  1909. saveWatermarkType = .stamp
  1910. } else if (anno.isKind(of: CPDFListSignatureAnnotation.self)) { // 签名注释
  1911. saveWatermark = true
  1912. saveWatermarkType = .sign
  1913. }
  1914. }
  1915. if (saveWatermark) {
  1916. self.recordSaveWatermarkFlag(type: saveWatermarkType)
  1917. }
  1918. self.hasAddRedact = addRedact
  1919. if self.isReadMode || self.listView.toolMode == .moveToolMode {
  1920. self.listView.toolMode = .textToolMode
  1921. self.listView.annotationType = .unkown
  1922. self.toolbarController.toolbarType = .Annatiton
  1923. }
  1924. if (self.rightMouseEventing) {
  1925. self.rightMouseEventing = false
  1926. if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
  1927. self.listView.toolMode = .textToolMode
  1928. self.listView.annotationType = .unkown
  1929. }
  1930. }
  1931. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  1932. }
  1933. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  1934. if (!self.listView.isEqual(to: pdfListView)) {
  1935. return
  1936. }
  1937. if (self.listView.toolMode != .selectToolMode) {
  1938. return
  1939. }
  1940. if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
  1941. return
  1942. }
  1943. let tipView = self.topTipBox.contentView?.subviews.first
  1944. if (tipView?.isKind(of: KMCropTipView.self) == false) {
  1945. return
  1946. }
  1947. (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
  1948. }
  1949. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  1950. if(speedy == .right) {
  1951. self.toggleRightPane()
  1952. } else if (speedy == .left) {
  1953. self.menuItemAction_hiddenLeftSide(speedy)
  1954. }
  1955. }
  1956. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  1957. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  1958. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1959. return KMAnnotationPropertiesColorManager.manager.markHighlightColors
  1960. } else {
  1961. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1962. }
  1963. } else {
  1964. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1965. }
  1966. }
  1967. func pdfListViewHaveDocumentAttribute() -> Bool {
  1968. if(!self.listView.document.allowsCopying) {
  1969. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  1970. if (result == .cancel) {
  1971. return
  1972. }
  1973. self?.isSaveKeyChain = false
  1974. self?.listView.document.unlock(withPassword: password)
  1975. self?.hiddenSecureLimitTip()
  1976. }
  1977. return false
  1978. }
  1979. return true
  1980. }
  1981. func addTopTip(_ view: NSView?) {
  1982. if (Thread.isMainThread) {
  1983. if (view == nil) {
  1984. let contentView: NSView = self.topTipBox.contentView!
  1985. for subview in contentView.subviews {
  1986. subview.removeFromSuperview()
  1987. }
  1988. self.topTipBox.isHidden = true
  1989. return
  1990. }
  1991. let contentView: NSView = self.topTipBox.contentView!
  1992. for subview in contentView.subviews {
  1993. subview.removeFromSuperview()
  1994. }
  1995. self.topTipBox.isHidden = false
  1996. self.topTipBox.contentView?.addSubview(view!)
  1997. } else {
  1998. DispatchQueue.main.async {
  1999. if (view == nil) {
  2000. let contentView: NSView = self.topTipBox.contentView!
  2001. for subview in contentView.subviews {
  2002. subview.removeFromSuperview()
  2003. }
  2004. self.topTipBox.isHidden = true
  2005. return
  2006. }
  2007. let contentView: NSView = self.topTipBox.contentView!
  2008. for subview in contentView.subviews {
  2009. subview.removeFromSuperview()
  2010. }
  2011. self.topTipBox.isHidden = false
  2012. self.topTipBox.contentView?.addSubview(view!)
  2013. }
  2014. }
  2015. }
  2016. }
  2017. extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
  2018. func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
  2019. self.isPDFTextImageEdited = true
  2020. }
  2021. }