KMHomeViewController.swift 43 KB

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