KMHomeViewController.swift 40 KB

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