KMMainViewController.swift 106 KB

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