KMHomeViewController.swift 41 KB

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