KMHomeViewController.swift 33 KB

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