KMMainViewController.swift 107 KB

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