KMMainViewController.swift 109 KB

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