KMMainViewController.swift 106 KB

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