KMMainViewController.swift 106 KB

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