KMMainViewController.swift 105 KB

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