KMHomeViewController.swift 44 KB

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