KMHomeViewController.swift 43 KB

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