KMMainViewController.swift 111 KB

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