KMMainViewController.swift 107 KB

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