KMHomeViewController.swift 34 KB

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