KMMainViewController.swift 94 KB

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