KMHomeViewController.swift 37 KB

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