KMHomeViewController.swift 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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. if needShowTabbingHintWindow() {
  557. showTabbingHintWindow()
  558. return
  559. }
  560. let openPanel = NSOpenPanel()
  561. openPanel.allowedFileTypes = ["pdf", "PDF"]
  562. openPanel.allowsMultipleSelection = false
  563. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  564. if result == NSApplication.ModalResponse.OK {
  565. NSDocumentController.shared.km_safe_limit_openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  566. }
  567. }
  568. }
  569. }
  570. func needShowTabbingHintWindow() -> Bool {
  571. let controll: KMBrowserWindowController? = self.view.window?.windowController as? KMBrowserWindowController
  572. if controll?.browser.tabCount() ?? 0 > 1 && !IAPProductsManager.default().isAvailableAllFunction() {
  573. return true
  574. }
  575. return false
  576. }
  577. func showTabbingHintWindow(){
  578. if !KMDataManager.default.isTabbingWin{
  579. KMDataManager.default.isTabbingWin = true
  580. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  581. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  582. KMDataManager.default.isTabbingWin = false
  583. if continueOrNot {
  584. self?.reopenDocument(forPaths: nil)
  585. } else {
  586. }
  587. }
  588. self.km_beginSheet(windowC: tabbingWin)
  589. }
  590. }
  591. func creatPDFAction(_ sender: KMBox) {
  592. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  593. NSLocalizedString("New From Images", comment: ""),
  594. NSLocalizedString("New From Web Page", comment: ""),
  595. NSLocalizedString("Import From Camera", comment: ""),
  596. NSLocalizedString("Import From Scanner", comment: "")]
  597. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  598. vc.background = KMAppearance.Layout.bgColor()
  599. vc.textColor = KMAppearance.Layout.h0Color()
  600. vc.enterFillColor = KMAppearance.Interactive.s0Color()
  601. let createFilePopover: NSPopover = NSPopover.init()
  602. createFilePopover.contentViewController = vc
  603. createFilePopover.delegate = self
  604. createFilePopover.animates = true
  605. createFilePopover.behavior = .semitransient
  606. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  607. 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)
  608. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  609. if count == NSLocalizedString("New Blank Page", comment: "") {
  610. self.openBlankPage()
  611. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  612. self.importFromCamera()
  613. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  614. self.importFromScanner()
  615. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  616. self.importFromWebPage()
  617. } else if count == NSLocalizedString("New From Images", comment: "") {
  618. self.newFromImages()
  619. }
  620. createFilePopover.close()
  621. }
  622. }
  623. func openBlankPage() {
  624. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  625. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  626. let filePath = savePath.deletingLastPathComponent
  627. if FileManager.default.fileExists(atPath: filePath) == false {
  628. try?FileManager.default.createDirectory(atPath: filePath, withIntermediateDirectories: false)
  629. }
  630. let pdfDocument = CPDFDocument()
  631. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  632. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  633. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  634. if error != nil {
  635. NSApp.presentError(error!)
  636. } else {
  637. if document is KMMainDocument {
  638. let newDocument = document
  639. (newDocument as! KMMainDocument).isNewCreated = true
  640. }
  641. }
  642. // self.homeContentView?.reloadData()
  643. }
  644. }
  645. func importFromWebPage() {
  646. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  647. self.urlToPDFWindowController?.beginSheetModalForWindow(NSWindow.currentWindow(), completionHandler: { filePath in
  648. if FileManager.default.fileExists(atPath: filePath) {
  649. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  650. if error != nil {
  651. NSApp.presentError(error!)
  652. } else {
  653. if document is KMMainDocument {
  654. (document as! KMMainDocument).isNewCreated = true
  655. }
  656. }
  657. // self.homeContentView.reloadData()
  658. }
  659. }
  660. })
  661. }
  662. func importFromScanner() {
  663. let vc = KMDeviceBrowserWindowController.shared
  664. vc.type = .scanner
  665. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  666. self?.openFile(withFilePath: url as URL)
  667. }
  668. vc.showWindow(NSApp.mainWindow)
  669. }
  670. func importFromCamera() {
  671. let vc = KMDeviceBrowserWindowController.shared
  672. vc.type = .camera
  673. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  674. self?.openFile(withFilePath: url as URL)
  675. }
  676. vc.showWindow(NSApp.mainWindow)
  677. }
  678. func newFromImages() {
  679. fastTool_ImageToPDF()
  680. // let openPanel = NSOpenPanel()
  681. // openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  682. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  683. // openPanel.allowsMultipleSelection = true
  684. // } else {
  685. // openPanel.allowsMultipleSelection = false
  686. // }
  687. // 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: "")
  688. // openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  689. // if result == .OK {
  690. // DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  691. // debugPrint("缺少图片转PDF")
  692. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  693. // var arr: [KMBatchOperateFile] = []
  694. // for url in openPanel.urls {
  695. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  696. // arr.append(file)
  697. // }
  698. //
  699. // if #available(macOS 10.13, *) {
  700. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  701. // } else {
  702. // baseWindowController.showWindow(nil)
  703. // }
  704. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  705. // if #available(macOS 10.13, *) {
  706. // baseWindowController.release()
  707. // }
  708. // }
  709. // }
  710. // }
  711. }
  712. //MARK: - AI
  713. func loadAIIconView() -> Void {
  714. NotificationCenter.default.addObserver(self, selector: #selector(aiTipIconViewShowStateChangeNoti), name: NSNotification.Name(rawValue: "kAIIconShowStateChangeNotification"), object: nil)
  715. self.aiTipView = AITipIconView.createFromNib()
  716. self.aiTipView.clickHandle = { [weak self] view in
  717. self?.showAITypeChooseView()
  718. }
  719. self.aiTipView.rightClickHandle = { [weak self] view in
  720. AIInfoManager.default().showAIIcon = false
  721. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kAIIconShowStateChangeNotification"), object: nil)
  722. }
  723. self.aiTipView.frame = CGRectMake(CGRectGetWidth(self.view.frame)-84, CGRectGetHeight(self.view.frame)-84-100, 72, 72)
  724. self.aiTipView.autoresizingMask = [.minXMargin, .minYMargin]
  725. self.view.addSubview(self.aiTipView)
  726. self.updateAITipViewShowState()
  727. }
  728. func updateAITipViewShowState() {
  729. if AIInfoManager.default().showAIIcon {
  730. self.aiTipView.isHidden = false
  731. } else {
  732. self.aiTipView.isHidden = true
  733. }
  734. }
  735. func showAITypeChooseView() -> Void {
  736. // if AIInfoManager.default().aiInfo.infoDict.isEmpty == true {
  737. //#if VERSION_DMG
  738. // KMPurchaseCompareWindowController.dmgPurchaseInstance().showWindow(nil)
  739. //#else
  740. // AIPurchaseWindowController.currentWC().showWindow(nil)
  741. //#endif
  742. // return
  743. // }
  744. let controller = NSViewController.init()
  745. let view = NSView.init()
  746. controller.view = view
  747. var string: String = NSLocalizedString("AI Summarize", comment: "")
  748. if string.count < NSLocalizedString("AI Rewrite", comment: "").count {
  749. string = NSLocalizedString("AI Rewrite", comment: "")
  750. }
  751. if string.count < NSLocalizedString("AI Proofread", comment: "").count {
  752. string = NSLocalizedString("AI Proofread", comment: "")
  753. }
  754. if string.count < NSLocalizedString("AI Translate", comment: "").count {
  755. string = NSLocalizedString("AI Translate", comment: "")
  756. }
  757. let font = NSFont.SFProTextRegularFont(13)
  758. var style = NSMutableParagraphStyle.init()
  759. style.alignment = .center
  760. style.lineBreakMode = .byCharWrapping
  761. let size: NSSize = string.boundingRect(with: NSSize(width: 1000, height: 100),
  762. options: NSString.DrawingOptions(rawValue: 3),
  763. attributes: [NSAttributedString.Key.font : NSFont.SFProTextRegularFont(13), NSAttributedString.Key.paragraphStyle : style]).size
  764. controller.view.frame = CGRectMake(0, 0, size.width+80, 160)
  765. if self.aiTypeChooseView == nil {
  766. self.aiTypeChooseView = AITypeChooseView.createFromNib()
  767. }
  768. self.aiTypeChooseView.clickHandle = { [weak self] view, type in
  769. DispatchQueue.main.async {
  770. let windowVC = AIConfigWindowController.currentWC()
  771. windowVC.configType = type
  772. if type == .summarize {
  773. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 500), display: true)
  774. } else if type == .reWriting {
  775. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 460), display: true)
  776. } else if type == .proofreading {
  777. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 460), display: true)
  778. } else if type == .translate {
  779. windowVC.window?.setFrame(CGRectMake(0, 0, 800, 545), display: true)
  780. }
  781. windowVC.cancelHandle = { [weak self] windowVC in
  782. self?.view.window?.endSheet(windowVC.window!)
  783. }
  784. windowVC.refreshUI()
  785. self?.view.window?.beginSheet(windowVC.window!)
  786. windowVC.refreshUI()
  787. }
  788. }
  789. self.aiTypeChooseView.frame = controller.view.bounds
  790. self.aiTypeChooseView.autoresizingMask = [.width, .height]
  791. controller.view.addSubview(self.aiTypeChooseView)
  792. let popover = NSPopover.init()
  793. popover.contentViewController = controller
  794. popover.animates = true
  795. popover.behavior = .transient
  796. var rect = self.aiTipView.bounds
  797. rect.origin.y += 20
  798. popover.show(relativeTo: rect, of: self.aiTipView, preferredEdge: .minY)
  799. }
  800. func loadAITipIconGuide() {
  801. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  802. let guideWC = KMGuideInfoWindowController.currentWC()
  803. guideWC.type = .aiTipIconInfo
  804. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  805. guideWC.finishHandle = { [weak self] windowVC, type in
  806. }
  807. if self.view.window != nil {
  808. var rect = self.view.window?.frame
  809. rect!.size.height -= 20
  810. guideWC.window?.setFrame(rect!, display: true)
  811. guideWC.window?.minSize = rect!.size
  812. guideWC.window?.maxSize = rect!.size
  813. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  814. guideWC.show()
  815. }
  816. }
  817. }
  818. //MARK: - 引导
  819. func loadFunctionGuide() -> Void {
  820. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  821. self.loadNewUserGuide()
  822. }
  823. }
  824. // MARK: - what's New
  825. func loadNewUserGuide() -> Void {
  826. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  827. let guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  828. guideWindowVC.type = .functionMulti
  829. guideWindowVC.showWindow(nil)
  830. guideWindowVC.window?.orderFront(nil)
  831. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  832. }
  833. }
  834. func checkRepeatTrialExpiredController() -> Void {
  835. //试用过期提示比较表弹窗
  836. if didTrialExpiredLoad == true {
  837. return
  838. }
  839. didTrialExpiredLoad = true
  840. let singleTon = KMPurchaseCompareDMGWindowController.init()
  841. singleTon.showWindow(nil)
  842. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  843. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  844. }
  845. }
  846. func checkRepeatTrialAlertController() -> Void {
  847. //允许二次试用时弹出二次试用引导弹窗
  848. if repeatTrialAlertLoad == true {
  849. return
  850. }
  851. repeatTrialAlertLoad = true
  852. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  853. vc?.showWindow(nil)
  854. }
  855. // MARK: - Noti Actions
  856. func deviceVerifyFinishNotification(_ sender: Notification) {
  857. #if VERSION_DMG
  858. if KMVerificationWindowController.allowsShowExpired() {
  859. self.checkRepeatTrialExpiredController()
  860. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  861. self.checkRepeatTrialAlertController()
  862. }
  863. #endif
  864. }
  865. @objc func aiTipIconViewShowStateChangeNoti() {
  866. self.updateAITipViewShowState()
  867. }
  868. }