KMMainViewController.swift 106 KB

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