KMHomeViewController.swift 38 KB

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