KMMainViewController.swift 106 KB

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