KMMainViewController.swift 104 KB

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