KMMainViewController.swift 106 KB

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