KMHomeViewController.swift 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. //
  2. // KMHomeViewController.swift
  3. // PDF Reader Pro
  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. //广告 互推
  56. @IBOutlet weak var advertisementTableView: KMAdvertisementTableView!
  57. @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint!
  58. @IBOutlet weak var advertisementShowView: KMAdvertisementShowView!
  59. var aiHomeState: KMAIHomeToolState = .Home
  60. let ScrollerViewWidget: CGFloat = 15.0
  61. var homeWindowController : MainWindowController!
  62. var isShowQuickTour: Bool = false
  63. var myDocument: NSDocument?
  64. var currentWindowController: NSWindowController?
  65. var homeState: KMHomeToolState = .Home
  66. var urlToPDFWindowController: KMURLToPDFWindowController?
  67. var openPDFButtonVC: KMDesignButton!
  68. var createPDFButtonVC: KMDesignButton!
  69. var createPDFImage: KMDesignButton!
  70. var createPDFAddButtonVC: KMDesignButton!
  71. var homeButtonVC: KMTextImageButtonVC!
  72. var pdfToolsButtonVC: KMTextImageButtonVC!
  73. var cloudDocumentsButtonVC: KMTextImageButtonVC!
  74. var pdfSeriesButtonVC: KMTextImageButtonVC!
  75. var pdfOthersButtonVC: KMTextImageButtonVC!
  76. var popover: NSPopover?
  77. var deviceBrowserWC: KMDeviceBrowserWindowController?
  78. var progressController: SKProgressController?
  79. var timer: Timer?
  80. var timerCounter = 0.0
  81. //AI相关
  82. var aiTipView: AITipIconView!
  83. var aiTypeChooseView: AITypeChooseView!
  84. //试用相关
  85. var didTrialExpiredLoad: Bool = false
  86. var repeatTrialAlertLoad: Bool = false
  87. @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
  88. var currentController: NSWindowController?
  89. deinit {
  90. NotificationCenter.default.removeObserver(self)
  91. }
  92. override func viewWillAppear() {
  93. super.viewWillAppear()
  94. if !KMLightMemberManager.manager.isLogin() {
  95. KMLightMemberManager.manager.canShowAdvancedView = true
  96. }
  97. }
  98. override func viewDidLoad() {
  99. super.viewDidLoad()
  100. // Do view setup here.
  101. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  102. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  103. createPDFImage = KMDesignButton.init(withType: .Image)
  104. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  105. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  106. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  107. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  108. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  109. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  110. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  111. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  112. self.rightBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  113. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  114. self.otherMouseDown(with: aEvent)
  115. return aEvent
  116. }
  117. self.initNetworkingData()
  118. // self.initLocalization()
  119. // self.initializeUI()
  120. self.initializeUI_DMG()
  121. self.setup()
  122. // refreshUI()
  123. self.updateUI()
  124. self.changeEffectiveAppearance()
  125. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  126. NotificationCenter.default.addObserver(self, selector: #selector(changeEffectiveAppearance), name: NSNotification.Name(rawValue: "kEffectiveAppearance"), object: nil)
  127. // setAppearance(isDarkMode: KMAdvertisementConfig.isDarkModel())
  128. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSApplication.didUpdateNotification.rawValue), object: nil)
  129. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name(NSWindow.didBecomeMainNotification.rawValue), object: nil)
  130. // NotificationCenter.default.addObserver(self, selector: #selector(appearanceChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  131. #if VERSION_DMG
  132. NotificationCenter.default.addObserver(self, selector: #selector(deviceVerifyFinishNotification), name: Notification.Name.init(NSNotification.Name.deviceVerifyFinish.rawValue), object: nil)
  133. #endif
  134. self.loadFunctionGuide()
  135. self.loadAIIconView()
  136. }
  137. override func viewDidAppear() {
  138. super.viewDidAppear()
  139. refreshScrollView()
  140. }
  141. override func viewDidLayout() {
  142. super.viewDidLayout()
  143. refreshScrollView()
  144. }
  145. func initNetworkingData() {
  146. KMAdvertisementManager.manager.fetchDataWithResponseObject { [unowned self] data, responseObject, error in
  147. KMPrint("获取广告数据成功")
  148. if data != nil {
  149. advertisementTableView.inputData = data!.recommondContent
  150. advertisementTableView.didSelect = { view, item in
  151. let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  152. if string.count != 0 {
  153. NSWorkspace.shared.open(URL.init(string: string)!)
  154. }
  155. }
  156. advertisementShowView.inputData = data!.advertisement
  157. }
  158. }
  159. }
  160. func setup() {
  161. //creatPDF
  162. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  163. self.openPDFAction(sender)
  164. }
  165. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  166. self.creatPDFAction(sender)
  167. }
  168. //history
  169. self.homeContentView.historyDidSelect = { [unowned self] view, item in
  170. self.openHistoryFilePath(url: item.url!)
  171. }
  172. self.homeContentView.historyRemoveFileAction = { [unowned self] view, item in
  173. self.historyFile(deleteDocuments: [ item.url!])
  174. }
  175. self.homeContentView.historyShowPathAction = { [unowned self] view, item in
  176. if FileManager.default.fileExists(atPath: item.url!.path) {
  177. NSWorkspace.shared.activateFileViewerSelecting([item.url!])
  178. }
  179. }
  180. self.homeContentView.historyRemoveAllFileAction = { [unowned self] view in
  181. let alert = NSAlert()
  182. alert.alertStyle = .critical
  183. alert.messageText = String(format: "%@?", NSLocalizedString("Clear All Recents", comment: ""))
  184. alert.addButton(withTitle: NSLocalizedString("Delete", comment: ""))
  185. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  186. alert.beginSheetModal(for: self.view.window!) { response in
  187. if response == .alertFirstButtonReturn {
  188. let urls: Array<URL> = NSDocumentController.shared.recentDocumentURLs
  189. self.historyFileDeleteAction(urls)
  190. }
  191. }
  192. }
  193. //quciktools
  194. self.homeContentView.qucikToolsDidSelect = { [unowned self] view, item in
  195. self.fastToolItemAction(item.type!)
  196. }
  197. self.homeContentView.qucikToolsAddAction = { [unowned self] view, item in
  198. KMBatchQuickActionManager.defaultManager.actionType = .add
  199. self.fastToolItemAction(item.type!)
  200. }
  201. self.homeContentView.qucikToolsRemoveAction = { [unowned self] view, item in
  202. KMBatchQuickActionManager.defaultManager.actionType = .remove
  203. self.fastToolItemAction(item.type!)
  204. }
  205. }
  206. // MARK: Init
  207. func initializeUI() {
  208. rightTopBox.fillColor = .white
  209. rightBottomBox.fillColor = .white
  210. rightFullBox.fillColor = .white
  211. self.refreshRightBoxUI(.Home)
  212. fastToolViewController.delete = self
  213. historyFileViewController.delete = self
  214. pdfToolsViewController.delete = self
  215. dragView.delete = self
  216. }
  217. func initLocalization() {
  218. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  219. homeButtonVC.stringValue = NSLocalizedString("Home", comment: "")
  220. pdfToolsButtonVC.stringValue = NSLocalizedString("PDF Tools", comment: "")
  221. cloudDocumentsButtonVC.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  222. openPDFButtonVC.stringValue = NSLocalizedString("Open File", comment: "")
  223. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  224. createPDFButtonVC.stringValue = NSLocalizedString("Create PDF", comment: "")
  225. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  226. pdfSeriesButtonVC.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  227. pdfOthersButtonVC.stringValue = NSLocalizedString("Others", comment: "")
  228. }
  229. // MARK: Action
  230. func initializeUI_DMG() -> Void {
  231. rightTopBox.fillColor = .white
  232. rightBottomBox.fillColor = .white
  233. rightFullBox.fillColor = .white
  234. self.aiHomeBox.fillColor = .clear
  235. self.aiHomeBox.cornerRadius = 8.0
  236. self.aiHomeImageView.image = NSImage(named: "icon_home")
  237. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  238. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  239. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  240. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  241. if aiHomeState != .Home {
  242. if mouseEntered {
  243. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  244. } else {
  245. self.aiHomeBox.fillColor = .clear
  246. }
  247. }
  248. }
  249. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  250. if aiHomeState != .Home {
  251. if downEntered {
  252. self.aiHomeState = .Home
  253. self.refreshAIUI()
  254. }
  255. }
  256. }
  257. self.aiTranslationBox.fillColor = .clear
  258. self.aiTranslationBox.cornerRadius = 8.0
  259. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  260. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  261. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  262. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  263. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  264. if aiHomeState != .AITranslation {
  265. if mouseEntered {
  266. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  267. } else {
  268. self.aiTranslationBox.fillColor = .clear
  269. }
  270. }
  271. }
  272. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  273. if aiHomeState != .AITranslation {
  274. if downEntered {
  275. self.aiHomeState = .AITranslation
  276. self.trackEvent_ai(eventName: "AI Translation")
  277. self.refreshAIUI()
  278. }
  279. }
  280. }
  281. self.aiRewritingBox.fillColor = .clear
  282. self.aiRewritingBox.cornerRadius = 8.0
  283. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  284. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  285. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  286. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  287. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  288. if aiHomeState != .AIRewriting {
  289. if mouseEntered {
  290. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  291. } else {
  292. self.aiRewritingBox.fillColor = .clear
  293. }
  294. }
  295. }
  296. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  297. if aiHomeState != .AIRewriting {
  298. if downEntered {
  299. self.aiHomeState = .AIRewriting
  300. self.trackEvent_ai(eventName: "AI Rewriting")
  301. self.refreshAIUI()
  302. }
  303. }
  304. }
  305. self.aiErrorCorrectionBox.fillColor = .clear
  306. self.aiErrorCorrectionBox.cornerRadius = 8.0
  307. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  308. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  309. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  310. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  311. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  312. if aiHomeState != .AIErrorCorrection {
  313. if mouseEntered {
  314. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  315. } else {
  316. self.aiErrorCorrectionBox.fillColor = .clear
  317. }
  318. }
  319. }
  320. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  321. if aiHomeState != .AIErrorCorrection {
  322. if downEntered {
  323. self.aiHomeState = .AIErrorCorrection
  324. self.trackEvent_ai(eventName: "AI Correction")
  325. self.refreshAIUI()
  326. }
  327. }
  328. }
  329. self.refreshAIUI()
  330. historyFileViewController.delete = self
  331. dragView.delete = self
  332. }
  333. func updateUI() {
  334. self.leftBox.fillColor = KMAppearance.Layout.l0Color()
  335. self.homeSplitView.backgroundColor(KMAppearance.Layout.l0Color())
  336. }
  337. @objc func changeEffectiveAppearance() {
  338. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  339. if isDarkModel {
  340. self.view.appearance = NSAppearance(named: .darkAqua)
  341. } else {
  342. self.view.appearance = NSAppearance(named: .aqua)
  343. }
  344. self.updateUI()
  345. self.advertisementTableView.reloadData()
  346. }
  347. // MARK: Public Methods
  348. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  349. DispatchQueue.global(qos: .`default`).async {
  350. var isSuccessfully = false
  351. if pdf.isEncrypted {
  352. let dic = [
  353. CPDFDocumentWriteOption.userPasswordOption : password,
  354. CPDFDocumentWriteOption.ownerPasswordOption : password
  355. ]
  356. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  357. } else {
  358. isSuccessfully = pdf.write(to: pdf.documentURL)
  359. }
  360. if !isSuccessfully {
  361. if let data = pdf.dataRepresentation() {
  362. isSuccessfully = NSData(data: data).write(to: pdf.documentURL, atomically: true)
  363. }
  364. }
  365. DispatchQueue.main.sync {
  366. if isSuccessfully {
  367. let workspace = NSWorkspace.shared
  368. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  369. workspace.activateFileViewerSelecting([url])
  370. } else {
  371. let alert = NSAlert()
  372. alert.alertStyle = .critical
  373. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  374. alert.runModal()
  375. }
  376. }
  377. }
  378. }
  379. // MARK: Private Methods
  380. func refreshUI() -> Void {
  381. homeButtonVC.updateUI()
  382. pdfToolsButtonVC.updateUI()
  383. cloudDocumentsButtonVC.updateUI()
  384. }
  385. func refreshAIUI() -> Void {
  386. self.aiHomeBox.fillColor = .clear
  387. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  388. self.aiTranslationBox.fillColor = .clear
  389. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  390. self.aiRewritingBox.fillColor = .clear
  391. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  392. self.aiErrorCorrectionBox.fillColor = .clear
  393. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  394. rightFullBox.isHidden = true
  395. rightTopBox.isHidden = true
  396. rightBottomBox.isHidden = true
  397. switch self.aiHomeState {
  398. case .Home:
  399. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  400. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  401. self.rightTopBox.isHidden = false
  402. self.rightBottomBox.isHidden = false
  403. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  404. self.rightBottomBox.contentView = self.historyFileViewController.view
  405. self.rightFullBox.contentView = nil
  406. self.rightTopBoxHeightConstraint.constant = 388.0
  407. self.dragView.isHidden = false
  408. break
  409. case .AITranslation:
  410. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  411. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  412. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  413. self.rightFullBox.isHidden = false
  414. self.rightTopBox.contentView = nil
  415. self.rightBottomBox.contentView = nil
  416. self.rightFullBox.contentView = self.aiTranslationViewController.view
  417. self.dragView.isHidden = false
  418. break
  419. case .AIRewriting:
  420. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  421. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  422. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  423. self.rightFullBox.isHidden = false
  424. self.rightTopBox.contentView = nil
  425. self.rightBottomBox.contentView = nil
  426. self.rightFullBox.contentView = self.aiRewritingViewController.view
  427. // self.aiRewritingViewController.state = .AIRewriting
  428. self.aiRewritingViewController.initLocalization()
  429. self.aiRewritingViewController.acquisition_uiState()
  430. self.dragView.isHidden = true
  431. break
  432. case .AIErrorCorrection:
  433. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  434. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  435. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  436. self.rightFullBox.isHidden = false
  437. self.rightTopBox.contentView = nil
  438. self.rightBottomBox.contentView = nil
  439. self.rightFullBox.contentView = self.aiRewritingViewController.view
  440. // self.aiRewritingViewController.state = .AIErrorCorrection
  441. self.aiRewritingViewController.initLocalization()
  442. self.aiRewritingViewController.acquisition_uiState()
  443. self.dragView.isHidden = true
  444. break
  445. default:
  446. break
  447. }
  448. }
  449. func fetchDifferentFilePath(filePath: String) -> String {
  450. var resultFilePath = filePath
  451. var index: Int = 0
  452. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  453. index += 1
  454. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  455. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  456. }
  457. return resultFilePath;
  458. }
  459. func showProgressWindow() {
  460. let progress = SKProgressController()
  461. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  462. progress.window?.contentView?.wantsLayer = true
  463. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  464. progress.progressField.textColor = NSColor.white
  465. progress.message = NSLocalizedString("Translating...", comment: "")
  466. progress.closeBlock = { [unowned self] in
  467. }
  468. self.progressController = progress
  469. self.view.window?.beginSheet(progress.window!)
  470. }
  471. func hiddenProgressWindow() {
  472. DispatchQueue.main.async {
  473. self.progressController?.doubleValue = 100.0
  474. }
  475. self.stopTimer()
  476. if (self.progressController != nil) {
  477. self.view.window?.endSheet((self.progressController?.window)!)
  478. self.progressController = nil
  479. }
  480. }
  481. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  482. let fileManager = FileManager.default
  483. do {
  484. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  485. if let fileSize = fileAttributes[.size] as? UInt64 {
  486. let megabyteSize = fileSize / (1024 * 1024)
  487. return megabyteSize >= 10
  488. }
  489. } catch {
  490. KMPrint("Error: \(error)")
  491. }
  492. return false
  493. }
  494. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  495. let url = URL(fileURLWithPath: filePath)
  496. guard let document = PDFDocument(url: url) else {
  497. return false
  498. }
  499. let pageCount = document.pageCount
  500. return pageCount > 30
  501. }
  502. @objc func timerTick() {
  503. timerCounter += 1.0
  504. self.progressController?.increment(by: 1.0)
  505. if timerCounter >= 95 {
  506. stopTimer()
  507. }
  508. }
  509. func stopTimer() {
  510. timer?.invalidate()
  511. timer = nil
  512. }
  513. // MARK: Common methods
  514. func workSpaceOpenUrl(_ url: NSString) {
  515. let httpUrl: NSURL = NSURL.init(string: url as String)!
  516. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  517. if !tWorkSpace.open(httpUrl as URL) {
  518. tWorkSpace.open(httpUrl as URL)
  519. }
  520. }
  521. }
  522. //MARK: Open Creat PDF
  523. extension KMHomeViewController: NSPopoverDelegate {
  524. }
  525. extension KMHomeViewController {
  526. func openPDFAction(_ sender: KMBox) {
  527. let openPanel = NSOpenPanel()
  528. openPanel.allowedFileTypes = ["pdf", "PDF"]
  529. openPanel.allowsMultipleSelection = false
  530. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  531. if result == NSApplication.ModalResponse.OK {
  532. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  533. if let error = error {
  534. NSApp.presentError(error)
  535. } else {
  536. self.view.window?.windowController?.close()
  537. }
  538. self.homeContentView.reloadData()
  539. }
  540. }
  541. }
  542. }
  543. func creatPDFAction(_ sender: KMBox) {
  544. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  545. NSLocalizedString("New From Images", comment: ""),
  546. NSLocalizedString("New From Web Page", comment: ""),
  547. NSLocalizedString("Import From Camera", comment: ""),
  548. NSLocalizedString("Import From Scanner", comment: "")]
  549. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  550. let createFilePopover: NSPopover = NSPopover.init()
  551. createFilePopover.contentViewController = vc
  552. createFilePopover.delegate = self
  553. createFilePopover.animates = true
  554. createFilePopover.behavior = .semitransient
  555. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  556. 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)
  557. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  558. if count == NSLocalizedString("New Blank Page", comment: "") {
  559. self.openBlankPage()
  560. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  561. self.importFromCamera()
  562. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  563. self.importFromScanner()
  564. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  565. self.importFromWebPage()
  566. } else if count == NSLocalizedString("New From Images", comment: "") {
  567. self.newFromImages()
  568. }
  569. createFilePopover.close()
  570. }
  571. }
  572. func openBlankPage() {
  573. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  574. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  575. let filePath = savePath.deletingLastPathComponent
  576. if FileManager.default.fileExists(atPath: filePath) == false {
  577. try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  578. }
  579. let pdfDocument = CPDFDocument()
  580. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  581. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  582. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  583. if error != nil {
  584. NSApp.presentError(error!)
  585. } else {
  586. if document is KMMainDocument {
  587. let newDocument = document
  588. (newDocument as! KMMainDocument).isNewCreated = true
  589. }
  590. }
  591. // self.homeContentView?.reloadData()
  592. }
  593. }
  594. func importFromWebPage() {
  595. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  596. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  597. if FileManager.default.fileExists(atPath: filePath) {
  598. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  599. if error != nil {
  600. NSApp.presentError(error!)
  601. } else {
  602. if document is KMMainDocument {
  603. (document as! KMMainDocument).isNewCreated = true
  604. }
  605. }
  606. // self.homeContentView.reloadData()
  607. }
  608. }
  609. })
  610. }
  611. func importFromScanner() {
  612. let vc = KMDeviceBrowserWindowController.shared
  613. vc.type = .scanner
  614. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  615. self?.openFile(withFilePath: url as URL)
  616. }
  617. vc.showWindow(NSApp.mainWindow)
  618. }
  619. func importFromCamera() {
  620. let vc = KMDeviceBrowserWindowController.shared
  621. vc.type = .camera
  622. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  623. self?.openFile(withFilePath: url as URL)
  624. }
  625. vc.showWindow(NSApp.mainWindow)
  626. }
  627. func newFromImages() {
  628. fastTool_ImageToPDF()
  629. // let openPanel = NSOpenPanel()
  630. // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  631. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  632. // openPanel.allowsMultipleSelection = true
  633. // } else {
  634. // openPanel.allowsMultipleSelection = false
  635. // }
  636. // 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: "")
  637. // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  638. // if result == .OK {
  639. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  640. // debugPrint("缺少图片转PDF")
  641. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  642. // var arr: [KMBatchOperateFile] = []
  643. // for url in openPanel.urls {
  644. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  645. // arr.append(file)
  646. // }
  647. //
  648. // if #available(macOS 10.13, *) {
  649. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  650. // } else {
  651. // baseWindowController.showWindow(nil)
  652. // }
  653. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  654. // if #available(macOS 10.13, *) {
  655. // baseWindowController.release()
  656. // }
  657. // }
  658. // }
  659. // }
  660. }
  661. //MARK: - AI
  662. func loadAIIconView() -> Void {
  663. self.aiTipView = AITipIconView.createFromNib()
  664. self.aiTipView.clickHandle = { [weak self] view in
  665. self?.showAITypeChooseView()
  666. }
  667. self.aiTipView.frame = CGRectMake(CGRectGetWidth(self.view.frame)-84, CGRectGetHeight(self.view.frame)-84, 72, 72)
  668. self.aiTipView.autoresizingMask = [.minXMargin, .minYMargin]
  669. self.view.addSubview(self.aiTipView)
  670. }
  671. func showAITypeChooseView() -> Void {
  672. if AIInfoManager.default().aiInfo.infoDict.isEmpty == true {
  673. #if VERSION_DMG
  674. KMPurchaseCompareWindowController.dmgPurchaseInstance().showWindow(nil)
  675. #else
  676. AIPurchaseWindowController.currentWC().showWindow(nil)
  677. #endif
  678. return
  679. }
  680. let controller = NSViewController.init()
  681. let view = NSView.init()
  682. controller.view = view
  683. var string: String = NSLocalizedString("AI Summarize", comment: "")
  684. if string.count < NSLocalizedString("AI Rewrite", comment: "").count {
  685. string = NSLocalizedString("AI Rewrite", comment: "")
  686. }
  687. if string.count < NSLocalizedString("AI Proofread", comment: "").count {
  688. string = NSLocalizedString("AI Proofread", comment: "")
  689. }
  690. if string.count < NSLocalizedString("AI Translate", comment: "").count {
  691. string = NSLocalizedString("AI Translate", comment: "")
  692. }
  693. let font = NSFont.SFProTextRegularFont(13)
  694. var style = NSMutableParagraphStyle.init()
  695. style.alignment = .center
  696. style.lineBreakMode = .byCharWrapping
  697. let size: NSSize = string.boundingRect(with: NSSize(width: 1000, height: 100),
  698. options: NSString.DrawingOptions(rawValue: 3),
  699. attributes: [NSAttributedString.Key.font : NSFont.SFProTextRegularFont(13), NSAttributedString.Key.paragraphStyle : style]).size
  700. controller.view.frame = CGRectMake(0, 0, size.width+80, 160)
  701. if self.aiTypeChooseView == nil {
  702. self.aiTypeChooseView = AITypeChooseView.createFromNib()
  703. }
  704. self.aiTypeChooseView.clickHandle = { [weak self] view, type in
  705. DispatchQueue.main.async {
  706. let windowVC = AIConfigWindowController.currentWC()
  707. windowVC.configType = type
  708. if type == .summarize {
  709. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 500), display: true)
  710. } else if type == .reWriting {
  711. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 460), display: true)
  712. } else if type == .proofreading {
  713. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 460), display: true)
  714. } else if type == .translate {
  715. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 545), display: true)
  716. }
  717. windowVC.cancelHandle = { [weak self] windowVC in
  718. self?.view.window?.endSheet(windowVC.window!)
  719. }
  720. self?.view.window?.beginSheet(windowVC.window!)
  721. windowVC.refreshUI()
  722. }
  723. }
  724. self.aiTypeChooseView.frame = controller.view.bounds
  725. self.aiTypeChooseView.autoresizingMask = [.width, .height]
  726. controller.view.addSubview(self.aiTypeChooseView)
  727. let popover = NSPopover.init()
  728. popover.contentViewController = controller
  729. popover.animates = true
  730. popover.behavior = .transient
  731. var rect = self.aiTipView.bounds
  732. rect.origin.y += 20
  733. popover.show(relativeTo: rect, of: self.aiTipView, preferredEdge: .minY)
  734. }
  735. //MARK: - 引导
  736. func loadFunctionGuide() -> Void {
  737. self.loadNewUserGuide()
  738. }
  739. //MARK: what's New
  740. func loadNewUserGuide() -> Void {
  741. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  742. let guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  743. guideWindowVC.type = .functionMulti
  744. guideWindowVC.showWindow(nil)
  745. guideWindowVC.window?.orderFront(nil)
  746. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  747. }
  748. }
  749. func checkRepeatTrialExpiredController() -> Void {
  750. //试用过期提示比较表弹窗
  751. if didTrialExpiredLoad == true {
  752. return
  753. }
  754. didTrialExpiredLoad = true
  755. let singleTon = KMPurchaseCompareDMGWindowController.init()
  756. singleTon.showWindow(nil)
  757. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  758. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  759. }
  760. }
  761. func checkRepeatTrialAlertController() -> Void {
  762. //允许二次试用时弹出二次试用引导弹窗
  763. if repeatTrialAlertLoad == true {
  764. return
  765. }
  766. repeatTrialAlertLoad = true
  767. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  768. vc?.showWindow(nil)
  769. }
  770. // MARK: - Noti Actions
  771. func deviceVerifyFinishNotification(_ sender: Notification) {
  772. #if VERSION_DMG
  773. if KMVerificationWindowController.allowsShowExpired() {
  774. self.checkRepeatTrialExpiredController()
  775. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  776. self.checkRepeatTrialAlertController()
  777. }
  778. #endif
  779. }
  780. }