KMMainViewController.swift 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. @objcMembers class KMMainViewController: KMBaseViewController, NSTextFieldDelegate,KMPresentationTopViewControllerDelegate {
  9. @IBOutlet var PDFContendView: NSView!
  10. @IBOutlet var centerContentView: NSView!
  11. @IBOutlet var listView: CPDFListView!
  12. @IBOutlet var secondaryPdfView: KMSecondaryPDFView?
  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 newPDFSplitView: KMSplitView!
  20. @IBOutlet weak var pdfContentView: NSView!
  21. @IBOutlet weak var pdfSplitSecondView: NSBox!
  22. @IBOutlet weak var locationPageView: NSView!
  23. @IBOutlet weak var tipLabel: NSTextField!
  24. @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
  25. @IBOutlet var childToolbarController: KMToolbarViewController!
  26. @IBOutlet var toolbarController: KMToolbarController!
  27. @IBOutlet weak var toolbarBox: NSBox!
  28. @IBOutlet weak var heightOffset: NSLayoutConstraint!
  29. //阅读模式界面
  30. @IBOutlet weak var readModelView: KMReadModelView!
  31. @IBOutlet weak var bottomAreaView: KMBox!
  32. @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
  33. //页码显示器
  34. @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
  35. @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
  36. @IBOutlet weak var topTipBox: NSBox!
  37. @IBOutlet weak var exitFullButton: NSButton!
  38. var model = KMMainModel()
  39. var isReadMode: Bool = false
  40. var readAlertView: CustomAlertView?
  41. var readLeftMethodType: BotaType = .None
  42. var readLeftPanelOpen = false
  43. var readLastLeftPanWidth = 0.0
  44. var readLeftViewShowPanel = false
  45. var readRightPanelOpen = false
  46. var readToolbarType: KMToolbarViewType = .None
  47. var readToolbarItemIdentifier: String = ""
  48. var readToolMode: CToolMode = .textToolMode
  49. var readAnnotationType: CAnnotationType = .unkown
  50. var readSubViewType: RightSubViewType = .None
  51. //自动滚动
  52. var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
  53. //Search
  54. var searchIndex: Int = 0
  55. //Form
  56. var formAlertView: KMFormAlertView?
  57. //Secure
  58. var secureAlertView: KMSecureAlertView?
  59. //对比
  60. var isCompareModel: Bool = false {
  61. didSet {
  62. self.toolbarController.updataItemVisible()
  63. }
  64. }
  65. //合并
  66. var mergeWindowController: KMMergeWindowController?
  67. //水印
  68. var watermarkWindowController: KMWatermarkWindowController?
  69. //密码弹窗
  70. var passwordWindow: KMPasswordInputWindow?
  71. //对比
  72. var compressWIndowControllerNew: KMCompressWIndowControllerNew?
  73. //
  74. var securityWindowController: KMSecurityWindowController?
  75. //引导
  76. var guideInfoWindowController: KMGuideInfoWindowController?
  77. var presentationTopViewController: KMPresentationTopViewController?
  78. //春季活动
  79. var recommondPopWindowVC: KMRecommondPopWindow?
  80. private var _needSave = false
  81. var needSave: Bool {
  82. set {
  83. _needSave = newValue
  84. if (_needSave == false) {
  85. self.clearIsPDFDocumentEdited()
  86. }
  87. }
  88. get {
  89. return _needSave
  90. }
  91. }
  92. var isPDFDocumentEdited: Bool {
  93. get {
  94. return self.model.isPDFDocumentEdited
  95. }
  96. }
  97. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  98. var rightSideViewController: KMRightSideViewController!
  99. var searchResults: [KMSearchMode] = []
  100. var mwcFlags: MwcFlags = MwcFlags()
  101. var document: CPDFDocument?
  102. var myDocument: NSDocument?
  103. weak var browserWindowController: KMBrowserWindowController? //慎直接使用这个方法
  104. var cropSettingWindowController: KMCropSettingWindowController!
  105. var currentWindowController: NSWindowController!
  106. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  107. //数字签名
  108. var digitalSignController: KMPDFDigitalSignViewController?
  109. var redactController: KMPDFRedactViewController!
  110. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  111. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  112. var extract: KMExtractImageWindowController?
  113. var functionWidth: Double {
  114. get {
  115. if self.isReadMode {
  116. if !self.model.isShowBOTA {
  117. return 0
  118. }
  119. }
  120. return 48-4
  121. }
  122. }
  123. var pageNumber: UInt?
  124. var openSecondaryPdfView: KMSecondaryViewController?
  125. var secondaryPdfContentView: NSView?
  126. var lastSplitPDFHeight: Float = 0.0
  127. var pdfEditController: KMPDFEditViewController? {
  128. get {
  129. return self.getPDFEditController()
  130. }
  131. }
  132. var autoSaveTimer: Timer?
  133. private var _documentFirstLoad: Bool = true
  134. var eventMonitor: Any?
  135. var keyEventMonitor: Any?
  136. var mouseRightMenuEvent: NSEvent?
  137. var aiTranslationWindow: KMAITranslationWindowController?
  138. var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
  139. lazy private var homeVC: KMHomeViewController? = {
  140. let vc = KMHomeViewController()
  141. return vc
  142. }()
  143. private var background_mask: NSView?
  144. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  145. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  146. get {
  147. return self._secureOptions
  148. }
  149. }
  150. var documentAttribute: [CPDFDocumentAttribute : Any]?
  151. fileprivate var _removeSecureFlag = false
  152. var removeSecureFlag: Bool {
  153. get {
  154. return self._removeSecureFlag
  155. }
  156. }
  157. fileprivate var _saveWatermarkFlag = false
  158. var saveWatermarkFlag: Bool {
  159. get {
  160. return self._saveWatermarkFlag
  161. }
  162. }
  163. private var mainWindow_: NSWindow?
  164. var mainWindow: NSWindow? {
  165. get {
  166. return self.mainWindow_
  167. }
  168. set {
  169. self.mainWindow_ = newValue
  170. }
  171. }
  172. let editPDFHanddler = KMEditPDfHanddler()
  173. var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
  174. var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
  175. var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
  176. var srHanddler: KMSearchReplaceHanddler = KMSearchReplaceHanddler()
  177. deinit {
  178. let fontManager = NSFontManager.shared
  179. fontManager.target = nil
  180. NotificationCenter.default.removeObserver(self)
  181. self.listView.delegate = nil
  182. self.listView.document?.delegate = nil
  183. self.editPDFHanddler.clearData()
  184. self.removeEventMonitor()
  185. self.removeKeyEventMonitor()
  186. }
  187. override func awakeFromNib() {
  188. super.awakeFromNib()
  189. self.addBackgroundMaskView()
  190. self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
  191. listView.delegate = self
  192. listView.pdfListViewDelegate = self
  193. // listView.editingConfig().isSupportMultipleSelectEditingArea = true
  194. if (document != nil) {
  195. // if (self.document!.isLocked) {
  196. //
  197. // } else {
  198. // }
  199. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  200. self.listView.document = self.document
  201. self.listView.document?.delegate = self
  202. // }
  203. let autoScale = listView.autoScales
  204. if !autoScale {
  205. listView.scaleFactor = 1.0
  206. }
  207. }
  208. self.initPDFLeftViewVC()
  209. self.initRightSideView()
  210. self.toolbarController.listView = self.listView
  211. self.toolbarController.mainViewController = self
  212. self.leftSideViewController.mainViewController = self
  213. self.newPDFSplitView.delegate = self
  214. }
  215. override func viewDidAppear() {
  216. super.viewDidAppear()
  217. //春季活动
  218. if KMAdvertisementManager.manager.appClosedCount == 1 {
  219. if ((KMAdvertisementManager.manager.info.popWindowContent) != nil) {
  220. if KMAdvertisementManager.manager.info.popWindowContent!.content!.count > 0 {
  221. let info = KMAdvertisementManager.manager.info.popWindowContent!.content?.first
  222. if KMAdvertisementManager.checkAdvertisementValid(info!) {
  223. self.loadRecommondPopWindow()
  224. }
  225. }
  226. }
  227. KMAdvertisementManager.manager.appClosedCount = 2
  228. }
  229. //刷新前一页后一页按钮
  230. self.updateNextAndPreViousButtonState()
  231. KMLightMemberManager.manager.canShowAdvancedView = false
  232. // Task { @MainActor in
  233. // await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
  234. // }
  235. self.addEventMonitor()
  236. self.view.window?.makeFirstResponder(self.listView)
  237. // 更新属性页面的信息
  238. NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
  239. self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
  240. if (self.document == nil) {
  241. return
  242. }
  243. if (self.document == nil || self.document!.isLocked == false) {
  244. self.loadFunctionGuide()
  245. }
  246. if (self.document?.isLocked == false) {
  247. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  248. self.showConvertNotesProgress()
  249. }
  250. return
  251. }
  252. if (self.view.window == nil) {
  253. return
  254. }
  255. if (self.model.password != nil) {
  256. if let data = self.listView.document?.unlock(withPassword: self.model.password), data {
  257. self.model.isSaveKeyChain = false
  258. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  259. self.showConvertNotesProgress()
  260. }
  261. return
  262. }
  263. }
  264. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  265. if self.view.window != nil && self.tabViewIsDragging() == false {
  266. self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [weak self] result , password in
  267. if (result == .cancel) {
  268. // self.browserWindowController?.browser?.closeTab()
  269. (self?.myDocument as? KMMainDocument)?.browser?.closeTab()
  270. return
  271. }
  272. self?.model.isSaveKeyChain = true
  273. self?.listView?.document = self?.document
  274. self?.document?.unlock(withPassword: password)
  275. }
  276. } else {
  277. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  278. self.showConvertNotesProgress()
  279. }
  280. }
  281. }
  282. }
  283. override func viewWillDisappear() {
  284. super.viewWillDisappear()
  285. if self.interactionMode != .presentation {
  286. self.removeEventMonitor()
  287. }
  288. self.editPDFHanddler.hiddenWindows()
  289. }
  290. override func viewWillLayout() {
  291. super.viewWillLayout()
  292. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  293. self.exitFullButton.isHidden = false
  294. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  295. } else {
  296. self.exitFullButton.isHidden = true
  297. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  298. }
  299. if let guideWC = self.guideInfoWindowController{
  300. var rect = self.view.window!.frame
  301. rect.size.height -= 20
  302. guideWC.window?.setFrame(rect, display: false)
  303. guideWC.window?.minSize = rect.size
  304. guideWC.window?.maxSize = rect.size
  305. guideWC.show()
  306. }
  307. }
  308. override func viewDidLoad() {
  309. super.viewDidLoad()
  310. mwcFlags.settingUpWindow = 1
  311. toolbarController.delegate = self
  312. self.editPDFHanddler.viewC = self
  313. self.srHanddler.pdfView = self.listView
  314. //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
  315. toolbarBox.contentView = toolbarController.view
  316. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  317. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  318. UserDefaults.standard.synchronize()
  319. }
  320. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  321. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  322. UserDefaults.standard.synchronize()
  323. }
  324. let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
  325. mianSplitView.setPosition(position, ofDividerAt: 0)
  326. mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0)
  327. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0)
  328. self.locationPageView.wantsLayer = true;
  329. self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
  330. 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: "")
  331. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  332. if (self.listView.document != nil) {
  333. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document?.documentURL.path ?? "")
  334. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document?.documentURL.path ?? "")
  335. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < (self.listView.document?.pageCount ?? 0)) {
  336. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  337. if (pageScale != nil) {
  338. self.listView.scaleFactor = CGFloat(pageScale!)
  339. }
  340. self.listView.go(toPageIndex: pageNumber!, animated: false)
  341. }
  342. } else {
  343. self._goToFirstPageForFristAppear()
  344. }
  345. }
  346. } else {
  347. self._goToFirstPageForFristAppear()
  348. }
  349. //阅读页面
  350. readModelView.delegate = self
  351. pageNumberDisplayView.delegate = self
  352. tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
  353. if !isReadMode {
  354. if mouseEntered {
  355. self.pageNumberDisplayView.hover = true
  356. } else {
  357. self.pageNumberDisplayView.hover = false
  358. }
  359. }
  360. }
  361. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  362. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  363. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  364. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  365. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  366. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  367. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  368. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  369. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  370. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  371. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.listView)
  372. NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayBoxChangedNotification), name: NSNotification.Name.CPDFViewDisplayBoxChanged, object: self.listView)
  373. // 互动模式
  374. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  375. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  376. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  377. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  378. NotificationCenter.default.addObserver(self, selector: #selector(didAddContentViewNotification), name: NSWindow.didAddContentViewNotification, object: nil)
  379. NotificationCenter.default.addObserver(self, selector: #selector(addAutoSaveEvent), name: AutoSaveManager.kTimeValueChangedNotificationName, object: nil)
  380. NotificationCenter.default.addObserver(self, selector: #selector(didRemoveAnnotationNotification), name: NSNotification.Name.CPDFPageDidRemoveAnnotation, object: nil)
  381. Task {
  382. self.addAutoSaveEvent()
  383. }
  384. self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
  385. self.closeRightPane()
  386. self.addKeyEventMonitor()
  387. self.addAdsBannerView()
  388. //检测OCR包是否需要更新
  389. #if VERSION_DMG
  390. // KMResourceDownloadManager.manager.checkDocumentAIVersion()
  391. #endif
  392. // Open snapshots?
  393. var snapshotSetups: NSArray?
  394. // if (hasWindowSetup)
  395. // snapshotSetups = [savedNormalSetup objectForKey:SNAPSHOTS_KEY];
  396. // else if ([sud boolForKey:SKRememberSnapshotsKey])
  397. if KMPreferenceManager.shared.rememberSnapshot {
  398. // snapshotSetups = [[SKBookmarkController sharedBookmarkController] snapshotsForRecentDocumentAtURL:[(NSDocument *)[self document] fileURL]];
  399. if let fileUrl = (self.myDocument as? KMMainDocument)?.fileURL {
  400. snapshotSetups = SKBookmarkController.shared().snapshotsForRecentDocument(at: fileUrl) as NSArray?
  401. }
  402. }
  403. if let cnt = snapshotSetups?.count, cnt > 0 {
  404. if let data = self.listView?.document?.isLocked, data {
  405. self.savedNormalSetup.setObject(snapshotSetups as Any, forKey: "snapshots" as NSCopying)
  406. } else {
  407. self.showSnapshots(setups: snapshotSetups)
  408. }
  409. }
  410. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  411. if readModel == true {
  412. self.openReadModel()
  413. }
  414. let hasWindowSetup = savedNormalSetup.count > 0
  415. if UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey) != nil {
  416. let pdfSettings: NSDictionary = hasWindowSetup ? savedNormalSetup : UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey)! as NSDictionary
  417. self.applyPDFSettings(pdfSettings)
  418. } else {
  419. self.applyPDFSettings(savedNormalSetup)
  420. }
  421. //文字
  422. let fontManager = NSFontManager.shared
  423. fontManager.target = self
  424. fontManager.action = #selector(changeFont(_:))
  425. }
  426. //MARK: - PDFListView
  427. func initPDFLeftViewVC() {
  428. var frame = self.leftView.frame
  429. frame.size.width += 44
  430. self.leftView.frame = frame
  431. leftSideViewController.isFirst = true
  432. leftSideViewController.listView = self.listView
  433. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  434. leftSideViewController.view.autoresizingMask = [.height,.width]
  435. leftSideViewController.delegate = self
  436. self.leftView.addSubview(leftSideViewController.view)
  437. }
  438. func initRightSideView() {
  439. self.rightSideViewController = KMRightSideViewController.init()
  440. self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
  441. self.rightSideViewController.view.autoresizingMask = [.height,.width]
  442. self.rightSideViewController.listView = self.listView
  443. // self.rightSideViewController.view.isHidden = true
  444. self.rightSideViewController.isHidden = true
  445. self.rightSideViewController.delegate = self
  446. self.rightView.addSubview(self.rightSideViewController.view)
  447. self.rightSideViewController.mainController = self
  448. self.rightSideViewController.propertyDidChange = { [weak self] model in
  449. if let anno = model as? CSelfSignAnnotation {
  450. self?.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: nil)
  451. }
  452. }
  453. }
  454. func addAdsBannerView() {
  455. #if VERSION_FREE
  456. if !KMMemberInfo.shared.isMemberAllFunction {
  457. guard let document = self.listView.document else {
  458. return
  459. }
  460. if !document.isLocked {
  461. KMAdsManager.defaultManager.beginSheetModalForView(self.readContentView, directions: .down, adPosY: 30, animated: false) { pageIndex in
  462. }
  463. }
  464. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  465. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  466. }
  467. #endif
  468. }
  469. // MARK: Private Methods
  470. // 是否阿拉伯语言
  471. private func _isArabicLanguage() -> Bool {
  472. return NSLocalizedString("Right click a color and select “Change Color...“.", comment: "") == "انقر بزر الماوس الأيمن فوق اللون وحدد \"تغيير اللون...\"."
  473. }
  474. internal func removeNotifications() {
  475. NotificationCenter.default.removeObserver(self)
  476. self.leftSideViewController.clearAnnotationFilterData()
  477. self.leftSideViewController.clearNotification()
  478. }
  479. func checkShouldAutoOpenLeftVC() {
  480. if KMPreference.shared.showLeftSideBar == false {
  481. return
  482. }
  483. if self.model.leftPanelOpen {
  484. return
  485. }
  486. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  487. if readModel == true {
  488. return
  489. }
  490. DispatchQueue.main.async {
  491. self.leftSideViewController.showThumbnail()
  492. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  493. }
  494. }
  495. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  496. mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  497. mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  498. self.model.lastLeftPanWidth = leftSideWidth
  499. self.model.lastRightPanWidth = rightSideWidth
  500. }
  501. internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  502. internal func removeAllAnnotations() {
  503. let alert = NSAlert()
  504. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  505. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  506. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  507. if (alert.runModal() != .alertFirstButtonReturn) {
  508. return
  509. }
  510. DispatchQueue.main.async {
  511. self.removeAllAnnotationsStore.store(t: self.listView)
  512. }
  513. }
  514. @objc func cancelMeasureType() {
  515. self.hideMeasureFloatingWindows()
  516. self.toolbarController?.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = false
  517. }
  518. func hideMeasureFloatingWindows() {
  519. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  520. distanceMeasureInfoWindowController?.hideFloatingWindow()
  521. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  522. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  523. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  524. areaMeasureInfoWindowController?.hideFloatingWindow()
  525. }
  526. }
  527. func showMeasureFloatingWindowsIfNeed() {
  528. let toolMode = self.listView?.toolMode ?? .none
  529. if toolMode != .measureToolMode {
  530. return
  531. }
  532. let type = self.listView?.annotationType ?? .none
  533. if type == .line {
  534. self.distanceMeasureInfoWindowController?.window?.orderFront(nil)
  535. } else if type == .polyLine {
  536. self.perimeterMeasureInfoWindowController?.window?.orderFront(nil)
  537. } else if type == .polyGon {
  538. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  539. } else if type == .square {
  540. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  541. }
  542. }
  543. // MARK: Set Methods
  544. var setDocument: CPDFDocument? {
  545. get {
  546. return document
  547. }
  548. set {
  549. if document != newValue {
  550. document = newValue
  551. }
  552. listView.document = document
  553. listView.document?.delegate = self
  554. self.listView.layoutDocumentView()
  555. self.leftSideViewController.refreshUIForDocumentChanged()
  556. }
  557. }
  558. var setPageNumber: UInt {
  559. get {
  560. return pageNumber!
  561. }
  562. set {
  563. let pageCount = listView.document?.pageCount ?? 0
  564. var value = newValue
  565. if value > pageCount {
  566. value = pageCount
  567. }
  568. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  569. listView.go(to: listView.document?.page(at: value-1))
  570. }
  571. if pageNumber != value {
  572. pageNumber = value
  573. }
  574. }
  575. }
  576. // MARK: - 标记密文
  577. func enterRedact() {
  578. if KMMemberInfo.shared.isMemberAllFunction == false {
  579. let winC = KMProductCompareWC.shared
  580. winC.kEventName = "Reading_Redact_BuyNow"
  581. KMMemberInfo.shared.advancedFunctionUsage()
  582. return
  583. }
  584. if self.listView.document?.allowsPrinting == false || self.listView.document?.allowsCopying == false {
  585. Task {
  586. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  587. }
  588. return
  589. }
  590. if self.hasEnterRedact() {
  591. self.exitRedact()
  592. return
  593. }
  594. self.commitEditingIfNeed()
  595. self.leftSideViewController.thumbnailTableView.isEnabled = false
  596. self.leftSideViewController.tocOutlineView.isEnabled = false
  597. self.leftSideViewController.noteOutlineView.isEnabled = false
  598. self.leftSideViewController.findTableView.isEnabled = false
  599. self.leftSideViewController.groupedFindTableView.isEnabled = false
  600. self.leftSideViewController.snapshotTableView.isEnabled = false
  601. let ttsWindowC = KMTTSWindowController.share
  602. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  603. if let data = ttsWindowC.window?.isVisible, data {
  604. ttsWindowC.stopSpeaking()
  605. ttsWindowC.close()
  606. }
  607. }
  608. NSColorPanel.shared.showsAlpha = false
  609. redactController = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document?.password)
  610. self.addChild(redactController)
  611. self.PDFContendView.addSubview(redactController.view)
  612. redactController.view.frame = self.PDFContendView.bounds
  613. redactController.view.autoresizingMask = [.width, .height]
  614. self.listView.isHidden = true
  615. redactController.scaleFactor = self.listView.scaleFactor
  616. redactController.titleBack = { [weak self] title in
  617. self?.view.window?.title = title
  618. }
  619. redactController.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
  620. self?.listView.go(toPageIndex: self!.redactController.redactPdfView.currentPageIndex, animated: false)
  621. if result == false { // 退出
  622. self?.exitRedact()
  623. return
  624. }
  625. let controller = self?._getPDFRedactController()
  626. controller?.redactPdfView.newAddAnnotation.removeAll()
  627. self?.exitRedact()
  628. if saveResult {
  629. let newDocument = CPDFDocument(url: saveUrl)
  630. if let data = newDocument?.isLocked, data {
  631. newDocument?.unlock(withPassword: self?.listView.document?.password ?? "")
  632. }
  633. self?.document = newDocument
  634. self?.listView.document = newDocument
  635. self?.listView.layoutDocumentView()
  636. }
  637. }
  638. redactController.setCurrentPageIndex(self.listView.currentPageIndex)
  639. }
  640. func exitRedact() {
  641. self.leftSideViewController.thumbnailTableView.isEnabled = true
  642. self.leftSideViewController.tocOutlineView.isEnabled = true
  643. self.leftSideViewController.noteOutlineView.isEnabled = true
  644. self.leftSideViewController.findTableView.isEnabled = true
  645. self.leftSideViewController.groupedFindTableView.isEnabled = true
  646. self.leftSideViewController.snapshotTableView.isEnabled = true
  647. let controller = self._getPDFRedactController()
  648. if let data = controller {
  649. if data.redactPdfView.newAddAnnotation.count > 0 {
  650. KMAlertTool.runModel(message: "", informative: KMLocalizedString("There are unapplied redactions in this file. Exit will not save redaction.", nil), buttons: [KMLocalizedString("Exit", nil), KMLocalizedString("Cancel", nil)]) { response in
  651. if response == .alertFirstButtonReturn {
  652. controller?.redactPdfView.newAddAnnotation.removeAll()
  653. self.exitRedact()
  654. }
  655. }
  656. return
  657. }
  658. }
  659. NSColorPanel.shared.showsAlpha = true
  660. self.toolbarController.findItem(KMDocumentRedactToolbarItemIdentifier)?.isSelected = false
  661. // self.toolbarController.toolbarType = .None
  662. // self.listView.toolMode = .moveToolMode
  663. controller?.redactPdfView.resignMonitor()
  664. controller?.view.removeFromSuperview()
  665. controller?.removeFromParent()
  666. self.listView.isHidden = false
  667. // self.listView.layoutDocumentView()
  668. // self.view.window?.makeFirstResponder(self.listView)
  669. self.listView.annotationType = .unkown
  670. }
  671. func hasEnterRedact() -> Bool {
  672. return self._getPDFRedactController() != nil
  673. }
  674. //MARK: - AI
  675. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  676. if (self.document != nil) {
  677. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  678. } else {
  679. AIChatInfoManager.defaultManager.currentFilePath = ""
  680. }
  681. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  682. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  683. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  684. let documentArray = NSDocumentController.shared.documents
  685. var didFileEdit: Bool = false
  686. var curDoc: KMMainDocument!
  687. for document in documentArray {
  688. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  689. didFileEdit = document.isDocumentEdited
  690. curDoc = document as! KMMainDocument
  691. break
  692. }
  693. }
  694. if didFileEdit {
  695. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  696. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  697. do {
  698. try FileManager.default.removeItem(at: tempFileURL)
  699. } catch {
  700. }
  701. }
  702. if curDoc != nil {
  703. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  704. }
  705. }
  706. windowVC.window?.becomeMain()
  707. }
  708. }
  709. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  710. } else {
  711. var windowRect = windowVC.window?.frame
  712. windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  713. windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  714. windowVC.window?.setFrame(windowRect!, display: true)
  715. windowVC.didSetOriginFrame = true
  716. }
  717. windowVC.eventLabel = "AITools_Tbr"
  718. windowVC.showWindow(nil)
  719. if (aiConfigType != .none) {
  720. windowVC.eventLabel = "AITools_Start"
  721. if self.listView.currentSelection?.string()?.isEmpty == false {
  722. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  723. }
  724. windowVC.chooseAIFunctionWithType(aiConfigType)
  725. }
  726. }
  727. @objc func aiTipIconViewShowStateChangeNoti() {
  728. }
  729. //MARK: - 引导
  730. func loadFunctionGuide() -> Void {
  731. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  732. if self.view.window != nil {
  733. self.loadOpenFileFunctionGuide(.openFileNormal)
  734. }
  735. }
  736. }
  737. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  738. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  739. let leftPanelItem:KMToolbarItemView = self.toolbarController.findItem("KMLeftControlToolbarItemIdentifier")!
  740. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  741. guard let guideWC = self.guideInfoWindowController else { return }
  742. guideWC.type = .openFileNormal
  743. guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? .zero
  744. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  745. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  746. let rightPanelItem = self?.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  747. let digitalPanelItem = self?.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier)
  748. if let data = rightPanelItem, data.isHidden {
  749. let view = self?.toolbarController.mainToolBarView?.toolbar?.moreButton
  750. windowVC.rightPanelRect = (self?.view.window?.contentView?.convert(view?.frame ?? .zero, from: view?.superview)) ?? .zero
  751. } else {
  752. windowVC.rightPanelRect = (self?.view.window?.contentView?.convert(rightPanelItem?.frame ?? .zero, from: rightPanelItem?.superview)) ?? .zero
  753. }
  754. guideWC.digitalBoxRect = (self?.view.window?.contentView?.convert(digitalPanelItem?.frame ?? .zero, from: digitalPanelItem?.superview)) ?? .zero
  755. }
  756. guideWC.finishHandle = { [weak self] windowVC, type in
  757. if type == .windowNewFinish ||
  758. type == . windowDigitalFinish {
  759. self?.checkFirstTrialController()
  760. }
  761. }
  762. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  763. self?.checkFirstTrialController()
  764. }
  765. var rect = self.view.window!.frame
  766. rect.size.height -= 20
  767. guideWC.window?.setFrame(rect, display: false)
  768. guideWC.window?.minSize = rect.size
  769. guideWC.window?.maxSize = rect.size
  770. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  771. guideWC.show()
  772. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  773. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  774. guard let guideWC = self.guideInfoWindowController else { return }
  775. guideWC.type = .digitalSignGuide
  776. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  777. return
  778. }
  779. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  780. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  781. guideWC.finishHandle = { [weak self] windowVC, type in
  782. self?.checkFirstTrialController()
  783. }
  784. var rect = self.view.window!.frame
  785. rect.size.height -= 20
  786. guideWC.window?.setFrame(rect, display: false)
  787. guideWC.window?.minSize = rect.size
  788. guideWC.window?.maxSize = rect.size
  789. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  790. guideWC.show()
  791. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  792. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  793. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  794. guard let guideWC = self.guideInfoWindowController else { return }
  795. guideWC.type = .pdfCompareGuide
  796. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  797. return
  798. }
  799. guard let win = self.view.window else {
  800. return
  801. }
  802. guideWC.digitalBoxRect = (win.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview)) ?? .zero
  803. let compareItem = self.toolbarController.findItem(KMToolbarComparisonItemIdentifier)
  804. guideWC.compareItemRect = (win.contentView?.convert(compareItem?.frame ?? .zero, from: compareItem?.superview)) ?? .zero
  805. guideWC.finishHandle = { [weak self] winC, type in
  806. if type == .windowNewFinish {
  807. DispatchQueue.main.async {
  808. self?.loadOpenFileFunctionGuide(.measureGuide)
  809. }
  810. return
  811. }
  812. }
  813. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  814. var rect = self.view.window!.frame
  815. rect.size.height -= 20
  816. guideWC.window?.setFrame(rect, display: false)
  817. guideWC.window?.minSize = rect.size
  818. guideWC.window?.maxSize = rect.size
  819. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  820. guideWC.show()
  821. }
  822. } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
  823. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  824. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  825. guard let guideWC = self.guideInfoWindowController else { return }
  826. guard let _ = self.view.window else {
  827. return
  828. }
  829. guideWC.type = .measureGuide
  830. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  831. return
  832. }
  833. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview)) ?? .zero
  834. let compareItem:KMToolbarItemView = self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)!
  835. guideWC.compareItemRect = (self.view.window?.contentView?.convert(compareItem.frame, from: compareItem.superview)) ?? .zero
  836. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  837. var rect = self.view.window?.frame ?? .zero
  838. rect.size.height -= 20
  839. guideWC.window?.setFrame(rect, display: false)
  840. guideWC.window?.minSize = rect.size
  841. guideWC.window?.maxSize = rect.size
  842. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  843. guideWC.show()
  844. }
  845. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  846. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  847. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  848. guard let guideWC = self.guideInfoWindowController else { return }
  849. guideWC.type = .convertGuide
  850. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  851. return
  852. }
  853. guard let win = self.view.window else {
  854. return
  855. }
  856. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview)) ?? .zero
  857. guideWC.purchaseHandle = { [weak self] windowVC in
  858. #if VERSION_DMG
  859. if KMMemberInfo.shared.isMemberAllFunction {
  860. if KMMemberInfo.shared.isPermitConvert {
  861. //Convert:
  862. self?.showAllConvertWindow(convertT: .Word)
  863. } else {
  864. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  865. limitWC.continueBlock = { windowController in
  866. }
  867. limitWC.window?.center()
  868. limitWC.showWindow(nil)
  869. }
  870. } else {
  871. KMProductCompareWC.shared.orientation = false
  872. KMProductCompareWC.shared.showWindow(nil)
  873. }
  874. #else
  875. if KMMemberInfo.shared.isMemberAllFunction == true {
  876. if KMMemberInfo.shared.isPermitConvert == true {
  877. } else {
  878. let userScenarioType = KMMemberInfo.shared.userScenarioType
  879. let platforms = KMMemberInfo.shared.vip_platforms
  880. let platformsArray = platforms
  881. .components(separatedBy: ",")
  882. .map { $0.trimmingCharacters(in: .whitespaces) }
  883. if userScenarioType == .lite_type2 ||
  884. userScenarioType == .lite_type4 ||
  885. userScenarioType == .lite_type6 ||
  886. userScenarioType == .lite_type8 {
  887. // 订阅中,Android单平台高级版月订阅或者全平台标准版年订阅,不能升级,提示联系客服
  888. if !platformsArray.contains("mac") ||
  889. KMMemberInfo.shared.vip_levels != "3" {
  890. let alert = NSAlert()
  891. alert.alertStyle = .critical
  892. alert.informativeText = NSLocalizedString("Sorry, you do not have the rights to this paid feature and cannot use it. If you have any questions, please contact customer service at support@pdfreaderpro.com", comment: "")
  893. alert.addButton(withTitle: NSLocalizedString("Got it", comment: ""))
  894. alert.runModal()
  895. }
  896. }
  897. }
  898. } else {
  899. KMMemberInfo.shared.advancedFunctionUsage()
  900. }
  901. #endif
  902. }
  903. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  904. var rect = self.view.window?.frame ?? .zero
  905. rect.size.height -= 20
  906. guideWC.window?.setFrame(rect, display: false)
  907. guideWC.window?.minSize = rect.size
  908. guideWC.window?.maxSize = rect.size
  909. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  910. guideWC.show()
  911. }
  912. } else {
  913. }
  914. }
  915. func checkFirstTrialController() -> Void {
  916. #if VERSION_DMG
  917. //打开文档后引导相关
  918. if VerificationManager.default().status == .none {
  919. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  920. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  921. if lastVersion.isEmpty || lastVersion != appVersion {
  922. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  923. UserDefaults.standard.synchronize()
  924. KMProductCompareWC.shared.orientation = false
  925. KMProductCompareWC.shared.showWindow(nil)
  926. }
  927. }
  928. #endif
  929. }
  930. // MARK: - 页面编辑
  931. open func enterPageEdit(_ pages: [Int] = []) {
  932. if let doc = self.listView?.document {
  933. if doc.allowsCopying == false || doc.allowsPrinting == false {
  934. KMBaseWindowController.checkPassword(url: doc.documentURL, type: .owner) { result, pwd in
  935. if result && pwd.isEmpty == false {
  936. self.listView?.document?.unlock(withPassword: pwd)
  937. Task { @MainActor in
  938. self.enterPageEdit(pages)
  939. }
  940. } else {
  941. self.exitPageEdit()
  942. }
  943. }
  944. return
  945. }
  946. }
  947. //选中page
  948. var tPages = pages
  949. if tPages.count == 0 {
  950. if self.leftSideViewController.type.methodType == .Thumbnail {
  951. tPages = self.leftSideViewController.thumb_fetchSelectedRows() ?? [self.listView.currentPageIndex]
  952. }
  953. }
  954. if (hasEnterPageEdit()) {
  955. exitPageEdit()
  956. return
  957. }
  958. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  959. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  960. for (key, value) in toolBarView.toolbarItems {
  961. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  962. (value as! KMToolbarItemView).unEnabled = true
  963. }
  964. }
  965. }
  966. self.editPDFHanddler.clearData()
  967. let controller = KMPDFEditViewController(self.listView.document)
  968. controller.selectedPages = tPages
  969. controller.listView = self.listView
  970. self.addChild(controller)
  971. self.PDFContendView.addSubview(controller.view)
  972. controller.view.frame = self.PDFContendView.bounds
  973. controller.view.autoresizingMask = [.width,.height]
  974. self.listView.isHidden = true
  975. controller.itemClick = { [weak self] index, params in
  976. if (index == 1) { /// 双击退出
  977. self?.enterEditMode(self!.leftSideViewController, [])
  978. DispatchQueue.main.async {
  979. let pageIndex: Int = params.first as! Int
  980. self?.listView.go(toPageIndex: pageIndex, animated: true)
  981. }
  982. } else if (index == 2) { // 打印
  983. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  984. }
  985. }
  986. controller.documentEditedCallback = { [weak self] params in
  987. self?.recordIsPDFDocumentEdited()
  988. }
  989. controller.selectionDidChange = { selectedIndexs in
  990. var indexSet = IndexSet()
  991. for indexPath in selectedIndexs {
  992. indexSet.insert(indexPath.item)
  993. }
  994. if indexSet.count != 0 {
  995. // self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
  996. // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
  997. }
  998. }
  999. }
  1000. open func exitPageEdit() {
  1001. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  1002. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  1003. for (key, value) in toolBarView.toolbarItems {
  1004. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  1005. (value as! KMToolbarItemView).unEnabled = false
  1006. }
  1007. }
  1008. }
  1009. self.toolbarController.findItem(KMDocumentPageToolbarItemIdentifier)?.isSelected = false
  1010. let editController = getPDFEditController()
  1011. if (editController == nil) {
  1012. return
  1013. }
  1014. self.listView.annotationType = .highlight
  1015. // FIXME: - sdk修复插入特定文档crash后,这行代码可以去掉
  1016. self.leftSideViewController.model.insertedDocumentSet.formUnion(editController?.model.insertedDocumentSet ?? [])
  1017. editController?.view.removeFromSuperview()
  1018. editController?.removeFromParent()
  1019. self.listView.isHidden = false
  1020. self.listView.layoutDocumentView()
  1021. self.view.window?.makeFirstResponder(self.listView)
  1022. self.listView.annotationType = .unkown
  1023. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  1024. if let data = editController?.isEdited, data {
  1025. self.leftSideViewController.reloadThumbnailDataIfNeed()
  1026. self.leftSideViewController.note_reloadDataIfNeed()
  1027. self.leftSideViewController.refreshUIOfOutlineIfNeed()
  1028. self.leftSideViewController.refreshUIOfSeachListIfNeed()
  1029. self.leftSideViewController.refreshUIOfBookmarkIfNeed()
  1030. }
  1031. }
  1032. open func hasEnterPageEdit() -> Bool {
  1033. return self.getPDFEditController() != nil
  1034. }
  1035. // MARK: - Edit PDF
  1036. func enterEditPDF() {
  1037. self.editPDFHanddler.enterEditPDF()
  1038. }
  1039. // MARK: - 数字签名
  1040. func hasShowDigitalSign() -> Bool {
  1041. return self.digitalSignController?.view.superview != nil
  1042. }
  1043. func canEnterDigitalSign() -> Bool {
  1044. guard let doc = self.listView?.document else {
  1045. return false
  1046. }
  1047. return doc.allowsPrinting && doc.allowsCopying
  1048. }
  1049. func enterDigitalSign() {
  1050. self.listView.toolMode = .textToolMode
  1051. if self.hasShowDigitalSign() {
  1052. self.exitDigitalSign()
  1053. } else {
  1054. if self.needSaveDocument() {
  1055. self.saveDocumentWithProgressAlert { [unowned self] params in
  1056. if (self.listView.document != nil) {
  1057. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  1058. }
  1059. }
  1060. return
  1061. }
  1062. if (self.listView.document != nil) {
  1063. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  1064. }
  1065. }
  1066. }
  1067. func exitDigitalSign() {
  1068. self.digitalSignController?.view.removeFromSuperview()
  1069. // self.digitalSignController = nil
  1070. // KMDocumentDigitalSignToolbarItemIdentifier
  1071. self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier)?.isSelected = false
  1072. }
  1073. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  1074. if KMMemberInfo.shared.isMemberAllFunction == false {
  1075. let winC = KMProductCompareWC.shared
  1076. winC.kEventName = "Reading_DigitalSign_BuyNow"
  1077. KMMemberInfo.shared.advancedFunctionUsage()
  1078. return
  1079. }
  1080. if hasShowDigitalSign() {
  1081. self.exitDigitalSign()
  1082. }
  1083. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  1084. var password: String = ""
  1085. self.toolbarController.toolbarType = .None
  1086. // if digitalSignController == nil {
  1087. password = listView.document?.password ?? ""
  1088. digitalSignController = KMPDFDigitalSignViewController()
  1089. // }
  1090. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  1091. digitalSignController?.url = listView.document?.documentURL
  1092. digitalSignController?.password = password
  1093. digitalSignController?.scaleFactor = listView.scaleFactor
  1094. digitalSignController?.titleChangeBlock = { title, index in
  1095. currentPageIndex = UInt(index)
  1096. }
  1097. digitalSignController?.buttonActionBlock = { [weak self] type, isChanged in
  1098. if type == .cancel {
  1099. if let page = self?.listView?.document?.page(at: currentPageIndex) {
  1100. self?.listView.go(to: page)
  1101. }
  1102. self?.exitDigitalSign()
  1103. }
  1104. }
  1105. if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
  1106. digitalSignView.frame = splitViewSuperview.bounds
  1107. digitalSignView.autoresizingMask = [.width, .height]
  1108. splitViewSuperview.addSubview(digitalSignView)
  1109. digitalSignController?.setCurrentPageIndex(Int(currentPageIndex))
  1110. }
  1111. }
  1112. // MARK: - Toolbar
  1113. func toolbarItemClickForExitMode(_ toolbarItem: KMToolbarItemView) {
  1114. if(toolbarItem.itemIdentifier != KMDocumentPageToolbarItemIdentifier) {
  1115. if (hasEnterPageEdit()) {
  1116. self.exitPageEdit()
  1117. }
  1118. }
  1119. if toolbarItem.itemIdentifier != KMDocumentRedactToolbarItemIdentifier {
  1120. if self.hasEnterRedact() {
  1121. self.exitRedact()
  1122. }
  1123. }
  1124. if toolbarItem.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  1125. if self.hasShowDigitalSign() {
  1126. self.exitDigitalSign()
  1127. }
  1128. }
  1129. if toolbarItem.itemIdentifier != KMDocumentEditToolbarItemIdentifier && toolbarItem.itemIdentifier != KMRightControlToolbarItemIdentifier && toolbarItem.itemIdentifier != KMLeftControlToolbarItemIdentifier {
  1130. // self.editPDFHanddler.clearData()
  1131. self.commitEditingIfNeed()
  1132. }
  1133. }
  1134. // MARK: - Private Methods
  1135. private func getPDFEditController() -> KMPDFEditViewController? {
  1136. var editController: KMPDFEditViewController?
  1137. for controller in self.children {
  1138. if (controller.isKind(of: KMPDFEditViewController.self)) {
  1139. editController = (controller as! KMPDFEditViewController)
  1140. break
  1141. }
  1142. }
  1143. return editController
  1144. }
  1145. private func _getPDFRedactController() -> KMPDFRedactViewController? {
  1146. var controller: KMPDFRedactViewController?
  1147. for childC in self.children {
  1148. if (childC.isKind(of: KMPDFRedactViewController.self)) {
  1149. controller = (childC as! KMPDFRedactViewController)
  1150. break
  1151. }
  1152. }
  1153. return controller
  1154. }
  1155. private func addBackgroundMaskView() {
  1156. self.removeBackgroundMaskView()
  1157. if let superview = self.mianSplitView.superview {
  1158. let view = NSView()
  1159. superview.addSubview(view)
  1160. view.frame = superview.bounds
  1161. view.autoresizingMask = [.width, .height]
  1162. view.wantsLayer = true
  1163. view.layer?.backgroundColor = .white
  1164. self.background_mask = view
  1165. }
  1166. }
  1167. private func removeBackgroundMaskView() {
  1168. self.background_mask?.removeFromSuperview()
  1169. self.background_mask = nil
  1170. }
  1171. private func _goToFirstPageForFristAppear() {
  1172. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  1173. self.listView.go(toPageIndex: 0, animated: false)
  1174. }
  1175. }
  1176. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  1177. let url = URL(fileURLWithPath: filePath)
  1178. guard let document = PDFDocument(url: url) else {
  1179. return false
  1180. }
  1181. let pageCount = document.pageCount
  1182. return pageCount > 30
  1183. }
  1184. // MARK: - Redact 【标记密文】
  1185. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  1186. let windowController = KMRedactConfirmWindowController(type)
  1187. self.currentWindowController = windowController
  1188. self.view.window?.beginSheet(windowController.window!)
  1189. windowController.itemClick = { [weak self] index in
  1190. if (index == 2) { /// 取消
  1191. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1192. self?.currentWindowController = nil
  1193. callback()
  1194. return
  1195. }
  1196. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1197. self?.currentWindowController = nil
  1198. let panel = NSSavePanel()
  1199. panel.nameFieldStringValue = "[新文件]"+((self?.listView.document?.documentURL.lastPathComponent) ?? "")
  1200. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  1201. button.state = .on
  1202. panel.accessoryView = button
  1203. panel.isExtensionHidden = true
  1204. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  1205. if response != .OK {
  1206. callback()
  1207. return
  1208. }
  1209. if (type == .redactOne) {
  1210. let anno = self!.listView.activeAnnotation
  1211. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1212. callback()
  1213. return
  1214. }
  1215. (anno as! CPDFRedactAnnotation).applyRedaction()
  1216. } else if (type == .redactAll) {
  1217. self?.listView.document?.applyRedactions()
  1218. } else if (type == .eraserOne) {
  1219. let anno = self!.listView?.activeAnnotation
  1220. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1221. callback()
  1222. return
  1223. }
  1224. anno?.page.erasureRedact(from: anno!.bounds)
  1225. } else if (type == .eraserAll) {
  1226. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  1227. if (result == false) {
  1228. callback()
  1229. return
  1230. }
  1231. }
  1232. }
  1233. self!.listView.document?.write(to: panel.url)
  1234. if (button.state == .on) {
  1235. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  1236. }
  1237. } else {
  1238. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  1239. }
  1240. callback()
  1241. }
  1242. }
  1243. }
  1244. // MARK: - Secure 【安全】
  1245. public func showSecureLimitTip() {
  1246. self.hiddenSecureLimitTip()
  1247. if self.secureAlertView == nil {
  1248. self.secureAlertView = KMSecureAlertView()
  1249. self.secureAlertView?.show(in: self.listView)
  1250. self.secureAlertView?.closeAction = { [unowned self] view in
  1251. self.hiddenSecureLimitTip()
  1252. self.removeFromAlertView()
  1253. self.showFormAlertView()
  1254. }
  1255. self.secureAlertView?.passwordAction = { [unowned self] view in
  1256. self.removeOwnerPassword()
  1257. self.removeFromAlertView()
  1258. self.showFormAlertView()
  1259. }
  1260. }
  1261. }
  1262. func removeOwnerPassword() {
  1263. guard let doc = self.listView?.document else {
  1264. NSSound.beep()
  1265. return
  1266. }
  1267. if doc.allowsCopying && doc.allowsPrinting {
  1268. NSSound.beep()
  1269. return
  1270. }
  1271. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1272. if result == .cancel { /// 关闭
  1273. return
  1274. }
  1275. /// 解密成功
  1276. self?.hiddenSecureLimitTip()
  1277. self?.model.isSaveKeyChain = false
  1278. self?.listView.document?.unlock(withPassword: password)
  1279. }
  1280. }
  1281. public func hiddenSecureLimitTip() {
  1282. self.secureAlertView?.removeFromSuperview()
  1283. self.secureAlertView = nil
  1284. }
  1285. //MARK: - Form
  1286. func showFormAlertView() {
  1287. if (formAlertView == nil) {
  1288. formAlertView = KMFormAlertView()
  1289. formAlertView?.isCloseSecureView = self.secureAlertView != nil ? false : true
  1290. formAlertView?.showInView(self.listView)
  1291. } else {
  1292. self.removeFromAlertView()
  1293. }
  1294. }
  1295. func removeFromAlertView() {
  1296. formAlertView?.removeFromSuperview()
  1297. formAlertView = nil
  1298. }
  1299. override func mouseMoved(with event: NSEvent) {
  1300. self.view.window?.mouseMoved(with: event)
  1301. }
  1302. func savePageNumberIfNeed() {
  1303. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1304. let scaleFactor = self.listView?.scaleFactor ?? 0
  1305. if scaleFactor <= 0 {
  1306. return
  1307. }
  1308. if self.listView.document != nil {
  1309. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1310. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  1311. }
  1312. }
  1313. }
  1314. // MARK: - 显示合并窗口
  1315. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  1316. DispatchQueue.main.async {
  1317. var documentURL = url
  1318. if documentURL == nil {
  1319. documentURL = self.listView.document?.documentURL
  1320. }
  1321. guard let _url = documentURL else { return }
  1322. guard let document = PDFDocument(url: _url) else { return }
  1323. self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
  1324. self.mergeWindowController!.oriDucumentUrl = self.listView.document?.documentURL
  1325. self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  1326. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  1327. self.view.window?.endSheet(mergeWindowController!.window!)
  1328. }
  1329. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  1330. self.view.window?.endSheet(mergeWindowController!.window!)
  1331. }
  1332. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  1333. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  1334. }
  1335. }
  1336. // MARK: - 显示加密弹窗
  1337. public func showSecureWindow(_ url: URL) {
  1338. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1339. guard let securityWindowController = securityWindowController else { return }
  1340. securityWindowController.documentURL = self.listView.document?.documentURL
  1341. securityWindowController.batchAction = { [unowned self] controller, files in
  1342. self.view.window?.endSheet((securityWindowController.window)!)
  1343. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1344. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1345. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  1346. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  1347. batchWindowController.window?.makeKeyAndOrderFront("")
  1348. }
  1349. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  1350. let openPanel = NSOpenPanel()
  1351. openPanel.canChooseFiles = false
  1352. openPanel.canChooseDirectories = true
  1353. openPanel.canCreateDirectories = true
  1354. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1355. if result == NSApplication.ModalResponse.OK {
  1356. for fileURL in openPanel.urls {
  1357. let document = CPDFDocument(url: self.document?.documentURL)
  1358. if document != nil {
  1359. document!.setDocumentAttributes(attribute)
  1360. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1361. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1362. if success {
  1363. self.view.window?.endSheet((securityWindowController.window)!)
  1364. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1365. }
  1366. }
  1367. }
  1368. }
  1369. }
  1370. }
  1371. securityWindowController.cancelAction = { [unowned self] controller in
  1372. self.view.window?.endSheet((securityWindowController.window)!)
  1373. }
  1374. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  1375. }
  1376. // MARK: - 保存文档
  1377. internal func needSaveDocument() -> Bool {
  1378. if (self.isPDFDocumentEdited) {
  1379. return self.isPDFDocumentEdited
  1380. }
  1381. if (self.needSave) {
  1382. return self.needSave
  1383. }
  1384. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1385. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  1386. return false
  1387. }
  1388. return true
  1389. }
  1390. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  1391. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1392. if (overlook) {
  1393. document?.save(nil)
  1394. return
  1395. }
  1396. if (self.isPDFDocumentEdited) {
  1397. self.clearIsPDFDocumentEdited()
  1398. self.needSave = false
  1399. document?.save(nil)
  1400. return
  1401. }
  1402. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  1403. return
  1404. }
  1405. document?.save(nil)
  1406. }
  1407. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  1408. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1409. if (overlook) {
  1410. DispatchQueue.main.async {
  1411. document?.save(nil)
  1412. callback()
  1413. }
  1414. return
  1415. }
  1416. if (self.isPDFDocumentEdited) {
  1417. self.clearIsPDFDocumentEdited()
  1418. self.needSave = false
  1419. DispatchQueue.main.async {
  1420. document?.save(nil)
  1421. callback()
  1422. }
  1423. return
  1424. }
  1425. if (document?.isDocumentEdited == nil || document?.isDocumentEdited == false) {
  1426. callback()
  1427. return
  1428. }
  1429. DispatchQueue.main.async {
  1430. document?.save(nil)
  1431. callback()
  1432. }
  1433. }
  1434. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  1435. // 显示进度
  1436. AutoSaveManager.manager.isSaving = true
  1437. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  1438. self.progressC?.maxValue = 3.0
  1439. self.progressC?.increment(by: 1.0)
  1440. // 保存文档
  1441. self.asyncSaveDocument { [weak self] params in
  1442. // 执行进度 [假进度]
  1443. self?.progressC?.increment(by: 1.0)
  1444. self?.progressC?.increment(by: 1.0)
  1445. // DispatchQueue.main.async {
  1446. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  1447. // 隐藏进度
  1448. self?.hiddenProgressWindow()
  1449. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  1450. AutoSaveManager.manager.isSaving = false
  1451. }
  1452. // 回调
  1453. callback()
  1454. }
  1455. }
  1456. }
  1457. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  1458. self.document?.write(toFile: tempPath)
  1459. }
  1460. // MARK: - 定时保存
  1461. func addAutoSaveEvent() {
  1462. if (self.autoSaveTimer != nil) {
  1463. self.autoSaveTimer?.invalidate()
  1464. self.autoSaveTimer = nil
  1465. }
  1466. if self.document != nil {
  1467. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  1468. self?.autoSaveTimerAction(timer)
  1469. })
  1470. }
  1471. self.checkAutoSaveInfo()
  1472. }
  1473. func checkAutoSaveInfo() {
  1474. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  1475. return
  1476. }
  1477. if AutoSaveManager.manager.autoSaveAlertShow {
  1478. return
  1479. }
  1480. AutoSaveManager.manager.autoSaveDidEndAction = false
  1481. AutoSaveManager.manager.autoSaveAlertShow = true
  1482. let blockSaveWindow = AutoSavePopController()
  1483. blockSaveWindow.cancelHandle = { [weak self] windowController in
  1484. AutoSaveManager.manager.autoSaveDidEndAction = true
  1485. AutoSaveManager.manager.clearCache()
  1486. self?.km_quick_endSheet()
  1487. }
  1488. blockSaveWindow.confirmHandle = { [weak self] windowController in
  1489. self?.km_quick_endSheet()
  1490. self?.saveAutoSaveInfo()
  1491. }
  1492. self.km_beginSheet(windowC: blockSaveWindow)
  1493. }
  1494. func saveAutoSaveInfo() {
  1495. let openPanel = NSOpenPanel()
  1496. openPanel.canChooseDirectories = true
  1497. openPanel.canChooseFiles = false
  1498. openPanel.allowsMultipleSelection = false
  1499. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  1500. openPanel.beginSheetModal(for: win!) { result in
  1501. if (result == .OK) {
  1502. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  1503. for path in AutoSaveManager.manager.opendPaths ?? [] {
  1504. let _path = path as? String
  1505. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  1506. newPath = self.getValidFilePath(newPath)
  1507. do {
  1508. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  1509. } catch {
  1510. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  1511. }
  1512. }
  1513. AutoSaveManager.manager.clearCache()
  1514. }
  1515. AutoSaveManager.manager.autoSaveDidEndAction = true
  1516. }
  1517. }
  1518. func autoSaveTimerAction(_ timer: Timer) {
  1519. if (self.document == nil || self.listView?.document?.documentURL.path == nil) {
  1520. return
  1521. }
  1522. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1523. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1524. return
  1525. }
  1526. if let data = self.document?.isLocked, data {
  1527. return
  1528. }
  1529. if AutoSaveManager.manager.autoSaveEnabled == false {
  1530. return
  1531. }
  1532. let documentArray = NSDocumentController.shared.documents
  1533. var didFileEdit = false
  1534. for doc in documentArray {
  1535. if doc.fileURL?.path == self.document?.documentURL.path {
  1536. didFileEdit = doc.isDocumentEdited
  1537. break
  1538. }
  1539. }
  1540. if (didFileEdit == false) {
  1541. return
  1542. }
  1543. AutoSaveManager.manager.isSaving = true
  1544. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView?.document?.documentURL.path ?? "")
  1545. if (!self.document!.isLocked) {
  1546. self.document?.write(to: URL(fileURLWithPath: savePath))
  1547. }
  1548. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  1549. AutoSaveManager.manager.isSaving = false
  1550. }
  1551. }
  1552. func removeAutoSaveInfo() {
  1553. if self.autoSaveTimer != nil {
  1554. self.autoSaveTimer?.invalidate()
  1555. self.autoSaveTimer = nil
  1556. }
  1557. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1558. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1559. return
  1560. }
  1561. if AutoSaveManager.manager.autoSaveEnabled == false {
  1562. return
  1563. }
  1564. if self.document == nil || self.listView?.document?.documentURL.path == nil {
  1565. return
  1566. }
  1567. AutoSaveManager.manager.removeAutoSavePath(self.listView?.document?.documentURL.path ?? "")
  1568. }
  1569. // MARK: - 选择 PDFDisplay 模式
  1570. @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
  1571. let toolModel = self.listView.toolMode
  1572. self.isReadMode = false
  1573. switch display {
  1574. case .singlePage:
  1575. self.listView.setDisplay(.singlePage)
  1576. break
  1577. case .singlePageContinuous:
  1578. self.listView.setDisplay(.singlePageContinuous)
  1579. break
  1580. case .twoUp:
  1581. self.listView.setDisplay(.twoUp)
  1582. break
  1583. case .twoUpContinuous:
  1584. self.listView.setDisplay(.twoUpContinuous)
  1585. break
  1586. case .bookMode:
  1587. self.listView.displaysAsBook = true
  1588. self.listView.displayTwoUp = true
  1589. self.listView.displayDirection = .horizontal
  1590. break
  1591. case .bookContinuous:
  1592. self.listView.displaysAsBook = true
  1593. self.listView.displayTwoUp = true
  1594. self.listView.displayDirection = .vertical
  1595. break
  1596. case .readModel:
  1597. self.openReadModel()
  1598. break
  1599. case .readContinuous:
  1600. self.openReadModel()
  1601. break
  1602. }
  1603. self.listView.layoutDocumentView()
  1604. // if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
  1605. // self.leftSideViewController.panelSetViewController.reloadListViewModel()
  1606. // }
  1607. if (toolModel == .editPDFToolMode) {
  1608. if self.rightSideViewController.eidtPDFImageProperty != nil {
  1609. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  1610. self.rightSideViewController.isHidden = true
  1611. self.closeRightPane()
  1612. }
  1613. }
  1614. }
  1615. // MARK: - 选择缩放模式
  1616. @objc public func selectZoom(_ type: KMPDFZoomType) {
  1617. switch type {
  1618. case .width:
  1619. self.listView.autoScales = true
  1620. // self.listView.autoScales = false
  1621. break
  1622. case .fit:
  1623. // self.listView.autoScales = !self.listView.autoScales
  1624. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  1625. let pdfviewHeight = self.listView.bounds.size.height
  1626. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1627. self.listView.autoScales = false
  1628. }
  1629. break
  1630. case .actualSize:
  1631. if self.listView.scaleFactor != 1.0 {
  1632. self.listView.scaleFactor = 1.0
  1633. self.listView.autoScales = false
  1634. }
  1635. break
  1636. }
  1637. }
  1638. internal func createPdf(index:Int) {
  1639. if index == 1 {
  1640. self.homeVC?.openBlankPage()
  1641. } else if index == 4 {
  1642. self.homeVC?.importFromCamera()
  1643. } else if index == 5 {
  1644. self.homeVC?.importFromScanner()
  1645. } else if index == 3 {
  1646. self.homeVC?.importFromWebPage()
  1647. } else if index == 2 {
  1648. self.homeVC?.newFromImages()
  1649. }
  1650. }
  1651. // MARK - Event 监听
  1652. private func addEventMonitor() {
  1653. if (self.eventMonitor != nil) {
  1654. self.removeEventMonitor()
  1655. }
  1656. // KMPrint("已添加事件监听")
  1657. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: [.scrollWheel, .leftMouseDown]) { [weak self] event in
  1658. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  1659. self?.listView.magnifyWheel(event)
  1660. return nil
  1661. } else if event.type == .leftMouseDown {
  1662. let point = event.locationInView(self?.listView ?? NSView())
  1663. let presentationDrawView = self?.listView.presentationDrawView
  1664. if let data = self?.interactionMode, data == .presentation,CGRectContainsPoint(self?.listView.frame ?? .zero, point),presentationDrawView?.isHidden == true { // 幻灯片模式下
  1665. if point.x >= (self?.listView.frame.maxX ?? 0) / 2 {
  1666. let can = self?.listView?.canGoToNextPage() ?? false
  1667. if can {
  1668. self?.listView.goToNextPage(nil)
  1669. }
  1670. } else {
  1671. let can = self?.listView?.canGoToPreviousPage() ?? false
  1672. if can {
  1673. self?.listView.goToPreviousPage(nil)
  1674. }
  1675. }
  1676. return nil
  1677. }
  1678. }
  1679. return event
  1680. }
  1681. }
  1682. func addKeyEventMonitor() {
  1683. if (self.keyEventMonitor != nil) {
  1684. self.removeKeyEventMonitor()
  1685. }
  1686. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  1687. // print(event.keyCode)
  1688. if event.keyCode == 53 {
  1689. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1690. if let data = self?.canExitPresentation(), data {
  1691. let mainDocument = self?.myDocument as? KMMainDocument
  1692. let browserWindowController = mainDocument?.browser?.windowController as? KMBrowserWindowController
  1693. browserWindowController?.exitFullscreen()
  1694. }
  1695. return nil
  1696. }
  1697. if self?.listView.toolMode == .editPDFToolMode {
  1698. if self != nil {
  1699. //使用editingSelectionString获取内容文字
  1700. if self!.listView.editingAreas() != nil {
  1701. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  1702. self!.listView.clearEditingSelectCharItem()
  1703. } else if self!.listView.editingAreas().count > 0 {
  1704. if self?.listView.annotationType == .addImage ||
  1705. self?.listView.annotationType == .addText {
  1706. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1707. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1708. textItem?.isSelected = false
  1709. imageItem?.isSelected = false
  1710. }
  1711. self?.rightSideViewController.isHidden = true
  1712. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  1713. self?.listView.updateEditing([])
  1714. self?.listView.isEditImage = false
  1715. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  1716. if self?.listView.annotationType == .addImage {
  1717. self?.listView.change([.text, .image])
  1718. }
  1719. self?.listView.annotationType = .editTextImage
  1720. self?.closeRightPane()
  1721. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1722. if self?.listView.annotationType == .addImage ||
  1723. self?.listView.annotationType == .addText {
  1724. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1725. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1726. textItem?.isSelected = false
  1727. imageItem?.isSelected = false
  1728. }
  1729. self?.rightSideViewController.isHidden = true
  1730. self?.listView.setShouAddEdit([])
  1731. self?.listView.change([.text, .image])
  1732. self?.listView.annotationType = .editTextImage
  1733. self?.closeRightPane()
  1734. }
  1735. } else {
  1736. if self?.listView.annotationType == .addImage ||
  1737. self?.listView.annotationType == .addText {
  1738. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1739. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1740. textItem?.isSelected = false
  1741. imageItem?.isSelected = false
  1742. }
  1743. }
  1744. }
  1745. }
  1746. } else {
  1747. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1748. self?.listView.keyDown(with: event)
  1749. return nil
  1750. } else {
  1751. let cmd = event.modifierFlags.contains(.command)
  1752. let shift = event.modifierFlags.contains(.shift)
  1753. if event.keyCode == 6 { // z
  1754. let editPDFIng = self?.editPDFHanddler.isEditing ?? false
  1755. if cmd && shift { // 恢复
  1756. let can = self?.editPDFHanddler.listView?.canEditTextRedo() ?? false
  1757. if can == false {
  1758. return event
  1759. }
  1760. if editPDFIng {
  1761. _ = CustomAlertView.alertView(message: NSLocalizedString("Redo", comment: ""), fromView: self!.view, withStyle: .black)
  1762. // if let data = self?.listView.canEditTextRedo(), data {
  1763. // self?.listView.editTextRedo()
  1764. // }
  1765. }
  1766. } else if cmd { // 撤回
  1767. let can = self?.editPDFHanddler.listView?.canEditTextUndo() ?? false
  1768. if can == false {
  1769. return event
  1770. }
  1771. if editPDFIng {
  1772. _ = CustomAlertView.alertView(message: NSLocalizedString("Undo", comment: ""), fromView: self!.view, withStyle: .black)
  1773. // if let data = self?.listView.canEditTextUndo(), data {
  1774. // self?.listView.editTextUndo()
  1775. // }
  1776. }
  1777. }
  1778. }
  1779. }
  1780. }
  1781. return event
  1782. }
  1783. }
  1784. func removeKeyEventMonitor() {
  1785. if (self.keyEventMonitor != nil) {
  1786. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1787. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1788. self.keyEventMonitor = nil
  1789. }
  1790. }
  1791. private func removeEventMonitor() {
  1792. if (self.eventMonitor != nil) {
  1793. KMPrint("已移除事件监听")
  1794. NSEvent.removeMonitor(self.eventMonitor as Any)
  1795. self.eventMonitor = nil
  1796. }
  1797. }
  1798. // MARK: - Tools
  1799. func pdfViewCanHorizontalScroll() -> Bool {
  1800. let scroll = self.listView.scroll()
  1801. if (scroll == nil) {
  1802. return false
  1803. }
  1804. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1805. }
  1806. func pdfViewCanVerticalScroll() -> Bool {
  1807. let scroll = self.listView.scroll()
  1808. if (scroll == nil) {
  1809. return false
  1810. }
  1811. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1812. }
  1813. // MARK: - Public Methods
  1814. // 清理数据 [eg. 通知]
  1815. public func clearData() {
  1816. KMThumbnailCache.shared.clearCache()
  1817. self.removeNotifications()
  1818. if (self.listView.spellingTag() > 0) {
  1819. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1820. }
  1821. self.removeAutoSaveInfo()
  1822. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1823. self.myDocument = nil
  1824. }
  1825. public func clearSecureOptions() {
  1826. self._secureOptions = nil
  1827. self.documentAttribute = nil
  1828. }
  1829. public func recordRemoveSecureFlag() {
  1830. self._removeSecureFlag = true
  1831. self.clearSecureOptions()
  1832. self.recordIsPDFDocumentEdited(type: .removePassword)
  1833. self._needSave = true
  1834. }
  1835. public func clearRemoveSecureFlag() {
  1836. self._removeSecureFlag = false
  1837. }
  1838. public func clearSaveWatermarkFlag() {
  1839. km_synchronized(self) {
  1840. self._saveWatermarkFlag = false
  1841. }
  1842. }
  1843. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1844. km_synchronized(self) {
  1845. self.model.isPDFDocumentEdited = true
  1846. if type == .editText || type == .editImage {
  1847. self.leftSideViewController.updateThumbnail(at: self.listView.currentPageIndex)
  1848. }
  1849. if let _document = self.myDocument {
  1850. KMTools.setDocumentEditedState(document: _document)
  1851. }
  1852. }
  1853. }
  1854. public func clearIsPDFDocumentEdited() {
  1855. km_synchronized(self) {
  1856. self.model.isPDFDocumentEdited = false
  1857. }
  1858. }
  1859. func showSnapshots(setups: NSArray?) {
  1860. if self.listView.document != nil {
  1861. for setup in setups ?? [] {
  1862. let swc = KMSnapshotWindowController()
  1863. swc.delegate = self
  1864. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  1865. swc.setForceOnTop(self.interactionMode != .normal)
  1866. self.myDocument?.addWindowController(swc)
  1867. }
  1868. }
  1869. }
  1870. func dealDocumentDidLoaded() {
  1871. self.removeBackgroundMaskView()
  1872. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1873. self.showSecureLimitTip()
  1874. }
  1875. // let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  1876. // if readModel == true {
  1877. // self.openReadModel()
  1878. // }
  1879. if self.model.needConvertNotes {
  1880. self.showConvertNotesProgress()
  1881. }
  1882. if (self._documentFirstLoad) {
  1883. self.checkShouldAutoOpenLeftVC()
  1884. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1885. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document?.documentURL.path ?? "")
  1886. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document?.documentURL.path ?? "")
  1887. if (pageScale != nil) {
  1888. self.listView.scaleFactor = CGFloat(pageScale!)
  1889. }
  1890. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < (self.listView.document?.pageCount ?? 0)) {
  1891. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1892. } else {
  1893. self._goToFirstPageForFristAppear()
  1894. }
  1895. } else {
  1896. self._goToFirstPageForFristAppear()
  1897. }
  1898. self._documentFirstLoad = false
  1899. }
  1900. }
  1901. func tabViewIsDragging() -> Bool {
  1902. let level = self.view.window?.level ?? .normal
  1903. return level == .floating
  1904. }
  1905. // MARK: - Noti Actions
  1906. internal func documentDidUnlockNotification(_ sender: Notification) {
  1907. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1908. if (self.myDocument == nil) {
  1909. return
  1910. }
  1911. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1912. self.hiddenSecureLimitTip()
  1913. }
  1914. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  1915. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  1916. return
  1917. }
  1918. let type = KMPreferenceManager.shared.savePasswordType
  1919. if (type == .never) {
  1920. return
  1921. }
  1922. if (type == .always) {
  1923. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1924. return
  1925. }
  1926. // 保存到钥匙串
  1927. let alert = NSAlert()
  1928. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1929. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1930. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1931. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1932. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1933. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1934. return
  1935. }
  1936. }
  1937. }
  1938. func annotationsAttributeHasChange(_ sender: Notification) {
  1939. guard let dict = sender.object as? [String : Any] else {
  1940. return
  1941. }
  1942. if let anno = dict["object"] as? CPDFAnnotation {
  1943. let value = dict["keyPath"] as? String ?? ""
  1944. let didEnd = dict["didEnd"] as? Bool ?? false
  1945. if didEnd {
  1946. if value == CPDFAnnotationBoundsKey {
  1947. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  1948. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  1949. }
  1950. }
  1951. if anno.km_isMeasure() && anno.contents == nil {
  1952. anno.contents = anno.string() ?? ""
  1953. }
  1954. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1955. } else {
  1956. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  1957. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1958. }
  1959. }
  1960. }
  1961. }
  1962. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1963. self.savePageNumberIfNeed()
  1964. self.saveDocument()
  1965. }
  1966. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1967. if self.isReadMode {
  1968. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1969. }
  1970. //刷新前一页后一页按钮
  1971. self.updateNextAndPreViousButtonState()
  1972. }
  1973. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1974. if self.isReadMode {
  1975. self.readModelView.totalPagesCount = Int(self.listView.document?.pageCount ?? 0)
  1976. }
  1977. //刷新前一页后一页按钮
  1978. self.updateNextAndPreViousButtonState()
  1979. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(nil, attributes: nil)
  1980. }
  1981. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1982. var editSelectd = false
  1983. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1984. editSelectd = true
  1985. }
  1986. if self.listView.toolMode == .editPDFToolMode {
  1987. if editSelectd {
  1988. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1989. }
  1990. }
  1991. }
  1992. @objc func handlePageChangedNotification(_ sender: Notification) {
  1993. // When the PDFView is changing scale, or when view settings change when switching fullscreen modes,
  1994. // a lot of wrong page change notifications may be send, which we better ignore.
  1995. // Full screen switching and zooming should not change the current page anyway.
  1996. if self.mwcFlags.isSwitchingFullScreen > 0 {
  1997. // if ([pdfView isZooming] || mwcFlags.isSwitchingFullScreen) {
  1998. // [self updatePageNumber];
  1999. // [self updateLeftStatus];
  2000. return
  2001. }
  2002. //
  2003. let page = self.listView.currentPage()
  2004. let pageIndex = page?.pageIndex() ?? 0
  2005. //
  2006. // if ([lastViewedPages count] == 0) {
  2007. // [lastViewedPages addPointer:(void *)pageIndex];
  2008. // } else if ((NSUInteger)[lastViewedPages pointerAtIndex:0] != pageIndex) {
  2009. // [lastViewedPages insertPointer:(void *)pageIndex atIndex:0];
  2010. // if ([lastViewedPages count] > 5)
  2011. // [lastViewedPages setCount:5];
  2012. // }
  2013. self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
  2014. self.leftSideViewController.thumbnailTableView.needsDisplay = true
  2015. self.leftSideViewController.tocOutlineView.needsDisplay = true
  2016. //
  2017. // [self updatePageNumber];
  2018. // [self updatePageLabel];
  2019. //
  2020. // [self updateOutlineSelection];
  2021. // [self updateNoteSelection];
  2022. // [self updateThumbnailSelection];
  2023. //
  2024. // if (beforeMarkedPageIndex != NSNotFound && [[pdfView currentPage] pageIndex] != markedPageIndex)
  2025. // beforeMarkedPageIndex = NSNotFound;
  2026. //
  2027. // [self synchronizeWindowTitleWithDocumentName];
  2028. // [self updateLeftStatus];
  2029. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  2030. // [self updateRightStatus];
  2031. // if ([self interactionMode] == SKPresentationMode)
  2032. // [[self presentationNotesDocument] setCurrentPage:[[[self presentationNotesDocument] pdfDocument] pageAtIndex:[page pageIndex]]];
  2033. }
  2034. @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
  2035. self.leftSideViewController.reloadThumbnailDataIfNeed()
  2036. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  2037. // [self updateRightStatus];
  2038. }
  2039. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  2040. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  2041. return
  2042. }
  2043. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  2044. if interactionMode == .presentation {
  2045. let backgroundColor = NSColor.black
  2046. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  2047. let wasInteractionMode = self.interactionMode
  2048. if wasInteractionMode == .normal {
  2049. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  2050. }
  2051. // if findController.view().window() != nil {
  2052. // findController.toggleAboveView(nil, animate: false)
  2053. // }
  2054. if wasInteractionMode == .legacyFullScreen {
  2055. self.enterPresentationMode()
  2056. // updatePresentationOptions(for: self.view.window!)
  2057. self.pdfSplitView.frame = CGRect(x: 0, y: 0, width: NSWidth(centerContentView.bounds), height: NSHeight(centerContentView.bounds)-1)
  2058. self.centerContentView.addSubview(pdfSplitView)
  2059. self.listView.frame = (self.view.window?.contentView?.bounds)!
  2060. self.view.window?.contentView?.addSubview(listView)
  2061. self.view.window?.backgroundColor = backgroundColor
  2062. self.view.window?.level = level
  2063. self.listView.layoutDocumentView()
  2064. self.listView.requiresDisplay()
  2065. self.forceSubwindowsOnTop(false)
  2066. self.hideLeftSideWindow()
  2067. self.hideRightSideWindow()
  2068. self.removeBlankingWindows()
  2069. }
  2070. } else {
  2071. KMPrint("2")
  2072. }
  2073. }
  2074. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  2075. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  2076. return
  2077. }
  2078. if self.interactionMode == .presentation {
  2079. // if self.pdfView().currentPage()?.isEqual(page) == false {
  2080. // self.pdfView().go(to: page)
  2081. // }
  2082. // pdfView().setInteractionMode(SKPresentationMode)
  2083. self.listView?.layoutDocumentView()
  2084. self.listView?.requiresDisplay()
  2085. }
  2086. }
  2087. @objc func willShowFullScreenNotification(_ sender: Notification) {
  2088. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  2089. return
  2090. }
  2091. if self.interactionMode == .presentation {
  2092. let view = self.view.window?.firstResponder as? NSView
  2093. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  2094. self.view.window?.makeFirstResponder(nil)
  2095. }
  2096. }
  2097. }
  2098. @objc func didShowFullScreenNotification(_ sender: Notification) {
  2099. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  2100. return
  2101. }
  2102. if self.interactionMode == .presentation {
  2103. self.enterPresentationMode()
  2104. }
  2105. }
  2106. @objc func didAddContentViewNotification(_ sender: Notification) {
  2107. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  2108. return
  2109. }
  2110. if self.interactionMode == .presentation {
  2111. }
  2112. }
  2113. @objc func purchaseStateUpdateNoti() {
  2114. if KMMemberInfo.shared.isMemberAllFunction {
  2115. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  2116. }
  2117. }
  2118. //!!!: - CPDFFreeTextAnnotation 空注释时会删除,删除时sdk内部删除的,只能接受通知来刷选UI【正常的注释删除会走两遍】
  2119. @objc func didRemoveAnnotationNotification(_ sender: Notification) {
  2120. guard let anno = sender.object as? CPDFAnnotation else {
  2121. return
  2122. }
  2123. if anno.page?.document != self.listView.document {
  2124. return
  2125. }
  2126. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: [anno], page: anno.page)
  2127. }
  2128. // MARK: Split View
  2129. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  2130. let openPanel = NSOpenPanel()
  2131. openPanel.allowedFileTypes = ["pdf", "PDF"]
  2132. openPanel.allowsMultipleSelection = false
  2133. guard let mainWindow = NSApp.mainWindow else {
  2134. return
  2135. }
  2136. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  2137. if response == NSApplication.ModalResponse.OK {
  2138. guard let url = openPanel.url else {
  2139. return
  2140. }
  2141. if let document = CPDFDocument(url: url) {
  2142. self?.secondaryPdfView?.document = nil
  2143. self?.secondaryPdfView?.document = document
  2144. if isChange {
  2145. self!.openSecondaryPdfView!.view.removeFromSuperview()
  2146. }
  2147. replaceBlock(document.documentURL?.path ?? "")
  2148. } else {
  2149. let alert = NSAlert()
  2150. alert.alertStyle = .critical
  2151. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  2152. alert.runModal()
  2153. }
  2154. }
  2155. }
  2156. }
  2157. }
  2158. extension KMMainViewController {
  2159. func currentSetup() -> [String: Any] {
  2160. var setup: [String: Any] = [:]
  2161. var point = NSZeroPoint
  2162. // var rotated = listView.currentPage().rotation
  2163. if listView == nil {
  2164. return setup
  2165. }
  2166. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  2167. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  2168. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  2169. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  2170. setup[KMMainModel.Key.pageIndex] = pageIndex
  2171. // if rotated != 0 {
  2172. // setup[SCROLLPOINT_KEY] = NSStringFromPoint(point)
  2173. // }
  2174. // if !snapshots.isEmpty {
  2175. // setup[SNAPSHOTS_KEY] = snapshots.map { $0[SKSnapshotCurrentSetupKey] }
  2176. // }
  2177. // if interactionMode == SKNormalMode {
  2178. // setup.merge(currentPDFSettings(), uniquingKeysWith: { $1 })
  2179. // } else {
  2180. // setup.merge(savedNormalSetup, uniquingKeysWith: { $1 })
  2181. // ["HASHORIZONTALSCROLLER_KEY", "HASVERTICALSCROLLER_KEY", "AUTOHIDESSCROLLERS_KEY", "LOCKED_KEY"].forEach { setup.removeValue(forKey: $0) }
  2182. // }
  2183. return setup
  2184. }
  2185. // MARK: - Recommond活动
  2186. func loadRecommondPopWindow() {
  2187. if KMMemberInfo.shared.isMemberAllFunction {
  2188. return
  2189. }
  2190. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  2191. if recommondPopWindowVC == nil {
  2192. recommondPopWindowVC = KMRecommondPopWindow.default()
  2193. }
  2194. recommondPopWindowVC?.recommondInfo = info
  2195. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  2196. return
  2197. }
  2198. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  2199. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  2200. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  2201. recommondPopWindowVC?.window?.orderFront((Any).self)
  2202. recommondPopWindowVC?.window?.becomeMain()
  2203. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  2204. UserDefaults.standard.synchronize()
  2205. }
  2206. }
  2207. }
  2208. extension KMMainViewController {
  2209. func changeFont(_ sender: NSFontManager) {
  2210. KMPrint("changeFont ...")
  2211. if let annotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  2212. var font = NSFont(name: annotation.fontName() ?? "Helvetica", size: (annotation.fontSize()) )
  2213. font = sender.convert(font!)
  2214. annotation.fontSize = font?.pointSize ?? 12
  2215. self.listView.commitEditAnnotationFreeText(annotation)
  2216. self.listView.setNeedsDisplay(annotation)
  2217. // self.listView.setNeedsDisplayAnnotationViewFor(annotation.page)
  2218. }
  2219. }
  2220. }