1
0
mirror of https://github.com/nicoverbruggen/phpmon.git synced 2025-08-07 03:50:08 +02:00

♻️ Refactor DispatchQueue to new Task API

This commit is contained in:
2022-10-19 13:44:53 +02:00
parent 658cec27c1
commit 4bfa98fc20
26 changed files with 54 additions and 51 deletions

View File

@ -80,7 +80,7 @@
</CommandLineArgument>
<CommandLineArgument
argument = "--configuration:~/.phpmon_fconf_working.json"
isEnabled = "YES">
isEnabled = "NO">
</CommandLineArgument>
<CommandLineArgument
argument = "--configuration:~/.phpmon_fconf_broken.json"

View File

@ -89,8 +89,7 @@ class Actions {
}
public static func openGlobalComposerFolder() {
let file = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".composer/composer.json")
let file = URL(string: "~/.composer/composer.json".replacingTildeWithHomeDirectory)!
NSWorkspace.shared.activateFileViewerSelecting([file] as [URL])
}
@ -100,14 +99,12 @@ class Actions {
}
public static func openValetConfigFolder() {
let file = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".config/valet")
let file = URL(string: "~/.config/valet".replacingTildeWithHomeDirectory)!
NSWorkspace.shared.activateFileViewerSelecting([file] as [URL])
}
public static func openPhpMonitorConfigFile() {
let file = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent(".config/phpmon")
let file = URL(string: "~/.config/phpmon".replacingTildeWithHomeDirectory)!
NSWorkspace.shared.activateFileViewerSelecting([file] as [URL])
}
@ -115,6 +112,7 @@ class Actions {
public static func createTempPhpInfoFile() async -> URL {
// Write a file called `phpmon_phpinfo.php` to /tmp
// TODO: Use FileSystem abstraction
try! "<?php phpinfo();".write(toFile: "/tmp/phpmon_phpinfo.php", atomically: true, encoding: .utf8)
// Tell php-cgi to run the PHP and output as an .html file

View File

@ -57,6 +57,7 @@ class PhpHelper {
"""
// Write to the destination
// TODO: Use FileSystem abstraction
try script.write(
to: URL(fileURLWithPath: destination),
atomically: true,

View File

@ -89,7 +89,7 @@ class PhpExtension {
if !isRunningTests {
// When running unit tests, the MainMenu will not be available
// TODO: Fix this dependency issue, set up a notification mechanism
DispatchQueue.main.async {
Task { @MainActor in
MainMenu.shared.rebuild(async: false)
}
}

View File

@ -26,13 +26,12 @@ class InternalSwitcher: PhpSwitcher {
Log.info("Switching to \(version), unlinking all versions...")
let versions = getVersionsToBeHandled(version)
let group = DispatchGroup()
PhpEnv.shared.availablePhpVersions.forEach { (available) in
group.enter()
Task { // TODO: Use structured concurrency
Task {
await self.disableDefaultPhpFpmPool(available)
await self.stopPhpVersion(available)
group.leave()
@ -40,7 +39,7 @@ class InternalSwitcher: PhpSwitcher {
}
group.notify(queue: .global(qos: .userInitiated)) {
Task { // TODO: Use structured concurrency
Task {
Log.info("All versions have been unlinked!")
Log.info("Linking the new version!")

View File

@ -119,7 +119,7 @@ class AppUpdateChecker {
}
private static func notifyVersionDoesNotNeedUpgrade() {
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert().withInformation(
title: "updater.alerts.is_latest_version.title".localized,
subtitle: "updater.alerts.is_latest_version.subtitle".localized(App.shortVersion),
@ -134,7 +134,7 @@ class AppUpdateChecker {
let devSuffix = isDev ? "-dev" : ""
let command = isDev ? "brew upgrade phpmon-dev" : "brew upgrade phpmon"
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert().withInformation(
title: "updater.alerts.newer_version_available.title".localized(version.humanReadable),
subtitle: "updater.alerts.newer_version_available.subtitle".localized,
@ -160,7 +160,7 @@ class AppUpdateChecker {
}
private static func notifyAboutConnectionIssue() {
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert().withInformation(
title: "updater.alerts.cannot_check_for_update.title".localized,
subtitle: "updater.alerts.cannot_check_for_update.subtitle".localized,

View File

@ -60,7 +60,7 @@ class InterApp {
if PhpEnv.shared.availablePhpVersions.contains(version) {
MainMenu.shared.switchToPhpVersion(version)
} else {
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert().withInformation(
title: "alert.php_switch_unavailable.title".localized,
subtitle: "alert.php_switch_unavailable.subtitle".localized(version)

View File

@ -32,7 +32,7 @@ class ServicesManager: ObservableObject {
.decode([HomebrewService].self, from: normalJson)
.filter({ return rootServiceNames.contains($0.name) })
DispatchQueue.main.async {
Task { @MainActor in
ServicesManager.shared.rootServices = Dictionary(
uniqueKeysWithValues: normalServices.map { ($0.name, $0) }
)
@ -51,7 +51,7 @@ class ServicesManager: ObservableObject {
.decode([HomebrewService].self, from: rootJson)
.filter({ return userServiceNames.contains($0.name) })
DispatchQueue.main.async {
Task { @MainActor in
ServicesManager.shared.userServices = Dictionary(
uniqueKeysWithValues: rootServices.map { ($0.name, $0) }
)

View File

@ -73,7 +73,7 @@ class Startup {
initialized when it is done working. The switcher must be initialized on the main thread.
*/
private func initializeSwitcher() {
DispatchQueue.main.async {
Task { @MainActor in
let appDelegate = NSApplication.shared.delegate as! AppDelegate
appDelegate.initializeSwitcher()
}

View File

@ -75,7 +75,8 @@ class AddProxyVC: NSViewController, NSTextFieldDelegate {
await Shell.quiet("\(Paths.valet) proxy \(domain) \(proxyName)\(secure)")
await Actions.restartNginx()
DispatchQueue.main.async {
Task { @MainActor in
// TODO: Check if this can be removed
App.shared.domainListWindowController?.contentVC.setUINotBusy()
App.shared.domainListWindowController?.pressedReload(nil)
}

View File

@ -35,7 +35,7 @@ extension DomainListVC {
await Actions.restartNginx()
// 4. Reload site list
DispatchQueue.main.async {
Task { @MainActor in
App.shared.domainListWindowController?.pressedReload(nil)
}
}

View File

@ -110,7 +110,9 @@ class DomainListVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource
@MainActor public func setUIBusy() {
// If it takes more than 0.5s to set the UI to not busy, show a spinner
timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { _ in
DispatchQueue.main.async { self.progressIndicator.startAnimation(true) }
Task {
@MainActor in self.progressIndicator.startAnimation(true)
}
})
tableView.alphaValue = 0.3
@ -141,7 +143,8 @@ class DomainListVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource
setUIBusy()
await execute()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { [self] in
Task { @MainActor in
await delay(seconds: 0.2)
completion()
setUINotBusy()
}
@ -188,7 +191,7 @@ class DomainListVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource
domains = Valet.getDomainListable()
searchedFor(text: "")
if let site = domains.enumerated().first(where: { $0.element.getListableName() == name }) {
DispatchQueue.main.async {
Task { @MainActor in
self.tableView.selectRowIndexes([site.offset], byExtendingSelection: false)
self.tableView.scrollRowToVisible(site.offset)
if secure && !site.element.getListableSecured() {
@ -257,7 +260,7 @@ class DomainListVC: NSViewController, NSTableViewDelegate, NSTableViewDataSource
self.applySortDescriptor(sortDescriptor)
}
DispatchQueue.main.async {
Task { @MainActor in
self.tableView.reloadData()
}
}

View File

@ -74,7 +74,8 @@ import Foundation
private func composerUpdateSucceeded() {
// Closing the window should happen after a slight delay
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [self] in
Task { @MainActor in
await delay(seconds: 1.0)
window?.close()
if shouldNotify {
LocalNotification.send(
@ -91,7 +92,7 @@ import Foundation
private func composerUpdateFailed() {
// Showing that something failed should be shown immediately
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
window?.setType(info: false)
window?.progressView?.labelTitle.stringValue = "alert.composer_failure.title".localized
window?.progressView?.labelDescription.stringValue = "alert.composer_failure.info".localized
@ -105,7 +106,7 @@ import Foundation
private func removeBusyStatus() {
PhpEnv.shared.isBusy = false
DispatchQueue.main.async {
Task { @MainActor in
MainMenu.shared.updatePhpVersionInStatusBar()
}
}

View File

@ -125,7 +125,7 @@ class HomebrewDiagnostics {
Show this alert in case the tapped Cask does cause issues because of the conflict.
*/
private static func presentAlertAboutConflict() {
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert()
.withInformation(
title: "alert.php_alias_conflict.title".localized,

View File

@ -79,7 +79,7 @@ class Valet {
*/
public static func notifyAboutUnsupportedTLD() {
if Valet.shared.config.tld != "test" && Preferences.isEnabled(.warnAboutNonStandardTLD) {
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert().withInformation(
title: "alert.warnings.tld_issue.title".localized,
subtitle: "alert.warnings.tld_issue.subtitle".localized,
@ -171,7 +171,7 @@ class Valet {
if version.versionCompare(Constants.MinimumRecommendedValetVersion) == .orderedAscending {
let version = version
Log.warn("Valet version \(version!) is too old! (recommended: \(Constants.MinimumRecommendedValetVersion))")
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert()
.withInformation(
title: "alert.min_valet_version.title".localized,

View File

@ -237,7 +237,7 @@ extension MainMenu {
PhpEnv.shared.delegate = self
PhpEnv.shared.delegate?.switcherDidStartSwitching(to: version)
DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
Task(priority: .userInitiated) { [unowned self] in
updatePhpVersionInStatusBar()
rebuild()
PhpEnv.switcher.performSwitch(
@ -263,7 +263,7 @@ extension MainMenu {
any code after will run only after the switcher is done.
*/
func switchToPhp(_ version: String) async {
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
setBusyImage()
PhpEnv.shared.isBusy = true
PhpEnv.shared.delegate = self

View File

@ -53,7 +53,7 @@ extension MainMenu {
setBusyImage()
}
DispatchQueue.global(qos: .userInitiated).async { [unowned self] in
Task(priority: .userInitiated) { [unowned self] in
var error: Error?
do { try execute() } catch let e { error = e }
@ -62,7 +62,7 @@ extension MainMenu {
PhpEnv.shared.isBusy = false
}
DispatchQueue.main.async { [self] in
Task { @MainActor [self, error] in
if behaviours.contains(.reloadsPhpInstallation) {
PhpEnv.shared.currentInstall = ActivePhpInstallation()
}

View File

@ -32,7 +32,7 @@ extension MainMenu {
}
Actions.fixMyValet {
DispatchQueue.main.async {
Task { @MainActor in
if previousVersion == PhpEnv.brewPhpAlias {
self.presentAlertForSameVersion()
} else {

View File

@ -14,7 +14,7 @@ extension MainMenu {
*/
func startup() async {
// Start with the icon
DispatchQueue.main.async {
Task { @MainActor in
self.setStatusBar(image: NSImage(named: NSImage.Name("StatusBarIcon"))!)
}
@ -105,7 +105,7 @@ extension MainMenu {
// Present first launch screen if needed
if Stats.successfulLaunchCount == 0 && !isRunningSwiftUIPreview {
Log.info("Should present the first launch screen!")
DispatchQueue.main.async {
Task { @MainActor in
OnboardingWindowController.show()
}
}
@ -121,7 +121,7 @@ extension MainMenu {
When the environment is not OK, present an alert to inform the user.
*/
private func onEnvironmentFail() async {
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
BetterAlert()
.withInformation(
title: "alert.cannot_start.title".localized,
@ -145,7 +145,7 @@ extension MainMenu {
Schedule a request to fetch the PHP version every 60 seconds.
*/
private func startSharedTimer() {
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
App.shared.timer = Timer.scheduledTimer(
timeInterval: 60,
target: self,

View File

@ -22,7 +22,7 @@ extension MainMenu {
await self.reloadDomainListData()
// Perform UI updates on main thread
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
updatePhpVersionInStatusBar()
rebuild()

View File

@ -38,7 +38,7 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate, PhpSwitcherDelegate
}
// Update the menu item on the main thread
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
self.rebuildMenu()
}
}
@ -106,7 +106,7 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate, PhpSwitcherDelegate
@MainActor @objc func reloadPhpMonitorMenuInForeground() async {
refreshActiveInstallation()
refreshIcon()
DispatchQueue.main.async {
Task { @MainActor in
self.rebuild(async: false)
}
await ServicesManager.loadHomebrewServices()
@ -117,7 +117,7 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate, PhpSwitcherDelegate
Did this need a comment? No, probably not.
*/
@objc func showWelcomeTour() {
DispatchQueue.main.async {
Task { @MainActor in
OnboardingWindowController.show()
}
}
@ -137,7 +137,7 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate, PhpSwitcherDelegate
/** Refreshes the icon with the PHP version. */
@objc func refreshIcon() {
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
if PhpEnv.shared.isBusy {
setStatusBar(image: NSImage(named: NSImage.Name("StatusBarIcon"))!)
} else {
@ -155,7 +155,7 @@ class MainMenu: NSObject, NSWindowDelegate, NSMenuDelegate, PhpSwitcherDelegate
/** Updates the icon to be displayed as busy. */
@objc func setBusyImage() {
DispatchQueue.main.async { [self] in
Task { @MainActor [self] in
setStatusBar(image: NSImage(named: NSImage.Name("StatusBarIcon"))!)
}
}

View File

@ -26,7 +26,7 @@ extension ActivePhpInstallation {
return
}
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert()
.withInformation(
title: "alert.php_fpm_broken.title".localized,

View File

@ -100,7 +100,7 @@ class Stats {
"times, switched \(Stats.successfulSwitchCount) times).")
}
DispatchQueue.main.async {
Task { @MainActor in
let donate = BetterAlert()
.withInformation(
title: "startup.sponsor_encouragement.title".localized,

View File

@ -104,7 +104,7 @@ struct Preset: Codable, Equatable {
// Restart PHP FPM process (also reloads menu, which will show the preset rollback)
await Actions.restartPhpFpm()
DispatchQueue.main.async {
Task { @MainActor in
// Show the correct notification
if wasRollback {
LocalNotification.send(
@ -134,7 +134,7 @@ struct Preset: Codable, Equatable {
await MainMenu.shared.switchToPhp(self.version!)
return true
} else {
DispatchQueue.main.async {
Task { @MainActor in
BetterAlert().withInformation(
title: "alert.php_switch_unavailable.title".localized,
subtitle: "alert.php_switch_unavailable.subtitle".localized(version!),

View File

@ -35,7 +35,7 @@ class TerminalProgressWindowController: NSWindowController, NSWindowDelegate {
}
public func addToConsole(_ string: String) {
DispatchQueue.main.async {
Task { @MainActor in
guard let textView = self.progressView?.textView else {
return
}

View File

@ -38,7 +38,7 @@ extension App {
// Check whether the watcher exists and schedule on the main thread
// if we don't consistently do this, the app will create duplicate watchers
// due to timing issues, which creates retain cycles.
DispatchQueue.main.async {
Task { @MainActor in
// Watcher needs to be created
if self.watcher == nil {
self.startWatcher(url)