KMMainViewController.swift 109 KB

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