KMHomeViewController.swift 42 KB

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