KMMainViewController.swift 97 KB

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