KMMainViewController.swift 108 KB

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