KMMainViewController.swift 107 KB

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