KMMainViewController.swift 103 KB

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