KMHomeViewController.swift 42 KB

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