KMMainViewController.swift 106 KB

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