KMHomeViewController.swift 43 KB

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