KMMainViewController.swift 105 KB

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