KMHomeViewController.swift 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. //
  2. // KMHomeViewController.swift
  3. // EaseUS PDF Editor
  4. //
  5. // Created by wanjun on 2022/10/13.
  6. //
  7. import Cocoa
  8. @objc enum KMHomeToolState : Int {
  9. case OpenPDF = 0
  10. case CreatePDF
  11. case Home
  12. case PDFTools
  13. case FavoriteDocuments
  14. case CloudDocuments
  15. }
  16. @objc enum KMAIHomeToolState : Int {
  17. case Home = 0
  18. case AITranslation
  19. case AIRewriting
  20. case AIErrorCorrection
  21. }
  22. @objcMembers class KMHomeViewController: NSViewController {
  23. @IBOutlet weak var leftBox: NSBox!
  24. @IBOutlet weak var rightBox: NSBox!
  25. @IBOutlet weak var homeSplitView: NSSplitView!
  26. @IBOutlet weak var homeRightScrollViewView: NSScrollView!
  27. @IBOutlet weak var rightTopBox: NSBox!
  28. @IBOutlet weak var rightBottomBox: NSBox!
  29. @IBOutlet weak var rightFullBox: NSBox!
  30. @IBOutlet weak var rightTopBoxHeightConstraint: NSLayoutConstraint!
  31. @IBOutlet var fastToolViewController: KMHomeFastToolViewController!
  32. @IBOutlet var historyFileViewController: KMHomeHistoryFileViewController!
  33. @IBOutlet var pdfToolsViewController: KMPDFToolsViewController!
  34. @IBOutlet var cloudDocumentsViewController: KMCloudDocumentsViewController!
  35. @IBOutlet weak var dragView: KMHomeDragView!
  36. // AI 临时UI
  37. @IBOutlet weak var aiHomeBox: KMBox!
  38. @IBOutlet weak var aiHomeImageView: NSImageView!
  39. @IBOutlet weak var aiHomeLabel: NSTextField!
  40. @IBOutlet weak var aiTranslationBox: KMBox!
  41. @IBOutlet weak var aiTranslationImageView: NSImageView!
  42. @IBOutlet weak var aiTranslationLabel: NSTextField!
  43. @IBOutlet weak var aiRewritingBox: KMBox!
  44. @IBOutlet weak var aiRewritingImageView: NSImageView!
  45. @IBOutlet weak var aiRewritingLabel: NSTextField!
  46. @IBOutlet weak var aiErrorCorrectionBox: KMBox!
  47. @IBOutlet weak var aiErrorCorrectionImageView: NSImageView!
  48. @IBOutlet weak var aiErrorCorrectionLabel: NSTextField!
  49. @IBOutlet var aiOpenPDFFilesViewController: KMAIOpenPDFFilesVC!
  50. @IBOutlet var aiTranslationViewController: KMAITranslationVC!
  51. @IBOutlet var aiRewritingViewController: KMAIRewritingVC!
  52. @IBOutlet weak var creatPDFView: KMCreatPDFView!
  53. //HomeContentView
  54. @IBOutlet weak var homeContentView: KMHomeContentView!
  55. @IBOutlet weak var otherLabel: NSTextField!
  56. @IBOutlet weak var screenRecorderLabel: NSTextField!
  57. @IBOutlet weak var ntfsMacLabel: NSTextField!
  58. //合并
  59. var mergeWindowController: KMMergeWindowController?
  60. var aiHomeState: KMAIHomeToolState = .Home
  61. let ScrollerViewWidget: CGFloat = 15.0
  62. var homeWindowController : MainWindowController!
  63. var isShowQuickTour: Bool = false
  64. weak var myDocument: NSDocument?
  65. var currentWindowController: NSWindowController?
  66. var homeState: KMHomeToolState = .Home
  67. var urlToPDFWindowController: KMURLToPDFWindowController?
  68. var openPDFButtonVC: KMDesignButton?
  69. var createPDFButtonVC: KMDesignButton?
  70. var createPDFImage: KMDesignButton?
  71. var createPDFAddButtonVC: KMDesignButton?
  72. var homeButtonVC: KMTextImageButtonVC?
  73. var pdfToolsButtonVC: KMTextImageButtonVC?
  74. var cloudDocumentsButtonVC: KMTextImageButtonVC?
  75. var pdfSeriesButtonVC: KMTextImageButtonVC?
  76. var pdfOthersButtonVC: KMTextImageButtonVC?
  77. var popover: NSPopover?
  78. var deviceBrowserWC: KMDeviceBrowserWindowController?
  79. var progressController: SKProgressController?
  80. var timer: Timer?
  81. var timerCounter = 0.0
  82. //AI相关
  83. //试用相关
  84. var didTrialExpiredLoad: Bool = false
  85. var repeatTrialAlertLoad: Bool = false
  86. var guideWindowVC: KMFunctionGuideWindowController!
  87. var showCoupon: Bool = true
  88. var couponDueWindowVC: KMCouponDueWindowController!
  89. @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
  90. var currentController: NSWindowController?
  91. deinit {
  92. NotificationCenter.default.removeObserver(self)
  93. }
  94. override func viewWillAppear() {
  95. super.viewWillAppear()
  96. if !KMLightMemberManager.manager.isLogin() {
  97. KMLightMemberManager.manager.canShowAdvancedView = true
  98. }
  99. self.homeContentView.reloadData()
  100. #if VERSION_DMG
  101. let kDMGFirstInstallKey = "DMGFirstInstallKey"
  102. if KMDataManager.ud_object(forKey: kDMGFirstInstallKey) == nil {
  103. KMDataManager.ud_set("Show", forKey: kDMGFirstInstallKey)
  104. KMTools.openURL(urlString: "https://www.easeus-software.com/pdf-editor/mac-installation.html")
  105. }
  106. #else
  107. // [self loadAIInfo];
  108. #endif
  109. }
  110. override func viewWillDisappear() {
  111. super.viewWillDisappear()
  112. // self.homeContentView.reloadData()
  113. }
  114. override func viewDidLoad() {
  115. super.viewDidLoad()
  116. // Do view setup here.
  117. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  118. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  119. createPDFImage = KMDesignButton.init(withType: .Image)
  120. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  121. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  122. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  123. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  124. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  125. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  126. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  127. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  128. self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  129. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  130. self.otherMouseDown(with: aEvent)
  131. return aEvent
  132. }
  133. // self.initLocalization()
  134. // self.initializeUI()
  135. self.initializeUI_DMG()
  136. self.setup()
  137. // refreshUI()
  138. self.updateUI()
  139. self.changeEffectiveAppearance()
  140. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  141. NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  142. // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
  143. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
  144. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
  145. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  146. NotificationCenter.default.addObserver(self, selector: #selector(openNewWindowAlertV), name: Notification.Name("KMCTTableChangeShowAlertView"), object: nil)
  147. #if VERSION_DMG
  148. NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
  149. #endif
  150. NotificationCenter.default.addObserver(self, selector: #selector(importFromCamera), name: Notification.Name("kDeviceCameraMenuItemNotification"), object: nil)
  151. NotificationCenter.default.addObserver(self, selector: #selector(importFromScanner), name: Notification.Name("kDeviceScannerMenuItemNotification"), object: nil)
  152. self.loadFunctionGuide()
  153. }
  154. override func viewDidAppear() {
  155. super.viewDidAppear()
  156. refreshScrollView()
  157. }
  158. override func viewDidLayout() {
  159. super.viewDidLayout()
  160. refreshScrollView()
  161. // self.loadAITipIconGuide()
  162. }
  163. func setup() {
  164. //creatPDF
  165. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  166. self.openPDFAction(sender)
  167. }
  168. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  169. self.creatPDFAction(sender)
  170. }
  171. //history
  172. self.homeContentView.historyDidSelect = { [unowned self] view, item in
  173. self.openHistoryFilePath(url: item.url!)
  174. }
  175. self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
  176. self.historyFile(deleteDocuments: [ item.url!])
  177. }
  178. self.homeContentView.historyShowPathAction = { [unowned self] view, item in
  179. if FileManager.default.fileExists(atPath: item.url!.path) {
  180. NSWorkspace.shared.activateFileViewerSelecting([item.url!])
  181. }
  182. }
  183. self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
  184. let alert = NSAlert()
  185. alert.alertStyle = .critical
  186. alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
  187. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  188. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  189. alert.beginSheetModal(for: self.view.window!) { response in
  190. if response == .alertFirstButtonReturn {
  191. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  192. self.historyFileDeleteAction(urls)
  193. }
  194. }
  195. }
  196. //quciktools
  197. self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
  198. self.fastToolItemAction(item.type!)
  199. }
  200. self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
  201. KMBatchQuickActionManager.defaultManager.actionType = .add
  202. self.fastToolItemAction(item.type!)
  203. }
  204. self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
  205. KMBatchQuickActionManager.defaultManager.actionType = .remove
  206. self.fastToolItemAction(item.type!)
  207. }
  208. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  209. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  210. }
  211. // MARK: Init
  212. func initializeUI() {
  213. rightTopBox.fillColor = .white
  214. rightBottomBox.fillColor = .white
  215. rightFullBox.fillColor = .white
  216. self.refreshRightBoxUI(.Home)
  217. fastToolViewController.delete = self
  218. historyFileViewController.delete = self
  219. pdfToolsViewController.delete = self
  220. dragView.delete = self
  221. }
  222. func initLocalization() {
  223. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  224. homeButtonVC?.stringValue = NSLocalizedString("Home", comment: "")
  225. pdfToolsButtonVC?.stringValue = NSLocalizedString("PDF Tools", comment: "")
  226. cloudDocumentsButtonVC?.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  227. openPDFButtonVC?.stringValue = NSLocalizedString("Open File", comment: "")
  228. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  229. createPDFButtonVC?.stringValue = NSLocalizedString("Create PDF", comment: "")
  230. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  231. pdfSeriesButtonVC?.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  232. pdfOthersButtonVC?.stringValue = NSLocalizedString("Others", comment: "")
  233. }
  234. // MARK: Action
  235. func initializeUI_DMG() -> Void {
  236. rightTopBox.fillColor = .white
  237. rightBottomBox.fillColor = .white
  238. rightFullBox.fillColor = .white
  239. otherLabel.stringValue = NSLocalizedString("Others", comment: "")
  240. otherLabel.font = NSFont.SFProTextSemiboldFont(12.0)
  241. screenRecorderLabel.stringValue = NSLocalizedString("Screen Recorder", comment: "")
  242. screenRecorderLabel.font = NSFont.SFProTextRegularFont(13.0)
  243. ntfsMacLabel.stringValue = NSLocalizedString("NTFS for Mac", comment: "")
  244. ntfsMacLabel.font = NSFont.SFProTextRegularFont(13.0)
  245. self.aiHomeBox.fillColor = .clear
  246. self.aiHomeBox.cornerRadius = 8.0
  247. self.aiHomeImageView.image = NSImage(named: "icon_home")
  248. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  249. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  250. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  251. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  252. if aiHomeState != .Home {
  253. if mouseEntered {
  254. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  255. } else {
  256. self.aiHomeBox.fillColor = .clear
  257. }
  258. }
  259. }
  260. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  261. if aiHomeState != .Home {
  262. if downEntered {
  263. self.aiHomeState = .Home
  264. self.refreshAIUI()
  265. }
  266. }
  267. }
  268. self.aiTranslationBox.fillColor = .clear
  269. self.aiTranslationBox.cornerRadius = 8.0
  270. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  271. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  272. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  273. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  274. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  275. if aiHomeState != .AITranslation {
  276. if mouseEntered {
  277. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  278. } else {
  279. self.aiTranslationBox.fillColor = .clear
  280. }
  281. }
  282. }
  283. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  284. if aiHomeState != .AITranslation {
  285. if downEntered {
  286. self.aiHomeState = .AITranslation
  287. self.trackEvent_ai(eventName: "AI Translation")
  288. self.refreshAIUI()
  289. }
  290. }
  291. }
  292. self.aiRewritingBox.fillColor = .clear
  293. self.aiRewritingBox.cornerRadius = 8.0
  294. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  295. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  296. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  297. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  298. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  299. if aiHomeState != .AIRewriting {
  300. if mouseEntered {
  301. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  302. } else {
  303. self.aiRewritingBox.fillColor = .clear
  304. }
  305. }
  306. }
  307. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  308. if aiHomeState != .AIRewriting {
  309. if downEntered {
  310. self.aiHomeState = .AIRewriting
  311. self.trackEvent_ai(eventName: "AI Rewriting")
  312. self.refreshAIUI()
  313. }
  314. }
  315. }
  316. self.aiErrorCorrectionBox.fillColor = .clear
  317. self.aiErrorCorrectionBox.cornerRadius = 8.0
  318. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  319. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  320. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  321. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  322. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  323. if aiHomeState != .AIErrorCorrection {
  324. if mouseEntered {
  325. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  326. } else {
  327. self.aiErrorCorrectionBox.fillColor = .clear
  328. }
  329. }
  330. }
  331. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  332. if aiHomeState != .AIErrorCorrection {
  333. if downEntered {
  334. self.aiHomeState = .AIErrorCorrection
  335. self.trackEvent_ai(eventName: "AI Correction")
  336. self.refreshAIUI()
  337. }
  338. }
  339. }
  340. self.refreshAIUI()
  341. historyFileViewController.delete = self
  342. dragView.delete = self
  343. }
  344. func updateUI() {
  345. self.leftBox.fillColor = KMAppearance.Layout.l0Color()
  346. // self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
  347. }
  348. @objc func changeEffectiveAppearance() {
  349. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  350. if isDarkModel {
  351. self.view.appearance = NSAppearance(named: .darkAqua)
  352. } else {
  353. self.view.appearance = NSAppearance(named: .aqua)
  354. }
  355. self.updateUI()
  356. }
  357. @IBAction func screenRecorderAction(_ sender: NSButton) {
  358. let httpUrl: NSURL = NSURL.init(string: "https://apps.apple.com/app/apple-store/id1581903884?pt=855050&ct=pdfmac&mt=8")!
  359. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  360. if !tWorkSpace.open(httpUrl as URL) {
  361. tWorkSpace.open(httpUrl as URL)
  362. }
  363. }
  364. @IBAction func ntfsMacAction(_ sender: NSButton) {
  365. let httpUrl: NSURL = NSURL.init(string: "https://apps.apple.com/app/apple-store/id6468982811?pt=855050&ct=pdfmac&mt=8")!
  366. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  367. if !tWorkSpace.open(httpUrl as URL) {
  368. tWorkSpace.open(httpUrl as URL)
  369. }
  370. }
  371. // MARK: Public Methods
  372. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  373. DispatchQueue.global(qos: .`default`).async {
  374. var isSuccessfully = false
  375. if pdf.isEncrypted {
  376. let dic = [
  377. CPDFDocumentWriteOption.userPasswordOption : password,
  378. CPDFDocumentWriteOption.ownerPasswordOption : password
  379. ]
  380. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  381. } else {
  382. isSuccessfully = pdf.write(to: pdf.documentURL)
  383. }
  384. if !isSuccessfully {
  385. if let data = pdf.dataRepresentation() {
  386. isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
  387. }
  388. }
  389. DispatchQueue.main.sync {
  390. if isSuccessfully {
  391. let workspace = NSWorkspace.shared
  392. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  393. workspace.activateFileViewerSelecting([url])
  394. } else {
  395. let alert = NSAlert()
  396. alert.alertStyle = .critical
  397. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  398. alert.runModal()
  399. }
  400. }
  401. }
  402. }
  403. // MARK: Private Methods
  404. func refreshUI() -> Void {
  405. homeButtonVC?.updateUI()
  406. pdfToolsButtonVC?.updateUI()
  407. cloudDocumentsButtonVC?.updateUI()
  408. }
  409. func refreshAIUI() -> Void {
  410. self.aiHomeBox.fillColor = .clear
  411. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  412. self.aiTranslationBox.fillColor = .clear
  413. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  414. self.aiRewritingBox.fillColor = .clear
  415. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  416. self.aiErrorCorrectionBox.fillColor = .clear
  417. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  418. rightFullBox.isHidden = true
  419. rightTopBox.isHidden = true
  420. rightBottomBox.isHidden = true
  421. switch self.aiHomeState {
  422. case .Home:
  423. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  424. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  425. self.rightTopBox.isHidden = false
  426. self.rightBottomBox.isHidden = false
  427. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  428. self.rightBottomBox.contentView = self.historyFileViewController.view
  429. self.rightFullBox.contentView = nil
  430. self.rightTopBoxHeightConstraint.constant = 388.0
  431. self.dragView.isHidden = false
  432. break
  433. case .AITranslation:
  434. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  435. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  436. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  437. self.rightFullBox.isHidden = false
  438. self.rightTopBox.contentView = nil
  439. self.rightBottomBox.contentView = nil
  440. self.rightFullBox.contentView = self.aiTranslationViewController.view
  441. self.dragView.isHidden = false
  442. break
  443. case .AIRewriting:
  444. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  445. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  446. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  447. self.rightFullBox.isHidden = false
  448. self.rightTopBox.contentView = nil
  449. self.rightBottomBox.contentView = nil
  450. self.rightFullBox.contentView = self.aiRewritingViewController.view
  451. // self.aiRewritingViewController.state = .AIRewriting
  452. self.aiRewritingViewController.initLocalization()
  453. self.aiRewritingViewController.acquisition_uiState()
  454. self.dragView.isHidden = true
  455. break
  456. case .AIErrorCorrection:
  457. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  458. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  459. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  460. self.rightFullBox.isHidden = false
  461. self.rightTopBox.contentView = nil
  462. self.rightBottomBox.contentView = nil
  463. self.rightFullBox.contentView = self.aiRewritingViewController.view
  464. // self.aiRewritingViewController.state = .AIErrorCorrection
  465. self.aiRewritingViewController.initLocalization()
  466. self.aiRewritingViewController.acquisition_uiState()
  467. self.dragView.isHidden = true
  468. break
  469. default:
  470. break
  471. }
  472. }
  473. func fetchDifferentFilePath(filePath: String) -> String {
  474. var resultFilePath = filePath
  475. var index: Int = 0
  476. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  477. index += 1
  478. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  479. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  480. }
  481. return resultFilePath;
  482. }
  483. func showProgressWindow() {
  484. let progress = SKProgressController()
  485. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  486. progress.window?.contentView?.wantsLayer = true
  487. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  488. progress.progressField.textColor = NSColor.white
  489. progress.message = NSLocalizedString("Translating...", comment: "")
  490. progress.closeBlock = { [weak self] in
  491. }
  492. self.progressController = progress
  493. self.view.window?.beginSheet(progress.window!)
  494. }
  495. func hiddenProgressWindow() {
  496. DispatchQueue.main.async {
  497. self.progressController?.doubleValue = 100.0
  498. }
  499. self.stopTimer()
  500. if (self.progressController != nil) {
  501. self.view.window?.endSheet((self.progressController?.window)!)
  502. self.progressController = nil
  503. }
  504. }
  505. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  506. let fileManager = FileManager.default
  507. do {
  508. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  509. if let fileSize = fileAttributes[.size] as? UInt64 {
  510. let megabyteSize = fileSize / (1024 * 1024)
  511. return megabyteSize >= 10
  512. }
  513. } catch {
  514. KMPrint("Error: \(error)")
  515. }
  516. return false
  517. }
  518. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  519. let url = URL(fileURLWithPath: filePath)
  520. guard let document = PDFDocument(url: url) else {
  521. return false
  522. }
  523. let pageCount = document.pageCount
  524. return pageCount > 30
  525. }
  526. @objc func timerTick() {
  527. timerCounter += 1.0
  528. self.progressController?.increment(by: 1.0)
  529. if timerCounter >= 95 {
  530. stopTimer()
  531. }
  532. }
  533. func stopTimer() {
  534. timer?.invalidate()
  535. timer = nil
  536. }
  537. // MARK: Common methods
  538. func workSpaceOpenUrl(_ url: NSString) {
  539. let httpUrl: NSURL = NSURL.init(string: url as String)!
  540. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  541. if !tWorkSpace.open(httpUrl as URL) {
  542. tWorkSpace.open(httpUrl as URL)
  543. }
  544. }
  545. }
  546. //MARK: Open Creat PDF
  547. extension KMHomeViewController: NSPopoverDelegate {
  548. }
  549. extension KMHomeViewController {
  550. func openPDFAction(_ sender: KMBox) {
  551. if needShowTabbingHintWindow() {
  552. showTabbingHintWindow()
  553. return
  554. }
  555. let openPanel = NSOpenPanel()
  556. openPanel.allowedFileTypes = ["pdf", "PDF"]
  557. openPanel.allowsMultipleSelection = false
  558. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  559. if result == NSApplication.ModalResponse.OK {
  560. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  561. if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
  562. self.reopenDocument(forPaths: openPanel.url!)
  563. }else {
  564. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  565. }
  566. }
  567. }
  568. }
  569. }
  570. func needShowTabbingHintWindow() -> Bool {
  571. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  572. if controll?.browser?.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  573. return true
  574. }
  575. return false
  576. }
  577. func showTabbingHintWindow(){
  578. if !KMDataManager.default.isTabbingWin{
  579. KMDataManager.default.isTabbingWin = true
  580. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  581. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  582. KMDataManager.default.isTabbingWin = false
  583. if continueOrNot {
  584. self?.reopenDocument(forPaths: nil)
  585. } else {
  586. }
  587. }
  588. self.km_beginSheet(windowC: tabbingWin)
  589. }
  590. }
  591. func creatPDFAction(_ sender: KMBox) {
  592. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  593. NSLocalizedString("New From Images", comment: ""),
  594. NSLocalizedString("New From Web Page", comment: ""),
  595. NSLocalizedString("Import From Camera", comment: ""),
  596. NSLocalizedString("Import From Scanner", comment: "")]
  597. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  598. vc.background = KMAppearance.Layout.bgColor()
  599. vc.textColor = KMAppearance.Layout.h0Color()
  600. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  601. let createFilePopover: NSPopover = NSPopover.init()
  602. createFilePopover.contentViewController = vc
  603. createFilePopover.delegate = self
  604. createFilePopover.animates = true
  605. createFilePopover.behavior = .semitransient
  606. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  607. createFilePopover.show(relativeTo: CGRect(x: sender.bounds.origin.x, y: 10, width: sender.bounds.size.width, height: sender.bounds.size.height), of: sender, preferredEdge: .minY)
  608. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  609. if count == NSLocalizedString("New Blank Page", comment: "") {
  610. self.openBlankPage()
  611. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  612. self.importFromCamera()
  613. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  614. self.importFromScanner()
  615. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  616. self.importFromWebPage()
  617. } else if count == NSLocalizedString("New From Images", comment: "") {
  618. self.newFromImages()
  619. }
  620. createFilePopover.close()
  621. }
  622. }
  623. func openBlankPage() {
  624. // let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  625. // let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  626. // let filePath = savePath.deletingLastPathComponent
  627. // if FileManager.default.fileExists(atPath: filePath) == false {
  628. // try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  629. // }
  630. //
  631. // let pdfDocument = CPDFDocument()
  632. // pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  633. // pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  634. // let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  635. // if controll?.browser?.tabCount() ?? 0 > 1 && KMPreference.shared.openDocumentType == .newWindow{
  636. // self.reopenDocument(forPaths: URL(fileURLWithPath: savePath))
  637. // }else {
  638. // NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  639. // if error != nil {
  640. // NSApp.presentError(error!)
  641. // } else {
  642. // if document is KMMainDocument {
  643. // let newDocument = document
  644. // (newDocument as! KMMainDocument).isNewCreated = true
  645. // }
  646. // }
  647. // // self.homeContentView?.reloadData()
  648. // }
  649. // }
  650. NSApplication.newBlankDocument()
  651. }
  652. func importFromWebPage() {
  653. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  654. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  655. if FileManager.default.fileExists(atPath: filePath) {
  656. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  657. if error != nil {
  658. NSApp.presentError(error!)
  659. } else {
  660. if document is KMMainDocument {
  661. (document as! KMMainDocument).isNewCreated = true
  662. }
  663. }
  664. // self.homeContentView.reloadData()
  665. }
  666. }
  667. })
  668. }
  669. func importFromScanner() {
  670. let vc = KMDeviceBrowserWindowController.shared
  671. vc.type = .scanner
  672. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  673. self?.openFile(withFilePath: url as URL)
  674. }
  675. vc.showWindow(NSApp.mainWindow)
  676. }
  677. func importFromCamera() {
  678. let vc = KMDeviceBrowserWindowController.shared
  679. vc.type = .camera
  680. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  681. self?.openFile(withFilePath: url as URL)
  682. }
  683. vc.showWindow(NSApp.mainWindow)
  684. }
  685. func newFromImages() {
  686. fastTool_ImageToPDF()
  687. // let openPanel = NSOpenPanel()
  688. // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  689. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  690. // openPanel.allowsMultipleSelection = true
  691. // } else {
  692. // openPanel.allowsMultipleSelection = false
  693. // }
  694. // openPanel.message = NSLocalizedString("Select images to create a new document. To select multiple files press cmd ⌘ button on the keyboard and click on the target files one by one.", comment: "")
  695. // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  696. // if result == .OK {
  697. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  698. // debugPrint("缺少图片转PDF")
  699. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  700. // var arr: [KMBatchOperateFile] = []
  701. // for url in openPanel.urls {
  702. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  703. // arr.append(file)
  704. // }
  705. //
  706. // if #available(macOS 10.13, *) {
  707. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  708. // } else {
  709. // baseWindowController.showWindow(nil)
  710. // }
  711. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  712. // if #available(macOS 10.13, *) {
  713. // baseWindowController.release()
  714. // }
  715. // }
  716. // }
  717. // }
  718. }
  719. //MARK: Purchase
  720. @objc func purchaseStateUpdateNoti() {
  721. if IAPProductsManager.default().isAvailableAllFunction() {
  722. }
  723. }
  724. //MARK: - AI
  725. func showAITypeChooseView() -> Void {
  726. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  727. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  728. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  729. let documentArray = NSDocumentController.shared.documents
  730. var didFileEdit: Bool = false
  731. var curDoc: KMMainDocument!
  732. for document in documentArray {
  733. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  734. didFileEdit = document.isDocumentEdited
  735. curDoc = document as! KMMainDocument
  736. break
  737. }
  738. }
  739. if didFileEdit {
  740. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  741. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  742. do {
  743. try FileManager.default.removeItem(at: tempFileURL)
  744. } catch {
  745. }
  746. }
  747. if curDoc != nil {
  748. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  749. }
  750. }
  751. windowVC.window?.becomeMain()
  752. }
  753. }
  754. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  755. } else {
  756. windowVC.window?.center()
  757. windowVC.didSetOriginFrame = true
  758. }
  759. windowVC.eventLabel = "AITools_Onboard"
  760. windowVC.showWindow(nil)
  761. }
  762. func loadAITipIconGuide() {
  763. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  764. let guideWC = KMGuideInfoWindowController.currentWC()
  765. guideWC.type = .aiTipIconInfo
  766. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  767. guideWC.finishHandle = { [weak self] windowVC, type in
  768. }
  769. if self.view.window != nil {
  770. var rect = self.view.window?.frame
  771. rect!.size.height -= 20
  772. guideWC.window?.setFrame(rect!, display: true)
  773. guideWC.window?.minSize = rect!.size
  774. guideWC.window?.maxSize = rect!.size
  775. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  776. guideWC.show()
  777. }
  778. }
  779. }
  780. //MARK: - 引导
  781. func loadFunctionGuide() -> Void {
  782. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  783. self.loadNewUserGuide()
  784. }
  785. }
  786. // MARK: - what's New
  787. func loadNewUserGuide() -> Void {
  788. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  789. // guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  790. // guideWindowVC.type = .functionMulti
  791. // guideWindowVC.showWindow(nil)
  792. // guideWindowVC.window?.orderFront(nil)
  793. //
  794. // KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  795. }
  796. }
  797. func checkRepeatTrialExpiredController() -> Void {
  798. //试用过期提示比较表弹窗
  799. if didTrialExpiredLoad == true {
  800. return
  801. }
  802. didTrialExpiredLoad = true
  803. let singleTon = KMPurchaseCompareDMGWindowController.init()
  804. singleTon.showWindow(nil)
  805. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  806. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  807. }
  808. }
  809. func checkRepeatTrialAlertController() -> Void {
  810. //允许二次试用时弹出二次试用引导弹窗
  811. if repeatTrialAlertLoad == true {
  812. return
  813. }
  814. repeatTrialAlertLoad = true
  815. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  816. vc?.showWindow(nil)
  817. }
  818. //MARK: 试用到期优惠券弹窗
  819. func checkTrialEndCouponInfo() {
  820. #if VERSION_DMG
  821. KMRequestServerManager.manager.getDeviceRetensionCoupon {[weak self] success, result in
  822. if success == true {
  823. if result != nil {
  824. guard let dataDict = result!["data"] as? NSDictionary else {
  825. return
  826. }
  827. // if dataDict!["pop_up"] as? Bool == true {
  828. let discount = dataDict["discount"] as? Int
  829. let coupon_code = dataDict["coupon_code"] as? String
  830. let end_up_at = dataDict["end_up_at"] as? String
  831. let pop_up = dataDict["pop_up"] as? Bool
  832. if pop_up == true {
  833. if let versionKey = KMAdsInfoManager.shareInstance.couponInfo?.versionKey {
  834. if KMAdsInfoManager.shareInstance.couponInfo?.show == true {
  835. if (UserDefaults.standard.object(forKey: versionKey) != nil) {
  836. } else {
  837. UserDefaults.standard.set("Show", forKey: versionKey)
  838. UserDefaults.standard.synchronize()
  839. self?.showCouponInfoWindow(discount: discount, couponCode: coupon_code, endUpAt: end_up_at)
  840. }
  841. }
  842. }
  843. }
  844. }
  845. } else {
  846. if KMVerificationWindowController.allowsShowExpired() {
  847. self?.checkRepeatTrialExpiredController()
  848. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  849. self?.checkRepeatTrialAlertController()
  850. }
  851. }
  852. }
  853. #endif
  854. }
  855. func showCouponInfoWindow(discount: Int?, couponCode: String?, endUpAt: String?) {
  856. if self.couponDueWindowVC == nil {
  857. self.couponDueWindowVC = KMCouponDueWindowController(windowNibName: "KMCouponDueWindowController")
  858. }
  859. self.couponDueWindowVC.disCount = discount ?? 20
  860. self.couponDueWindowVC.couponCode = couponCode ?? ""
  861. self.couponDueWindowVC.endUpAt = endUpAt ?? ""
  862. self.couponDueWindowVC.showWindow(nil)
  863. self.couponDueWindowVC.reloadData()
  864. }
  865. // MARK: - Noti Actions
  866. func deviceVerifyFinishNotification(_ sender: Notification) {
  867. #if VERSION_DMG
  868. #endif
  869. }
  870. @objc func aiTipIconViewShowStateChangeNoti() {
  871. }
  872. }