KMHomeViewController.swift 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  759. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  760. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  761. let documentArray = NSDocumentController.shared.documents
  762. var didFileEdit: Bool = false
  763. var curDoc: KMMainDocument!
  764. for document in documentArray {
  765. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  766. didFileEdit = document.isDocumentEdited
  767. curDoc = document as! KMMainDocument
  768. break
  769. }
  770. }
  771. if didFileEdit {
  772. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  773. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  774. do {
  775. try FileManager.default.removeItem(at: tempFileURL)
  776. } catch {
  777. }
  778. }
  779. if curDoc != nil {
  780. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  781. }
  782. }
  783. windowVC.window?.becomeMain()
  784. }
  785. }
  786. windowVC.window?.center()
  787. windowVC.eventLabel = "AITools_Onboard"
  788. windowVC.showWindow(nil)
  789. }
  790. func loadAITipIconGuide() {
  791. if KMGuideInfoWindowController.availableShow(.aiTipIconInfo) {
  792. let guideWC = KMGuideInfoWindowController.currentWC()
  793. guideWC.type = .aiTipIconInfo
  794. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  795. guideWC.finishHandle = { [weak self] windowVC, type in
  796. }
  797. if self.view.window != nil {
  798. var rect = self.view.window?.frame
  799. rect!.size.height -= 20
  800. guideWC.window?.setFrame(rect!, display: true)
  801. guideWC.window?.minSize = rect!.size
  802. guideWC.window?.maxSize = rect!.size
  803. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  804. guideWC.show()
  805. }
  806. }
  807. }
  808. //MARK: - 引导
  809. func loadFunctionGuide() -> Void {
  810. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  811. self.loadNewUserGuide()
  812. }
  813. }
  814. // MARK: - what's New
  815. func loadNewUserGuide() -> Void {
  816. if KMFunctionGuideWindowController.availableShow(.functionMultiAIGuide) {
  817. let guideWindowVC = KMFunctionGuideWindowController.init(windowNibName: "KMFunctionGuideWindowController")
  818. guideWindowVC.type = .functionMulti
  819. guideWindowVC.showWindow(nil)
  820. guideWindowVC.window?.orderFront(nil)
  821. KMFunctionGuideWindowController.setDidShowFor(.functionMultiAIGuide)
  822. }
  823. }
  824. func checkRepeatTrialExpiredController() -> Void {
  825. //试用过期提示比较表弹窗
  826. if didTrialExpiredLoad == true {
  827. return
  828. }
  829. didTrialExpiredLoad = true
  830. let singleTon = KMPurchaseCompareDMGWindowController.init()
  831. singleTon.showWindow(nil)
  832. if singleTon.className == KMPurchaseCompareDMGWindowController.className() {
  833. singleTon.updateTitle(NSLocalizedString("Trial Expired, Upgrade to Pro Version", comment: ""), andColor: NSColor(red: 1, green: 59/255, blue: 47/255, alpha: 1))
  834. }
  835. }
  836. func checkRepeatTrialAlertController() -> Void {
  837. //允许二次试用时弹出二次试用引导弹窗
  838. if repeatTrialAlertLoad == true {
  839. return
  840. }
  841. repeatTrialAlertLoad = true
  842. let vc = KMVerificationWindowController.verification(with:.repeatTrialGuide)
  843. vc?.showWindow(nil)
  844. }
  845. // MARK: - Noti Actions
  846. func deviceVerifyFinishNotification(_ sender: Notification) {
  847. #if VERSION_DMG
  848. if KMVerificationWindowController.allowsShowExpired() {
  849. self.checkRepeatTrialExpiredController()
  850. } else if KMVerificationWindowController.allowRepeatTrialAlertShow() {
  851. self.checkRepeatTrialAlertController()
  852. }
  853. #endif
  854. }
  855. @objc func aiTipIconViewShowStateChangeNoti() {
  856. self.updateAITipViewShowState()
  857. }
  858. }