Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift script for changing macos scroll bars visibility changes input sources settings

I have the following Swift script for changing scroll bars visibility in macOS:

import Foundation

func getSelectedValue() -> String {
  if CommandLine.argc < 2 {
    print("No arguments passed. Please pass one of the following values: \"Always\", \"Automatic\", \"WhenScrolling\".")
    exit(1)
  }

  let args = CommandLine.arguments
  let value = args[1]

  if value != "Always" && value != "Automatic" && value != "WhenScrolling" {
    return "Automatic"
  }

  return value
}

func setScrollBars(_ value: String) {
  let domain = "AppleShowScrollBars"

  UserDefaults.standard.setPersistentDomain(
    [domain: Optional(value) as Any],
    forName: UserDefaults.globalDomain
  )

  let notifyEvent = Notification.Name("AppleShowScrollBarsSettingChanged")
  DistributedNotificationCenter.default().post(name: notifyEvent, object: nil)
}

let value = getSelectedValue()
setScrollBars(value)

Usage example:

./set-scroll-bars Always

For some reason, running this script also causes a reset of the input source settings to their defaults:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

input sources settings

I don’t know why it happens because I don’t see any code that is responsible for input source settings.

>Solution :

You’re updating the entire global domain to contain just one setting. All other settings in the global domain, including the input source settings, are discarded.

You need to use UserDefaults.sharedDefaults.persistentDomain(forName: UserDefaults.globalDomain) to get a dictionary containing the current settings in the global domain, and update that dictionary.

if var settings = UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain) {
    settings["AppleShowsScrollBars"] = value
    UserDefaults.standard.setPersistentDomain(settings, forName: UserDefaults.globalDomain)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading