KMBrowserWindowController.swift 21 KB

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