KMMainViewController.swift 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. @objcMembers class KMMainViewController: KMBaseViewController, NSTextFieldDelegate,KMPresentationTopViewControllerDelegate {
  9. @IBOutlet var PDFContendView: NSView!
  10. @IBOutlet var centerContentView: NSView!
  11. @IBOutlet var listView: CPDFListView!
  12. @IBOutlet var secondaryPdfView: KMSecondaryPDFView?
  13. @IBOutlet weak var readContentView: NSView!
  14. @IBOutlet weak var tipCurrentPageBox: KMBox!
  15. @IBOutlet weak var rightView: NSView!
  16. @IBOutlet weak var leftView: NSView!
  17. @IBOutlet weak var mianSplitView: KMSplitView!
  18. @IBOutlet weak var pdfSplitView: KMSplitView!
  19. @IBOutlet weak var newPDFSplitView: KMSplitView!
  20. @IBOutlet weak var pdfContentView: NSView!
  21. @IBOutlet weak var pdfSplitSecondView: NSBox!
  22. @IBOutlet weak var locationPageView: NSView!
  23. @IBOutlet weak var tipLabel: NSTextField!
  24. @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
  25. @IBOutlet var childToolbarController: KMToolbarViewController!
  26. @IBOutlet var toolbarController: KMToolbarController!
  27. @IBOutlet weak var toolbarBox: NSBox!
  28. @IBOutlet weak var heightOffset: NSLayoutConstraint!
  29. //阅读模式界面
  30. @IBOutlet weak var readModelView: KMReadModelView!
  31. @IBOutlet weak var bottomAreaView: KMBox!
  32. @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
  33. //页码显示器
  34. @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
  35. @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
  36. @IBOutlet weak var topTipBox: NSBox!
  37. @IBOutlet weak var exitFullButton: NSButton!
  38. var model = KMMainModel()
  39. var isReadMode: Bool = false
  40. var readAlertView: CustomAlertView?
  41. var readLeftMethodType: BotaType = .None
  42. var readLeftPanelOpen = false
  43. var readLastLeftPanWidth = 0.0
  44. var readLeftViewShowPanel = false
  45. var readRightPanelOpen = false
  46. var readToolbarType: KMToolbarViewType = .None
  47. var readToolbarItemIdentifier: String = ""
  48. var readToolMode: CToolMode = .textToolMode
  49. var readAnnotationType: CAnnotationType = .unkown
  50. var readSubViewType: RightSubViewType = .None
  51. //自动滚动
  52. var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
  53. //Search
  54. var searchIndex: Int = 0
  55. //Form
  56. var formAlertView: KMFormAlertView?
  57. //Secure
  58. var secureAlertView: KMSecureAlertView?
  59. //对比
  60. var isCompareModel: Bool = false {
  61. didSet {
  62. self.toolbarController.updataItemVisible()
  63. }
  64. }
  65. //合并
  66. var mergeWindowController: KMMergeWindowController?
  67. //水印
  68. var watermarkWindowController: KMWatermarkWindowController?
  69. //密码弹窗
  70. var passwordWindow: KMPasswordInputWindow?
  71. //对比
  72. var compressWIndowControllerNew: KMCompressWIndowControllerNew?
  73. //
  74. var securityWindowController: KMSecurityWindowController?
  75. //引导
  76. var guideInfoWindowController: KMGuideInfoWindowController?
  77. var presentationTopViewController: KMPresentationTopViewController?
  78. //春季活动
  79. var recommondPopWindowVC: KMRecommondPopWindow?
  80. private var _needSave = false
  81. var needSave: Bool {
  82. set {
  83. _needSave = newValue
  84. if (_needSave == false) {
  85. self.clearIsPDFDocumentEdited()
  86. }
  87. }
  88. get {
  89. return _needSave
  90. }
  91. }
  92. var isPDFDocumentEdited: Bool {
  93. get {
  94. return self.model.isPDFDocumentEdited
  95. }
  96. }
  97. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  98. var rightSideViewController: KMRightSideViewController!
  99. var searchResults: [KMSearchMode] = []
  100. var mwcFlags: MwcFlags = MwcFlags()
  101. var document: CPDFDocument?
  102. var myDocument: NSDocument?
  103. weak var browserWindowController: KMBrowserWindowController? //慎直接使用这个方法
  104. var cropSettingWindowController: KMCropSettingWindowController!
  105. var currentWindowController: NSWindowController!
  106. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  107. //数字签名
  108. var digitalSignController: KMPDFDigitalSignViewController?
  109. var redactController: KMPDFRedactViewController!
  110. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  111. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  112. var extract: KMExtractImageWindowController?
  113. var functionWidth: Double {
  114. get {
  115. if self.isReadMode {
  116. if !self.model.isShowBOTA {
  117. return 0
  118. }
  119. }
  120. return 48-4
  121. }
  122. }
  123. var pageNumber: UInt?
  124. var openSecondaryPdfView: KMSecondaryViewController?
  125. var secondaryPdfContentView: NSView?
  126. var lastSplitPDFHeight: Float = 0.0
  127. var pdfEditController: KMPDFEditViewController? {
  128. get {
  129. return self.getPDFEditController()
  130. }
  131. }
  132. var autoSaveTimer: Timer?
  133. private var _documentFirstLoad: Bool = true
  134. var eventMonitor: Any?
  135. var keyEventMonitor: Any?
  136. var mouseRightMenuEvent: NSEvent?
  137. var aiTranslationWindow: KMAITranslationWindowController?
  138. var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
  139. lazy private var homeVC: KMHomeViewController? = {
  140. let vc = KMHomeViewController()
  141. return vc
  142. }()
  143. private var background_mask: NSView?
  144. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  145. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  146. get {
  147. return self._secureOptions
  148. }
  149. }
  150. var documentAttribute: [CPDFDocumentAttribute : Any]?
  151. fileprivate var _removeSecureFlag = false
  152. var removeSecureFlag: Bool {
  153. get {
  154. return self._removeSecureFlag
  155. }
  156. }
  157. fileprivate var _saveWatermarkFlag = false
  158. var saveWatermarkFlag: Bool {
  159. get {
  160. return self._saveWatermarkFlag
  161. }
  162. }
  163. private var mainWindow_: NSWindow?
  164. var mainWindow: NSWindow? {
  165. get {
  166. return self.mainWindow_
  167. }
  168. set {
  169. self.mainWindow_ = newValue
  170. }
  171. }
  172. let editPDFHanddler = KMEditPDfHanddler()
  173. var distanceMeasureInfoWindowController: CDistanceMeasureInfoWindowController?
  174. var perimeterMeasureInfoWindowController: CPerimeterMeasureInfoWindowController?
  175. var areaMeasureInfoWindowController: CAreaMeasureInfoWindowController?
  176. var srHanddler: KMSearchReplaceHanddler = KMSearchReplaceHanddler()
  177. deinit {
  178. let fontManager = NSFontManager.shared
  179. fontManager.target = nil
  180. NotificationCenter.default.removeObserver(self)
  181. self.listView.delegate = nil
  182. self.listView.document?.delegate = nil
  183. self.editPDFHanddler.clearData()
  184. self.removeEventMonitor()
  185. self.removeKeyEventMonitor()
  186. }
  187. override func awakeFromNib() {
  188. super.awakeFromNib()
  189. self.addBackgroundMaskView()
  190. self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
  191. listView.delegate = self
  192. listView.pdfListViewDelegate = self
  193. // listView.editingConfig().isSupportMultipleSelectEditingArea = true
  194. if (document != nil) {
  195. // if (self.document!.isLocked) {
  196. //
  197. // } else {
  198. // }
  199. // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  200. self.listView.document = self.document
  201. self.listView.document?.delegate = self
  202. // }
  203. let autoScale = listView.autoScales
  204. if !autoScale {
  205. listView.scaleFactor = 1.0
  206. }
  207. }
  208. self.initPDFLeftViewVC()
  209. self.initRightSideView()
  210. self.toolbarController.listView = self.listView
  211. self.toolbarController.mainViewController = self
  212. self.leftSideViewController.mainViewController = self
  213. self.newPDFSplitView.delegate = self
  214. }
  215. override func viewDidAppear() {
  216. super.viewDidAppear()
  217. //春季活动
  218. if KMAdvertisementManager.manager.appClosedCount == 1 {
  219. if ((KMAdvertisementManager.manager.info.popWindowContent) != nil) {
  220. if KMAdvertisementManager.manager.info.popWindowContent!.content!.count > 0 {
  221. let info = KMAdvertisementManager.manager.info.popWindowContent!.content?.first
  222. if KMAdvertisementManager.checkAdvertisementValid(info!) {
  223. self.loadRecommondPopWindow()
  224. }
  225. }
  226. }
  227. KMAdvertisementManager.manager.appClosedCount = 2
  228. }
  229. //刷新前一页后一页按钮
  230. self.updateNextAndPreViousButtonState()
  231. KMLightMemberManager.manager.canShowAdvancedView = false
  232. // Task { @MainActor in
  233. // await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
  234. // }
  235. self.addEventMonitor()
  236. self.view.window?.makeFirstResponder(self.listView)
  237. // 更新属性页面的信息
  238. NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
  239. self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
  240. if (self.document == nil) {
  241. return
  242. }
  243. if (self.document == nil || self.document!.isLocked == false) {
  244. self.loadFunctionGuide()
  245. }
  246. if (self.document?.isLocked == false) {
  247. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  248. self.showConvertNotesProgress()
  249. }
  250. return
  251. }
  252. if (self.view.window == nil) {
  253. return
  254. }
  255. if (self.model.password != nil) {
  256. if let data = self.listView.document?.unlock(withPassword: self.model.password), data {
  257. self.model.isSaveKeyChain = false
  258. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  259. self.showConvertNotesProgress()
  260. }
  261. return
  262. }
  263. }
  264. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  265. if self.view.window != nil && self.tabViewIsDragging() == false {
  266. self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [weak self] result , password in
  267. if (result == .cancel) {
  268. // self.browserWindowController?.browser?.closeTab()
  269. (self?.myDocument as? KMMainDocument)?.browser?.closeTab()
  270. return
  271. }
  272. self?.model.isSaveKeyChain = true
  273. self?.listView?.document = self?.document
  274. self?.document?.unlock(withPassword: password)
  275. }
  276. } else {
  277. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  278. self.showConvertNotesProgress()
  279. }
  280. }
  281. }
  282. }
  283. override func viewWillDisappear() {
  284. super.viewWillDisappear()
  285. if self.interactionMode != .presentation {
  286. self.removeEventMonitor()
  287. }
  288. self.editPDFHanddler.hiddenWindows()
  289. }
  290. override func viewWillLayout() {
  291. super.viewWillLayout()
  292. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  293. self.exitFullButton.isHidden = false
  294. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  295. } else {
  296. self.exitFullButton.isHidden = true
  297. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  298. }
  299. if let guideWC = self.guideInfoWindowController{
  300. var rect = self.view.window!.frame
  301. rect.size.height -= 20
  302. guideWC.window?.setFrame(rect, display: false)
  303. guideWC.window?.minSize = rect.size
  304. guideWC.window?.maxSize = rect.size
  305. guideWC.show()
  306. }
  307. }
  308. override func viewDidLoad() {
  309. super.viewDidLoad()
  310. mwcFlags.settingUpWindow = 1
  311. toolbarController.delegate = self
  312. self.editPDFHanddler.viewC = self
  313. self.srHanddler.pdfView = self.listView
  314. //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
  315. toolbarBox.contentView = toolbarController.view
  316. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  317. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  318. UserDefaults.standard.synchronize()
  319. }
  320. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  321. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  322. UserDefaults.standard.synchronize()
  323. }
  324. let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
  325. mianSplitView.setPosition(position, ofDividerAt: 0)
  326. mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0)
  327. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0)
  328. self.locationPageView.wantsLayer = true;
  329. self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
  330. self.tipLabel.stringValue = NSLocalizedString("Please use the scroll bar, thumbnail tool to locate the target page, click or box the area to select the target range.", comment: "")
  331. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  332. if (self.listView.document != nil) {
  333. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document?.documentURL.path ?? "")
  334. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document?.documentURL.path ?? "")
  335. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < (self.listView.document?.pageCount ?? 0)) {
  336. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  337. if (pageScale != nil) {
  338. self.listView.scaleFactor = CGFloat(pageScale!)
  339. }
  340. self.listView.go(toPageIndex: pageNumber!, animated: false)
  341. }
  342. } else {
  343. self._goToFirstPageForFristAppear()
  344. }
  345. }
  346. } else {
  347. self._goToFirstPageForFristAppear()
  348. }
  349. //阅读页面
  350. readModelView.delegate = self
  351. pageNumberDisplayView.delegate = self
  352. tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
  353. if !isReadMode {
  354. if mouseEntered {
  355. self.pageNumberDisplayView.hover = true
  356. } else {
  357. self.pageNumberDisplayView.hover = false
  358. }
  359. }
  360. }
  361. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  362. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  363. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  364. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  365. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  366. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  367. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  368. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  369. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  370. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  371. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.listView)
  372. NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayBoxChangedNotification), name: NSNotification.Name.CPDFViewDisplayBoxChanged, object: self.listView)
  373. // 互动模式
  374. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  375. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  376. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  377. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  378. NotificationCenter.default.addObserver(self, selector: #selector(didAddContentViewNotification), name: NSWindow.didAddContentViewNotification, object: nil)
  379. NotificationCenter.default.addObserver(self, selector: #selector(addAutoSaveEvent), name: AutoSaveManager.kTimeValueChangedNotificationName, object: nil)
  380. NotificationCenter.default.addObserver(self, selector: #selector(didRemoveAnnotationNotification), name: NSNotification.Name.CPDFPageDidRemoveAnnotation, object: nil)
  381. Task {
  382. self.addAutoSaveEvent()
  383. }
  384. self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
  385. self.closeRightPane()
  386. self.addKeyEventMonitor()
  387. self.addAdsBannerView()
  388. //检测OCR包是否需要更新
  389. #if VERSION_DMG
  390. // KMResourceDownloadManager.manager.checkDocumentAIVersion()
  391. #endif
  392. // Open snapshots?
  393. var snapshotSetups: NSArray?
  394. // if (hasWindowSetup)
  395. // snapshotSetups = [savedNormalSetup objectForKey:SNAPSHOTS_KEY];
  396. // else if ([sud boolForKey:SKRememberSnapshotsKey])
  397. if KMPreferenceManager.shared.rememberSnapshot {
  398. // snapshotSetups = [[SKBookmarkController sharedBookmarkController] snapshotsForRecentDocumentAtURL:[(NSDocument *)[self document] fileURL]];
  399. if let fileUrl = (self.myDocument as? KMMainDocument)?.fileURL {
  400. snapshotSetups = SKBookmarkController.shared().snapshotsForRecentDocument(at: fileUrl) as NSArray?
  401. }
  402. }
  403. if let cnt = snapshotSetups?.count, cnt > 0 {
  404. if let data = self.listView?.document?.isLocked, data {
  405. self.savedNormalSetup.setObject(snapshotSetups as Any, forKey: "snapshots" as NSCopying)
  406. } else {
  407. self.showSnapshots(setups: snapshotSetups)
  408. }
  409. }
  410. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  411. if readModel == true {
  412. self.openReadModel()
  413. }
  414. let hasWindowSetup = savedNormalSetup.count > 0
  415. if UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey) != nil {
  416. let pdfSettings: NSDictionary = hasWindowSetup ? savedNormalSetup : UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey)! as NSDictionary
  417. self.applyPDFSettings(pdfSettings)
  418. } else {
  419. self.applyPDFSettings(savedNormalSetup)
  420. }
  421. //文字
  422. let fontManager = NSFontManager.shared
  423. fontManager.target = self
  424. fontManager.action = #selector(changeFont(_:))
  425. }
  426. //MARK: - PDFListView
  427. func initPDFLeftViewVC() {
  428. var frame = self.leftView.frame
  429. frame.size.width += 44
  430. self.leftView.frame = frame
  431. leftSideViewController.isFirst = true
  432. leftSideViewController.listView = self.listView
  433. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  434. leftSideViewController.view.autoresizingMask = [.height,.width]
  435. leftSideViewController.delegate = self
  436. self.leftView.addSubview(leftSideViewController.view)
  437. }
  438. func initRightSideView() {
  439. self.rightSideViewController = KMRightSideViewController.init()
  440. self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
  441. self.rightSideViewController.view.autoresizingMask = [.height,.width]
  442. self.rightSideViewController.listView = self.listView
  443. // self.rightSideViewController.view.isHidden = true
  444. self.rightSideViewController.isHidden = true
  445. self.rightSideViewController.delegate = self
  446. self.rightView.addSubview(self.rightSideViewController.view)
  447. self.rightSideViewController.mainController = self
  448. self.rightSideViewController.propertyDidChange = { [weak self] model in
  449. if let anno = model as? CSelfSignAnnotation {
  450. self?.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: nil)
  451. }
  452. }
  453. }
  454. func addAdsBannerView() {
  455. #if VERSION_FREE
  456. if !KMMemberInfo.shared.isMemberAllFunction {
  457. guard let document = self.listView.document else {
  458. return
  459. }
  460. if !document.isLocked {
  461. KMAdsManager.defaultManager.beginSheetModalForView(self.readContentView, directions: .down, adPosY: 30, animated: false) { pageIndex in
  462. }
  463. }
  464. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  465. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  466. }
  467. #endif
  468. }
  469. // MARK: Private Methods
  470. // 是否阿拉伯语言
  471. private func _isArabicLanguage() -> Bool {
  472. return NSLocalizedString("Right click a color and select “Change Color...“.", comment: "") == "انقر بزر الماوس الأيمن فوق اللون وحدد \"تغيير اللون...\"."
  473. }
  474. internal func removeNotifications() {
  475. NotificationCenter.default.removeObserver(self)
  476. self.leftSideViewController.clearAnnotationFilterData()
  477. self.leftSideViewController.clearNotification()
  478. }
  479. func checkShouldAutoOpenLeftVC() {
  480. if KMPreference.shared.showLeftSideBar == false {
  481. return
  482. }
  483. if self.model.leftPanelOpen {
  484. return
  485. }
  486. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  487. if readModel == true {
  488. return
  489. }
  490. DispatchQueue.main.async {
  491. self.leftSideViewController.showThumbnail()
  492. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  493. }
  494. }
  495. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  496. mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  497. mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  498. self.model.lastLeftPanWidth = leftSideWidth
  499. self.model.lastRightPanWidth = rightSideWidth
  500. }
  501. internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  502. internal func removeAllAnnotations() {
  503. let alert = NSAlert()
  504. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  505. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  506. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  507. if (alert.runModal() != .alertFirstButtonReturn) {
  508. return
  509. }
  510. DispatchQueue.main.async {
  511. self.removeAllAnnotationsStore.store(t: self.listView)
  512. }
  513. }
  514. @objc func cancelMeasureType() {
  515. self.hideMeasureFloatingWindows()
  516. self.toolbarController?.findItem(KMToolbarMeasureItemIdentifier)?.isSelected = false
  517. }
  518. func hideMeasureFloatingWindows() {
  519. if distanceMeasureInfoWindowController?.window?.isVisible == true {
  520. distanceMeasureInfoWindowController?.hideFloatingWindow()
  521. } else if perimeterMeasureInfoWindowController?.window?.isVisible == true {
  522. perimeterMeasureInfoWindowController?.hideFloatingWindow()
  523. } else if areaMeasureInfoWindowController?.window?.isVisible == true {
  524. areaMeasureInfoWindowController?.hideFloatingWindow()
  525. }
  526. }
  527. func showMeasureFloatingWindowsIfNeed() {
  528. let toolMode = self.listView?.toolMode ?? .none
  529. if toolMode != .measureToolMode {
  530. return
  531. }
  532. let type = self.listView?.annotationType ?? .none
  533. if type == .line {
  534. self.distanceMeasureInfoWindowController?.window?.orderFront(nil)
  535. } else if type == .polyLine {
  536. self.perimeterMeasureInfoWindowController?.window?.orderFront(nil)
  537. } else if type == .polyGon {
  538. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  539. } else if type == .square {
  540. self.areaMeasureInfoWindowController?.window?.orderFront(nil)
  541. }
  542. }
  543. // MARK: Set Methods
  544. var setDocument: CPDFDocument? {
  545. get {
  546. return document
  547. }
  548. set {
  549. if document != newValue {
  550. document = newValue
  551. }
  552. listView.document = document
  553. listView.document?.delegate = self
  554. self.listView.layoutDocumentView()
  555. self.leftSideViewController.refreshUIForDocumentChanged()
  556. }
  557. }
  558. var setPageNumber: UInt {
  559. get {
  560. return pageNumber!
  561. }
  562. set {
  563. let pageCount = listView.document?.pageCount ?? 0
  564. var value = newValue
  565. if value > pageCount {
  566. value = pageCount
  567. }
  568. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  569. listView.go(to: listView.document?.page(at: value-1))
  570. }
  571. if pageNumber != value {
  572. pageNumber = value
  573. }
  574. }
  575. }
  576. // MARK: - 标记密文
  577. func enterRedact() {
  578. if KMMemberInfo.shared.isMemberAllFunction == false {
  579. let winC = KMProductCompareWC.shared
  580. winC.kEventName = "Reading_Redact_BuyNow"
  581. KMMemberInfo.shared.advancedFunctionUsage()
  582. return
  583. }
  584. if self.listView.document?.allowsPrinting == false || self.listView.document?.allowsCopying == false {
  585. Task {
  586. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  587. }
  588. return
  589. }
  590. if self.hasEnterRedact() {
  591. self.exitRedact()
  592. return
  593. }
  594. self.commitEditingIfNeed()
  595. self.leftSideViewController.thumbnailTableView.isEnabled = false
  596. self.leftSideViewController.tocOutlineView.isEnabled = false
  597. self.leftSideViewController.noteOutlineView.isEnabled = false
  598. self.leftSideViewController.findTableView.isEnabled = false
  599. self.leftSideViewController.groupedFindTableView.isEnabled = false
  600. self.leftSideViewController.snapshotTableView.isEnabled = false
  601. let ttsWindowC = KMTTSWindowController.share
  602. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  603. if let data = ttsWindowC.window?.isVisible, data {
  604. ttsWindowC.stopSpeaking()
  605. ttsWindowC.close()
  606. }
  607. }
  608. NSColorPanel.shared.showsAlpha = false
  609. redactController = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document?.password)
  610. self.addChild(redactController)
  611. self.PDFContendView.addSubview(redactController.view)
  612. redactController.view.frame = self.PDFContendView.bounds
  613. redactController.view.autoresizingMask = [.width, .height]
  614. self.listView.isHidden = true
  615. redactController.scaleFactor = self.listView.scaleFactor
  616. redactController.titleBack = { [weak self] title in
  617. self?.view.window?.title = title
  618. }
  619. redactController.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
  620. self?.listView.go(toPageIndex: self!.redactController.redactPdfView.currentPageIndex, animated: false)
  621. if result == false { // 退出
  622. self?.exitRedact()
  623. return
  624. }
  625. let controller = self?._getPDFRedactController()
  626. controller?.redactPdfView.newAddAnnotation.removeAll()
  627. self?.exitRedact()
  628. if saveResult {
  629. let newDocument = CPDFDocument(url: saveUrl)
  630. if let data = newDocument?.isLocked, data {
  631. newDocument?.unlock(withPassword: self?.listView.document?.password ?? "")
  632. }
  633. self?.document = newDocument
  634. self?.listView.document = newDocument
  635. self?.listView.layoutDocumentView()
  636. }
  637. }
  638. redactController.setCurrentPageIndex(self.listView.currentPageIndex)
  639. }
  640. func exitRedact() {
  641. self.leftSideViewController.thumbnailTableView.isEnabled = true
  642. self.leftSideViewController.tocOutlineView.isEnabled = true
  643. self.leftSideViewController.noteOutlineView.isEnabled = true
  644. self.leftSideViewController.findTableView.isEnabled = true
  645. self.leftSideViewController.groupedFindTableView.isEnabled = true
  646. self.leftSideViewController.snapshotTableView.isEnabled = true
  647. let controller = self._getPDFRedactController()
  648. if let data = controller {
  649. if data.redactPdfView.newAddAnnotation.count > 0 {
  650. KMAlertTool.runModel(message: "", informative: KMLocalizedString("There are unapplied redactions in this file. Exit will not save redaction.", nil), buttons: [KMLocalizedString("Exit", nil), KMLocalizedString("Cancel", nil)]) { response in
  651. if response == .alertFirstButtonReturn {
  652. controller?.redactPdfView.newAddAnnotation.removeAll()
  653. self.exitRedact()
  654. }
  655. }
  656. return
  657. }
  658. }
  659. NSColorPanel.shared.showsAlpha = true
  660. self.toolbarController.findItem(KMDocumentRedactToolbarItemIdentifier)?.isSelected = false
  661. // self.toolbarController.toolbarType = .None
  662. // self.listView.toolMode = .moveToolMode
  663. controller?.redactPdfView.resignMonitor()
  664. controller?.view.removeFromSuperview()
  665. controller?.removeFromParent()
  666. self.listView.isHidden = false
  667. // self.listView.layoutDocumentView()
  668. // self.view.window?.makeFirstResponder(self.listView)
  669. self.listView.annotationType = .unkown
  670. }
  671. func hasEnterRedact() -> Bool {
  672. return self._getPDFRedactController() != nil
  673. }
  674. //MARK: - AI
  675. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  676. if (self.document != nil) {
  677. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  678. } else {
  679. AIChatInfoManager.defaultManager.currentFilePath = ""
  680. }
  681. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  682. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  683. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  684. let documentArray = NSDocumentController.shared.documents
  685. var didFileEdit: Bool = false
  686. var curDoc: KMMainDocument!
  687. for document in documentArray {
  688. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  689. didFileEdit = document.isDocumentEdited
  690. curDoc = document as! KMMainDocument
  691. break
  692. }
  693. }
  694. if didFileEdit {
  695. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  696. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  697. do {
  698. try FileManager.default.removeItem(at: tempFileURL)
  699. } catch {
  700. }
  701. }
  702. if curDoc != nil {
  703. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  704. }
  705. }
  706. windowVC.window?.becomeMain()
  707. }
  708. }
  709. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  710. } else {
  711. var windowRect = windowVC.window?.frame
  712. windowRect!.origin.x = NSMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  713. windowRect!.origin.y = NSMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  714. windowVC.window?.setFrame(windowRect!, display: true)
  715. windowVC.didSetOriginFrame = true
  716. }
  717. windowVC.eventLabel = "AITools_Tbr"
  718. windowVC.showWindow(nil)
  719. if (aiConfigType != .none) {
  720. windowVC.eventLabel = "AITools_Start"
  721. if self.listView.currentSelection?.string()?.isEmpty == false {
  722. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  723. }
  724. windowVC.chooseAIFunctionWithType(aiConfigType)
  725. }
  726. }
  727. @objc func aiTipIconViewShowStateChangeNoti() {
  728. }
  729. //MARK: - 引导
  730. func loadFunctionGuide() -> Void {
  731. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  732. if self.view.window != nil {
  733. self.loadOpenFileFunctionGuide(.openFileNormal)
  734. }
  735. }
  736. }
  737. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  738. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  739. let leftPanelItem:KMToolbarItemView = self.toolbarController.findItem("KMLeftControlToolbarItemIdentifier")!
  740. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  741. guard let guideWC = self.guideInfoWindowController else { return }
  742. guideWC.type = .openFileNormal
  743. guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? .zero
  744. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  745. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  746. let rightPanelItem = self?.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  747. let digitalPanelItem = self?.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier)
  748. if let data = rightPanelItem, data.isHidden {
  749. let view = self?.toolbarController.mainToolBarView?.toolbar?.moreButton
  750. windowVC.rightPanelRect = (self?.view.window?.contentView?.convert(view?.frame ?? .zero, from: view?.superview)) ?? .zero
  751. } else {
  752. windowVC.rightPanelRect = (self?.view.window?.contentView?.convert(rightPanelItem?.frame ?? .zero, from: rightPanelItem?.superview)) ?? .zero
  753. }
  754. guideWC.digitalBoxRect = (self?.view.window?.contentView?.convert(digitalPanelItem?.frame ?? .zero, from: digitalPanelItem?.superview)) ?? .zero
  755. }
  756. guideWC.finishHandle = { [weak self] windowVC, type in
  757. if type == .windowNewFinish ||
  758. type == . windowDigitalFinish {
  759. self?.checkFirstTrialController()
  760. }
  761. }
  762. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  763. self?.checkFirstTrialController()
  764. }
  765. var rect = self.view.window!.frame
  766. rect.size.height -= 20
  767. guideWC.window?.setFrame(rect, display: false)
  768. guideWC.window?.minSize = rect.size
  769. guideWC.window?.maxSize = rect.size
  770. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  771. guideWC.show()
  772. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  773. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  774. guard let guideWC = self.guideInfoWindowController else { return }
  775. guideWC.type = .digitalSignGuide
  776. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  777. return
  778. }
  779. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  780. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  781. guideWC.finishHandle = { [weak self] windowVC, type in
  782. self?.checkFirstTrialController()
  783. }
  784. var rect = self.view.window!.frame
  785. rect.size.height -= 20
  786. guideWC.window?.setFrame(rect, display: false)
  787. guideWC.window?.minSize = rect.size
  788. guideWC.window?.maxSize = rect.size
  789. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  790. guideWC.show()
  791. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  792. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  793. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  794. guard let guideWC = self.guideInfoWindowController else { return }
  795. guideWC.type = .pdfCompareGuide
  796. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  797. return
  798. }
  799. guard let win = self.view.window else {
  800. return
  801. }
  802. guideWC.digitalBoxRect = (win.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview)) ?? .zero
  803. let compareItem = self.toolbarController.findItem(KMToolbarComparisonItemIdentifier)
  804. guideWC.compareItemRect = (win.contentView?.convert(compareItem?.frame ?? .zero, from: compareItem?.superview)) ?? .zero
  805. guideWC.finishHandle = { [weak self] winC, type in
  806. if type == .windowNewFinish {
  807. DispatchQueue.main.async {
  808. self?.loadOpenFileFunctionGuide(.measureGuide)
  809. }
  810. return
  811. }
  812. }
  813. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  814. var rect = self.view.window!.frame
  815. rect.size.height -= 20
  816. guideWC.window?.setFrame(rect, display: false)
  817. guideWC.window?.minSize = rect.size
  818. guideWC.window?.maxSize = rect.size
  819. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  820. guideWC.show()
  821. }
  822. } else if showType == .measureGuide && KMGuideInfoWindowController.availableShow(.measureGuide) {
  823. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
  824. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  825. guard let guideWC = self.guideInfoWindowController else { return }
  826. guard let _ = self.view.window else {
  827. return
  828. }
  829. guideWC.type = .measureGuide
  830. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  831. return
  832. }
  833. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview)) ?? .zero
  834. let compareItem:KMToolbarItemView = self.toolbarController.findItem(KMToolbarMeasureItemIdentifier)!
  835. guideWC.compareItemRect = (self.view.window?.contentView?.convert(compareItem.frame, from: compareItem.superview)) ?? .zero
  836. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  837. var rect = self.view.window?.frame ?? .zero
  838. rect.size.height -= 20
  839. guideWC.window?.setFrame(rect, display: false)
  840. guideWC.window?.minSize = rect.size
  841. guideWC.window?.maxSize = rect.size
  842. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  843. guideWC.show()
  844. }
  845. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  846. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  847. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  848. guard let guideWC = self.guideInfoWindowController else { return }
  849. guideWC.type = .convertGuide
  850. guard let digitalPanelItem = self.toolbarController.findItem(KMDocumentSignToolbarItemIdentifier) else {
  851. return
  852. }
  853. guard let win = self.view.window else {
  854. return
  855. }
  856. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview)) ?? .zero
  857. guideWC.purchaseHandle = { [weak self] windowVC in
  858. #if VERSION_DMG
  859. if KMMemberInfo.shared.isMemberAllFunction {
  860. if KMMemberInfo.shared.isPermitConvert {
  861. //Convert:
  862. self?.showAllConvertWindow(convertT: .Word)
  863. } else {
  864. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  865. limitWC.continueBlock = { windowController in
  866. }
  867. limitWC.window?.center()
  868. limitWC.showWindow(nil)
  869. }
  870. } else {
  871. KMProductCompareWC.shared.orientation = false
  872. KMProductCompareWC.shared.showWindow(nil)
  873. }
  874. #else
  875. if KMMemberInfo.shared.isMemberAllFunction == true {
  876. if KMMemberInfo.shared.isPermitConvert == true {
  877. } else {
  878. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  879. vc.showWindow(nil)
  880. }
  881. let userScenarioType = KMMemberInfo.shared.userScenarioType
  882. let platforms = KMMemberInfo.shared.vip_platforms
  883. let platformsArray = platforms
  884. .components(separatedBy: ",")
  885. .map { $0.trimmingCharacters(in: .whitespaces) }
  886. if userScenarioType == .lite_type2 ||
  887. userScenarioType == .lite_type4 ||
  888. userScenarioType == .lite_type6 ||
  889. userScenarioType == .lite_type8 {
  890. // 订阅中,Android单平台高级版月订阅或者全平台标准版年订阅,不能升级,提示联系客服
  891. if !platformsArray.contains("mac") ||
  892. KMMemberInfo.shared.vip_levels != "3" {
  893. let alert = NSAlert()
  894. alert.alertStyle = .critical
  895. alert.informativeText = NSLocalizedString("Sorry, you do not have the rights to this paid feature and cannot use it. If you have any questions, please contact customer service at support@pdfreaderpro.com", comment: "")
  896. alert.addButton(withTitle: NSLocalizedString("Got it", comment: ""))
  897. alert.runModal()
  898. }
  899. }
  900. } else {
  901. KMMemberInfo.shared.advancedFunctionUsage()
  902. }
  903. #endif
  904. }
  905. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  906. var rect = self.view.window?.frame ?? .zero
  907. rect.size.height -= 20
  908. guideWC.window?.setFrame(rect, display: false)
  909. guideWC.window?.minSize = rect.size
  910. guideWC.window?.maxSize = rect.size
  911. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  912. guideWC.show()
  913. }
  914. } else {
  915. }
  916. }
  917. func checkFirstTrialController() -> Void {
  918. #if VERSION_DMG
  919. //打开文档后引导相关
  920. if VerificationManager.default().status == .none {
  921. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  922. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  923. if lastVersion.isEmpty || lastVersion != appVersion {
  924. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  925. UserDefaults.standard.synchronize()
  926. KMProductCompareWC.shared.orientation = false
  927. KMProductCompareWC.shared.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 KMMemberInfo.shared.isMemberAllFunction == false {
  1077. let winC = KMProductCompareWC.shared
  1078. winC.kEventName = "Reading_DigitalSign_BuyNow"
  1079. KMMemberInfo.shared.advancedFunctionUsage()
  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 KMMemberInfo.shared.isMemberAllFunction {
  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 KMMemberInfo.shared.isMemberAllFunction {
  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. }