KMBrowserWindowController.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. //
  2. // KMBrowserWindowController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/9.
  6. //
  7. import Cocoa
  8. @objcMembers class KMBrowserWindowController: CTBrowserWindowController {
  9. var rightSegmentControl: KMSegmentedBox?
  10. var filterType: Int = 0
  11. var mainViewController: NSViewController?
  12. var isShowingTokenTimeOutAlert: Bool = false
  13. var currentTimer: Timer?
  14. private(set) var isMultiTabMode: Bool = false
  15. var rightMessageVC: KMVerificationMessageViewController!
  16. var rightToolbarItemView: NSView!
  17. var createWC: KMURLCreatePDFWindowController = KMURLCreatePDFWindowController(windowNibName: "KMURLCreatePDFWindowController")
  18. private var homeVC: KMNHomeViewController?
  19. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  20. // 记录当前显示模式
  21. // var _mwcFlags: MwcFlags = MwcFlags()
  22. deinit {
  23. KMPrint("KMBrowserWindowController deinit...")
  24. DistributedNotificationCenter.default().removeObserver(self)
  25. NotificationCenter.default.removeObserver(self)
  26. }
  27. override func loadWindow() {
  28. super.loadWindow()
  29. }
  30. override func windowDidLoad() {
  31. super.windowDidLoad()
  32. NSImage.makeTextAlignImages()
  33. NSImage.makeAdornImages()
  34. window?.backgroundColor = NSColor.km_init(hex: "#DFE1E5")
  35. self.window?.appearance = NSApp.appearance
  36. self.window?.titlebarAppearsTransparent = true
  37. self.window?.delegate = self
  38. rightTabStripView_.delete = self
  39. homeRightTabStripView_.delete = self
  40. rightTabStripView_.updateView()
  41. fileUploadPanel.delete = self
  42. homeRightTabStripView_.homeRightSearchField.delegate = self
  43. isMultiTabMode = true
  44. NotificationCenter.default.addObserver(self, selector: #selector(closeAllTabs(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseAllTabs"), object: nil)
  45. NotificationCenter.default.addObserver(self, selector: #selector(openNewWindow(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerOpenNewWindow"), object: nil)
  46. DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
  47. updateViewColor()
  48. var tabbingMode = NSWindow.TabbingMode.automatic
  49. let openDocumentType = KMPreference.shared.openDocumentType
  50. if openDocumentType == .inSameWindow {
  51. tabbingMode = .preferred
  52. } else if openDocumentType == .newWindow {
  53. tabbingMode = .disallowed
  54. }
  55. #if VERSION_FREE
  56. if IAPProductsManager.default().isAvailableAllFunction() == false {
  57. tabbingMode = .disallowed
  58. }
  59. #endif
  60. }
  61. @objc func closeAction() {
  62. self.window?.performClose(nil)
  63. }
  64. override func windowShouldClose(_ sender: NSWindow) -> Bool {
  65. if let cnt = self.browser?.tabStripModel?.count(), cnt > 1 {
  66. if self.browser?.window != nil {
  67. self.browser?.windowDidBeginToClose()
  68. }
  69. return false
  70. }
  71. return true
  72. }
  73. override func windowWillClose(_ notification: Notification) {
  74. }
  75. override func windowDidResize(_ notification: Notification) {
  76. let model = self.browser?.tabStripModel
  77. if let cnt = model?.count(), cnt <= 0 {
  78. return
  79. }
  80. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  81. document.homeViewController?.rightInfoView.windowFrameUpdated()
  82. }
  83. override func layoutSubviews() {
  84. super.layoutSubviews()
  85. }
  86. @objc private func _themeChanged(_ sender: Notification) {
  87. let isDarkModel = KMAdvertisementConfig.isDarkModel()
  88. if isDarkModel {
  89. self.window?.appearance = .init(named: .darkAqua)
  90. } else {
  91. self.window?.appearance = .init(named: .aqua)
  92. }
  93. self.window?.contentView?.appearance = self.window?.appearance ?? .init(named: .aqua)
  94. self.interfaceThemeDidChanged(self.window?.appearance?.name ?? .aqua)
  95. }
  96. override func updateViewColor() {
  97. super.updateViewColor()
  98. window?.backgroundColor = KMTabAppearance.tabsViewBackgroundColor()
  99. }
  100. override var hasToolbar: Bool {
  101. get {
  102. return false
  103. }
  104. }
  105. func showSnapshots(setups: NSArray?) {
  106. let doc = self.document as? KMMainDocument
  107. doc?.mainViewController?.showSnapshots(setups: setups)
  108. }
  109. var km_browser: KMBrowser? {
  110. get {
  111. return self.browser as? KMBrowser
  112. }
  113. }
  114. // MARK: Private Methods
  115. func openDocumentWindow() -> Void {
  116. // MARK TODO: + 号开启
  117. // self.browser.addHomeTabContents()
  118. self.tabStripView?.addTabButton?.layer?.backgroundColor = .clear
  119. self.km_browser?.addNewTabContents()
  120. }
  121. func selectTabContents(path filePath: String) -> KMMainDocument? {
  122. let document = NSDocumentController.shared.document(for: URL(fileURLWithPath: filePath))
  123. var selectDocument: KMMainDocument?
  124. if document != nil {
  125. if document!.isKind(of: KMMainDocument.self) {
  126. selectDocument = document as! KMMainDocument
  127. }
  128. }
  129. return selectDocument
  130. }
  131. // MARK: Getter
  132. override var rightStripView: NSView! {
  133. get {
  134. if self.rightToolbarItemView == nil {
  135. self.rightToolbarItemView = NSView.init(frame: NSMakeRect(0, 10, 184, 40))
  136. self.rightToolbarItemView.wantsLayer = true
  137. if self.rightMessageVC == nil {
  138. self.rightMessageVC = KMVerificationMessageViewController.init()
  139. }
  140. self.rightMessageVC.frameUpdateHandle = { [weak self] rect in
  141. guard let rsView = self?.rightToolbarItemView else {
  142. return
  143. }
  144. var superRect = rsView.frame
  145. if (superRect.size.width < self!.rightMessageVC.view.frame.size.width + 8) {
  146. superRect.size.width = self!.rightMessageVC.view.frame.size.width + 8
  147. }
  148. if let supView = rsView.superview {
  149. let viewRect = supView.frame
  150. if (superRect.origin.x) + (superRect.size.width) > (viewRect.origin.x) + (viewRect.size.width) {
  151. let offsetValue = ((superRect.origin.x) + (superRect.size.width) - (viewRect.origin.x) - (viewRect.size.width))
  152. superRect.origin.x -= offsetValue
  153. }
  154. }
  155. self?.rightToolbarItemView.frame = superRect
  156. }
  157. var rect = self.rightMessageVC.view.frame;
  158. rect.origin.x = NSWidth(self.rightToolbarItemView.frame) - rect.size.width - 8
  159. rect.origin.y = (NSHeight(self.rightToolbarItemView.frame) - rect.size.height)/2
  160. self.rightMessageVC.view.frame = rect
  161. self.rightMessageVC.view.autoresizingMask = [ .maxXMargin]
  162. self.rightToolbarItemView.addSubview(self.rightMessageVC.view)
  163. }
  164. return self.rightToolbarItemView
  165. }
  166. }
  167. override var homeRightStripView: NSView! {
  168. get {
  169. return homeRightTabStripView_
  170. }
  171. }
  172. // MARK: Button Action
  173. func commandDispatch(_ sender: Any) -> Void {
  174. var needShowChooseWindow = false
  175. //#if VERSION_FREE
  176. //#if VERSION_DMG
  177. if (!IAPProductsManager.default().isAvailableAllFunction()) {
  178. needShowChooseWindow = true
  179. }
  180. //#endif
  181. if needShowChooseWindow {
  182. let preferenceNoteShow = UserDefaults.standard.bool(forKey: KMTabbingHintShowFlag)
  183. if preferenceNoteShow {
  184. } else {
  185. if !KMDataManager.default.isTabbingWin{
  186. KMDataManager.default.isTabbingWin = true
  187. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  188. tabbingWin.selectCallBack = {[weak self] continueOrNot in
  189. KMDataManager.default.isTabbingWin = false
  190. let winC = self?.kmCurrentWindowC as? KMTabbingHintWindowController
  191. let newTab = winC?.newTabInWindowButton.state == .on
  192. if continueOrNot {
  193. if IAPProductsManager.default().isAvailableAllFunction() && newTab {
  194. self?.openDocumentWindow()
  195. } else {
  196. self?.reopenDocument(forPaths: nil)
  197. }
  198. } else {
  199. }
  200. }
  201. self.km_beginSheet(windowC: tabbingWin)
  202. }
  203. }
  204. } else {
  205. openDocumentWindow()
  206. }
  207. }
  208. func reopenDocument(forPaths path: String?) -> Void {
  209. if path == nil {
  210. let browser = KMBrowser.init() as KMBrowser
  211. browser.windowController = KMBrowserWindowController.init(browser: browser)
  212. browser.addHomeTabContents()
  213. browser.windowController.showWindow(self)
  214. }else {
  215. NSDocumentController.shared.km_safe_openDocument(withContentsOf: URL(fileURLWithPath: path!), display: true) { doc, open, err in
  216. }
  217. }
  218. }
  219. func closeAllTabs(_ sender: Any) -> Void {
  220. if let noti = sender as? NSNotification, noti.object is CTTabController {
  221. if let window_ = (noti.object as! CTTabController).view.window, window_.isEqual(to: self.window) == false {
  222. return
  223. }
  224. }
  225. if self.browser != nil {
  226. self.browser.closeAllTabs()
  227. }
  228. }
  229. func openNewWindow(_ sender: Any) -> Void {
  230. if let noti = sender as? NSNotification, noti.object is CTTabController {
  231. if let window_ = (noti.object as! CTTabController).view.window, window_.isEqual(to: self.window) == false {
  232. return
  233. }
  234. }
  235. // 分离 Tab
  236. let windowC = self.detachTab(toNewWindow: self.activeTabView() as? CTTabView)
  237. // 新增 home Tab
  238. (windowC as? CTBrowserWindowController)?.browser?.addHomeTabContentsWithDrag()
  239. windowC?.showWindow(nil)
  240. // if self.browser != nil {
  241. // let activeInt = self.browser.activeTabIndex()
  242. // let activeTab = self.browser.activeTabContents()
  243. //
  244. // self.browser.closeTab(at: activeInt, makeHistory: false)
  245. //
  246. // let browser: KMBrowser = KMBrowser.init()
  247. // browser.windowController = KMBrowserWindowController.init(browser: browser)
  248. // browser.addHomeTabContents()
  249. // browser.windowController.showWindow(self)
  250. //
  251. //// browser.add(activeTab, inForeground: false)
  252. //// browser.selectTab(at: 1)
  253. // if activeTab?.fileURL == nil {
  254. // return
  255. // }
  256. // let pdfDoc = CPDFDocument.init(url: (activeTab?.fileURL)!)
  257. // let document = NSDocumentController.shared.document(for: (activeTab?.fileURL)!)
  258. // KMMainDocument().tryToUnlockDocument(pdfDoc!)
  259. //
  260. // if ((pdfDoc?.isLocked)! == true) {
  261. // KMPasswordInputWindow.openWindow(window: self.window!, url: (activeTab?.fileURL)!) { result, password in
  262. // if result == .cancel { /// 关闭
  263. // return
  264. // }
  265. // /// 解密成功
  266. // var selectDocument: KMMainDocument? = nil
  267. // if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  268. // selectDocument = (document as! KMMainDocument)
  269. // }
  270. // if selectDocument != nil {
  271. // let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  272. // selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  273. // if (selectDocument?.browser.window.isVisible)! as Bool {
  274. // selectDocument?.browser.window.orderFront(nil)
  275. // } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  276. // selectDocument?.browser.window.orderFront(nil)
  277. // }
  278. // } else {
  279. // NSDocumentController.shared.km_safe_openDocument(withContentsOf: (activeTab?.fileURL)!, display: true) { document, _, error in
  280. // if (error == nil) {
  281. // (document as! KMMainDocument).mainViewController?.model.password = password
  282. // }
  283. // }
  284. // }
  285. // }
  286. // } else {
  287. // var selectDocument: KMMainDocument? = nil
  288. // if ((document?.isKind(of: KMMainDocument.self)) != nil) {
  289. // selectDocument = (document as! KMMainDocument)
  290. // }
  291. // if selectDocument != nil {
  292. // let currentIndex = selectDocument?.browser.tabStripModel.index(of: selectDocument)
  293. // selectDocument?.browser.tabStripModel.selectTabContents(at: Int32(currentIndex!), userGesture: true)
  294. // if (selectDocument?.browser.window.isVisible)! as Bool {
  295. // selectDocument?.browser.window.orderFront(nil)
  296. // } else if (selectDocument?.browser.window.isMiniaturized)! as Bool {
  297. // selectDocument?.browser.window.orderFront(nil)
  298. // }
  299. // } else {
  300. // NSDocumentController.shared.km_safe_openDocument(withContentsOf: (activeTab?.fileURL)!, display: true) { _, _, _ in
  301. //
  302. // }
  303. // }
  304. // }
  305. // }
  306. }
  307. func canMergeAllWindow() -> Bool {
  308. return self.fetchBrowserWindowControllers().count > 0
  309. }
  310. fileprivate func fetchBrowserWindowControllers() -> [KMBrowserWindowController] {
  311. var windowArray: [KMBrowserWindowController] = []
  312. for window in NSApp.windows {
  313. guard let windowController = window.windowController, windowController is KMBrowserWindowController else {
  314. continue
  315. }
  316. if let _tabScripC = (windowController as? KMBrowserWindowController)?.tabStripController, _tabScripC.viewsCount() <= 1 {
  317. continue
  318. }
  319. if (window.isVisible && (windowController.isEqual(to: self) == false)) {
  320. windowArray.append(windowController as! KMBrowserWindowController)
  321. }
  322. }
  323. return windowArray
  324. }
  325. func mergeAllWindow(_ sender: Any) {
  326. let windowArray = self.fetchBrowserWindowControllers()
  327. if (windowArray.count <= 0) {
  328. return
  329. }
  330. for windowC in windowArray {
  331. // 拼接窗口 [拼接窗口里的标签,除了home标签]
  332. self.append(windowC, toTabView: NSView())
  333. if let browser = windowC.browser {
  334. if (browser.tabCount() <= 1 && browser.activeTabContents().isHome) {
  335. windowC.close()
  336. }
  337. }
  338. }
  339. }
  340. override func tabDidSelect(_ notification: Notification!) {
  341. super.tabDidSelect(notification)
  342. if let _userInfo = notification.userInfo, let _newContents = _userInfo[CTTabNewContentsUserInfoKey] as? KMMainDocument {
  343. _newContents.addWindowController(self)
  344. _newContents.mainViewController?.showMeasureFloatingWindowsIfNeed()
  345. }
  346. if let _userInfo = notification.userInfo, let _oldContents = _userInfo[CTTabContentsUserInfoKey] as? KMMainDocument {
  347. _oldContents.mainViewController?.hideMeasureFloatingWindows()
  348. }
  349. }
  350. override func layoutTabContentArea(_ frame: NSRect) {
  351. super.layoutTabContentArea(frame)
  352. self.rightStripView.autoresizingMask = [.minXMargin, .minYMargin]
  353. }
  354. override func openDocument(_ sender: Any!) {
  355. guard let _window = self.window else {
  356. KMPrint("openDocument error: window is nil.", beep: true)
  357. return
  358. }
  359. if let cnt = self.browser?.tabCount(), cnt > 1{
  360. if !IAPProductsManager.default().isAvailableAllFunction() {
  361. if !KMDataManager.default.isTabbingWin{
  362. KMDataManager.default.isTabbingWin = true
  363. let tabbingWin: KMTabbingHintWindowController = KMTabbingHintWindowController()
  364. tabbingWin.selectCallBack = { [weak self] continueOrNot in
  365. KMDataManager.default.isTabbingWin = false
  366. if continueOrNot {
  367. self?.reopenDocument(forPaths: nil)
  368. } else {
  369. }
  370. }
  371. self.km_beginSheet(windowC: tabbingWin)
  372. }
  373. return
  374. }
  375. if KMPreference.shared.openDocumentType == .newWindow {
  376. self.reopenDocument(forPaths: nil)
  377. return
  378. }
  379. }
  380. NSOpenPanel.km_open_multi_success(_window) { panel in
  381. panel.allowedFileTypes = KMTools.imageExtensions + KMTools.pdfExtensions
  382. } completion: { urls in
  383. var imageUrls: [URL] = []
  384. for url in urls {
  385. if KMTools.isPDFType(url.pathExtension.lowercased()) {
  386. NSDocumentController.shared.km_safe_openDocument(withContentsOf: url, display: true) { _, _, _ in
  387. }
  388. } else {
  389. imageUrls.append(url)
  390. }
  391. }
  392. if imageUrls.isEmpty == false {
  393. NSApplication.ShowImageToPDFWindow(urls: imageUrls)
  394. }
  395. }
  396. }
  397. }
  398. // MARK: - KMInterfaceThemeChangedProtocol
  399. extension KMBrowserWindowController: KMInterfaceThemeChangedProtocol {
  400. func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
  401. Task { @MainActor in
  402. self.updateViewColor()
  403. let selector = #selector(interfaceThemeDidChanged)
  404. let mainWindow = self.window
  405. var responder = mainWindow?.firstResponder
  406. while (responder != nil) {
  407. // KMPrint("res: \(responder)")
  408. //
  409. if self.isEqual(to: responder) {
  410. responder = responder?.nextResponder
  411. continue
  412. }
  413. if let res = responder?.responds(to: selector), res {
  414. responder?.perform(selector, with: appearance)
  415. }
  416. responder = responder!.nextResponder
  417. }
  418. let childWins = self.window?.childWindows ?? []
  419. for childWin in childWins {
  420. if let winC = childWin.windowController {
  421. if winC.responds(to: selector) {
  422. winC.perform(selector, with: appearance)
  423. }
  424. } else {
  425. if childWin.responds(to: selector) {
  426. childWin.perform(selector, with: appearance)
  427. }
  428. }
  429. }
  430. }
  431. }
  432. }
  433. // MARK: - KMToolbarRightViewDelegate
  434. extension KMBrowserWindowController: KMToolbarRightViewDelegate {
  435. func pdfRightSegmentedControlAction(_ sender: KMSegmentedBox?) {
  436. DispatchQueue.main.async {
  437. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  438. }
  439. }
  440. func userInfoButtonAction(_ sender: NSButton) {
  441. }
  442. func homeRefreshButtonAction(_ sender: NSButton?) {
  443. self.layoutSubviews()
  444. }
  445. func homeUploadButtonAction(_ sender: NSButton) {
  446. }
  447. func homeMenuSortAction(_ sender: NSPopUpButton) {
  448. }
  449. func homeMenuFilterAction(_ sender: NSPopUpButton) {
  450. }
  451. }
  452. // MARK: - KMUploadFileDelegate
  453. extension KMBrowserWindowController: KMUploadFileDelegate {
  454. // override func cancelOperation(_ sender: Any?) {
  455. //
  456. // }
  457. }
  458. // MARK: - NSSearchFieldDelegate
  459. extension KMBrowserWindowController: NSSearchFieldDelegate {
  460. func controlTextDidChange(_ obj: Notification) {
  461. }
  462. func controlTextDidEndEditing(_ obj: Notification) {
  463. }
  464. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
  465. var result = false
  466. return result
  467. }
  468. }
  469. // MARK: -
  470. // MARK: Menu Actions
  471. extension KMBrowserWindowController {
  472. func canResponseDocumentAction() -> Bool {
  473. if (self.browser == nil) {
  474. return false
  475. }
  476. guard let _ = self.browser.activeTabContents() as? KMMainDocument else {
  477. return false
  478. }
  479. return true
  480. }
  481. }
  482. // MARK: -
  483. // MARK: File Menu