KMHomeViewController.swift 39 KB

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