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