KMMainViewController.swift 105 KB

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