KMMainViewController.swift 105 KB

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