KMHomeViewController.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. //
  2. // KMHomeViewController.swift
  3. // PDF Master
  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. //广告 互推
  54. @IBOutlet weak var advertisementTableView: KMAdvertisementTableView!
  55. @IBOutlet weak var advertisementTableViewHeightConstraint: NSLayoutConstraint!
  56. @IBOutlet weak var advertisementShowView: KMAdvertisementShowView!
  57. var aiHomeState: KMAIHomeToolState = .Home
  58. let ScrollerViewWidget: CGFloat = 15.0
  59. var homeWindowController : MainWindowController!
  60. // 产品推广数据
  61. var productPromotionPDFProSeries: NSArray!
  62. var productPromotionOthers: NSArray!
  63. var productPromotionData: NSDictionary!
  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. @IBOutlet weak var rightBottonHeight: NSLayoutConstraint!
  84. deinit {
  85. }
  86. override func viewWillAppear() {
  87. super.viewWillAppear()
  88. if !KMLightMemberManager.manager.isLogin() {
  89. KMLightMemberManager.manager.canShowAdvancedView = true
  90. }
  91. }
  92. override func viewDidLoad() {
  93. super.viewDidLoad()
  94. // Do view setup here.
  95. openPDFButtonVC = KMDesignButton.init(withType: .Text)
  96. createPDFButtonVC = KMDesignButton.init(withType: .Text)
  97. createPDFImage = KMDesignButton.init(withType: .Image)
  98. createPDFAddButtonVC = KMDesignButton.init(withType: .Image)
  99. homeButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  100. pdfToolsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  101. cloudDocumentsButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  102. pdfSeriesButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  103. pdfOthersButtonVC = KMTextImageButtonVC.init(nibName: "KMTextImageButtonVC", bundle: nil)
  104. self.homeSplitView.setPosition(270.0, ofDividerAt: 0)
  105. self.leftBox.fillColor = NSColor.km_init(hex: "#F7F8FA")
  106. self.productPromotionPDFProSeries = ["Windows", "iPhone / iPad", "Android"]
  107. self.productPromotionOthers = ["ComPDFKit", "SignFlow", "FiImage Editor", "FiImage Screen", "Free PDF Templates"]
  108. self.productPromotionData = ["Windows": ["Name" : "Windows", "Image" : "icon_home_logo_windows", "link":""],
  109. "iPhone / iPad" : ["Name" : "iPhone / iPad", "Image" : "icon_home_logo_mac", "link":""],
  110. "Android" : ["Name" : "Android", "Image" : "icon_home_logo_android", "link":""],
  111. "ComPDFKit" : ["Name" : "ComPDFKit", "Image" : "icon_home_logo_comPDFKit", "link":""],
  112. "SignFlow" : ["Name" : "SignFlow", "Image" : "icon_home_logo_signflow", "link":""],
  113. "FiImage Editor" : ["Name" : "FiImage Editor", "Image" : "icon_home_logo_editor", "link":""],
  114. "FiImage Screen" : ["Name" : "FiImage Screen", "Image" : "icon_home_logo_screen", "link":""],
  115. "Free PDF Templates" : ["Name" : "Free PDF Templates", "Image" : "icon_home_logo_templates"], "link":""]
  116. NSEvent.addLocalMonitorForEvents(matching: .leftMouseDown) { (aEvent) -> NSEvent? in
  117. self.otherMouseDown(with: aEvent)
  118. return aEvent
  119. }
  120. self.initNetworkingData()
  121. // self.initLocalization()
  122. // self.initializeUI()
  123. self.initializeUI_DMG()
  124. self.setup()
  125. // refreshUI()
  126. NotificationCenter.default.addObserver(self, selector: #selector(homeFileRectChange(_:)), name: Notification.Name("KMHomeFileRectChange"), object: nil)
  127. }
  128. override func viewDidAppear() {
  129. super.viewDidAppear()
  130. refreshScrollView()
  131. }
  132. override func viewDidLayout() {
  133. super.viewDidLayout()
  134. refreshScrollView()
  135. }
  136. func initNetworkingData() {
  137. KMAdvertisementManager.manager.fetchDataWithResponseObject { [unowned self] data, responseObject, error in
  138. KMPrint("获取广告数据成功")
  139. if data != nil {
  140. advertisementTableView.inputData = data!.recommondContent
  141. advertisementTableView.didSelect = { view, item in
  142. let string = KMAdvertisementModelTransition.transitionLanguage(langeuage: item.linkURL)
  143. if NSWorkspace.shared.open(URL.init(string: string)!) {
  144. NSWorkspace.shared.open(URL.init(string: string)!)
  145. }
  146. }
  147. advertisementShowView.inputData = data!.advertisement
  148. }
  149. }
  150. }
  151. func setup() {
  152. self.creatPDFView.openPDFAction = { [unowned self] view, sender in
  153. self.openPDFAction(sender)
  154. }
  155. self.creatPDFView.creatPDFAction = { [unowned self] view, sender in
  156. self.creatPDFAction(sender)
  157. }
  158. }
  159. // MARK: Init
  160. func initializeUI() {
  161. // pdfToolsBox.fillColor = .clear
  162. // pdfToolsBox.contentView = pdfToolsButtonVC.view
  163. // pdfToolsButtonVC.target = self
  164. // pdfToolsButtonVC.action = #selector(self.homeToolAction(_:))
  165. // pdfToolsButtonVC.image = NSImage(named: "icon_home_sidebar_tool_false")!
  166. // pdfToolsButtonVC.image_hover = NSImage(named: "icon_home_sidebar_tool_false")!
  167. // pdfToolsButtonVC.image_click = NSImage(named: "icon_home_sidebar_tool_true")!
  168. // pdfToolsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.norm", text: "navmenu.win-text.def", height: pdfToolsBoxHeight)
  169. // pdfToolsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.hov", text: "navmenu.win-text.def", state:.Hov)
  170. // pdfToolsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.sel", text: "navmenu.win-text.sel", state:.Sel)
  171. //
  172. // cloudDocumentsBox.fillColor = .clear
  173. // cloudDocumentsBox.contentView = cloudDocumentsButtonVC.view
  174. // cloudDocumentsButtonVC.target = self
  175. // cloudDocumentsButtonVC.action = #selector(self.homeToolAction(_:))
  176. // cloudDocumentsButtonVC.image = NSImage(named: "icon_home_sidebar_cloud_false")!
  177. // cloudDocumentsButtonVC.image_hover = NSImage(named: "icon_home_sidebar_cloud_false")!
  178. // cloudDocumentsButtonVC.image_click = NSImage(named: "icon_home_sidebar_cloud_true")!
  179. // cloudDocumentsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.norm", text: "navmenu.win-text.def", height: cloudDocumentsBoxHeight)
  180. // cloudDocumentsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.hov", text: "navmenu.win-text.def", state:.Hov)
  181. // cloudDocumentsButtonVC.navMenu(bg: "navmenu.has-icon.m.bg.sel", text: "navmenu.win-text.sel", state:.Sel)
  182. //
  183. // pdfSeriesBox.fillColor = .clear
  184. // pdfSeriesBox.contentView = pdfSeriesButtonVC.view
  185. // pdfSeriesButtonVC.target = self
  186. // pdfSeriesButtonVC.action = #selector(self.productPromotionFoldOrUnfold(_:))
  187. // pdfSeriesButtonVC.type = .Right
  188. // pdfSeriesButtonVC.canHover = false
  189. // pdfSeriesButtonVC.imageWidth = 12.0
  190. // pdfSeriesButtonVC.imageHeight = 12.0
  191. // pdfSeriesButtonVC.image = NSImage(named: "icon_btn_expand_lv2_down_false")!
  192. // pdfSeriesButtonVC.navMenu(bg: "collapse.ad-list.bg", text: "collapse.ad-list.mac-text.norm", height: pdfSeriesBoxHeight)
  193. //
  194. // pdfOthersBox.fillColor = .clear
  195. // pdfOthersBox.contentView = pdfOthersButtonVC.view
  196. // pdfOthersButtonVC.target = self
  197. // pdfOthersButtonVC.action = #selector(self.productPromotionFoldOrUnfold(_:))
  198. // pdfOthersButtonVC.type = .Right
  199. // pdfOthersButtonVC.canHover = false
  200. // pdfOthersButtonVC.imageWidth = 12.0
  201. // pdfOthersButtonVC.imageHeight = 12.0
  202. // pdfOthersButtonVC.image = NSImage(named: "icon_btn_expand_lv2_down_false")!
  203. // pdfOthersButtonVC.navMenu(bg: "collapse.ad-list.bg", text: "collapse.ad-list.mac-text.norm", height: othersBoxHeightConstraint)
  204. // if self.activitiesBox.isHidden {
  205. // self.productPromotionShow(self.productPromotionPDFProSeries, withOthers: self.productPromotionOthers, isInitialize: true)
  206. // } else {
  207. // self.productPromotionShow(self.productPromotionPDFProSeries, withOthers: [], isInitialize: true)
  208. // }
  209. self.productPromotionShow(self.productPromotionPDFProSeries, withOthers: self.productPromotionOthers, isInitialize: true)
  210. // self.activitiesBox.contentView = KMProductPromotionViewController.init().view
  211. // activitiesBox.cornerRadius = 8.0
  212. rightTopBox.fillColor = .white
  213. rightBottomBox.fillColor = .white
  214. rightFullBox.fillColor = .white
  215. // productPromotionBox.fillColor = .clear
  216. //
  217. // product_active_scrollView.verticalScrollElasticity = .none
  218. self.refreshRightBoxUI(.Home)
  219. fastToolViewController.delete = self
  220. historyFileViewController.delete = self
  221. pdfToolsViewController.delete = self
  222. dragView.delete = self
  223. }
  224. func initLocalization() {
  225. // self.favoriteDocumentsLabel.stringValue = NSLocalizedString("Favorite Documents", comment: "")
  226. homeButtonVC.stringValue = NSLocalizedString("Home", comment: "")
  227. pdfToolsButtonVC.stringValue = NSLocalizedString("PDF Tools", comment: "")
  228. cloudDocumentsButtonVC.stringValue = NSLocalizedString("Cloud Documents", comment: "")
  229. openPDFButtonVC.stringValue = NSLocalizedString("Open File", comment: "")
  230. // openPDFBox.toolTip = NSLocalizedString("Open PDF", comment: "")
  231. createPDFButtonVC.stringValue = NSLocalizedString("Create PDF", comment: "")
  232. // createPDFBox.toolTip = NSLocalizedString("Create PDF", comment: "")
  233. pdfSeriesButtonVC.stringValue = NSLocalizedString("PDF Pro Series", comment: "")
  234. pdfOthersButtonVC.stringValue = NSLocalizedString("Others", comment: "")
  235. }
  236. // MARK: Action
  237. func initializeUI_DMG() -> Void {
  238. rightTopBox.fillColor = .white
  239. rightBottomBox.fillColor = .white
  240. rightFullBox.fillColor = .white
  241. self.aiHomeBox.fillColor = .clear
  242. self.aiHomeBox.cornerRadius = 8.0
  243. self.aiHomeImageView.image = NSImage(named: "icon_home")
  244. self.aiHomeLabel.stringValue = NSLocalizedString("Home", comment: "")
  245. self.aiHomeLabel.textColor = NSColor.km_init(hex: "#252629")
  246. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  247. self.aiHomeBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  248. if aiHomeState != .Home {
  249. if mouseEntered {
  250. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  251. } else {
  252. self.aiHomeBox.fillColor = .clear
  253. }
  254. }
  255. }
  256. self.aiHomeBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  257. if aiHomeState != .Home {
  258. if downEntered {
  259. self.aiHomeState = .Home
  260. self.refreshAIUI()
  261. }
  262. }
  263. }
  264. self.aiTranslationBox.fillColor = .clear
  265. self.aiTranslationBox.cornerRadius = 8.0
  266. self.aiTranslationImageView.image = NSImage(named: "ic_function_other")
  267. self.aiTranslationLabel.stringValue = NSLocalizedString("AI Translation", comment: "")
  268. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  269. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  270. self.aiTranslationBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  271. if aiHomeState != .AITranslation {
  272. if mouseEntered {
  273. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  274. } else {
  275. self.aiTranslationBox.fillColor = .clear
  276. }
  277. }
  278. }
  279. self.aiTranslationBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  280. if aiHomeState != .AITranslation {
  281. if downEntered {
  282. self.aiHomeState = .AITranslation
  283. self.trackEvent_ai(eventName: "AI Translation")
  284. self.refreshAIUI()
  285. }
  286. }
  287. }
  288. self.aiRewritingBox.fillColor = .clear
  289. self.aiRewritingBox.cornerRadius = 8.0
  290. self.aiRewritingImageView.image = NSImage(named: "ic_ai_Rewriting")
  291. self.aiRewritingLabel.stringValue = NSLocalizedString("AI Rewriting", comment: "")
  292. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  293. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  294. self.aiRewritingBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  295. if aiHomeState != .AIRewriting {
  296. if mouseEntered {
  297. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  298. } else {
  299. self.aiRewritingBox.fillColor = .clear
  300. }
  301. }
  302. }
  303. self.aiRewritingBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  304. if aiHomeState != .AIRewriting {
  305. if downEntered {
  306. self.aiHomeState = .AIRewriting
  307. self.trackEvent_ai(eventName: "AI Rewriting")
  308. self.refreshAIUI()
  309. }
  310. }
  311. }
  312. self.aiErrorCorrectionBox.fillColor = .clear
  313. self.aiErrorCorrectionBox.cornerRadius = 8.0
  314. self.aiErrorCorrectionImageView.image = NSImage(named: "ic_ai_ErrorCorrection")
  315. self.aiErrorCorrectionLabel.stringValue = NSLocalizedString("AI Error Correction", comment: "")
  316. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  317. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  318. self.aiErrorCorrectionBox.moveCallback = { [unowned self](mouseEntered: Bool, mouseBox: KMBox) -> Void in
  319. if aiHomeState != .AIErrorCorrection {
  320. if mouseEntered {
  321. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#EDEEF0")
  322. } else {
  323. self.aiErrorCorrectionBox.fillColor = .clear
  324. }
  325. }
  326. }
  327. self.aiErrorCorrectionBox.downCallback = { [unowned self](downEntered: Bool, mouseBox: KMBox, event) -> Void in
  328. if aiHomeState != .AIErrorCorrection {
  329. if downEntered {
  330. self.aiHomeState = .AIErrorCorrection
  331. self.trackEvent_ai(eventName: "AI Correction")
  332. self.refreshAIUI()
  333. }
  334. }
  335. }
  336. self.refreshAIUI()
  337. historyFileViewController.delete = self
  338. dragView.delete = self
  339. }
  340. // MARK: Action
  341. @IBAction func productPromotionButtonAction(_ sender: NSButton) {
  342. self.productPromotionFoldOrUnfold(sender)
  343. }
  344. // MARK: Public Methods
  345. func savePDFDocument(_ pdf: CPDFDocument, password: String) -> Void {
  346. DispatchQueue.global(qos: .`default`).async {
  347. var isSuccessfully = false
  348. if pdf.isEncrypted {
  349. let dic = [
  350. CPDFDocumentWriteOption.userPasswordOption : password,
  351. CPDFDocumentWriteOption.ownerPasswordOption : password
  352. ]
  353. isSuccessfully = pdf.write(to: pdf.documentURL, withOptions: dic)
  354. } else {
  355. isSuccessfully = pdf.write(to: pdf.documentURL)
  356. }
  357. if !isSuccessfully {
  358. isSuccessfully = NSData(data: pdf.dataRepresentation()).write(to: pdf.documentURL, atomically: true)
  359. }
  360. DispatchQueue.main.sync {
  361. if isSuccessfully {
  362. let workspace = NSWorkspace.shared
  363. let url = URL(fileURLWithPath: pdf.documentURL?.path ?? "")
  364. workspace.activateFileViewerSelecting([url])
  365. } else {
  366. let alert = NSAlert()
  367. alert.alertStyle = .critical
  368. alert.messageText = NSLocalizedString("Failed to insert page(s)!", comment: "")
  369. alert.runModal()
  370. }
  371. }
  372. }
  373. }
  374. // MARK: Private Methods
  375. func refreshUI() -> Void {
  376. homeButtonVC.updateUI()
  377. pdfToolsButtonVC.updateUI()
  378. cloudDocumentsButtonVC.updateUI()
  379. }
  380. func refreshAIUI() -> Void {
  381. self.aiHomeBox.fillColor = .clear
  382. self.aiHomeLabel.font = NSFont.SFProTextRegularFont(16.0)
  383. self.aiTranslationBox.fillColor = .clear
  384. self.aiTranslationLabel.font = NSFont.SFProTextRegularFont(16.0)
  385. self.aiRewritingBox.fillColor = .clear
  386. self.aiRewritingLabel.font = NSFont.SFProTextRegularFont(16.0)
  387. self.aiErrorCorrectionBox.fillColor = .clear
  388. self.aiErrorCorrectionLabel.font = NSFont.SFProTextRegularFont(16.0)
  389. rightFullBox.isHidden = true
  390. rightTopBox.isHidden = true
  391. rightBottomBox.isHidden = true
  392. switch self.aiHomeState {
  393. case .Home:
  394. self.aiHomeBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  395. self.aiHomeLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  396. self.rightTopBox.isHidden = false
  397. self.rightBottomBox.isHidden = false
  398. self.rightTopBox.contentView = self.aiOpenPDFFilesViewController.view
  399. self.rightBottomBox.contentView = self.historyFileViewController.view
  400. self.rightFullBox.contentView = nil
  401. self.rightTopBoxHeightConstraint.constant = 388.0
  402. self.dragView.isHidden = false
  403. break
  404. case .AITranslation:
  405. self.aiTranslationBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  406. self.aiTranslationLabel.textColor = NSColor.km_init(hex: "#252629")
  407. self.aiTranslationLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  408. self.rightFullBox.isHidden = false
  409. self.rightTopBox.contentView = nil
  410. self.rightBottomBox.contentView = nil
  411. self.rightFullBox.contentView = self.aiTranslationViewController.view
  412. self.dragView.isHidden = false
  413. break
  414. case .AIRewriting:
  415. self.aiRewritingBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  416. self.aiRewritingLabel.textColor = NSColor.km_init(hex: "#252629")
  417. self.aiRewritingLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  418. self.rightFullBox.isHidden = false
  419. self.rightTopBox.contentView = nil
  420. self.rightBottomBox.contentView = nil
  421. self.rightFullBox.contentView = self.aiRewritingViewController.view
  422. self.aiRewritingViewController.state = .AIRewriting
  423. self.aiRewritingViewController.initLocalization()
  424. self.aiRewritingViewController.acquisition_uiState()
  425. self.dragView.isHidden = true
  426. break
  427. case .AIErrorCorrection:
  428. self.aiErrorCorrectionBox.fillColor = NSColor.km_init(hex: "#1770F4", alpha: 0.1)
  429. self.aiErrorCorrectionLabel.textColor = NSColor.km_init(hex: "#252629")
  430. self.aiErrorCorrectionLabel.font = NSFont.SFProTextSemiboldFont(16.0)
  431. self.rightFullBox.isHidden = false
  432. self.rightTopBox.contentView = nil
  433. self.rightBottomBox.contentView = nil
  434. self.rightFullBox.contentView = self.aiRewritingViewController.view
  435. self.aiRewritingViewController.state = .AIErrorCorrection
  436. self.aiRewritingViewController.initLocalization()
  437. self.aiRewritingViewController.acquisition_uiState()
  438. self.dragView.isHidden = true
  439. break
  440. default:
  441. break
  442. }
  443. }
  444. func refreshProductActiveSpacing() -> Void {
  445. // let height = self.view.frame.height - 32.0 - openPDFBoxHeight.constant - 16.0 - createPDFBoxHeight.constant - 24.0 - pdfSeriesBoxHeight.constant - pdfProSeriesBoxHeightConstraint.constant - 8 - othersBoxHeightConstraint.constant - pdfOthersBoxHeightConstraint.constant - 242 - 30
  446. //// print("height == %f", height)
  447. // if height > 24.0 {
  448. // self.product_active_spacing.constant = height
  449. // } else {
  450. // self.product_active_spacing.constant = 24.0
  451. // }
  452. }
  453. func fetchDifferentFilePath(filePath: String) -> String {
  454. var resultFilePath = filePath
  455. var index: Int = 0
  456. while (FileManager.default.fileExists(atPath: resultFilePath)) {
  457. index += 1
  458. let path = NSString(string: filePath).deletingPathExtension + "(" + String(index) + ")"
  459. resultFilePath = NSString(string: path).appendingPathExtension(NSString(string: filePath).pathExtension)!
  460. }
  461. return resultFilePath;
  462. }
  463. func showProgressWindow() {
  464. let progress = SKProgressController()
  465. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  466. progress.window?.contentView?.wantsLayer = true
  467. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  468. progress.progressField.textColor = NSColor.white
  469. progress.message = NSLocalizedString("Translating...", comment: "")
  470. progress.closeBlock = { [unowned self] in
  471. }
  472. self.progressController = progress
  473. self.view.window?.beginSheet(progress.window!)
  474. }
  475. func hiddenProgressWindow() {
  476. DispatchQueue.main.async {
  477. self.progressController?.doubleValue = 100.0
  478. }
  479. self.stopTimer()
  480. if (self.progressController != nil) {
  481. self.view.window?.endSheet((self.progressController?.window)!)
  482. self.progressController = nil
  483. }
  484. }
  485. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  486. let fileManager = FileManager.default
  487. do {
  488. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  489. if let fileSize = fileAttributes[.size] as? UInt64 {
  490. let megabyteSize = fileSize / (1024 * 1024)
  491. return megabyteSize >= 10
  492. }
  493. } catch {
  494. KMPrint("Error: \(error)")
  495. }
  496. return false
  497. }
  498. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  499. let url = URL(fileURLWithPath: filePath)
  500. guard let document = PDFDocument(url: url) else {
  501. return false
  502. }
  503. let pageCount = document.pageCount
  504. return pageCount > 30
  505. }
  506. @objc func timerTick() {
  507. timerCounter += 1.0
  508. self.progressController?.increment(by: 1.0)
  509. if timerCounter >= 95 {
  510. stopTimer()
  511. }
  512. }
  513. func stopTimer() {
  514. timer?.invalidate()
  515. timer = nil
  516. }
  517. // MARK: Common methods
  518. func workSpaceOpenUrl(_ url: NSString) {
  519. let httpUrl: NSURL = NSURL.init(string: url as String)!
  520. let tWorkSpace: NSWorkspace = NSWorkspace.shared
  521. if !tWorkSpace.open(httpUrl as URL) {
  522. tWorkSpace.open(httpUrl as URL)
  523. }
  524. }
  525. }
  526. //MARK: Open Creat PDF
  527. extension KMHomeViewController: NSPopoverDelegate {
  528. }
  529. extension KMHomeViewController {
  530. func openPDFAction(_ sender: KMBox) {
  531. let openPanel = NSOpenPanel()
  532. openPanel.allowedFileTypes = ["pdf", "PDF"]
  533. openPanel.allowsMultipleSelection = false
  534. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  535. if result == NSApplication.ModalResponse.OK {
  536. NSDocumentController.shared.openDocument(withContentsOf: openPanel.url!, display: true) { (document, documentWasAlreadyOpen, error) in
  537. if let error = error {
  538. NSApp.presentError(error)
  539. } else {
  540. self.view.window?.windowController?.close()
  541. }
  542. }
  543. }
  544. }
  545. }
  546. func creatPDFAction(_ sender: KMBox) {
  547. let popViewDataArr: [String] = [NSLocalizedString("New Blank Page", comment: ""),
  548. NSLocalizedString("New From Images", comment: ""),
  549. NSLocalizedString("New From Web Page", comment: ""),
  550. NSLocalizedString("Import From Camera", comment: ""),
  551. NSLocalizedString("Import From Scanner", comment: "")]
  552. let vc: KMHomePopViewController = KMHomePopViewController().initWithPopViewDataArr(popViewDataArr)
  553. let createFilePopover: NSPopover = NSPopover.init()
  554. createFilePopover.contentViewController = vc
  555. createFilePopover.delegate = self
  556. createFilePopover.animates = true
  557. createFilePopover.behavior = .semitransient
  558. createFilePopover.setValue(true, forKey: "shouldHideAnchor")
  559. 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)
  560. vc.downCallback = { [unowned self] (downEntered: Bool, count: String) -> Void in
  561. if count == NSLocalizedString("New Blank Page", comment: "") {
  562. self.openBlankPage()
  563. } else if count == NSLocalizedString("Import From Camera", comment: "") {
  564. self.importFromCamera()
  565. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  566. self.importFromScanner()
  567. } else if count == NSLocalizedString("New From Web Page", comment: "") {
  568. self.importFromWebPage()
  569. } else if count == NSLocalizedString("Import From Scanner", comment: "") {
  570. self.newFromImages()
  571. }
  572. createFilePopover.close()
  573. }
  574. }
  575. func openBlankPage() {
  576. let fileName: NSString = String(format: "%@.pdf", NSLocalizedString("Untitled", comment: "")) as NSString
  577. let savePath = fetchUniquePath(fileName.kUrlToPDFFolderPath() as String)
  578. let pdfDocument = CPDFDocument()
  579. pdfDocument?.insertPage(CGSize(width: 595, height: 842), at: 0)
  580. pdfDocument?.write(to: URL(fileURLWithPath: savePath))
  581. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: savePath), display: true) { document, documentWasAlreadyOpen, error in
  582. if error != nil {
  583. NSApp.presentError(error!)
  584. } else {
  585. if document is KMMainDocument {
  586. let newDocument = document
  587. (newDocument as! KMMainDocument).isNewCreated = true
  588. }
  589. }
  590. }
  591. }
  592. func importFromWebPage() {
  593. self.urlToPDFWindowController = KMURLToPDFWindowController.init(windowNibName: NSNib.Name("KMURLToPDFWindowController"))
  594. self.urlToPDFWindowController?.beginSheetModalForWindow(NSApp.mainWindow!, completionHandler: { filePath in
  595. if FileManager.default.fileExists(atPath: filePath) {
  596. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: filePath), display: true) { document, documentWasAlreadyOpen, error in
  597. if error != nil {
  598. NSApp.presentError(error!)
  599. } else {
  600. if document is KMMainDocument {
  601. (document as! KMMainDocument).isNewCreated = true
  602. }
  603. }
  604. }
  605. }
  606. })
  607. }
  608. func importFromScanner() {
  609. let vc = KMDeviceBrowserWindowController.shared
  610. vc.type = .scanner
  611. vc.importScannerFileCallback = { [weak self](url: NSURL) -> Void in
  612. self?.openFile(withFilePath: url as URL)
  613. }
  614. vc.showWindow(NSApp.mainWindow)
  615. }
  616. func importFromCamera() {
  617. let vc = KMDeviceBrowserWindowController.shared
  618. vc.type = .camera
  619. vc.importCameraFileCallback = { [weak self] (url: NSURL) -> Void in
  620. self?.openFile(withFilePath: url as URL)
  621. }
  622. vc.showWindow(NSApp.mainWindow)
  623. }
  624. func newFromImages() {
  625. let openPanel = NSOpenPanel()
  626. openPanel.allowedFileTypes = KMImageAccessoryController.supportedImageTypes()
  627. // if IAPProductsManager.defaultManager().isAvailableAllFunction {
  628. // openPanel.allowsMultipleSelection = true
  629. // } else {
  630. // openPanel.allowsMultipleSelection = false
  631. // }
  632. 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: "")
  633. openPanel.beginSheetModal(for: NSApp.mainWindow!) { result in
  634. if result == .OK {
  635. DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
  636. debugPrint("缺少图片转PDF")
  637. // let baseWindowController = KMBatchOperateBaseWindowController(windowNibName: "KMBatchOperateBaseWindowController")
  638. // var arr: [KMBatchOperateFile] = []
  639. // for url in openPanel.urls {
  640. // let file = KMBatchOperateFile(filePath: url.path, type: .createPDF)
  641. // arr.append(file)
  642. // }
  643. //
  644. // if #available(macOS 10.13, *) {
  645. // baseWindowController.window?.makeKeyAndOrderFront(nil)
  646. // } else {
  647. // baseWindowController.showWindow(nil)
  648. // }
  649. // baseWindowController.checkNeedPasswordSwitch(toOperateType: .createPDF, files: arr)
  650. // if #available(macOS 10.13, *) {
  651. // baseWindowController.release()
  652. // }
  653. }
  654. }
  655. }
  656. }
  657. }