KMHomeViewController.swift 43 KB

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