Compare commits

..

3 Commits

Author SHA1 Message Date
Kyle Neideck 53a19b8886 Compile MainMenu.xib with ibtool if for some reason Xcode 6 doesn't. 2016-04-28 08:08:50 +10:00
Kyle Neideck 23f94e3f4e Add runtime and compiler fallbacks for OS X 10.9/10.10 and their SDKs.
Now compiles in Xcode 6, which doesn't have generics, nullability or
__kindof. Also compiles against both the 10.10 and 10.9 SDKs.

Might work on 10.9 now, but I've only tested it on 10.11 (compiled
against the 10.9 SDK) so there are probably runtime bugs. I also only
tested it a tiny amount.
2016-04-28 03:10:25 +10:00
Kyle Neideck 88f4a96593 Hide nullability attributes from compilers that don't support them. 2016-04-24 00:48:05 +10:00
171 changed files with 4688 additions and 24081 deletions
-15
View File
@@ -1,15 +0,0 @@
# This file was added to get GitHub to display our source code correctly when
# it has mixed tabs and spaces. (I didn't realise the sample code BGMDriver is
# based on used tabs and it's too late to fix it now.)
#
# See http://editorconfig.org.
# This is the top-most .editorconfig file.
root = true
# Set tabs to the width of 4 spaces in C, C++, Objective-C and Objective-C++
# source files.
[*.{h,c,cpp,m,mm}]
tab_width = 4
-5
View File
@@ -2,11 +2,6 @@
.*.swp
/BGMDriver/BGMDriver/quick_install.conf
/build_and_install.log
.idea/
tags
cmake-build-debug/
/Background-Music-*/
BGM.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
# Everything below is from https://github.com/github/gitignore/blob/master/Objective-C.gitignore
-109
View File
@@ -1,109 +0,0 @@
language: objective-c
matrix:
include:
- os: osx
osx_image: xcode10
xcode_sdk: macosx10.14
sudo: required
env: DEPLOY=true
- os: osx
osx_image: xcode9.4
xcode_sdk: macosx10.13
sudo: required
- os: osx
osx_image: xcode9.3
xcode_sdk: macosx10.13
sudo: required
- os: osx
osx_image: xcode9.2
xcode_sdk: macosx10.13
sudo: required
- os: osx
osx_image: xcode8.3
xcode_sdk: macosx10.12
sudo: required
- os: osx
osx_image: xcode7.3
xcode_sdk: macosx10.11
sudo: required
env: PACKAGE=false
# branches:
# only:
# - master
install:
# Install Apple's NullAudio device. Travis' VMs don't have any audio devices installed.
- sudo xcodebuild -project BGMApp/BGMAppTests/NullAudio/AudioDriverExamples.xcodeproj -target NullAudio DSTROOT="/" install
- sudo launchctl kickstart -kp system/com.apple.audio.coreaudiod || sudo killall coreaudiod
script:
# Build in a case-sensitive disk image to catch failures that only happen on case-sensitive filesystems.
- hdiutil create -type SPARSEBUNDLE -fs 'Case-sensitive Journaled HFS+' -volname bgmbuild -nospotlight -verbose -attach -size 100m bgmbuild.dmg
- sudo cp -r . /Volumes/bgmbuild
- cd /Volumes/bgmbuild
# Install Background Music.
- yes | ./build_and_install.sh
- cat build_and_install.log
- find */build/Release/*/ -type f -exec md5 {} \;
# Log the installed audio devices...
- system_profiler SPAudioDataType
# ...and their IDs.
- say -a '?'
# Check the BGM dirs and files were installed. (These fail if the dir/file isn't found.)
- ls -la "/Applications/Background Music.app"
- ls -la "/Library/Audio/Plug-Ins/HAL/Background Music Device.driver"
- ls -la "/usr/local/libexec/BGMXPCHelper.xpc" || ls -la "/Library/Application Support/Background Music/BGMXPCHelper.xpc"
- ls -la "/Library/LaunchDaemons/com.bearisdriving.BGM.XPCHelper.plist"
# Close BGMApp (which the install script opened).
#
# The killall fallback command is necessary because the AppleScript gets "user canceled" on Travis'
# Xcode 9 images for some reason.
- osascript -e 'tell application "Background Music" to quit' || killall "Background Music"
# Skip the UI tests until Travis has support for them.
- BGMApp/BGMAppTests/UITests/travis-skip.py
# Run the tests.
- xcodebuild -workspace BGM.xcworkspace -scheme 'Background Music Device' test
- xcodebuild -workspace BGM.xcworkspace -scheme 'Background Music' test
- xcodebuild -workspace BGM.xcworkspace -scheme 'BGMXPCHelper' test
# Uninstall Background Music.
- yes | ./uninstall.sh
# Check the BGM dirs and files were removed.
- if ls -la "/Applications/Background Music.app"; then false; fi
- if ls -la "/Library/Audio/Plug-Ins/HAL/Background Music Device.driver"; then false; fi
- if ls -la "/usr/local/libexec/BGMXPCHelper.xpc"; then false; fi
- if ls -la "/Library/Application Support/Background Music/BGMXPCHelper.xpc"; then false; fi
- if ls -la "/Library/LaunchDaemons/com.bearisdriving.BGM.XPCHelper.plist"; then false; fi
# Return early if we're not testing packaging on this OS X version.
- if [[ "$PACKAGE" == "false" ]]; then exit 0; fi
# Build the .pkg installer. Print the build logs if it fails. If this build is for a tag with
# "DEBUG" in its name, build a debug package. (More detailed logging, no optimization, etc.)
- if [[ "$TRAVIS_TAG" =~ .*DEBUG.* ]]; then
./package.sh -d || (cat build_and_install.log && travis_terminate 1);
else
./package.sh || (cat build_and_install.log && travis_terminate 1);
fi
# Install the .pkg.
- sudo installer -pkg Background-Music-*/BackgroundMusic-*.pkg -target / -verbose -dumplog
# Check the BGM dirs and files were installed again.
- ls -la "/Applications/Background Music.app"
- ls -la "/Library/Audio/Plug-Ins/HAL/Background Music Device.driver"
- ls -la "/usr/local/libexec/BGMXPCHelper.xpc" || ls -la "/Library/Application Support/Background Music/BGMXPCHelper.xpc"
- ls -la "/Library/LaunchDaemons/com.bearisdriving.BGM.XPCHelper.plist"
# Post on IRC when Travis builds finish.
notifications:
irc: "irc.freenode.org#backgroundmusic"
# Upload the .pkg and dSYM zip to GitHub.
deploy:
provider: releases
api_key:
secure: j5GdMTkJI/9lfGMcAW4dnBnfNSW0EUGSuaKSXw49FfjfcshLL2RFxIbQkyA7QqjoJm6ohstU3tOCo7c9FrqIWjE/+5itGJpq7NXDRxFtd2qzcli1u+1IRvQUZJ4VYC9982pSS0IUynK9/f0rhbdkWsCuXWIjoClYPBRscc8soDBJvkDbfilPFfFgkc8TuSmtGDCdu9coGVi6b9HuTLNQU0g5DZkjmv71Vj3SwJ2CmvOk3GFfV1SjvG2SRgBDwyP1g9MRGRiNYkmK9lJRgsq2KLluzb04lt22x8RIcZ+kZYOQVmgDlCeWlOcXi0iz1wU/QzdoYFEAnJdG4q0hqKeqIi+p8Tc31nHPuc1ZlYpifzMQ6KuOoOP19eceJwriAT133t2RSB3Rl3nxh9bymNPNyQ2dJwGNFtO68f3aZsuE5L92lVgW/ipZ6e5Sw1ovXldR04mxNtyY4WvFXFlkn/776tKV0vgAubsHfceGM/aRoBj+E2gDvqkFqIR8wrZAZEeSM2reMHPMx5ICFppIZ8dCIVjF5bsxZQsbojY+LXV8BUU5kLAou0yD7Q+lHi9r3HYdN90+cC02HKGFYzsIiMAyf4IAngnLhwmmrLOwr3wWdACjYTJhznAZGNJh4lCeB4dx85iyj3EexJ6J/DL1k2+ZNKyMN3+i/215t+AvSsXuw5U=
file_glob: true
file: Background-Music-*/*
skip_cleanup: true
name: $TRAVIS_TAG
prerelease: true
on:
repo: kyleneideck/BackgroundMusic
tags: true
# TODO: Use "condition" to build master and tags?
condition: $DEPLOY = true
-24
View File
@@ -10,39 +10,15 @@
<FileRef
location = "group:README.md">
</FileRef>
<FileRef
location = "group:MANUAL-INSTALL.md">
</FileRef>
<FileRef
location = "group:MANUAL-UNINSTALL.md">
</FileRef>
<FileRef
location = "group:TODO.md">
</FileRef>
<FileRef
location = "group:DEVELOPING.md">
</FileRef>
<FileRef
location = "group:CONTRIBUTING.md">
</FileRef>
<FileRef
location = "group:LICENSE">
</FileRef>
<FileRef
location = "group:LICENSE-Apple-Sample-Code">
</FileRef>
<FileRef
location = "group:build_and_install.sh">
</FileRef>
<FileRef
location = "group:uninstall.sh">
</FileRef>
<FileRef
location = "group:package.sh">
</FileRef>
<FileRef
location = "group:pkg">
</FileRef>
<FileRef
location = "group:Images">
</FileRef>
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,8 +26,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
enableAddressSanitizer = "YES"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -57,8 +55,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
enableAddressSanitizer = "YES"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -74,13 +70,6 @@
ReferencedContainer = "container:BGMApp.xcodeproj">
</BuildableReference>
</MacroExpansion>
<EnvironmentVariables>
<EnvironmentVariable
key = "ASAN_OPTIONS"
value = "detect_odr_violation=1:use_odr_indicator=1:detect_stack_use_after_return=1:detect_invalid_pointer_pairs=2:check_initialization_order=1"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0900"
LastUpgradeVersion = "0720"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -26,26 +26,15 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
enableAddressSanitizer = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2743C9F51D86CFF90089613B"
BuildableName = "BGMAppUnitTests.xctest"
BlueprintName = "BGMAppUnitTests"
ReferencedContainer = "container:BGMApp.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "1CCC4F531E584081008053E4"
BuildableName = "BGMAppUITests.xctest"
BlueprintName = "BGMAppUITests"
BlueprintIdentifier = "1CB8B3481BBA75F0000E2DD1"
BuildableName = "BGMAppTests.xctest"
BlueprintName = "BGMAppTests"
ReferencedContainer = "container:BGMApp.xcodeproj">
</BuildableReference>
</TestableReference>
@@ -66,7 +55,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
enableAddressSanitizer = "YES"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -83,20 +71,10 @@
ReferencedContainer = "container:BGMApp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "--show-dock-icon"
isEnabled = "NO">
</CommandLineArgument>
<CommandLineArgument
argument = "--no-persistent-data"
isEnabled = "NO">
</CommandLineArgument>
</CommandLineArguments>
<EnvironmentVariables>
<EnvironmentVariable
key = "ASAN_OPTIONS"
value = "detect_odr_violation=1:use_odr_indicator=1:detect_stack_use_after_return=1:detect_invalid_pointer_pairs=2:check_initialization_order=1"
value = "detect_odr_violation=0"
isEnabled = "YES">
</EnvironmentVariable>
</EnvironmentVariables>
@@ -14,30 +14,24 @@
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAboutPanel.h
// AppDelegate.h
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// This class manages the "About Background Music" window.
// Sets up and tears down the app.
//
// System Includes
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
@interface AppDelegate : NSObject <NSApplicationDelegate>
@interface BGMAboutPanel : NSObject
- (instancetype)initWithPanel:(NSPanel*)inAboutPanel licenseView:(NSTextView*)inLicenseView;
- (void) show;
@property (weak) IBOutlet NSMenu* bgmMenu;
@property (weak) IBOutlet NSMenuItem* autoPauseMenuItem;
@property (weak) IBOutlet NSView* appVolumeView;
@property (weak) IBOutlet NSPanel* aboutPanel;
@property (unsafe_unretained) IBOutlet NSTextView *aboutPanelLicenseView;
@end
@interface BGMLinkField : NSTextField
@end
NS_ASSUME_NONNULL_END
+197
View File
@@ -0,0 +1,197 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// AppDelegate.mm
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// Self Includes
#import "AppDelegate.h"
// Local Includes
#include "BGM_Types.h"
#import "BGMAudioDeviceManager.h"
#import "BGMAutoPauseMusic.h"
#import "BGMAppVolumes.h"
#import "BGMPreferencesMenu.h"
#import "BGMXPCListener.h"
static float const kStatusBarIconPadding = 0.25;
@implementation AppDelegate {
// The button in the system status bar (the bar with volume, battery, clock, etc.) to show the main menu
// for the app. These are called "menu bar extras" in the Human Interface Guidelines.
NSStatusItem* statusBarItem;
BGMAutoPauseMusic* autoPauseMusic;
BGMAppVolumes* appVolumes;
BGMAudioDeviceManager* audioDevices;
BGMPreferencesMenu* prefsMenu;
BGMXPCListener* xpcListener;
}
- (void) awakeFromNib {
// Set up the status bar item
statusBarItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
// Set the icon
NSImage* icon = [NSImage imageNamed:@"FermataIcon"];
if (icon != nil) {
// Make the icon a "template image" so it gets drawn colour-inverted when it's highlighted or the status
// bar's in dark mode
[icon setTemplate:YES];
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_9
if ([statusBarItem respondsToSelector:@selector(button)]) {
CGFloat lengthMinusPadding = statusBarItem.button.frame.size.height * (1 - kStatusBarIconPadding);
[icon setSize:NSMakeSize(lengthMinusPadding, lengthMinusPadding)];
statusBarItem.button.image = icon;
} else
#endif
{
// OS X 10.9 fallback.
// TODO: It would be better to set this size dynamically, like we do for 10.10+.
icon.size = NSMakeSize(16, 16);
statusBarItem.image = icon;
}
} else {
// If our icon is missing for some reason, fallback to a fermata character (1D110)
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_9
if ([statusBarItem respondsToSelector:@selector(button)]) {
statusBarItem.button.title = @"𝄐";
} else
#endif
{
statusBarItem.title = @"𝄐";
}
}
// Set the main menu
statusBarItem.menu = self.bgmMenu;
}
- (void) applicationDidFinishLaunching:(NSNotification*)aNotification {
#pragma unused (aNotification)
// Set up the GUI and other external interfaces.
// Coordinates the audio devices (BGMDevice and the output device): manages playthrough, volume/mute controls, etc.
NSError* err;
audioDevices = [[BGMAudioDeviceManager alloc] initWithError:&err];
if (audioDevices == nil) {
[self showDeviceNotFoundErrorMessageAndExit:err.code];
}
[audioDevices setBGMDeviceAsOSDefault];
autoPauseMusic = [[BGMAutoPauseMusic alloc] initWithAudioDevices:audioDevices];
xpcListener = [[BGMXPCListener alloc] initWithAudioDevices:audioDevices
helperConnectionErrorHandler:^(NSError* error) {
[self showXPCHelperErrorMessageAndExit:error];
}];
appVolumes = [[BGMAppVolumes alloc] initWithMenu:[self bgmMenu]
appVolumeView:[self appVolumeView]
audioDevices:audioDevices];
prefsMenu = [[BGMPreferencesMenu alloc] initWithbgmMenu:[self bgmMenu]
audioDevices:audioDevices
aboutPanel:[self aboutPanel]
aboutPanelLicenseView:[self aboutPanelLicenseView]];
[self loadUserDefaults];
}
- (void) loadUserDefaults {
// Register the preference defaults. These are the preferences/state that only apply to BGMApp. The others are
// persisted on BGMDriver.
NSDictionary* appDefaults = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
forKey:@"AutoPauseMusicEnabled"];
[[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
// Enable auto-pausing music if it's enabled in the user's preferences (which it is by default).
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"AutoPauseMusicEnabled"]) {
[self toggleAutoPauseMusic:self];
}
}
- (void) showDeviceNotFoundErrorMessageAndExit:(NSInteger)code {
// Show an error dialog and exit if either BGMDevice wasn't found on the system or we couldn't find any output devices
// NSAlert should only be used on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert* alert = [NSAlert new];
if (code == kBGMErrorCode_BGMDeviceNotFound) {
// TODO: Check whether the driver files are in /Library/Audio/Plug-Ins/HAL and offer to install them if not. Also,
// it would be nice if we could restart coreaudiod automatically (using launchd).
[alert setMessageText:@"Could not find the Background Music virtual audio device."];
[alert setInformativeText:@"Make sure you've installed Background Music.driver to /Library/Audio/Plug-Ins/HAL and restarted coreaudiod (e.g. \"sudo killall coreaudiod\")."];
} else if (code == kBGMErrorCode_OutputDeviceNotFound) {
[alert setMessageText:@"Could not find an audio output device."];
[alert setInformativeText:@"If you do have one installed, this is probably a bug. Sorry about that. Feel free to file an issue on GitHub."];
}
[alert runModal];
[NSApp terminate:self];
});
}
- (void) showXPCHelperErrorMessageAndExit:(NSError*)error {
// NSAlert should only be used on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert* alert = [NSAlert new];
// TODO: Offer to install BGMXPCHelper if it's missing.
[alert setMessageText:@"Error connecting to BGMXPCHelper."];
[alert setInformativeText:[NSString stringWithFormat:@"%s%s%@ (%lu)",
"Make sure you have BGMXPCHelper installed. There are instructions in the README.md file.",
"\n\nDetails:\n",
[error localizedDescription],
[error code]]];
[alert runModal];
[NSApp terminate:self];
});
}
- (void) applicationWillTerminate:(NSNotification*)aNotification {
#pragma unused (aNotification)
[audioDevices unsetBGMDeviceAsOSDefault];
}
- (IBAction) toggleAutoPauseMusic:(id)sender {
#pragma unused (sender)
if (self.autoPauseMenuItem.state == NSOnState) {
self.autoPauseMenuItem.state = NSOffState;
[autoPauseMusic disable];
} else {
self.autoPauseMenuItem.state = NSOnState;
[autoPauseMusic enable];
}
// Persist the change in the user's preferences
[[NSUserDefaults standardUserDefaults] setBool:(self.autoPauseMenuItem.state == NSOnState)
forKey:@"AutoPauseMusicEnabled"];
}
@end
-57
View File
@@ -1,57 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppDelegate.h
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
//
// Sets up and tears down the app.
//
// Local Includes
#import "BGMAudioDeviceManager.h"
// System Includes
#import <Cocoa/Cocoa.h>
// Tags for UI elements in MainMenu.xib
static NSInteger const kVolumesHeadingMenuItemTag = 3;
static NSInteger const kSeparatorBelowVolumesMenuItemTag = 4;
@interface BGMAppDelegate : NSObject <NSApplicationDelegate, NSMenuDelegate>
@property (weak) IBOutlet NSMenu* bgmMenu;
@property (weak) IBOutlet NSView* outputVolumeView;
@property (weak) IBOutlet NSTextField* outputVolumeLabel;
@property (weak) IBOutlet NSSlider* outputVolumeSlider;
@property (weak) IBOutlet NSView* systemSoundsView;
@property (weak) IBOutlet NSSlider* systemSoundsSlider;
@property (weak) IBOutlet NSView* appVolumeView;
@property (weak) IBOutlet NSPanel* aboutPanel;
@property (unsafe_unretained) IBOutlet NSTextView* aboutPanelLicenseView;
@property (weak) IBOutlet NSMenuItem* autoPauseMenuItemUnwrapped;
@property (readonly) BGMAudioDeviceManager* audioDevices;
@end
-449
View File
@@ -1,449 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppDelegate.mm
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
//
// Self Includes
#import "BGMAppDelegate.h"
// Local Includes
#import "BGM_Utils.h"
#import "BGMUserDefaults.h"
#import "BGMMusicPlayers.h"
#import "BGMAutoPauseMusic.h"
#import "BGMAutoPauseMenuItem.h"
#import "BGMSystemSoundsVolume.h"
#import "BGMAppVolumesController.h"
#import "BGMPreferencesMenu.h"
#import "BGMXPCListener.h"
#import "BGMOutputVolumeMenuItem.h"
#import "BGMTermination.h"
#import "SystemPreferences.h"
// PublicUtility Includes
#import "CAPropertyAddress.h"
// System Includes
#import <AVFoundation/AVCaptureDevice.h>
#pragma clang assume_nonnull begin
static float const kStatusBarIconPadding = 0.25;
static NSString* const kOptNoPersistentData = @"--no-persistent-data";
static NSString* const kOptShowDockIcon = @"--show-dock-icon";
@implementation BGMAppDelegate {
// The button in the system status bar (the bar with volume, battery, clock, etc.) to show the main menu
// for the app. These are called "menu bar extras" in the Human Interface Guidelines.
NSStatusItem* statusBarItem;
// Only show the 'BGMXPCHelper is missing' error dialog once.
BOOL haveShownXPCHelperErrorMessage;
BGMAutoPauseMusic* autoPauseMusic;
BGMAutoPauseMenuItem* autoPauseMenuItem;
BGMMusicPlayers* musicPlayers;
BGMSystemSoundsVolume* systemSoundsVolume;
BGMAppVolumesController* appVolumes;
BGMPreferencesMenu* prefsMenu;
BGMXPCListener* xpcListener;
}
@synthesize audioDevices = audioDevices;
- (void) awakeFromNib {
// Show BGMApp in the dock, if the command-line option for that was passed. This is used by the
// UI tests.
if ([NSProcessInfo.processInfo.arguments indexOfObject:kOptShowDockIcon] != NSNotFound) {
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
}
haveShownXPCHelperErrorMessage = NO;
[self initStatusBarItem];
}
// Set up the status bar item. (The thing you click to show BGMApp's UI.)
- (void) initStatusBarItem {
statusBarItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
// NSStatusItem doesn't have the "button" property on OS X 10.9.
BOOL buttonAvailable = (floor(NSAppKitVersionNumber) >= NSAppKitVersionNumber10_10);
// Set the title/tooltip to "Background Music".
statusBarItem.title = [NSRunningApplication currentApplication].localizedName;
statusBarItem.toolTip = statusBarItem.title;
if (buttonAvailable) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
statusBarItem.button.accessibilityLabel = statusBarItem.title;
#pragma clang diagnostic pop
}
// Set the icon.
NSImage* icon = [NSImage imageNamed:@"FermataIcon"];
if (icon != nil) {
NSRect statusBarItemFrame;
if (buttonAvailable) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
statusBarItemFrame = statusBarItem.button.frame;
#pragma clang diagnostic pop
} else {
// OS X 10.9 fallback. I haven't tested this (or anything else on 10.9).
statusBarItemFrame = statusBarItem.view.frame;
}
CGFloat lengthMinusPadding = statusBarItemFrame.size.height * (1 - kStatusBarIconPadding);
[icon setSize:NSMakeSize(lengthMinusPadding, lengthMinusPadding)];
// Make the icon a "template image" so it gets drawn colour-inverted when it's highlighted or the status
// bar's in dark mode
[icon setTemplate:YES];
if (buttonAvailable) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
statusBarItem.button.image = icon;
#pragma clang diagnostic pop
} else {
statusBarItem.image = icon;
}
} else {
// If our icon is missing for some reason, fallback to a fermata character (1D110)
if (buttonAvailable) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
statusBarItem.button.title = @"𝄐";
#pragma clang diagnostic pop
} else {
statusBarItem.title = @"𝄐";
}
}
// Set the main menu
statusBarItem.menu = self.bgmMenu;
}
- (void) applicationDidFinishLaunching:(NSNotification*)aNotification {
#pragma unused (aNotification)
// Log the version/build number.
//
// TODO: NSLog should only be used for logging errors.
// TODO: Automatically add the commit ID to the end of the build number for unreleased builds. (In the
// Info.plist or something -- not here.)
NSLog(@"BGMApp version: %@, BGMApp build number: %@",
NSBundle.mainBundle.infoDictionary[@"CFBundleShortVersionString"],
NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"]);
// Set up audioDevices, which coordinates BGMDevice and the output device. It manages
// playthrough, volume/mute controls, etc.
if (![self initAudioDeviceManager]) {
return;
}
// Make BGMDevice the default device.
[self setBGMDeviceAsDefault];
// Handle some of the unusual reasons BGMApp might have to exit, mostly crashes.
BGMTermination::SetUpTerminationCleanUp(audioDevices);
// Set up the rest of the UI and other external interfaces.
BGMUserDefaults* userDefaults = [self createUserDefaults];
musicPlayers = [[BGMMusicPlayers alloc] initWithAudioDevices:audioDevices
userDefaults:userDefaults];
autoPauseMusic = [[BGMAutoPauseMusic alloc] initWithAudioDevices:audioDevices
musicPlayers:musicPlayers];
[self setUpMainMenu:userDefaults];
xpcListener = [[BGMXPCListener alloc] initWithAudioDevices:audioDevices
helperConnectionErrorHandler:^(NSError* error) {
NSLog(@"BGMAppDelegate::applicationDidFinishLaunching: (helperConnectionErrorHandler) "
"BGMXPCHelper connection error: %@",
error);
[self showXPCHelperErrorMessage:error];
}];
}
// Returns NO if (and only if) BGMApp is about to terminate because of a fatal error.
- (BOOL) initAudioDeviceManager {
NSError* error;
audioDevices = [[BGMAudioDeviceManager alloc] initWithError:&error];
if (!audioDevices) {
[self showDeviceNotFoundErrorMessageAndExit:error.code];
return NO;
}
return YES;
}
// Sets the "Background Music" virtual audio device (BGMDevice) as the user's default audio device.
- (void) setBGMDeviceAsDefault {
void (^setDefaultDevice)() = ^{
NSError* error = [audioDevices setBGMDeviceAsOSDefault];
if (error) {
[self showSetDeviceAsDefaultError:error
message:@"Could not set the Background Music device as your"
"default audio device."
informativeText:@"You might be able to change it yourself."];
}
};
// Skip this if we're compiling on a version of macOS before 10.14 as won't compile and it
// isn't needed.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 // MAC_OS_X_VERSION_10_14
if (@available(macOS 10.14, *)) {
// On macOS 10.14+ we need to get the user's permission to use input devices before we can
// use BGMDevice for playthrough (see BGMPlayThrough), so we wait until they've given it
// before making BGMDevice the default device. This way, if the user is playing audio when
// they open Background Music, we won't interrupt it while we're waiting for them to click
// OK.
//
// TODO: This isn't a perfect solution because, if the user takes too long to accept,
// BGMPlayThrough will try to use BGMDevice again and log some errors.
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio
completionHandler:^(BOOL granted) {
if (granted) {
DebugMsg("BGMAppDelegate::setBGMDeviceAsDefault: "
"Permission granted");
setDefaultDevice();
} else {
NSLog(@"BGMAppDelegate::setBGMDeviceAsDefault: "
"Permission denied");
// TODO: If they don't accept, Background Music won't work
// at all and the only way to fix it is in System
// Preferences, so we should show an error dialog
// with instructions.
}
}];
}
else
#endif
{
// We can change the device immediately on older versions of macOS because they don't
// require user permission for input devices.
setDefaultDevice();
}
}
- (void) setUpMainMenu:(BGMUserDefaults*)userDefaults {
autoPauseMenuItem =
[[BGMAutoPauseMenuItem alloc] initWithMenuItem:self.autoPauseMenuItemUnwrapped
autoPauseMusic:autoPauseMusic
musicPlayers:musicPlayers
userDefaults:userDefaults];
[self initVolumesMenuSection];
prefsMenu = [[BGMPreferencesMenu alloc] initWithBGMMenu:self.bgmMenu
audioDevices:audioDevices
musicPlayers:musicPlayers
aboutPanel:self.aboutPanel
aboutPanelLicenseView:self.aboutPanelLicenseView];
// Handle events about the main menu. (See the NSMenuDelegate methods below.)
self.bgmMenu.delegate = self;
}
- (BGMUserDefaults*) createUserDefaults {
BOOL persistentDefaults =
[NSProcessInfo.processInfo.arguments indexOfObject:kOptNoPersistentData] == NSNotFound;
NSUserDefaults* wrappedDefaults = persistentDefaults ? [NSUserDefaults standardUserDefaults] : nil;
return [[BGMUserDefaults alloc] initWithDefaults:wrappedDefaults];
}
- (void) initVolumesMenuSection {
// Create the menu item with the (main) output volume slider.
BGMOutputVolumeMenuItem* outputVolume =
[[BGMOutputVolumeMenuItem alloc] initWithAudioDevices:audioDevices
view:self.outputVolumeView
slider:self.outputVolumeSlider
deviceLabel:self.outputVolumeLabel];
[audioDevices setOutputVolumeMenuItem:outputVolume];
NSInteger headingIdx = [self.bgmMenu indexOfItemWithTag:kVolumesHeadingMenuItemTag];
// Add it to the main menu below the "Volumes" heading.
[self.bgmMenu insertItem:outputVolume atIndex:(headingIdx + 1)];
// Add the volume control for system (UI) sounds to the menu.
BGMAudioDevice uiSoundsDevice = [audioDevices bgmDevice].GetUISoundsBGMDeviceInstance();
systemSoundsVolume =
[[BGMSystemSoundsVolume alloc] initWithUISoundsDevice:uiSoundsDevice
view:self.systemSoundsView
slider:self.systemSoundsSlider];
[self.bgmMenu insertItem:systemSoundsVolume.menuItem atIndex:(headingIdx + 2)];
// Add the app volumes to the menu.
appVolumes = [[BGMAppVolumesController alloc] initWithMenu:self.bgmMenu
appVolumeView:self.appVolumeView
audioDevices:audioDevices];
}
- (void) applicationWillTerminate:(NSNotification*)aNotification {
#pragma unused (aNotification)
DebugMsg("BGMAppDelegate::applicationWillTerminate");
// Change the user's default output device back.
NSError* error = [audioDevices unsetBGMDeviceAsOSDefault];
if (error) {
[self showSetDeviceAsDefaultError:error
message:@"Failed to reset your system's audio output device."
informativeText:@"You'll have to change it yourself to get audio working again."];
}
}
#pragma mark Error messages
- (void) showDeviceNotFoundErrorMessageAndExit:(NSInteger)code {
// Show an error dialog and exit if either BGMDevice wasn't found on the system or we couldn't find any output devices
// NSAlert should only be used on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert* alert = [NSAlert new];
if (code == kBGMErrorCode_BGMDeviceNotFound) {
// TODO: Check whether the driver files are in /Library/Audio/Plug-Ins/HAL and offer to install them if not. Also,
// it would be nice if we could restart coreaudiod automatically (using launchd).
[alert setMessageText:@"Could not find the Background Music virtual audio device."];
[alert setInformativeText:@"Make sure you've installed Background Music Device.driver to /Library/Audio/Plug-Ins/HAL and restarted coreaudiod (e.g. \"sudo killall coreaudiod\")."];
} else if (code == kBGMErrorCode_OutputDeviceNotFound) {
[alert setMessageText:@"Could not find an audio output device."];
[alert setInformativeText:@"If you do have one installed, this is probably a bug. Sorry about that. Feel free to file an issue on GitHub."];
}
// This crashes if built with Xcode 9.0.1, but works with versions of Xcode before 9 and
// with 9.1.
[alert runModal];
[NSApp terminate:self];
});
}
- (void) showXPCHelperErrorMessage:(NSError*)error {
if (!haveShownXPCHelperErrorMessage) {
haveShownXPCHelperErrorMessage = YES;
// NSAlert should only be used on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
NSAlert* alert = [NSAlert new];
// TODO: Offer to install BGMXPCHelper if it's missing.
// TODO: Show suppression button?
[alert setMessageText:@"Error connecting to BGMXPCHelper."];
[alert setInformativeText:[NSString stringWithFormat:@"%s%s%@ (%lu)",
"Make sure you have BGMXPCHelper installed. There are instructions in the "
"README.md file.\n\n"
"Background Music might still work, but it won't work as well as it could.",
"\n\nDetails:\n",
[error localizedDescription],
[error code]]];
[alert runModal];
});
}
}
- (void) showSetDeviceAsDefaultError:(NSError*)error
message:(NSString*)msg
informativeText:(NSString*)info {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@ %@ Error: %@", msg, info, error);
NSAlert* alert = [NSAlert alertWithError:error];
alert.messageText = msg;
alert.informativeText = info;
[alert addButtonWithTitle:@"OK"];
[alert addButtonWithTitle:@"Open Sound in System Preferences"];
NSModalResponse buttonClicked = [alert runModal];
if (buttonClicked != NSAlertFirstButtonReturn) { // 'OK' is the first button.
[self openSysPrefsSoundOutput];
}
});
}
- (void) openSysPrefsSoundOutput {
SystemPreferencesApplication* __nullable sysPrefs =
[SBApplication applicationWithBundleIdentifier:@"com.apple.systempreferences"];
if (!sysPrefs) {
NSLog(@"Could not open System Preferences");
return;
}
// In System Preferences, go to the "Output" tab on the "Sound" pane.
for (SystemPreferencesPane* pane : [sysPrefs panes]) {
DebugMsg("BGMAppDelegate::openSysPrefsSoundOutput: pane = %s", [pane.name UTF8String]);
if ([pane.id isEqualToString:@"com.apple.preference.sound"]) {
sysPrefs.currentPane = pane;
for (SystemPreferencesAnchor* anchor : [pane anchors]) {
DebugMsg("BGMAppDelegate::openSysPrefsSoundOutput: anchor = %s", [anchor.name UTF8String]);
if ([[anchor.name lowercaseString] isEqualToString:@"output"]) {
DebugMsg("BGMAppDelegate::openSysPrefsSoundOutput: Showing Output in Sound pane.");
[anchor reveal];
}
}
}
}
// Bring System Preferences to the foreground.
[sysPrefs activate];
}
#pragma mark NSMenuDelegate
- (void) menuNeedsUpdate:(NSMenu*)menu {
if ([menu isEqual:self.bgmMenu]) {
[autoPauseMenuItem parentMenuNeedsUpdate];
} else {
DebugMsg("BGMAppDelegate::menuNeedsUpdate: Warning: unexpected menu. menu=%s", menu.description.UTF8String);
}
}
- (void) menu:(NSMenu*)menu willHighlightItem:(NSMenuItem* __nullable)item {
if ([menu isEqual:self.bgmMenu]) {
[autoPauseMenuItem parentMenuItemWillHighlight:item];
} else {
DebugMsg("BGMAppDelegate::menu: Warning: unexpected menu. menu=%s", menu.description.UTF8String);
}
}
@end
#pragma clang assume_nonnull end
+9 -37
View File
@@ -17,69 +17,41 @@
// BGMAppVolumes.h
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Local Includes
#import "BGMAppVolumesController.h"
#import "BGMAudioDeviceManager.h"
// System Includes
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
@interface BGMAppVolumes : NSObject
- (id) initWithController:(BGMAppVolumesController*)inController
bgmMenu:(NSMenu*)inMenu
appVolumeView:(NSView*)inView;
// Pass -1 for initialVolume or initialPan to leave the volume/pan at its default level.
- (void) insertMenuItemForApp:(NSRunningApplication*)app
initialVolume:(int)volume
initialPan:(int)pan;
- (void) removeMenuItemForApp:(NSRunningApplication*)app;
- (void) removeAllAppVolumeMenuItems;
- (id) initWithMenu:(NSMenu*)menu appVolumeView:(NSView*)view audioDevices:(BGMAudioDeviceManager*)audioDevices;
@end
// Protocol for the UI custom classes
@protocol BGMAppVolumeMenuItemSubview <NSObject>
@protocol BGMAppVolumeSubview <NSObject>
- (void) setUpWithApp:(NSRunningApplication*)app
context:(BGMAppVolumes*)ctx
controller:(BGMAppVolumesController*)ctrl
menuItem:(NSMenuItem*)item;
- (void) setUpWithApp:(NSRunningApplication*)app context:(BGMAppVolumes*)ctx;
@end
// Custom classes for the UI elements in the app volume menu items
@interface BGMAVM_AppIcon : NSImageView <BGMAppVolumeMenuItemSubview>
@interface BGMAVM_AppIcon : NSImageView <BGMAppVolumeSubview>
@end
@interface BGMAVM_AppNameLabel : NSTextField <BGMAppVolumeMenuItemSubview>
@interface BGMAVM_AppNameLabel : NSTextField <BGMAppVolumeSubview>
@end
@interface BGMAVM_ShowMoreControlsButton : NSButton <BGMAppVolumeMenuItemSubview>
@end
@interface BGMAVM_VolumeSlider : NSSlider <BGMAppVolumeSubview>
@interface BGMAVM_VolumeSlider : NSSlider <BGMAppVolumeMenuItemSubview>
- (void) setRelativeVolume:(int)relativeVolume;
- (void) setRelativeVolume:(NSNumber*)relativeVolume;
@end
@interface BGMAVM_PanSlider : NSSlider <BGMAppVolumeMenuItemSubview>
- (void) setPanPosition:(int)panPosition;
@end
#pragma clang assume_nonnull end
-449
View File
@@ -1,449 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppVolumes.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2017 Andrew Tonner
//
// Self Include
#import "BGMAppVolumes.h"
// Local Includes
#import "BGM_Types.h"
#import "BGM_Utils.h"
#import "BGMAppDelegate.h"
// PublicUtility Includes
#import "CADebugMacros.h"
static float const kSlidersSnapWithin = 5;
static CGFloat const kAppVolumeViewInitialHeight = 20;
static NSString* const kMoreAppsMenuTitle = @"More Apps";
@implementation BGMAppVolumes {
BGMAppVolumesController* controller;
NSMenu* bgmMenu;
NSMenu* moreAppsMenu;
NSView* appVolumeView;
CGFloat appVolumeViewFullHeight;
// The number of menu items this class has added to bgmMenu. Doesn't include the More Apps menu.
NSInteger numMenuItems;
}
- (id) initWithController:(BGMAppVolumesController*)inController
bgmMenu:(NSMenu*)inMenu
appVolumeView:(NSView*)inView {
if ((self = [super init])) {
controller = inController;
bgmMenu = inMenu;
moreAppsMenu = [[NSMenu alloc] initWithTitle:kMoreAppsMenuTitle];
appVolumeView = inView;
appVolumeViewFullHeight = appVolumeView.frame.size.height;
numMenuItems = 0;
// Add the More Apps menu to the main menu.
NSMenuItem* moreAppsMenuItem =
[[NSMenuItem alloc] initWithTitle:kMoreAppsMenuTitle action:nil keyEquivalent:@""];
moreAppsMenuItem.submenu = moreAppsMenu;
[bgmMenu insertItem:moreAppsMenuItem atIndex:([self lastMenuItemIndex] + 1)];
numMenuItems++;
// Put an empty menu item above the More Apps menu item to fix its top margin.
NSMenuItem* spacer = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
spacer.view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, 0, 4)];
spacer.hidden = YES; // Tells accessibility clients to ignore this menu item.
[bgmMenu insertItem:spacer atIndex:[self lastMenuItemIndex]];
numMenuItems++;
}
return self;
}
#pragma mark UI Modifications
- (void) insertMenuItemForApp:(NSRunningApplication*)app
initialVolume:(int)volume
initialPan:(int)pan {
NSMenuItem* appVolItem = [self createBlankAppVolumeMenuItem];
// Look through the menu item's subviews for the ones we want to set up
for (NSView* subview in appVolItem.view.subviews) {
if ([subview conformsToProtocol:@protocol(BGMAppVolumeMenuItemSubview)]) {
[(NSView<BGMAppVolumeMenuItemSubview>*)subview setUpWithApp:app
context:self
controller:controller
menuItem:appVolItem];
}
}
// Store the NSRunningApplication object with the menu item so when the app closes we can find the item to remove it
appVolItem.representedObject = app;
// Set the slider to the volume for this app if we got one from the driver
[self setVolumeOfMenuItem:appVolItem relativeVolume:volume panPosition:pan];
// NSMenuItem didn't implement NSAccessibility before OS X SDK 10.12.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 // MAC_OS_X_VERSION_10_12
if ([appVolItem respondsToSelector:@selector(setAccessibilityTitle:)]) {
// TODO: This doesn't show up in Accessibility Inspector for me. Not sure why.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
appVolItem.accessibilityTitle = [NSString stringWithFormat:@"%@", [app localizedName]];
#pragma clang diagnostic pop
}
#endif
// Add the menu item to its menu.
if (app.activationPolicy == NSApplicationActivationPolicyRegular) {
[bgmMenu insertItem:appVolItem atIndex:[self firstMenuItemIndex]];
numMenuItems++;
} else if (app.activationPolicy == NSApplicationActivationPolicyAccessory) {
[moreAppsMenu insertItem:appVolItem atIndex:0];
}
}
// Create a blank menu item to copy as a template.
- (NSMenuItem*) createBlankAppVolumeMenuItem {
NSMenuItem* menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
menuItem.view = appVolumeView;
menuItem = [menuItem copy]; // So we can modify a copy of the view, rather than the template itself.
return menuItem;
}
- (void) setVolumeOfMenuItem:(NSMenuItem*)menuItem relativeVolume:(int)volume panPosition:(int)pan {
// Update the sliders.
for (NSView* subview in menuItem.view.subviews) {
// Set the volume.
if (volume != -1 && [subview isKindOfClass:[BGMAVM_VolumeSlider class]]) {
[(BGMAVM_VolumeSlider*)subview setRelativeVolume:volume];
}
// Set the pan position.
if (pan != -1 && [subview isKindOfClass:[BGMAVM_PanSlider class]]) {
[(BGMAVM_PanSlider*)subview setPanPosition:pan];
}
}
}
- (NSInteger) firstMenuItemIndex {
return [self lastMenuItemIndex] - numMenuItems + 1;
}
- (NSInteger) lastMenuItemIndex {
return [bgmMenu indexOfItemWithTag:kSeparatorBelowVolumesMenuItemTag] - 1;
}
- (void) removeMenuItemForApp:(NSRunningApplication*)app {
// Subtract two extra positions to skip the More Apps menu and the spacer menu item above it.
NSInteger lastAppVolumeMenuItemIndex = [self lastMenuItemIndex] - 2;
// Check each app volume menu item and remove the item that controls the given app.
// Look through the main menu.
for (NSInteger i = [self firstMenuItemIndex]; i <= lastAppVolumeMenuItemIndex; i++) {
NSMenuItem* item = [bgmMenu itemAtIndex:i];
NSRunningApplication* itemApp = item.representedObject;
BGMAssert(itemApp, "!itemApp for %s", item.title.UTF8String);
if ([itemApp isEqual:app]) {
[bgmMenu removeItem:item];
numMenuItems--;
return;
}
}
// Look through the More Apps menu.
for (NSInteger i = 0; i < [moreAppsMenu numberOfItems]; i++) {
NSMenuItem* item = [moreAppsMenu itemAtIndex:i];
NSRunningApplication* itemApp = item.representedObject;
BGMAssert(itemApp, "!itemApp for %s", item.title.UTF8String);
if ([itemApp isEqual:app]) {
[moreAppsMenu removeItem:item];
return;
}
}
}
- (void) showHideExtraControls:(BGMAVM_ShowMoreControlsButton*)button {
// Show or hide an app's extra controls, currently only pan, in its App Volumes menu item.
NSMenuItem* menuItem = button.cell.representedObject;
BGMAssert(button, "!button");
BGMAssert(menuItem, "!menuItem");
CGFloat width = menuItem.view.frame.size.width;
CGFloat height = menuItem.view.frame.size.height;
#if DEBUG
const char* appName = [((NSRunningApplication*)menuItem.representedObject).localizedName UTF8String];
#endif
// Using this function (instead of just ==) shouldn't be necessary, but just in case.
BOOL(^nearEnough)(CGFloat x, CGFloat y) = ^BOOL(CGFloat x, CGFloat y) {
return fabs(x - y) < 0.01; // We don't need much precision.
};
if (nearEnough(button.frameCenterRotation, 0.0)) {
// Hide extra controls
DebugMsg("BGMAppVolumes::showHideExtraControls: Hiding extra controls (%s)", appName);
BGMAssert(nearEnough(height, appVolumeViewFullHeight), "Extra controls were already hidden");
// Make the menu item shorter to hide the extra controls. Keep the width unchanged.
menuItem.view.frameSize = NSMakeSize(width, kAppVolumeViewInitialHeight);
// Turn the button upside down so the arrowhead points down.
button.frameCenterRotation = 180.0;
// Move the button up slightly so it aligns with the volume slider.
[button setFrameOrigin:NSMakePoint(button.frame.origin.x, button.frame.origin.y - 1)];
// Set the extra controls, and anything else below the fold, to hidden so accessibility
// clients can skip over them.
for (NSView* subview in menuItem.view.subviews) {
CGFloat top = subview.frame.origin.y + subview.frame.size.height;
if (top <= 0.0) {
subview.hidden = YES;
}
}
} else {
// Show extra controls
DebugMsg("BGMAppVolumes::showHideExtraControls: Showing extra controls (%s)", appName);
BGMAssert(nearEnough(button.frameCenterRotation, 180.0), "Unexpected button rotation");
BGMAssert(nearEnough(height, kAppVolumeViewInitialHeight), "Extra controls were already shown");
// Make the menu item taller to show the extra controls. Keep the width unchanged.
menuItem.view.frameSize = NSMakeSize(width, appVolumeViewFullHeight);
// Turn the button rightside up so the arrowhead points up.
button.frameCenterRotation = 0.0;
// Move the button down slightly, back to it's original position.
[button setFrameOrigin:NSMakePoint(button.frame.origin.x, button.frame.origin.y + 1)];
// Set all of the UI elements in the menu item to "not hidden" for accessibility clients.
for (NSView* subview in menuItem.view.subviews) {
subview.hidden = NO;
}
}
}
- (void) removeAllAppVolumeMenuItems {
// Remove all of the menu items this class adds to the menu except for the last two, which are
// the More Apps menu item and the invisible spacer above it.
while (numMenuItems > 2) {
[bgmMenu removeItemAtIndex:[self firstMenuItemIndex]];
numMenuItems--;
}
// The More Apps menu only contains app volume menu items, so we can just remove everything.
[moreAppsMenu removeAllItems];
}
@end
#pragma mark Custom Classes (IB)
// Custom classes for the UI elements in the app volume menu items
@implementation BGMAVM_AppIcon
- (void) setUpWithApp:(NSRunningApplication*)app
context:(BGMAppVolumes*)ctx
controller:(BGMAppVolumesController*)ctrl
menuItem:(NSMenuItem*)menuItem {
#pragma unused (ctx, ctrl, menuItem)
self.image = app.icon;
// Remove the icon from the accessibility hierarchy.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 // MAC_OS_X_VERSION_10_10
if ([self.cell respondsToSelector:@selector(setAccessibilityElement:)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
self.cell.accessibilityElement = NO;
#pragma clang diagnostic pop
}
#endif
}
@end
@implementation BGMAVM_AppNameLabel
- (void) setUpWithApp:(NSRunningApplication*)app
context:(BGMAppVolumes*)ctx
controller:(BGMAppVolumesController*)ctrl
menuItem:(NSMenuItem*)menuItem {
#pragma unused (ctx, ctrl, menuItem)
NSString* name = app.localizedName ? (NSString*)app.localizedName : @"";
self.stringValue = name;
}
@end
@implementation BGMAVM_ShowMoreControlsButton
- (void) setUpWithApp:(NSRunningApplication*)app
context:(BGMAppVolumes*)ctx
controller:(BGMAppVolumesController*)ctrl
menuItem:(NSMenuItem*)menuItem {
#pragma unused (app, ctrl)
// Set up the button that show/hide the extra controls (currently only a pan slider) for the app.
self.cell.representedObject = menuItem;
self.target = ctx;
self.action = @selector(showHideExtraControls:);
// The menu item starts out with the extra controls visible, so we hide them here.
//
// TODO: Leave them visible if any of the controls are set to non-default values. The user has no way to
// tell otherwise. Maybe we should also make this button look different if the controls are hidden
// when they have non-default values.
[ctx showHideExtraControls:self];
if ([self respondsToSelector:@selector(setAccessibilityTitle:)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
self.accessibilityTitle = @"More options";
#pragma clang diagnostic pop
}
}
@end
@implementation BGMAVM_VolumeSlider {
// Will be set to -1 for apps without a pid
pid_t appProcessID;
NSString* __nullable appBundleID;
BGMAppVolumesController* controller;
}
- (void) setUpWithApp:(NSRunningApplication*)app
context:(BGMAppVolumes*)ctx
controller:(BGMAppVolumesController*)ctrl
menuItem:(NSMenuItem*)menuItem {
#pragma unused (ctx, menuItem)
controller = ctrl;
self.target = self;
self.action = @selector(appVolumeChanged);
appProcessID = app.processIdentifier;
appBundleID = app.bundleIdentifier;
self.maxValue = kAppRelativeVolumeMaxRawValue;
self.minValue = kAppRelativeVolumeMinRawValue;
if ([self respondsToSelector:@selector(setAccessibilityTitle:)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
self.accessibilityTitle = [NSString stringWithFormat:@"Volume for %@", [app localizedName]];
#pragma clang diagnostic pop
}
}
// We have to handle snapping for volume sliders ourselves because adding a tick mark (snap point) in Interface Builder
// changes how the slider looks.
- (void) snap {
// Snap to the 50% point.
float midPoint = (float)((self.maxValue + self.minValue) / 2);
if (self.floatValue > (midPoint - kSlidersSnapWithin) && self.floatValue < (midPoint + kSlidersSnapWithin)) {
self.floatValue = midPoint;
}
}
- (void) setRelativeVolume:(int)relativeVolume {
self.intValue = relativeVolume;
[self snap];
}
- (void) appVolumeChanged {
// TODO: This (sending updates to the driver) should probably be rate-limited. It uses a fair bit of CPU for me.
DebugMsg("BGMAppVolumes::appVolumeChanged: App volume for %s (%d) changed to %d",
appBundleID.UTF8String,
appProcessID,
self.intValue);
[self snap];
// The values from our sliders are in
// [kAppRelativeVolumeMinRawValue, kAppRelativeVolumeMaxRawValue] already.
[controller setVolume:self.intValue forAppWithProcessID:appProcessID bundleID:appBundleID];
}
@end
@implementation BGMAVM_PanSlider {
// Will be set to -1 for apps without a pid
pid_t appProcessID;
NSString* __nullable appBundleID;
BGMAppVolumesController* controller;
}
- (void) setUpWithApp:(NSRunningApplication*)app
context:(BGMAppVolumes*)ctx
controller:(BGMAppVolumesController*)ctrl
menuItem:(NSMenuItem*)menuItem {
#pragma unused (ctx, menuItem)
controller = ctrl;
self.target = self;
self.action = @selector(appPanPositionChanged);
appProcessID = app.processIdentifier;
appBundleID = app.bundleIdentifier;
self.minValue = kAppPanLeftRawValue;
self.maxValue = kAppPanRightRawValue;
if ([self respondsToSelector:@selector(setAccessibilityTitle:)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
self.accessibilityTitle = [NSString stringWithFormat:@"Pan for %@", [app localizedName]];
#pragma clang diagnostic pop
}
}
- (void) setPanPosition:(int)panPosition {
self.intValue = panPosition;
}
- (void) appPanPositionChanged {
// TODO: This (sending updates to the driver) should probably be rate-limited. It uses a fair bit of CPU for me.
DebugMsg("BGMAppVolumes::appPanPositionChanged: App pan position for %s changed to %d", appBundleID.UTF8String, self.intValue);
// The values from our sliders are in [kAppPanLeftRawValue, kAppPanRightRawValue] already.
[controller setPanPosition:self.intValue forAppWithProcessID:appProcessID bundleID:appBundleID];
}
@end
+298
View File
@@ -0,0 +1,298 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppVolumes.m
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMAppVolumes.h"
// BGM Includes
#include "BGM_Types.h"
// PublicUtility Includes
#include "CACFDictionary.h"
#include "CACFArray.h"
#include "CACFString.h"
static NSInteger const kAppVolumesMenuItemTag = 3;
static NSInteger const kSeparatorBelowAppVolumesMenuItemTag = 4;
static float const kSlidersSnapWithin = 5;
@implementation BGMAppVolumes {
NSMenu* bgmMenu;
NSView* appVolumeView;
BGMAudioDeviceManager* audioDevices;
}
- (id) initWithMenu:(NSMenu*)menu appVolumeView:(NSView*)view audioDevices:(BGMAudioDeviceManager*)devices {
if ((self = [super init])) {
bgmMenu = menu;
appVolumeView = view;
audioDevices = devices;
// Create the menu items for controlling app volumes
[self insertMenuItemsForApps:[[NSWorkspace sharedWorkspace] runningApplications]];
// Register for notifications when the user opens or closes apps, so we can update the menu
[[NSWorkspace sharedWorkspace] addObserver:self
forKeyPath:@"runningApplications"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
}
return self;
}
- (void) dealloc {
[[NSWorkspace sharedWorkspace] removeObserver:self forKeyPath:@"runningApplications" context:nil];
}
- (void) insertMenuItemsForApps:(BGMGeneric(NSArray, NSRunningApplication*)*)apps {
NSAssert([NSThread isMainThread], @"insertMenuItemsForApps is not thread safe");
#ifndef NS_BLOCK_ASSERTIONS // If assertions are enabled
NSInteger numMenuItemsBeforeInsert =
[bgmMenu indexOfItemWithTag:kSeparatorBelowAppVolumesMenuItemTag] - [bgmMenu indexOfItemWithTag:kAppVolumesMenuItemTag] - 1;
NSUInteger numApps = 0;
#endif
// Create a blank menu item to copy as a template
NSMenuItem* blankItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[blankItem setView:appVolumeView];
// Get the app volumes currently set on the device
CACFArray appVolumesOnDevice((CFArrayRef)[audioDevices bgmDevice].GetPropertyData_CFType(kBGMAppVolumesAddress), false);
NSInteger index = [bgmMenu indexOfItemWithTag:kAppVolumesMenuItemTag] + 1;
// Add a volume-control menu item for each app
for (NSRunningApplication* app in apps) {
// Only show apps that appear in the dock (at first)
// TODO: Would it be better to only show apps that are registered as HAL clients?
if ([app activationPolicy] != NSApplicationActivationPolicyRegular) continue;
// Don't show Finder
if ([[app bundleIdentifier] isEqualTo:@"com.apple.finder"]) continue;
#ifndef NS_BLOCK_ASSERTIONS // If assertions are enabled
// Count how many apps we should add menu items for so we can check it at the end of the method
numApps++;
#endif
NSMenuItem* appVolItem = [blankItem copy];
// Look through the menu item's subviews for the ones we want to set up
for (NSView* subview in [[appVolItem view] subviews]) {
if ([subview conformsToProtocol:@protocol(BGMAppVolumeSubview)]) {
[subview performSelector:@selector(setUpWithApp:context:) withObject:app withObject:self];
}
}
// Store the NSRunningApplication object with the menu item so when the app closes we can find the item to remove it
[appVolItem setRepresentedObject:app];
// Set the slider to the volume for this app if we got one from the driver
[self setVolumeOfMenuItem:appVolItem fromAppVolumes:appVolumesOnDevice];
[bgmMenu insertItem:appVolItem atIndex:index];
}
#ifndef NS_BLOCK_ASSERTIONS // If assertions are enabled
NSInteger numMenuItemsAfterInsert =
[bgmMenu indexOfItemWithTag:kSeparatorBelowAppVolumesMenuItemTag] - [bgmMenu indexOfItemWithTag:kAppVolumesMenuItemTag] - 1;
NSAssert3(numMenuItemsAfterInsert == (numMenuItemsBeforeInsert + numApps),
@"Did not add the expected number of menu items. numMenuItemsBeforeInsert=%ld numMenuItemsAfterInsert=%ld numAppsToAdd=%lu",
(long)numMenuItemsBeforeInsert,
(long)numMenuItemsAfterInsert,
(unsigned long)numApps);
#endif
}
- (void) removeMenuItemsForApps:(BGMGeneric(NSArray, NSRunningApplication*)*)apps {
NSAssert([NSThread isMainThread], @"removeMenuItemsForApps is not thread safe");
NSInteger firstItemIndex = [bgmMenu indexOfItemWithTag:kAppVolumesMenuItemTag] + 1;
NSInteger lastItemIndex = [bgmMenu indexOfItemWithTag:kSeparatorBelowAppVolumesMenuItemTag] - 1;
// Check each app volume menu item, removing the items that control one of the given apps
for (NSInteger i = firstItemIndex; i <= lastItemIndex; i++) {
NSMenuItem* item = [bgmMenu itemAtIndex:i];
for (NSRunningApplication* appToBeRemoved in apps) {
NSRunningApplication* itemApp = [item representedObject];
if ([itemApp isEqual:appToBeRemoved]) {
[bgmMenu removeItem:item];
// Correct i to account for the item we removed, since we're editing the menu in place
i--;
continue;
}
}
}
}
- (void) setVolumeOfMenuItem:(NSMenuItem*)menuItem fromAppVolumes:(CACFArray&)appVolumes {
// Set menuItem's volume slider to the volume of the app in appVolumes that menuItem represents
// Leaves menuItem unchanged if it doesn't match any of the apps in appVolumes
NSRunningApplication* representedApp = [menuItem representedObject];
for (UInt32 i = 0; i < appVolumes.GetNumberItems(); i++) {
CACFDictionary appVolume(false);
appVolumes.GetCACFDictionary(i, appVolume);
// Match the app to the menu item by pid or bundle id
CACFString bundleID;
bundleID.DontAllowRelease();
appVolume.GetCACFString(CFSTR(kBGMAppVolumesKey_BundleID), bundleID);
pid_t pid;
appVolume.GetSInt32(CFSTR(kBGMAppVolumesKey_ProcessID), pid);
if ([representedApp processIdentifier] == pid ||
[[representedApp bundleIdentifier] isEqualToString:(__bridge NSString*)bundleID.GetCFString()]) {
CFTypeRef relativeVolume;
appVolume.GetCFType(CFSTR(kBGMAppVolumesKey_RelativeVolume), relativeVolume);
// Update the slider
for (NSView* subview in [[menuItem view] subviews]) {
if ([subview respondsToSelector:@selector(setRelativeVolume:)]) {
[subview performSelector:@selector(setRelativeVolume:) withObject:(__bridge NSNumber*)relativeVolume];
}
}
}
}
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
#pragma unused (object, context)
// KVO callback for the apps currently running on the system. Adds/removes the associated menu items.
if ([keyPath isEqualToString:@"runningApplications"]) {
BGMGeneric(NSArray, NSRunningApplication*)* newApps = [change objectForKey:NSKeyValueChangeNewKey];
BGMGeneric(NSArray, NSRunningApplication*)* oldApps = [change objectForKey:NSKeyValueChangeOldKey];
int changeKind = [[change valueForKey:NSKeyValueChangeKindKey] intValue];
switch (changeKind) {
case NSKeyValueChangeInsertion:
[self insertMenuItemsForApps:newApps];
break;
case NSKeyValueChangeRemoval:
[self removeMenuItemsForApps:oldApps];
break;
case NSKeyValueChangeReplacement:
[self removeMenuItemsForApps:oldApps];
[self insertMenuItemsForApps:newApps];
break;
case NSKeyValueChangeSetting:
[bgmMenu removeAllItems];
[self insertMenuItemsForApps:newApps];
break;
}
}
}
- (void) sendVolumeChangeToBGMDevice:(SInt32)newVolume appProcessID:(pid_t)appProcessID appBundleID:(NSString*)appBundleID {
CACFDictionary appVolumeChange(true);
appVolumeChange.AddSInt32(CFSTR(kBGMAppVolumesKey_ProcessID), appProcessID);
appVolumeChange.AddString(CFSTR(kBGMAppVolumesKey_BundleID), (__bridge CFStringRef)appBundleID);
// The values from our sliders are in [kAppRelativeVolumeMinRawValue, kAppRelativeVolumeMaxRawValue] already
appVolumeChange.AddSInt32(CFSTR(kBGMAppVolumesKey_RelativeVolume), newVolume);
CACFArray appVolumeChanges(true);
appVolumeChanges.AppendDictionary(appVolumeChange.GetDict());
[audioDevices bgmDevice].SetPropertyData_CFType(kBGMAppVolumesAddress, appVolumeChanges.AsPropertyList());
}
@end
// Custom classes for the UI elements in the app volume menu items
@implementation BGMAVM_AppIcon
- (void) setUpWithApp:(NSRunningApplication*)app context:(BGMAppVolumes*)ctx {
#pragma unused (ctx)
[self setImage:[app icon]];
}
@end
@implementation BGMAVM_AppNameLabel
- (void) setUpWithApp:(NSRunningApplication*)app context:(BGMAppVolumes*)ctx {
#pragma unused (ctx)
[self setStringValue:[app localizedName]];
}
@end
@implementation BGMAVM_VolumeSlider {
// Will be set to -1 for apps without a pid
pid_t appProcessID;
NSString* appBundleID;
BGMAppVolumes* context;
}
- (void) setUpWithApp:(NSRunningApplication*)app context:(BGMAppVolumes*)ctx {
context = ctx;
[self setTarget:self];
[self setAction:@selector(appVolumeChanged)];
appProcessID = [app processIdentifier];
appBundleID = [app bundleIdentifier];
[self setMaxValue:kAppRelativeVolumeMaxRawValue];
[self setMinValue:kAppRelativeVolumeMinRawValue];
}
- (void) snap {
// Snap to the 50% point
float midPoint = static_cast<float>(([self maxValue] - [self minValue]) / 2);
if ([self floatValue] > (midPoint - kSlidersSnapWithin) && [self floatValue] < (midPoint + kSlidersSnapWithin)) {
[self setFloatValue:midPoint];
}
}
- (void) setRelativeVolume:(NSNumber*)relativeVolume {
[self setIntValue:[relativeVolume intValue]];
[self snap];
}
- (void) appVolumeChanged {
// TODO: This (sending updates to the driver) should probably be rate-limited. It uses a fair bit of CPU for me.
DebugMsg("BGMAppVolumes::appVolumeChanged: App volume for %s changed to %d", [appBundleID UTF8String], [self intValue]);
[self snap];
[context sendVolumeChangeToBGMDevice:[self intValue] appProcessID:appProcessID appBundleID:appBundleID];
}
@end
-51
View File
@@ -1,51 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppVolumesController.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Local Includes
#import "BGMAudioDeviceManager.h"
// System Includes
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
@interface BGMAppVolumesController : NSObject
- (id) initWithMenu:(NSMenu*)menu
appVolumeView:(NSView*)view
audioDevices:(BGMAudioDeviceManager*)audioDevices;
// See BGMBackgroundMusicDevice::SetAppVolume.
- (void) setVolume:(SInt32)volume
forAppWithProcessID:(pid_t)processID
bundleID:(NSString* __nullable)bundleID;
// See BGMBackgroundMusicDevice::SetPanVolume.
- (void) setPanPosition:(SInt32)pan
forAppWithProcessID:(pid_t)processID
bundleID:(NSString* __nullable)bundleID;
@end
#pragma clang assume_nonnull end
-249
View File
@@ -1,249 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppVolumesController.mm
// BGMApp
//
// Copyright © 2017, 2018 Kyle Neideck
// Copyright © 2017 Andrew Tonner
//
// Self Include
#import "BGMAppVolumesController.h"
// Local Includes
#import "BGM_Types.h"
#import "BGM_Utils.h"
#import "BGMAppVolumes.h"
// PublicUtility Includes
#import "CACFArray.h"
#import "CACFDictionary.h"
#import "CACFString.h"
// System Includes
#include <libproc.h>
#pragma clang assume_nonnull begin
typedef struct BGMAppVolumeAndPan {
int volume;
int pan;
} BGMAppVolumeAndPan;
@implementation BGMAppVolumesController {
// The App Volumes UI.
BGMAppVolumes* appVolumes;
BGMAudioDeviceManager* audioDevices;
}
#pragma mark Initialisation
- (id) initWithMenu:(NSMenu*)menu
appVolumeView:(NSView*)view
audioDevices:(BGMAudioDeviceManager*)devices {
if ((self = [super init])) {
audioDevices = devices;
appVolumes = [[BGMAppVolumes alloc] initWithController:self
bgmMenu:menu
appVolumeView:view];
// Create the menu items for controlling app volumes.
NSArray<NSRunningApplication*>* apps = [[NSWorkspace sharedWorkspace] runningApplications];
[self insertMenuItemsForApps:apps];
// Register for notifications when the user opens or closes apps, so we can update the menu.
auto opts = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
[[NSWorkspace sharedWorkspace] addObserver:self
forKeyPath:@"runningApplications"
options:opts
context:nil];
}
return self;
}
- (void) dealloc {
[[NSWorkspace sharedWorkspace] removeObserver:self
forKeyPath:@"runningApplications"
context:nil];
}
// Adds a volume control menu item for each given app.
- (void) insertMenuItemsForApps:(NSArray<NSRunningApplication*>*)apps {
NSAssert([NSThread isMainThread], @"insertMenuItemsForApps is not thread safe");
// TODO: Handle the C++ exceptions this method can throw. They can cause crashes because this
// method is called in a KVO handler.
// Get the app volumes currently set on the device
CACFArray volumesFromBGMDevice([audioDevices bgmDevice].GetAppVolumes(), false);
for (NSRunningApplication* app in apps) {
if ([self shouldBeIncludedInMenu:app]) {
BGMAppVolumeAndPan initial = [self getVolumeAndPanForApp:app
fromVolumes:volumesFromBGMDevice];
[appVolumes insertMenuItemForApp:app
initialVolume:initial.volume
initialPan:initial.pan];
}
}
}
- (BGMAppVolumeAndPan) getVolumeAndPanForApp:(NSRunningApplication*)app
fromVolumes:(const CACFArray&)volumes {
BGMAppVolumeAndPan volumeAndPan = {
.volume = -1,
.pan = -1
};
for (UInt32 i = 0; i < volumes.GetNumberItems(); i++) {
CACFDictionary appVolume(false);
volumes.GetCACFDictionary(i, appVolume);
// Match the app to the volume/pan by pid or bundle ID.
CACFString bundleID;
bundleID.DontAllowRelease();
appVolume.GetCACFString(CFSTR(kBGMAppVolumesKey_BundleID), bundleID);
pid_t pid;
appVolume.GetSInt32(CFSTR(kBGMAppVolumesKey_ProcessID), pid);
if ((app.processIdentifier == pid) ||
[app.bundleIdentifier isEqualToString:(__bridge NSString*)bundleID.GetCFString()]) {
// Found a match, so read the volume and pan.
appVolume.GetSInt32(CFSTR(kBGMAppVolumesKey_RelativeVolume), volumeAndPan.volume);
appVolume.GetSInt32(CFSTR(kBGMAppVolumesKey_PanPosition), volumeAndPan.pan);
break;
}
}
return volumeAndPan;
}
- (BOOL) shouldBeIncludedInMenu:(NSRunningApplication*)app {
// Ignore hidden apps and Background Music itself.
// TODO: Would it be better to only show apps that are registered as HAL clients?
BOOL isHidden = app.activationPolicy != NSApplicationActivationPolicyRegular &&
app.activationPolicy != NSApplicationActivationPolicyAccessory;
NSString* bundleID = app.bundleIdentifier;
BOOL isBGMApp = bundleID && [@kBGMAppBundleID isEqualToString:BGMNN(bundleID)];
return !isHidden && !isBGMApp;
}
- (void) removeMenuItemsForApps:(NSArray<NSRunningApplication*>*)apps {
NSAssert([NSThread isMainThread], @"removeMenuItemsForApps is not thread safe");
for (NSRunningApplication* app in apps) {
[appVolumes removeMenuItemForApp:app];
}
}
#pragma mark Accessors
- (void) setVolume:(SInt32)volume
forAppWithProcessID:(pid_t)processID
bundleID:(NSString* __nullable)bundleID {
// Update the app's volume.
audioDevices.bgmDevice.SetAppVolume(volume, processID, (__bridge_retained CFStringRef)bundleID);
// If this volume is for FaceTime, set the volume for the avconferenced process as well. This
// works around FaceTime not playing its own audio. It plays UI sounds through
// systemsoundserverd and call audio through avconferenced.
//
// This isn't ideal because other apps might play audio through avconferenced, but I don't see a
// good way we could find out which app is actually playing the audio. We could probably figure
// it out from reading avconferenced's logs, at least, if it turns out to be important. See
// https://github.com/kyleneideck/BackgroundMusic/issues/139.
if ([bundleID isEqual:@"com.apple.FaceTime"]) {
[self setAvconferencedVolume:volume];
}
}
- (void) setAvconferencedVolume:(SInt32)volume {
// TODO: This volume will be lost if avconferenced is restarted.
pid_t pids[1024];
size_t procCount = proc_listallpids(pids, 1024);
char path[PROC_PIDPATHINFO_MAXSIZE];
for (int i = 0; i < procCount; i++) {
pid_t pid = pids[i];
if (proc_pidpath(pid, path, sizeof(path)) > 0 &&
strncmp(path, "/usr/libexec/avconferenced", sizeof(path)) == 0) {
DebugMsg("Setting avconferenced volume: %d", volume);
audioDevices.bgmDevice.SetAppVolume(volume, pid, nullptr);
return;
}
}
LogWarning("Failed to set avconferenced volume.");
}
- (void) setPanPosition:(SInt32)pan
forAppWithProcessID:(pid_t)processID
bundleID:(NSString* __nullable)bundleID {
audioDevices.bgmDevice.SetAppPanPosition(pan,
processID,
(__bridge_retained CFStringRef)bundleID);
}
#pragma mark KVO
- (void) observeValueForKeyPath:(NSString* __nullable)keyPath
ofObject:(id __nullable)object
change:(NSDictionary* __nullable)change
context:(void* __nullable)context
{
#pragma unused (object, context)
// KVO callback for the apps currently running on the system. Adds/removes the associated menu
// items.
if (keyPath && change && [keyPath isEqualToString:@"runningApplications"]) {
NSArray<NSRunningApplication*>* newApps = change[NSKeyValueChangeNewKey];
NSArray<NSRunningApplication*>* oldApps = change[NSKeyValueChangeOldKey];
int changeKind = [change[NSKeyValueChangeKindKey] intValue];
switch (changeKind) {
case NSKeyValueChangeInsertion:
[self insertMenuItemsForApps:newApps];
break;
case NSKeyValueChangeRemoval:
[self removeMenuItemsForApps:oldApps];
break;
case NSKeyValueChangeReplacement:
[self removeMenuItemsForApps:oldApps];
[self insertMenuItemsForApps:newApps];
break;
case NSKeyValueChangeSetting:
[appVolumes removeAllAppVolumeMenuItems];
[self insertMenuItemsForApps:newApps];
break;
}
}
}
@end
#pragma clang assume_nonnull end
-386
View File
@@ -1,386 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAudioDevice.cpp
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Self Include
#include "BGMAudioDevice.h"
// Local Includes
#include "BGM_Types.h"
// System Includes
#include <AudioToolbox/AudioServices.h>
#pragma mark Construction/Destruction
BGMAudioDevice::BGMAudioDevice(AudioObjectID inAudioDevice)
:
CAHALAudioDevice(inAudioDevice)
{
}
BGMAudioDevice::BGMAudioDevice(CFStringRef inUID)
:
CAHALAudioDevice(inUID)
{
}
BGMAudioDevice::BGMAudioDevice(const CAHALAudioDevice& inDevice)
:
BGMAudioDevice(inDevice.GetObjectID())
{
};
BGMAudioDevice::~BGMAudioDevice()
{
}
bool BGMAudioDevice::CanBeOutputDeviceInBGMApp() const
{
CFStringRef uid = CopyDeviceUID();
bool isNullDevice = CFEqual(uid, CFSTR(kBGMNullDeviceUID));
CFRelease(uid);
bool hasOutputChannels = GetTotalNumberChannels(/* inIsInput = */ false) > 0;
bool canBeDefault = CanBeDefaultDevice(/* inIsInput = */ false, /* inIsSystem = */ false);
return !IsBGMDeviceInstance() &&
!isNullDevice &&
!IsHidden() &&
hasOutputChannels &&
canBeDefault;
}
#pragma mark Available Controls
bool BGMAudioDevice::HasSettableMasterVolume(AudioObjectPropertyScope inScope) const
{
return HasVolumeControl(inScope, kMasterChannel) &&
VolumeControlIsSettable(inScope, kMasterChannel);
}
bool BGMAudioDevice::HasSettableVirtualMasterVolume(AudioObjectPropertyScope inScope) const
{
AudioObjectPropertyAddress virtualMasterVolumeAddress = {
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
inScope,
kAudioObjectPropertyElementMaster
};
// TODO: Replace these calls deprecated AudioToolbox functions. There are more below.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Boolean virtualMasterVolumeIsSettable;
OSStatus err = AudioHardwareServiceIsPropertySettable(GetObjectID(),
&virtualMasterVolumeAddress,
&virtualMasterVolumeIsSettable);
virtualMasterVolumeIsSettable &= (err == kAudioServicesNoError);
bool hasVirtualMasterVolume =
AudioHardwareServiceHasProperty(GetObjectID(), &virtualMasterVolumeAddress);
#pragma clang diagnostic pop
return hasVirtualMasterVolume && virtualMasterVolumeIsSettable;
}
bool BGMAudioDevice::HasSettableMasterMute(AudioObjectPropertyScope inScope) const
{
return HasMuteControl(inScope, kMasterChannel) &&
MuteControlIsSettable(inScope, kMasterChannel);
}
#pragma mark Control Values Accessors
void BGMAudioDevice::CopyMuteFrom(const BGMAudioDevice inDevice,
AudioObjectPropertyScope inScope)
{
// TODO: Support for devices that have per-channel mute controls but no master mute control
if(HasSettableMasterMute(inScope) && inDevice.HasMuteControl(inScope, kMasterChannel))
{
SetMuteControlValue(inScope,
kMasterChannel,
inDevice.GetMuteControlValue(inScope, kMasterChannel));
}
}
void BGMAudioDevice::CopyVolumeFrom(const BGMAudioDevice inDevice,
AudioObjectPropertyScope inScope)
{
// Get the volume of the other device.
bool didGetVolume = false;
Float32 volume = FLT_MIN;
if(inDevice.HasVolumeControl(inScope, kMasterChannel))
{
volume = inDevice.GetVolumeControlScalarValue(inScope, kMasterChannel);
didGetVolume = true;
}
// Use the average channel volume of the other device if it has no master volume.
if(!didGetVolume)
{
UInt32 numChannels =
inDevice.GetTotalNumberChannels(inScope == kAudioObjectPropertyScopeInput);
volume = 0;
for(UInt32 channel = 1; channel <= numChannels; channel++)
{
if(inDevice.HasVolumeControl(inScope, channel))
{
volume += inDevice.GetVolumeControlScalarValue(inScope, channel);
didGetVolume = true;
}
}
if(numChannels > 0) // Avoid divide by zero.
{
volume /= numChannels;
}
}
// Set the volume of this device.
if(didGetVolume && volume != FLT_MIN)
{
bool didSetVolume = false;
try
{
didSetVolume = SetMasterVolumeScalar(inScope, volume);
}
catch(CAException e)
{
OSStatus err = e.GetError();
char err4CC[5] = CA4CCToCString(err);
CFStringRef uid = CopyDeviceUID();
LogWarning("BGMAudioDevice::CopyVolumeFrom: CAException '%s' trying to set master "
"volume of %s",
err4CC,
CFStringGetCStringPtr(uid, kCFStringEncodingUTF8));
CFRelease(uid);
}
if(!didSetVolume)
{
// Couldn't find a master volume control to set, so try to find a virtual one
Float32 virtualMasterVolume;
bool success = inDevice.GetVirtualMasterVolumeScalar(inScope, virtualMasterVolume);
if(success)
{
didSetVolume = SetVirtualMasterVolumeScalar(inScope, virtualMasterVolume);
}
}
if(!didSetVolume)
{
// Couldn't set a master or virtual master volume, so as a fallback try to set each
// channel individually.
UInt32 numChannels = GetTotalNumberChannels(inScope == kAudioObjectPropertyScopeInput);
for(UInt32 channel = 1; channel <= numChannels; channel++)
{
if(HasVolumeControl(inScope, channel) && VolumeControlIsSettable(inScope, channel))
{
SetVolumeControlScalarValue(inScope, channel, volume);
}
}
}
}
}
bool BGMAudioDevice::SetMasterVolumeScalar(AudioObjectPropertyScope inScope, Float32 inVolume)
{
if(HasSettableMasterVolume(inScope))
{
SetVolumeControlScalarValue(inScope, kMasterChannel, inVolume);
return true;
}
return false;
}
bool BGMAudioDevice::GetVirtualMasterVolumeScalar(AudioObjectPropertyScope inScope,
Float32& outVirtualMasterVolume) const
{
AudioObjectPropertyAddress virtualMasterVolumeAddress = {
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
inScope,
kAudioObjectPropertyElementMaster
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if(!AudioHardwareServiceHasProperty(GetObjectID(), &virtualMasterVolumeAddress))
{
return false;
}
#pragma clang diagnostic pop
UInt32 virtualMasterVolumePropertySize = sizeof(Float32);
return kAudioServicesNoError == AHSGetPropertyData(GetObjectID(),
&virtualMasterVolumeAddress,
&virtualMasterVolumePropertySize,
&outVirtualMasterVolume);
}
bool BGMAudioDevice::SetVirtualMasterVolumeScalar(AudioObjectPropertyScope inScope,
Float32 inVolume)
{
// TODO: For me, setting the virtual master volume sets all the device's channels to the same volume, meaning you can't
// keep any channels quieter than the others. The expected behaviour is to scale the channel volumes
// proportionally. So to do this properly I think we'd have to store BGMDevice's previous volume and calculate
// each channel's new volume from its current volume and the distance between BGMDevice's old and new volumes.
//
// The docs kAudioHardwareServiceDeviceProperty_VirtualMasterVolume for say
// "If the device has individual channel volume controls, this property will apply to those identified by the
// device's preferred multi-channel layout (or preferred stereo pair if the device is stereo only). Note that
// this control maintains the relative balance between all the channels it affects.
// so I'm not sure why that's not working here. As a workaround we take the to device's (virtual master) balance
// before changing the volume and set it back after, but of course that'll only work for stereo devices.
bool didSetVolume = false;
if(HasSettableVirtualMasterVolume(inScope))
{
// Not sure why, but setting the virtual master volume sets all channels to the same volume. As a workaround, we store
// the current balance here so we can reset it after setting the volume.
Float32 virtualMasterBalance;
bool didGetVirtualMasterBalance = GetVirtualMasterBalance(inScope, virtualMasterBalance);
AudioObjectPropertyAddress virtualMasterVolumeAddress = {
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
inScope,
kAudioObjectPropertyElementMaster
};
didSetVolume = (kAudioServicesNoError == AHSSetPropertyData(GetObjectID(),
&virtualMasterVolumeAddress,
sizeof(Float32),
&inVolume));
// Reset the balance
AudioObjectPropertyAddress virtualMasterBalanceAddress = {
kAudioHardwareServiceDeviceProperty_VirtualMasterBalance,
inScope,
kAudioObjectPropertyElementMaster
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if(didSetVolume &&
didGetVirtualMasterBalance &&
AudioHardwareServiceHasProperty(GetObjectID(), &virtualMasterBalanceAddress))
{
Boolean balanceIsSettable;
OSStatus err = AudioHardwareServiceIsPropertySettable(GetObjectID(),
&virtualMasterBalanceAddress,
&balanceIsSettable);
if(err == kAudioServicesNoError && balanceIsSettable)
{
AHSSetPropertyData(GetObjectID(),
&virtualMasterBalanceAddress,
sizeof(Float32),
&virtualMasterBalance);
}
}
#pragma clang diagnostic pop
}
return didSetVolume;
}
bool BGMAudioDevice::GetVirtualMasterBalance(AudioObjectPropertyScope inScope,
Float32& outVirtualMasterBalance) const
{
AudioObjectPropertyAddress virtualMasterBalanceAddress = {
kAudioHardwareServiceDeviceProperty_VirtualMasterBalance,
inScope,
kAudioObjectPropertyElementMaster
};
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if(!AudioHardwareServiceHasProperty(GetObjectID(), &virtualMasterBalanceAddress))
{
return false;
}
#pragma clang diagnostic pop
UInt32 virtualMasterVolumePropertySize = sizeof(Float32);
return kAudioServicesNoError == AHSGetPropertyData(GetObjectID(),
&virtualMasterBalanceAddress,
&virtualMasterVolumePropertySize,
&outVirtualMasterBalance);
}
#pragma mark Implementation
bool BGMAudioDevice::IsBGMDevice(bool inIncludeUISoundsInstance) const
{
bool isBGMDevice = false;
if(GetObjectID() != kAudioObjectUnknown)
{
// Check the device's UID to see whether it's BGMDevice.
CFStringRef uid = CopyDeviceUID();
isBGMDevice =
CFEqual(uid, CFSTR(kBGMDeviceUID)) ||
(inIncludeUISoundsInstance && CFEqual(uid, CFSTR(kBGMDeviceUID_UISounds)));
CFRelease(uid);
}
return isBGMDevice;
}
// static
OSStatus BGMAudioDevice::AHSGetPropertyData(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32* ioDataSize,
void* outData)
{
// The docs for AudioHardwareServiceGetPropertyData specifically allow passing NULL for
// inQualifierData as we do here, but it's declared in an assume_nonnull section so we have to
// disable the warning here. I'm not sure why inQualifierData isn't __nullable. I'm assuming
// it's either a backwards compatibility thing or just a bug.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// The non-depreciated version of this (and the setter below) doesn't seem to support devices
// other than the default
return AudioHardwareServiceGetPropertyData(inObjectID, inAddress, 0, NULL, ioDataSize, outData);
#pragma clang diagnostic pop
}
// static
OSStatus BGMAudioDevice::AHSSetPropertyData(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inDataSize,
const void* inData)
{
// See the explanation about these pragmas in AHSGetPropertyData
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
return AudioHardwareServiceSetPropertyData(inObjectID, inAddress, 0, NULL, inDataSize, inData);
#pragma clang diagnostic pop
}
-120
View File
@@ -1,120 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
// BGMAudioDevice.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// A HAL audio device. Note that this class's only state is the AudioObjectID of the device.
//
#ifndef BGMApp__BGMAudioDevice
#define BGMApp__BGMAudioDevice
// PublicUtility Includes
#include "CAHALAudioDevice.h"
class BGMAudioDevice
:
public CAHALAudioDevice
{
#pragma mark Construction/Destruction
public:
BGMAudioDevice(AudioObjectID inAudioDevice);
/*!
Creates a BGMAudioDevice with the Audio Object ID of the device whose UID is inUID or, if no
such device is found, kAudioObjectUnknown.
@throws CAException If the HAL returns an error when queried for the device's ID.
@see kAudioPlugInPropertyTranslateUIDToDevice in AudioHardwareBase.h.
*/
BGMAudioDevice(CFStringRef inUID);
BGMAudioDevice(const CAHALAudioDevice& inDevice);
virtual ~BGMAudioDevice();
#if defined(__OBJC__)
// Hack/workaround for Objective-C classes so we don't have to use pointers for instance
// variables.
BGMAudioDevice() : BGMAudioDevice(kAudioObjectUnknown) { }
#endif /* defined(__OBJC__) */
operator AudioObjectID() const { return GetObjectID(); }
/*!
@return True if this device is BGMDevice. (Specifically, the main instance of BGMDevice.)
@throws CAException If the HAL returns an error when queried.
*/
bool IsBGMDevice() const { return IsBGMDevice(false); };
/*!
@return True if this device is either the main instance of BGMDevice (the device named
"Background Music") or the instance used for UI sounds (the device named "Background
Music (UI Sounds)").
@throws CAException If the HAL returns an error when queried.
*/
bool IsBGMDeviceInstance() const { return IsBGMDevice(true); };
/*!
@return True if this device can be set as the output device in BGMApp.
@throws CAException If the HAL returns an error when queried.
*/
bool CanBeOutputDeviceInBGMApp() const;
#pragma mark Available Controls
bool HasSettableMasterVolume(AudioObjectPropertyScope inScope) const;
bool HasSettableVirtualMasterVolume(AudioObjectPropertyScope inScope) const;
bool HasSettableMasterMute(AudioObjectPropertyScope inScope) const;
#pragma mark Control Values Accessors
void CopyMuteFrom(const BGMAudioDevice inDevice,
AudioObjectPropertyScope inScope);
void CopyVolumeFrom(const BGMAudioDevice inDevice,
AudioObjectPropertyScope inScope);
bool SetMasterVolumeScalar(AudioObjectPropertyScope inScope, Float32 inVolume);
bool GetVirtualMasterVolumeScalar(AudioObjectPropertyScope inScope,
Float32& outVirtualMasterVolume) const;
bool SetVirtualMasterVolumeScalar(AudioObjectPropertyScope inScope,
Float32 inVolume);
bool GetVirtualMasterBalance(AudioObjectPropertyScope inScope,
Float32& outVirtualMasterBalance) const;
#pragma mark Implementation
private:
bool IsBGMDevice(bool inIncludingUISoundsInstance) const;
static OSStatus AHSGetPropertyData(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32* ioDataSize,
void* outData);
static OSStatus AHSSetPropertyData(AudioObjectID inObjectID,
const AudioObjectPropertyAddress* inAddress,
UInt32 inDataSize,
const void* inData);
};
#endif /* BGMApp__BGMAudioDevice */
+15 -66
View File
@@ -17,91 +17,40 @@
// BGMAudioDeviceManager.h
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Manages BGMDevice and the output device. Sets the system's current default device as the output
// device on init, then starts playthrough and mirroring the devices' controls.
// Manages the BGMDevice and the output device. Sets the system's current default device as the output device on init, then
// starts playthrough and mirroring the devices' controls. The output device can be changed but the BGMDevice is fixed.
//
#if defined(__cplusplus)
// Local Includes
#import "BGMBackgroundMusicDevice.h"
// PublicUtility Includes
#import "CAHALAudioDevice.h"
#endif /* defined(__cplusplus) */
#include "CAHALAudioDevice.h"
// System Includes
#import <Foundation/Foundation.h>
#import <CoreAudio/AudioHardwareBase.h>
// Forward Declarations
@class BGMOutputVolumeMenuItem;
#include <CoreAudio/AudioHardwareBase.h>
#pragma clang assume_nonnull begin
static const int kBGMErrorCode_BGMDeviceNotFound = 1;
static const int kBGMErrorCode_OutputDeviceNotFound = 2;
static const int kBGMErrorCode_ReturningEarly = 3;
extern int const kBGMErrorCode_BGMDeviceNotFound;
extern int const kBGMErrorCode_OutputDeviceNotFound;
@interface BGMAudioDeviceManager : NSObject
- (instancetype) initWithError:(NSError**)error;
// Set the BGMOutputVolumeMenuItem to be notified when the output device is changed.
- (void) setOutputVolumeMenuItem:(BGMOutputVolumeMenuItem*)item;
- (id) initWithError:(NSError**)error;
// Set BGMDevice as the default audio device for all processes
- (NSError* __nullable) setBGMDeviceAsOSDefault;
- (void) setBGMDeviceAsOSDefault;
// Replace BGMDevice as the default device with the output device
- (NSError* __nullable) unsetBGMDeviceAsOSDefault;
- (void) unsetBGMDeviceAsOSDefault;
#ifdef __cplusplus
// The virtual device published by BGMDriver.
- (BGMBackgroundMusicDevice) bgmDevice;
// The device BGMApp will play audio through, making it, from the user's perspective, the system's
// default output device.
- (CAHALAudioDevice) outputDevice;
#endif
- (CAHALAudioDevice) bgmDevice;
- (BOOL) isOutputDevice:(AudioObjectID)deviceID;
- (BOOL) isOutputDataSource:(UInt32)dataSourceID;
// Returns NO if the output device couldn't be changed and has been reverted
- (BOOL) setOutputDeviceWithID:(AudioObjectID)deviceID revertOnFailure:(BOOL)revertOnFailure;
// Set the audio output device that BGMApp uses.
//
// Returns an error if the output device couldn't be changed. If revertOnFailure is true in that case,
// this method will attempt to set the output device back to the original device. If it fails to
// revert, an additional error will be included in the error's userInfo with the key "revertError".
//
// Both errors' codes will be the code of the exception that caused the failure, if any, generally one
// of the error constants from AudioHardwareBase.h.
//
// Blocks while the old device stops IO (if there was one).
- (NSError* __nullable) setOutputDeviceWithID:(AudioObjectID)deviceID
revertOnFailure:(BOOL)revertOnFailure;
// As above, but also sets the new output device's data source. See kAudioDevicePropertyDataSource in
// AudioHardware.h.
- (NSError* __nullable) setOutputDeviceWithID:(AudioObjectID)deviceID
dataSourceID:(UInt32)dataSourceID
revertOnFailure:(BOOL)revertOnFailure;
// Start playthrough synchronously. Blocks until IO has started on the output device and playthrough
// is running. See BGMPlayThrough.
//
// Returns one of the error codes defined by this class or BGMPlayThrough, or an AudioHardware error
// code received from the HAL.
- (OSStatus) startPlayThroughSync:(BOOL)forUISoundsDevice;
// When the output device is changed, BGMAudioDeviceManager will send the ID of the new output
// device to BGMXPCHelper through this connection.
- (void) setBGMXPCHelperConnection:(NSXPCConnection* __nullable)connection;
// Returns when IO has started running on the output device (for playthrough).
- (OSStatus) waitForOutputDeviceToStart;
@end
#pragma clang assume_nonnull end
+134 -438
View File
@@ -17,84 +17,62 @@
// BGMAudioDeviceManager.mm
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMAudioDeviceManager.h"
// Local Includes
#import "BGM_Types.h"
#import "BGM_Utils.h"
#import "BGMDeviceControlSync.h"
#import "BGMPlayThrough.h"
#import "BGMAudioDevice.h"
#import "BGMXPCProtocols.h"
#import "BGMOutputVolumeMenuItem.h"
#include "BGM_Types.h"
#include "BGMDeviceControlSync.h"
#include "BGMPlayThrough.h"
// PublicUtility Includes
#import "CAHALAudioSystemObject.h"
#import "CAAutoDisposer.h"
#import "CAAtomic.h"
#include "CAHALAudioSystemObject.h"
#include "CAAutoDisposer.h"
#pragma clang assume_nonnull begin
int const kBGMErrorCode_BGMDeviceNotFound = 0;
int const kBGMErrorCode_OutputDeviceNotFound = 1;
// Hack/workaround that adds a default constructor to CAHALAudioDevice so we don't have to use pointers for the instance variables
class BGMAudioDevice : public CAHALAudioDevice {
using CAHALAudioDevice::CAHALAudioDevice;
public:
BGMAudioDevice() : CAHALAudioDevice(kAudioDeviceUnknown) { }
};
@implementation BGMAudioDeviceManager {
// This ivar is a pointer so that BGMBackgroundMusicDevice's constructor doesn't get called
// during [BGMAudioDeviceManager alloc] when the ivars are initialised. It queries the HAL for
// BGMDevice's AudioObject ID, which might throw a CAException, most likely because BGMDevice
// isn't installed.
//
// That would be the only way for [BGMAudioDeviceManager alloc] to throw a CAException, so we
// could wrap that call in a try/catch block instead, but it would make the code a bit
// confusing.
BGMBackgroundMusicDevice* bgmDevice;
BGMAudioDevice bgmDevice;
BGMAudioDevice outputDevice;
BGMDeviceControlSync deviceControlSync;
BGMPlayThrough playThrough;
BGMPlayThrough playThrough_UISounds;
// A connection to BGMXPCHelper so we can send it the ID of the output device.
NSXPCConnection* __nullable bgmXPCHelperConnection;
BGMOutputVolumeMenuItem* __nullable outputVolumeMenuItem;
NSRecursiveLock* stateLock;
}
#pragma mark Construction/Destruction
- (instancetype) initWithError:(NSError** __nullable)error {
- (id) initWithError:(NSError**)error {
if ((self = [super init])) {
stateLock = [NSRecursiveLock new];
bgmXPCHelperConnection = nil;
outputVolumeMenuItem = nil;
try {
bgmDevice = new BGMBackgroundMusicDevice;
} catch (const CAException& e) {
LogError("BGMAudioDeviceManager::initWithError: BGMDevice not found. (%d)", e.GetError());
bgmDevice = BGMAudioDevice(CFSTR(kBGMDeviceUID));
if (bgmDevice.GetObjectID() == kAudioObjectUnknown) {
DebugMsg("BGMAudioDeviceManager::initWithError: BGMDevice not found");
if (error) {
*error = [NSError errorWithDomain:@kBGMAppBundleID code:kBGMErrorCode_BGMDeviceNotFound userInfo:nil];
}
self = nil;
return self;
}
try {
[self initOutputDevice];
} catch (const CAException& e) {
LogError("BGMAudioDeviceManager::initWithError: failed to init output device (%d)",
e.GetError());
[self initOutputDevice];
if (outputDevice.GetObjectID() == kAudioDeviceUnknown) {
DebugMsg("BGMAudioDeviceManager::initWithError: output device not found");
if (error) {
*error = [NSError errorWithDomain:@kBGMAppBundleID code:kBGMErrorCode_OutputDeviceNotFound userInfo:nil];
}
self = nil;
return self;
}
@@ -103,433 +81,151 @@
return self;
}
- (void) dealloc {
@try {
[stateLock lock];
if (bgmDevice) {
delete bgmDevice;
bgmDevice = nullptr;
}
} @finally {
[stateLock unlock];
}
}
// Throws a CAException if it fails to set the output device.
- (void) initOutputDevice {
CAHALAudioSystemObject audioSystem;
// outputDevice = BGMAudioDevice(CFSTR("AppleHDAEngineOutput:1B,0,1,1:0"));
BGMAudioDevice defaultDevice = audioSystem.GetDefaultAudioDevice(false, false);
if (defaultDevice.IsBGMDeviceInstance()) {
// BGMDevice is already the default (it could have been set manually or BGMApp could have
// failed to change it back the last time it closed), so just pick the device with the
// lowest latency.
//
// TODO: Temporarily disable BGMDevice so we can find out what the previous default was and
// use that instead.
[self setOutputDeviceByLatency];
} else {
// TODO: Return the error from setOutputDeviceWithID so it can be returned by initWithError.
[self setOutputDeviceWithID:defaultDevice revertOnFailure:NO];
}
if (outputDevice == kAudioObjectUnknown) {
LogError("BGMAudioDeviceManager::initOutputDevice: Failed to set output device");
Throw(CAException(kAudioHardwareUnspecifiedError));
}
if (outputDevice.IsBGMDeviceInstance()) {
LogError("BGMAudioDeviceManager::initOutputDevice: Failed to change output device from "
"BGMDevice");
Throw(CAException(kAudioHardwareUnspecifiedError));
}
// Log message
CFStringRef outputDeviceUID = outputDevice.CopyDeviceUID();
DebugMsg("BGMAudioDeviceManager::initOutputDevice: Set output device to %s",
CFStringGetCStringPtr(outputDeviceUID, kCFStringEncodingUTF8));
CFRelease(outputDeviceUID);
}
- (void) setOutputDeviceByLatency {
CAHALAudioSystemObject audioSystem;
UInt32 numDevices = audioSystem.GetNumberAudioDevices();
if (numDevices > 0) {
BGMAudioDevice minLatencyDevice = kAudioObjectUnknown;
UInt32 minLatency = UINT32_MAX;
CAAutoArrayDelete<AudioObjectID> devices(numDevices);
audioSystem.GetAudioDevices(numDevices, devices);
for (UInt32 i = 0; i < numDevices; i++) {
BGMAudioDevice device(devices[i]);
if (!device.IsBGMDeviceInstance()) {
BOOL hasOutputChannels = NO;
BGMLogAndSwallowExceptionsMsg("BGMAudioDeviceManager::setOutputDeviceByLatency",
"GetTotalNumberChannels", ([&] {
hasOutputChannels = device.GetTotalNumberChannels(/* inIsInput = */ false) > 0;
}));
if (hasOutputChannels) {
BGMLogAndSwallowExceptionsMsg("BGMAudioDeviceManager::setOutputDeviceByLatency",
"GetLatency", ([&] {
UInt32 latency = device.GetLatency(false);
if (latency < minLatency) {
minLatencyDevice = devices[i];
minLatency = latency;
}
}));
AudioObjectID defaultDeviceID = audioSystem.GetDefaultAudioDevice(false, false);
if (defaultDeviceID == bgmDevice.GetObjectID()) {
// TODO: If BGMDevice is already the default (because BGMApp didn't shutdown properly or it was set manually)
// we should temporarily disable BGMDevice so we can find out what the previous default was.
// For now, just pick the device with the lowest latency
UInt32 numDevices = audioSystem.GetNumberAudioDevices();
if (numDevices > 0) {
SInt32 minLatencyDeviceIdx = -1;
UInt32 minLatency = UINT32_MAX;
CAAutoArrayDelete<AudioObjectID> devices(numDevices);
audioSystem.GetAudioDevices(numDevices, devices);
for (UInt32 i = 0; i < numDevices; i++) {
BGMAudioDevice device(devices[i]);
BOOL isBGMDevice = device.GetObjectID() == bgmDevice.GetObjectID();
BOOL hasOutputChannels = device.GetTotalNumberChannels(/* inIsInput = */ false) > 0;
if (!isBGMDevice && hasOutputChannels) {
if (minLatencyDeviceIdx == -1) {
// First, look for any device other than BGMDevice
minLatencyDeviceIdx = i;
} else if (device.GetLatency(false) < minLatency) {
// Then compare the devices by their latencies
minLatencyDeviceIdx = i;
minLatency = device.GetLatency(false);
}
}
}
[self setOutputDeviceWithID:devices[minLatencyDeviceIdx] revertOnFailure:NO];
}
if (minLatencyDevice != kAudioObjectUnknown) {
// TODO: On error, try a different output device.
[self setOutputDeviceWithID:minLatencyDevice revertOnFailure:NO];
}
} else {
[self setOutputDeviceWithID:defaultDeviceID revertOnFailure:NO];
}
assert(outputDevice.GetObjectID() != bgmDevice.GetObjectID());
// Log message
if (outputDevice.GetObjectID() == kAudioDeviceUnknown) {
CFStringRef outputDeviceUID = outputDevice.CopyDeviceUID();
DebugMsg("BGMAudioDeviceManager::initDevices: Set output device to %s",
CFStringGetCStringPtr(outputDeviceUID, kCFStringEncodingUTF8));
CFRelease(outputDeviceUID);
}
}
- (void) setOutputVolumeMenuItem:(BGMOutputVolumeMenuItem*)item {
outputVolumeMenuItem = item;
}
#pragma mark Systemwide Default Device
// Note that there are two different "default" output devices on OS X: "output" and "system output". See
// kAudioHardwarePropertyDefaultSystemOutputDevice in AudioHardware.h.
- (NSError* __nullable) setBGMDeviceAsOSDefault {
try {
// Intentionally avoid taking stateLock before making calls to the HAL. See
// startPlayThroughSync.
CAMemoryBarrier();
bgmDevice->SetAsOSDefault();
} catch (const CAException& e) {
BGMLogExceptionIn("BGMAudioDeviceManager::setBGMDeviceAsOSDefault", e);
return [NSError errorWithDomain:@kBGMAppBundleID code:e.GetError() userInfo:nil];
- (void) setBGMDeviceAsOSDefault {
CAHALAudioSystemObject audioSystem;
@synchronized (self) {
if (audioSystem.GetDefaultAudioDevice(false, true) == outputDevice.GetObjectID()) {
// The default system device was the same as the default device, so change that as well
audioSystem.SetDefaultAudioDevice(false, true, bgmDevice.GetObjectID());
}
audioSystem.SetDefaultAudioDevice(false, false, bgmDevice.GetObjectID());
}
return nil;
}
- (NSError* __nullable) unsetBGMDeviceAsOSDefault {
// Copy the devices so we can call the HAL without holding stateLock. See startPlayThroughSync.
BGMBackgroundMusicDevice* bgmDeviceCopy;
AudioDeviceID outputDeviceID;
@try {
[stateLock lock];
bgmDeviceCopy = bgmDevice;
outputDeviceID = outputDevice.GetObjectID();
} @finally {
[stateLock unlock];
}
if (outputDeviceID == kAudioObjectUnknown) {
return [NSError errorWithDomain:@kBGMAppBundleID
code:kBGMErrorCode_OutputDeviceNotFound
userInfo:nil];
}
try {
bgmDeviceCopy->UnsetAsOSDefault(outputDeviceID);
} catch (const CAException& e) {
BGMLogExceptionIn("BGMAudioDeviceManager::unsetBGMDeviceAsOSDefault", e);
return [NSError errorWithDomain:@kBGMAppBundleID code:e.GetError() userInfo:nil];
}
- (void) unsetBGMDeviceAsOSDefault {
CAHALAudioSystemObject audioSystem;
return nil;
@synchronized (self) {
if (audioSystem.GetDefaultAudioDevice(false, true) == bgmDevice.GetObjectID()) {
// We changed the system output device to BGMDevice, which we only do if it initially matches the
// default output device, so change it back
audioSystem.SetDefaultAudioDevice(false, true, outputDevice.GetObjectID());
}
if (audioSystem.GetDefaultAudioDevice(false, false) == bgmDevice.GetObjectID()) {
audioSystem.SetDefaultAudioDevice(false, false, outputDevice.GetObjectID());
}
}
}
#pragma mark Accessors
- (BGMBackgroundMusicDevice) bgmDevice {
return *bgmDevice;
}
- (CAHALAudioDevice) outputDevice {
return outputDevice;
- (CAHALAudioDevice) bgmDevice {
return bgmDevice;
}
- (BOOL) isOutputDevice:(AudioObjectID)deviceID {
@try {
[stateLock lock];
@synchronized (self) {
return deviceID == outputDevice.GetObjectID();
} @finally {
[stateLock unlock];
}
}
- (BOOL) isOutputDataSource:(UInt32)dataSourceID {
BOOL isOutputDataSource = NO;
@try {
[stateLock lock];
try {
AudioObjectPropertyScope scope = kAudioDevicePropertyScopeOutput;
UInt32 channel = 0;
isOutputDataSource =
outputDevice.HasDataSourceControl(scope, channel) &&
(dataSourceID == outputDevice.GetCurrentDataSourceID(scope, channel));
} catch (const CAException& e) {
BGMLogException(e);
}
} @finally {
[stateLock unlock];
}
return isOutputDataSource;
}
#pragma mark Output Device
- (NSError* __nullable) setOutputDeviceWithID:(AudioObjectID)deviceID
revertOnFailure:(BOOL)revertOnFailure {
return [self setOutputDeviceWithIDImpl:deviceID
dataSourceID:nil
revertOnFailure:revertOnFailure];
}
- (NSError* __nullable) setOutputDeviceWithID:(AudioObjectID)deviceID
dataSourceID:(UInt32)dataSourceID
revertOnFailure:(BOOL)revertOnFailure {
return [self setOutputDeviceWithIDImpl:deviceID
dataSourceID:&dataSourceID
revertOnFailure:revertOnFailure];
}
- (NSError* __nullable) setOutputDeviceWithIDImpl:(AudioObjectID)newDeviceID
dataSourceID:(UInt32* __nullable)dataSourceID
revertOnFailure:(BOOL)revertOnFailure {
DebugMsg("BGMAudioDeviceManager::setOutputDeviceWithIDImpl: Setting output device. newDeviceID=%u",
newDeviceID);
- (BOOL) setOutputDeviceWithID:(AudioObjectID)deviceID revertOnFailure:(BOOL)revertOnFailure {
DebugMsg("BGMAudioDeviceManager::setOutputDeviceWithID: Setting output device. deviceID=%u", deviceID);
@try {
[stateLock lock];
AudioDeviceID currentDeviceID = outputDevice.GetObjectID(); // (Doesn't throw.)
try {
if (newDeviceID != currentDeviceID) {
BGMAudioDevice newOutputDevice(newDeviceID);
[self setOutputDeviceForPlaythroughAndControlSync:newOutputDevice];
outputDevice = newOutputDevice;
}
// Set the output device to use the new data source.
if (dataSourceID) {
// TODO: If this fails, ideally we'd still start playthrough and return an error, but not
// revert the device. It would probably be a bit awkward, though.
[self setDataSource:*dataSourceID device:outputDevice];
}
if (newDeviceID != currentDeviceID) {
// We successfully changed to the new device. Start playthrough on it, since audio might be
// playing. (If we only changed the data source, playthrough will already be running if it
// needs to be.)
playThrough.Start();
playThrough_UISounds.Start();
// But stop playthrough if audio isn't playing, since it uses CPU.
playThrough.StopIfIdle();
playThrough_UISounds.StopIfIdle();
}
} catch (const CAException& e) {
BGMAssert(e.GetError() != kAudioHardwareNoError,
"CAException with kAudioHardwareNoError");
return [self failedToSetOutputDevice:newDeviceID
errorCode:e.GetError()
revertTo:(revertOnFailure ? &currentDeviceID : nullptr)];
} catch (...) {
return [self failedToSetOutputDevice:newDeviceID
errorCode:kAudioHardwareUnspecifiedError
revertTo:(revertOnFailure ? &currentDeviceID : nullptr)];
}
[self propagateOutputDeviceChange];
} @finally {
[stateLock unlock];
}
return nil;
}
// Changes the output device that playthrough plays audio to and that BGMDevice's controls are
// kept in sync with. Throws CAException.
- (void) setOutputDeviceForPlaythroughAndControlSync:(const BGMAudioDevice&)newOutputDevice {
// Deactivate playthrough rather than stopping it so it can't be started by HAL notifications
// while we're updating deviceControlSync.
playThrough.Deactivate();
playThrough_UISounds.Deactivate();
deviceControlSync.SetDevices(*bgmDevice, newOutputDevice);
deviceControlSync.Activate();
// Stream audio from BGMDevice to the new output device. This blocks while the old device stops
// IO.
playThrough.SetDevices(bgmDevice, &newOutputDevice);
playThrough.Activate();
// TODO: Support setting different devices as the default output device and the default system
// output device the way OS X does?
BGMAudioDevice uiSoundsDevice = bgmDevice->GetUISoundsBGMDeviceInstance();
playThrough_UISounds.SetDevices(&uiSoundsDevice, &newOutputDevice);
playThrough_UISounds.Activate();
}
- (void) setDataSource:(UInt32)dataSourceID device:(BGMAudioDevice&)device {
BGMLogAndSwallowExceptions("BGMAudioDeviceManager::setDataSource", ([&] {
AudioObjectPropertyScope scope = kAudioObjectPropertyScopeOutput;
UInt32 channel = 0;
if (device.DataSourceControlIsSettable(scope, channel)) {
DebugMsg("BGMAudioDeviceManager::setOutputDeviceWithID: Setting dataSourceID=%u",
dataSourceID);
device.SetCurrentDataSourceByID(scope, channel, dataSourceID);
}
}));
}
- (void) propagateOutputDeviceChange {
// Tell BGMXPCHelper that the output device has changed.
[self sendOutputDeviceToBGMXPCHelper];
// Update the menu item for the volume of the output device.
[outputVolumeMenuItem outputDeviceDidChange];
}
- (NSError*) failedToSetOutputDevice:(AudioDeviceID)deviceID
errorCode:(OSStatus)errorCode
revertTo:(AudioDeviceID*)revertTo {
// Using LogWarning from PublicUtility instead of NSLog here crashes from a bad access. Not sure why.
// TODO: Possibly caused by a bug in CADebugMacros.cpp. See commit ab9d4cd.
NSLog(@"BGMAudioDeviceManager::failedToSetOutputDevice: Couldn't set device with ID %u as output device. "
"%s%d. %@",
deviceID,
"Error: ", errorCode,
(revertTo ? [NSString stringWithFormat:@"Will attempt to revert to the previous device. "
"Previous device ID: %u.", *revertTo] : @""));
// Set up playthrough and control sync
BGMAudioDevice newOutputDevice(deviceID);
NSDictionary* __nullable info = nil;
if (revertTo) {
// Try to reactivate the original device listener and playthrough. (Sorry about the mutual recursion.)
NSError* __nullable revertError = [self setOutputDeviceWithID:*revertTo revertOnFailure:NO];
if (revertError) {
info = @{ @"revertError": (NSError*)revertError };
}
} else {
// TODO: Handle this error better in callers. Maybe show an error dialog and try to set the original
// default device as the output device.
NSLog(@"BGMAudioDeviceManager::failedToSetOutputDevice: Failed to revert to the previous device.");
}
return [NSError errorWithDomain:@kBGMAppBundleID code:errorCode userInfo:info];
}
- (OSStatus) startPlayThroughSync:(BOOL)forUISoundsDevice {
// We can only try for stateLock because setOutputDeviceWithID might have already taken it, then made a
// HAL request to BGMDevice and be waiting for the response. Some of the requests setOutputDeviceWithID
// makes to BGMDevice block in the HAL if another thread is in BGM_Device::StartIO.
//
// Since BGM_Device::StartIO calls this method (via XPC), waiting for setOutputDeviceWithID to release
// stateLock could cause deadlocks. Instead we return early with an error code that BGMDriver knows to
// ignore, since the output device is (almost certainly) being changed and we can't avoid dropping frames
// while the output device starts up.
OSStatus err;
BOOL gotLock;
@try {
gotLock = [stateLock tryLock];
if (gotLock) {
BGMPlayThrough& pt = (forUISoundsDevice ? playThrough_UISounds : playThrough);
// Playthrough might not have been notified that BGMDevice is starting yet, so make sure
// playthrough is starting. This way we won't drop any frames while waiting for the HAL to send
// that notification. We can't be completely sure this is safe from deadlocking, though, since
// CoreAudio is closed-source.
try {
@synchronized (self) {
// Mirror changes in BGMDevice's controls to the new output device's.
deviceControlSync = BGMDeviceControlSync(bgmDevice, newOutputDevice);
// Stream audio from BGMDevice to the output device.
//
// TODO: Test this on older OS X versions. Differences in the CoreAudio implementations could
// cause deadlocks.
BGMLogAndSwallowExceptionsMsg("BGMAudioDeviceManager::startPlayThroughSync",
"Starting playthrough", [&] {
pt.Start();
});
// TODO: Should this be done async? Some output devices take a long time to start IO (e.g. AirPlay) and I
// assume this blocks the main thread. Haven't tried it to check, though.
playThrough = BGMPlayThrough(bgmDevice, newOutputDevice);
err = pt.WaitForOutputDeviceToStart();
BGMAssert(err != BGMPlayThrough::kDeviceNotStarting, "Playthrough didn't start");
} else {
LogWarning("BGMAudioDeviceManager::startPlayThroughSync: Didn't get state lock. Returning "
"early with kBGMErrorCode_ReturningEarly.");
err = kBGMErrorCode_ReturningEarly;
dispatch_async(BGMGetDispatchQueue_PriorityUserInteractive(), ^{
@try {
[stateLock lock];
BGMPlayThrough& pt = (forUISoundsDevice ? playThrough_UISounds : playThrough);
BGMLogAndSwallowExceptionsMsg("BGMAudioDeviceManager::startPlayThroughSync",
"Starting playthrough (dispatched)", [&] {
pt.Start();
});
BGMLogAndSwallowExceptions("BGMAudioDeviceManager::startPlayThroughSync", [&] {
pt.StopIfIdle();
});
} @finally {
[stateLock unlock];
}
});
outputDevice = BGMAudioDevice(deviceID);
}
} @finally {
if (gotLock) {
[stateLock unlock];
// Start playthrough because audio might be playing.
//
// TODO: If audio isn't playing, this makes playthrough run until the user plays audio and then stops it again,
// which wastes CPU. I think we could just have Start() call StopIfIdle(), but I haven't tried it yet.
playThrough.Start();
} catch (CAException e) {
// Using LogWarning from PublicUtility instead of NSLog here crashes from a bad access. Not sure why.
NSLog(@"BGMAudioDeviceManager::setOutputDeviceWithID: Couldn't set device with ID %u as output device. %s %s%d.",
newOutputDevice.GetObjectID(),
(revertOnFailure ? "Will attempt to revert to the previous device." : ""),
"Error: ", e.GetError());
if (revertOnFailure) {
// Try to reactivate the original device listener and playthrough
[self setOutputDeviceWithID:outputDevice.GetObjectID() revertOnFailure:NO];
return NO;
} else {
// TODO: Handle in callers. (Maybe show an error dialog and try to set the original default device as the
// output device.)
Throw(e);
}
}
return err;
return YES;
}
#pragma mark BGMXPCHelper Communication
- (void) setBGMXPCHelperConnection:(NSXPCConnection* __nullable)connection {
bgmXPCHelperConnection = connection;
// Tell BGMXPCHelper which device is the output device, since it might not be up-to-date.
[self sendOutputDeviceToBGMXPCHelper];
}
- (void) sendOutputDeviceToBGMXPCHelper {
NSXPCConnection* __nullable connection = bgmXPCHelperConnection;
if (connection)
{
id<BGMXPCHelperXPCProtocol> helperProxy =
[connection remoteObjectProxyWithErrorHandler:^(NSError* error) {
// We could wait a bit and try again, but it isn't that important.
NSLog(@"BGMAudioDeviceManager::sendOutputDeviceToBGMXPCHelper: Connection"
"error: %@", error);
}];
[helperProxy setOutputDeviceToMakeDefaultOnAbnormalTermination:outputDevice.GetObjectID()];
- (OSStatus) waitForOutputDeviceToStart {
@synchronized (self) {
return playThrough.WaitForOutputDeviceToStart();
}
}
@end
#pragma clang assume_nonnull end
-201
View File
@@ -1,201 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAutoPauseMenuItem.m
// BGMApp
//
// Copyright © 2016 Kyle Neideck
// Copyright © 2016 Tanner Hoke
//
// Self Include
#import "BGMAutoPauseMenuItem.h"
// Local Includes
#import "BGMMusicPlayer.h"
#pragma clang assume_nonnull begin
static NSString* const kMenuItemTitleFormat = @"Auto-pause %@";
static NSString* const kMenuItemDisabledToolTipFormat = @"%@ doesn't appear to be running.";
// Wait time to disable/enable the auto-pause menu item, in seconds.
static SInt64 const kMenuItemUpdateWaitTime = 1;
@implementation BGMAutoPauseMenuItem {
BGMUserDefaults* userDefaults;
NSMenuItem* menuItem;
BGMAutoPauseMusic* autoPauseMusic;
BGMMusicPlayers* musicPlayers;
id<NSObject> didLaunchToken, didTerminateToken;
}
- (instancetype) initWithMenuItem:(NSMenuItem*)item
autoPauseMusic:(BGMAutoPauseMusic*)autoPause
musicPlayers:(BGMMusicPlayers*)players
userDefaults:(BGMUserDefaults*)defaults {
if ((self = [super init])) {
menuItem = item;
autoPauseMusic = autoPause;
musicPlayers = players;
userDefaults = defaults;
// Enable/disable auto-pause to match the user's preferences setting.
if (userDefaults.autoPauseMusicEnabled) {
menuItem.state = NSOnState;
[autoPauseMusic enable];
} else {
menuItem.state = NSOffState;
[autoPauseMusic disable];
}
// Toggle auto-pause when the menu item is clicked.
menuItem.target = self;
menuItem.action = @selector(toggleAutoPauseMusic);
[self updateMenuItemTitle];
[self initMusicPlayerObservers];
}
return self;
}
- (void) initMusicPlayerObservers {
// Add observers that enable/disable the Auto-pause Music menu item when the music player is launched/terminated.
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
id<NSObject> (^addObserver)(NSString*) = ^(NSString* name) {
return [center addObserverForName:name
object:nil
queue:nil
usingBlock:^(NSNotification* note) {
NSString* appBundleID = [note.userInfo[NSWorkspaceApplicationKey] bundleIdentifier];
BOOL isAboutThisMusicPlayer = musicPlayers.selectedMusicPlayer.bundleID &&
[appBundleID isEqualToString:(NSString*)musicPlayers.selectedMusicPlayer.bundleID];
if (isAboutThisMusicPlayer) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
kMenuItemUpdateWaitTime * NSEC_PER_SEC),
dispatch_get_main_queue(),
^{
[self updateMenuItemTitle];
});
}
}];
};
didLaunchToken = addObserver(NSWorkspaceDidLaunchApplicationNotification);
didTerminateToken = addObserver(NSWorkspaceDidTerminateApplicationNotification);
}
- (void) dealloc {
// Remove the application launch/termination observers.
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
if (didLaunchToken) {
[center removeObserver:didLaunchToken];
}
if (didTerminateToken) {
[center removeObserver:didTerminateToken];
}
}
- (void) toggleAutoPauseMusic {
// The menu item was clicked.
if (menuItem.state == NSOnState) {
menuItem.state = NSOffState;
[autoPauseMusic disable];
} else {
menuItem.state = NSOnState;
[autoPauseMusic enable];
}
// Persist the change in the user's preferences.
userDefaults.autoPauseMusicEnabled = (menuItem.state == NSOnState);
}
- (void) updateMenuItemTitle {
[self updateMenuItemTitleWithHighlight:menuItem.isHighlighted];
}
- (void) updateMenuItemTitleWithHighlight:(BOOL)highlight {
// Set the title of the Auto-pause Music menu item, including the name of the selected music player.
NSString* musicPlayerName = musicPlayers.selectedMusicPlayer.name;
menuItem.title = [NSString stringWithFormat:kMenuItemTitleFormat, musicPlayerName];
// Make the Auto-pause Music menu item appear disabled if the application is not running.
//
// We don't actually disable it just in case the user decides to disable auto-pause and their music player isn't
// running. E.g. someone who only recently installed Background Music and doesn't want to use auto-pause at all.
if (musicPlayers.selectedMusicPlayer.isRunning) {
menuItem.attributedTitle = nil;
menuItem.toolTip = nil;
} else {
// Hardcode the text colour grey to match disabled menu items (unless the menu item is highlighted, in which
// case use white).
//
// I couldn't figure out a way to do this without hardcoding the colours. There's no colour constant for this,
// except possibly disabledControlTextColor, which just leaves the text black for me. I also couldn't get the
// colours from the built-in NSColorLists.
//
// TODO: Can we make the tick mark grey as well?
NSString* __nullable appleInterfaceStyle =
[[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
BOOL darkMode = [appleInterfaceStyle isEqualToString:@"Dark"];
NSColor* textColor = [NSColor colorWithHue:0
saturation:0
brightness:(highlight ? 1 : (darkMode ? 0.25 : 0.75))
alpha:1];
NSDictionary* attributes = @{ NSFontAttributeName: [NSFont menuBarFontOfSize:0], // Default font size
NSForegroundColorAttributeName: textColor };
NSAttributedString* pseudoDisabledTitle = [[NSAttributedString alloc] initWithString:menuItem.title
attributes:attributes];
menuItem.attributedTitle = pseudoDisabledTitle;
menuItem.toolTip = [NSString stringWithFormat:kMenuItemDisabledToolTipFormat, musicPlayerName];
}
}
#pragma mark Parent menu events
- (void) parentMenuNeedsUpdate {
[self updateMenuItemTitle];
}
- (void) parentMenuItemWillHighlight:(NSMenuItem* __nullable)item {
// Used to make the auto-pause menu item's text white when it's highlighted and change it back after.
//
// TODO: If you click the auto-pause menu item while it's disabled, it will initially appear highlighted next time
// you open the main menu.
// If item is nil or any other menu item, the auto-pause menu item will be unhighlighted.
BOOL willHighlightMenuItem = [item isEqual:menuItem];
// Only update the menu item if it's changing (from highlighted to unhighlighted or vice versa) to save a little
// CPU.
if (willHighlightMenuItem != menuItem.highlighted) {
[self updateMenuItemTitleWithHighlight:willHighlightMenuItem];
}
}
@end
#pragma clang assume_nonnull end
+1 -7
View File
@@ -25,22 +25,16 @@
// Local Includes
#import "BGMAudioDeviceManager.h"
#import "BGMMusicPlayers.h"
// System Includes
#import <Foundation/Foundation.h>
#pragma clang assume_nonnull begin
@interface BGMAutoPauseMusic : NSObject
- (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices musicPlayers:(BGMMusicPlayers*)inMusicPlayers;
- (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices;
- (void) enable;
- (void) disable;
@end
#pragma clang assume_nonnull end
+38 -79
View File
@@ -17,7 +17,7 @@
// BGMAutoPauseMusic.m
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
@@ -27,9 +27,6 @@
#include "BGM_Types.h"
#import "BGMMusicPlayer.h"
// STL Includes
#import <algorithm> // std::max, std::min
// System Includes
#include <CoreAudio/AudioHardware.h>
#include <mach/mach_time.h>
@@ -39,63 +36,43 @@
// and other audio can have short periods of silence without causing music to play and quickly pause again. Of course, it's a
// trade-off against how long the music will overlap the other audio before it gets paused and how long the music will stay paused
// after a sound that was only slightly longer than the pause delay.
static UInt64 const kPauseDelayNSec = 1500 * NSEC_PER_MSEC;
// The delay before unpausing the music player is proportional to how long we paused it for, bounded by these limits. This makes it
// a bit less annoying when a sound is just long enough to cause an auto-pause.
//
// I haven't spent much time experimenting with different values for these constants, so they could probably be improved a fair
// bit.
//
// TODO: Would it be worth listening for kAudioDeviceCustomPropertyDeviceIsRunningSomewhereOtherThanBGMApp so we can unpause
// immediately if we haven't been paused for long and the non-music-player client stops IO? That would usually indicate that
// it doesn't intend to start playing audio again soon. We'd also have to deal with music players that don't stop IO when
// they're paused.
static UInt64 const kMaxUnpauseDelayNSec = 3500 * NSEC_PER_MSEC;
static UInt64 const kMinUnpauseDelayNSec = kMaxUnpauseDelayNSec / 10;
// We multiply the time spent paused by this factor to calculate the delay before we consider unpausing.
static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
// TODO: Make these settable in advanced settings?
static int const kPauseDelayMSecs = 1500;
static int const kUnpauseDelayMSecs = 3000;
@implementation BGMAutoPauseMusic {
BOOL enabled;
BGMAudioDeviceManager* audioDevices;
BGMMusicPlayers* musicPlayers;
dispatch_queue_t listenerQueue;
// Have to keep track of the listener block we add so we can remove it later.
// Have to keep track of the listener block we add so we can remove it later
AudioObjectPropertyListenerBlock listenerBlock;
dispatch_queue_t pauseUnpauseMusicQueue;
// True if BGMApp has paused musicPlayer and hasn't unpaused it yet. (Will be out of sync with the music player app if the
// user has unpaused it themselves.)
// True if BGMApp has paused musicPlayer and hasn't unpaused it yet. (Will be out of sync with the music player app if the user
// has unpaused it themselves.)
BOOL wePaused;
// The times, in absolute time, that the BGMDevice last changed its audible state to silent...
UInt64 wentSilent;
// ...and to audible.
// ...and to audible
UInt64 wentAudible;
dispatch_queue_t pauseUnpauseMusicQueue;
}
- (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices musicPlayers:(BGMMusicPlayers*)inMusicPlayers {
- (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices {
if ((self = [super init])) {
audioDevices = inAudioDevices;
musicPlayers = inMusicPlayers;
enabled = NO;
audioDevices = inAudioDevices;
wePaused = NO;
dispatch_queue_attr_t attr;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
if (&dispatch_queue_attr_make_with_qos_class) {
attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0);
} else {
// OS X 10.9 fallback
attr = DISPATCH_QUEUE_SERIAL;
}
#pragma clang diagnostic pop
dispatch_queue_attr_t attr =
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_9
// Runtime fallback for older versions of OS X.
(dispatch_queue_attr_make_with_qos_class != NULL ?
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0) :
DISPATCH_QUEUE_SERIAL);
#else
DISPATCH_QUEUE_SERIAL;
#endif
listenerQueue = dispatch_queue_create("com.bearisdriving.BGM.AutoPauseMusic.Listener", attr);
pauseUnpauseMusicQueue = dispatch_queue_create("com.bearisdriving.BGM.AutoPauseMusic.PauseUnpauseMusic", attr);
@@ -113,12 +90,12 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
// To avoid retain cycle
__unsafe_unretained BGMAutoPauseMusic* weakSelf = self;
listenerBlock = ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress * _Nonnull inAddresses) {
listenerBlock = ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress * __nonnull inAddresses) {
// inAddresses "may contain addresses for properties for which the listener is not signed up to receive notifications",
// so we have to check them all
for (int i = 0; i < inNumberAddresses; i++) {
if (inAddresses[i].mSelector == kAudioDeviceCustomPropertyDeviceAudibleState) {
BGMDeviceAudibleState audibleState = [weakSelf deviceAudibleState];
SInt32 audibleState = [weakSelf deviceAudibleState];
#if DEBUG
const char audibleStateStr[5] = CA4CCToCString(audibleState);
@@ -126,8 +103,6 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
audibleStateStr);
#endif
// TODO: We shouldn't assume this block will only get called when BGMDevice's audible state changes. (Even if
// the Core Audio docs did specify that, there's no reason not to be fault tolerant.)
if (audibleState == kBGMDeviceIsAudible) {
[weakSelf queuePauseBlock];
} else if (audibleState == kBGMDeviceIsSilent) {
@@ -144,8 +119,12 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
};
}
- (BGMDeviceAudibleState) deviceAudibleState {
return [audioDevices bgmDevice].GetAudibleState();
- (SInt32) deviceAudibleState {
SInt32 audibleState;
CFNumberRef audibleStateRef = static_cast<CFNumberRef>([audioDevices bgmDevice].GetPropertyData_CFType(kBGMAudibleStateAddress));
CFNumberGetValue(audibleStateRef, kCFNumberSInt32Type, &audibleState);
CFRelease(audibleStateRef);
return audibleState;
}
- (void) queuePauseBlock {
@@ -154,10 +133,10 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
UInt64 startedPauseDelay = now;
DebugMsg("BGMAutoPauseMusic::queuePauseBlock: Dispatching pause block at %llu", now);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPauseDelayNSec),
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kPauseDelayMSecs * NSEC_PER_MSEC),
pauseUnpauseMusicQueue,
^{
BOOL stillAudible = ([self deviceAudibleState] == kBGMDeviceIsAudible);
BOOL stillAudible = [self deviceAudibleState] == kBGMDeviceIsAudible;
DebugMsg("BGMAutoPauseMusic::queuePauseBlock: Running pause block dispatched at %llu.%s wentAudible=%llu",
startedPauseDelay,
@@ -167,8 +146,8 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
// Pause if this is the most recent pause block and the device is still audible, which means the audible
// state hasn't changed since this block was queued. Also set wePaused to true if the player wasn't
// already paused.
if (!wePaused && (startedPauseDelay == wentAudible) && stillAudible) {
wePaused = ([musicPlayers.selectedMusicPlayer pause] || wePaused);
if (!wePaused && startedPauseDelay == wentAudible && stillAudible) {
wePaused = [[BGMMusicPlayer selectedMusicPlayer] pause] || wePaused;
}
});
}
@@ -178,31 +157,11 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
wentSilent = now;
UInt64 startedUnpauseDelay = now;
// Unpause sooner if we've only been paused for a short time. This is so a notification sound causing an auto-pause is
// less of an interruption.
//
// TODO: Fading in and out would make short pauses a lot less jarring because, if they were short enough, we wouldn't
// actually pause the music player. So you'd hear a dip in the music's volume rather than a gap.
UInt64 unpauseDelayNsec =
static_cast<UInt64>((wentSilent - wentAudible) * kUnpauseDelayWeightingFactor);
// Convert from absolute time to nanos.
mach_timebase_info_data_t info;
mach_timebase_info(&info);
unpauseDelayNsec = unpauseDelayNsec * info.numer / info.denom;
// Clamp.
unpauseDelayNsec = std::min(kMaxUnpauseDelayNSec, unpauseDelayNsec);
unpauseDelayNsec = std::max(kMinUnpauseDelayNSec, unpauseDelayNsec);
DebugMsg("BGMAutoPauseMusic::queueUnpauseBlock: Dispatched unpause block at %llu. unpauseDelayNsec=%llu",
now,
unpauseDelayNsec);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, unpauseDelayNsec),
DebugMsg("BGMAutoPauseMusic::queueUnpauseBlock: Dispatched unpause block at %llu", now);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kUnpauseDelayMSecs * NSEC_PER_MSEC),
pauseUnpauseMusicQueue,
^{
BOOL stillSilent = ([self deviceAudibleState] == kBGMDeviceIsSilent);
BOOL stillSilent = [self deviceAudibleState] == kBGMDeviceIsSilent;
DebugMsg("BGMAutoPauseMusic::queueUnpauseBlock: Running unpause block dispatched at %llu.%s%s wentSilent=%llu",
startedUnpauseDelay,
@@ -212,9 +171,9 @@ static Float32 const kUnpauseDelayWeightingFactor = 0.1f;
// Unpause if we were the one who paused. Also check that this is the most recent unpause block and the
// device is still silent, which means the audible state hasn't changed since this block was queued.
if (wePaused && (startedUnpauseDelay == wentSilent) && stillSilent) {
if (wePaused && startedUnpauseDelay == wentSilent && stillSilent) {
wePaused = NO;
[musicPlayers.selectedMusicPlayer unpause];
[[BGMMusicPlayer selectedMusicPlayer] unpause];
}
});
}
-321
View File
@@ -1,321 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMBackgroundMusicDevice.cpp
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2017 Andrew Tonner
//
// Self Include
#include "BGMBackgroundMusicDevice.h"
// Local Includes
#include "BGM_Types.h"
#include "BGM_Utils.h"
// PublicUtility Includes
#include "CADebugMacros.h"
#include "CAHALAudioSystemObject.h"
#include "CACFArray.h"
#include "CACFDictionary.h"
// STL Includes
#include <map>
#pragma clang assume_nonnull begin
#pragma mark Construction/Destruction
BGMBackgroundMusicDevice::BGMBackgroundMusicDevice()
:
BGMAudioDevice(CFSTR(kBGMDeviceUID)),
mUISoundsBGMDevice(CFSTR(kBGMDeviceUID_UISounds))
{
if((GetObjectID() == kAudioObjectUnknown) || (mUISoundsBGMDevice == kAudioObjectUnknown))
{
LogError("BGMBackgroundMusicDevice::BGMBackgroundMusicDevice: Error getting BGMDevice ID");
Throw(CAException(kAudioHardwareIllegalOperationError));
}
};
BGMBackgroundMusicDevice::~BGMBackgroundMusicDevice()
{
}
#pragma mark Systemwide Default Device
void BGMBackgroundMusicDevice::SetAsOSDefault()
{
DebugMsg("BGMBackgroundMusicDevice::SetAsOSDefault: Setting the system's default audio device "
"to BGMDevice");
CAHALAudioSystemObject audioSystem;
AudioDeviceID defaultDevice = audioSystem.GetDefaultAudioDevice(false, false);
AudioDeviceID systemDefaultDevice = audioSystem.GetDefaultAudioDevice(false, true);
if(systemDefaultDevice == defaultDevice)
{
// The default system device is the same as the default device, so change both of them.
//
// Use the UI sounds instance of BGMDevice because the default system output device is the
// device "to use for system related sound". The allows BGMDriver to tell when the audio it
// receives is UI-related.
audioSystem.SetDefaultAudioDevice(false, true, mUISoundsBGMDevice);
}
audioSystem.SetDefaultAudioDevice(false, false, GetObjectID());
}
void BGMBackgroundMusicDevice::UnsetAsOSDefault(AudioDeviceID inOutputDeviceID)
{
CAHALAudioSystemObject audioSystem;
// Set BGMApp's output device as OS X's default output device.
bool bgmDeviceIsDefault =
(audioSystem.GetDefaultAudioDevice(false, false) == GetObjectID());
if(bgmDeviceIsDefault)
{
DebugMsg("BGMBackgroundMusicDevice::UnsetAsOSDefault: Setting the system's default output "
"device back to device %d", inOutputDeviceID);
audioSystem.SetDefaultAudioDevice(false, false, inOutputDeviceID);
}
// Set BGMApp's output device as OS X's default system output device.
bool bgmDeviceIsSystemDefault =
(audioSystem.GetDefaultAudioDevice(false, true) == mUISoundsBGMDevice);
// If we changed the default system output device to BGMDevice, which we only do if it's set to
// the same device as the default output device, change it back to the previous device.
if(bgmDeviceIsSystemDefault)
{
DebugMsg("BGMBackgroundMusicDevice::UnsetAsOSDefault: Setting the system's default system "
"output device back to device %d", inOutputDeviceID);
audioSystem.SetDefaultAudioDevice(false, true, inOutputDeviceID);
}
}
#pragma mark App Volumes
CFArrayRef BGMBackgroundMusicDevice::GetAppVolumes() const
{
CFTypeRef appVolumes = GetPropertyData_CFType(kBGMAppVolumesAddress);
ThrowIfNULL(appVolumes,
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetAppVolumes: !appVolumes");
ThrowIf(CFGetTypeID(appVolumes) != CFArrayGetTypeID(),
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetAppVolumes: Expected CFArray value");
return static_cast<CFArrayRef>(appVolumes);
}
void BGMBackgroundMusicDevice::SetAppVolume(SInt32 inVolume,
pid_t inAppProcessID,
CFStringRef __nullable inAppBundleID)
{
BGMAssert((kAppRelativeVolumeMinRawValue <= inVolume) &&
(inVolume <= kAppRelativeVolumeMaxRawValue),
"BGMBackgroundMusicDevice::SetAppVolume: Volume out of bounds");
// Clamp the volume to [kAppRelativeVolumeMinRawValue, kAppPanRightRawValue].
inVolume = std::max(kAppRelativeVolumeMinRawValue, inVolume);
inVolume = std::min(kAppRelativeVolumeMaxRawValue, inVolume);
SendAppVolumeOrPanToBGMDevice(inVolume,
CFSTR(kBGMAppVolumesKey_RelativeVolume),
inAppProcessID,
inAppBundleID);
}
void BGMBackgroundMusicDevice::SetAppPanPosition(SInt32 inPanPosition,
pid_t inAppProcessID,
CFStringRef __nullable inAppBundleID)
{
BGMAssert((kAppPanLeftRawValue <= inPanPosition) && (inPanPosition <= kAppPanRightRawValue),
"BGMBackgroundMusicDevice::SetAppPanPosition: Pan position out of bounds");
// Clamp the pan position to [kAppPanLeftRawValue, kAppPanRightRawValue].
inPanPosition = std::max(kAppPanLeftRawValue, inPanPosition);
inPanPosition = std::min(kAppPanRightRawValue, inPanPosition);
SendAppVolumeOrPanToBGMDevice(inPanPosition,
CFSTR(kBGMAppVolumesKey_PanPosition),
inAppProcessID,
inAppBundleID);
}
void BGMBackgroundMusicDevice::SendAppVolumeOrPanToBGMDevice(SInt32 inNewValue,
CFStringRef inVolumeTypeKey,
pid_t inAppProcessID,
CFStringRef __nullable inAppBundleID)
{
CACFArray appVolumeChanges(true);
auto addVolumeChange = [&] (pid_t pid, CFStringRef bundleID)
{
CACFDictionary appVolumeChange(true);
appVolumeChange.AddSInt32(CFSTR(kBGMAppVolumesKey_ProcessID), pid);
appVolumeChange.AddString(CFSTR(kBGMAppVolumesKey_BundleID), bundleID);
appVolumeChange.AddSInt32(inVolumeTypeKey, inNewValue);
appVolumeChanges.AppendDictionary(appVolumeChange.GetDict());
};
addVolumeChange(inAppProcessID, inAppBundleID);
// Add the same change for each process the app is responsible for.
for(CACFString responsibleBundleID : ResponsibleBundleIDsOf(CACFString(inAppBundleID)))
{
// Send -1 as the PID so this volume will only ever be matched by bundle ID.
addVolumeChange(-1, responsibleBundleID.GetCFString());
}
CFPropertyListRef changesPList = appVolumeChanges.AsPropertyList();
// Send the change to BGMDevice.
SetPropertyData_CFType(kBGMAppVolumesAddress, changesPList);
// Also send it to the instance of BGMDevice that handles UI sounds.
mUISoundsBGMDevice.SetPropertyData_CFType(kBGMAppVolumesAddress, changesPList);
}
// This is a temporary solution that lets us control the volumes of some multiprocess apps, i.e.
// apps that play their audio from a process with a different bundle ID.
//
// We can't just check the child processes of the apps' main processes because they're usually
// created with launchd rather than being actual child processes. There's a private API to get the
// processes that an app is "responsible for", so we'll try to use it in the proper fix and only use
// this list if the API doesn't work.
//
// static
std::vector<CACFString>
BGMBackgroundMusicDevice::ResponsibleBundleIDsOf(CACFString inParentBundleID)
{
if(!inParentBundleID.IsValid())
{
return {};
}
std::map<CACFString, std::vector<CACFString>> bundleIDMap = {
// Finder
{ "com.apple.finder",
{ "com.apple.quicklook.ui.helper",
"com.apple.quicklook.QuickLookUIService" } },
// Safari
{ "com.apple.Safari", { "com.apple.WebKit.WebContent" } },
// Firefox
{ "org.mozilla.firefox", { "org.mozilla.plugincontainer" } },
// Firefox Nightly
{ "org.mozilla.nightly", { "org.mozilla.plugincontainer" } },
// VMWare Fusion
{ "com.vmware.fusion", { "com.vmware.vmware-vmx" } },
// Parallels
{ "com.parallels.desktop.console", { "com.parallels.vm" } },
// MPlayer OSX Extended
{ "hu.mplayerhq.mplayerosx.extended",
{ "ch.sttz.mplayerosx.extended.binaries.officialsvn" } },
// Discord
{ "com.hnc.Discord", { "com.hnc.Discord.helper" } },
// Skype
{ "com.skype.skype", { "com.skype.skype.Helper" } }
};
// Parallels' VM "dock helper" apps have bundle IDs like
// com.parallels.winapp.87f6bfc236d64d70a81c47f6243add4c.f5a25fdede514f7aa0a475a1873d3287.fs
if(inParentBundleID.StartsWith(CFSTR("com.parallels.winapp.")))
{
return { "com.parallels.vm" };
}
return bundleIDMap[inParentBundleID];
}
#pragma mark Audible State
BGMDeviceAudibleState BGMBackgroundMusicDevice::GetAudibleState() const
{
CFTypeRef propertyDataRef = GetPropertyData_CFType(kBGMAudibleStateAddress);
ThrowIfNULL(propertyDataRef,
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetAudibleState: !propertyDataRef");
ThrowIf(CFGetTypeID(propertyDataRef) != CFNumberGetTypeID(),
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetAudibleState: Property was not a CFNumber");
CFNumberRef audibleStateRef = static_cast<CFNumberRef>(propertyDataRef);
BGMDeviceAudibleState audibleState;
Boolean success = CFNumberGetValue(audibleStateRef, kCFNumberSInt32Type, &audibleState);
CFRelease(audibleStateRef);
ThrowIf(!success,
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetMusicPlayerProcessID: CFNumberGetValue failed");
return audibleState;
}
#pragma mark Music Player
pid_t BGMBackgroundMusicDevice::GetMusicPlayerProcessID() const
{
CFTypeRef propertyDataRef = GetPropertyData_CFType(kBGMMusicPlayerProcessIDAddress);
ThrowIfNULL(propertyDataRef,
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetMusicPlayerProcessID: !propertyDataRef");
ThrowIf(CFGetTypeID(propertyDataRef) != CFNumberGetTypeID(),
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetMusicPlayerProcessID: Property was not a CFNumber");
CFNumberRef pidRef = static_cast<CFNumberRef>(propertyDataRef);
pid_t pid;
Boolean success = CFNumberGetValue(pidRef, kCFNumberIntType, &pid);
CFRelease(pidRef);
ThrowIf(!success,
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetMusicPlayerProcessID: CFNumberGetValue failed");
return pid;
}
CFStringRef BGMBackgroundMusicDevice::GetMusicPlayerBundleID() const
{
CFStringRef bundleID = GetPropertyData_CFString(kBGMMusicPlayerBundleIDAddress);
ThrowIfNULL(bundleID,
CAException(kAudioHardwareIllegalOperationError),
"BGMBackgroundMusicDevice::GetMusicPlayerBundleID: !bundleID");
return bundleID;
}
#pragma clang assume_nonnull end
-196
View File
@@ -1,196 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMBackgroundMusicDevice.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// The interface to BGMDevice, the main virtual device published by BGMDriver, and the second
// instance of that device, which handles UI-related audio. In most cases, users of this class
// should be able to think of it as representing a single device.
//
// BGMDevice is the device that appears as "Background Music" in programs that list the output
// devices, e.g. System Preferences. It receives the system's audio, processes it and sends it to
// BGMApp by publishing an input stream. BGMApp then plays the audio on the user's real output
// device.
//
// See BGMDriver/BGMDriver/BGM_Device.h.
//
#ifndef BGMApp__BGMBackgroundMusicDevice
#define BGMApp__BGMBackgroundMusicDevice
// Superclass Includes
#include "BGMAudioDevice.h"
// Local Includes
#include "BGM_Types.h"
// PublicUtility Includes
#include "CACFString.h"
// STL Includes
#include <vector>
#pragma clang assume_nonnull begin
class BGMBackgroundMusicDevice
:
public BGMAudioDevice
{
#pragma mark Construction/Destruction
public:
/*!
@throws CAException If BGMDevice is not found or the HAL returns an error when queried for
BGMDevice's current Audio Object ID.
*/
BGMBackgroundMusicDevice();
virtual ~BGMBackgroundMusicDevice();
#pragma mark Systemwide Default Device
public:
/*!
Set BGMDevice as the default audio device for all processes.
@throws CAException If the HAL responds with an error.
*/
void SetAsOSDefault();
/*!
Replace BGMDevice as the default device with the output device.
@throws CAException If the HAL responds with an error.
*/
void UnsetAsOSDefault(AudioDeviceID inOutputDeviceID);
#pragma mark App Volumes
public:
/*!
@return The current value of BGMDevice's kAudioDeviceCustomPropertyAppVolumes property. See
BGM_Types.h.
@throws CAException If the HAL returns an error or a non-array type. Callers are responsible
for validating and type-checking the values contained in the array.
*/
CFArrayRef GetAppVolumes() const;
/*!
@param inVolume A value between kAppRelativeVolumeMinRawValue and kAppRelativeVolumeMaxRawValue
from BGM_Types.h. See kBGMAppVolumesKey_RelativeVolume in BGM_Types.h.
@param inAppProcessID The ID of app's main process (or the process it uses to play audio, if
you've managed to figure that out). If an app has multiple audio
processes, you can just set the volume for each of them. Pass -1 to omit
this param.
@param inAppBundleID The app's bundle ID. Pass null to omit this param.
@throws CAException If the HAL returns an error when this function sends the volume change to
BGMDevice.
*/
void SetAppVolume(SInt32 inVolume,
pid_t inAppProcessID,
CFStringRef __nullable inAppBundleID);
/*!
@param inPanPosition A value between kAppPanLeftRawValue and kAppPanRightRawValue from
BGM_Types.h. A negative value has a higher proportion of left channel, and
a positive value has a higher proportion of right channel.
@param inAppProcessID The ID of app's main process (or the process it uses to play audio, if
you've managed to figure that out). If an app has multiple audio
processes, you can just set the pan position for each of them. Pass -1 to
omit this param.
@param inAppBundleID The app's bundle ID. Pass null to omit this param.
@throws CAException If the HAL returns an error when this function sends the pan position
change to BGMDevice.
*/
void SetAppPanPosition(SInt32 inPanPosition,
pid_t inAppProcessID,
CFStringRef __nullable inAppBundleID);
private:
void SendAppVolumeOrPanToBGMDevice(SInt32 inNewValue,
CFStringRef inVolumeTypeKey,
pid_t inAppProcessID,
CFStringRef __nullable inAppBundleID);
static std::vector<CACFString>
ResponsibleBundleIDsOf(CACFString inParentBundleID);
#pragma mark Audible State
public:
/*!
@return BGMDevice's current "audible state", which can be either silent, silent except for the
user's music player or audible, meaning a program other than the music player is
playing audio.
@throws CAException If the HAL returns an error or invalid data when queried.
@see kAudioDeviceCustomPropertyDeviceAudibleState in BGM_Types.h.
*/
BGMDeviceAudibleState GetAudibleState() const;
#pragma mark Music Player
public:
/*!
@return The value of BGMDevice's property for the selected music player's process ID. Zero if
the property is unset. (We assume kernel_task will never be the user's music player.)
@throws CAException If the HAL returns an error or an invalid PID when queried.
@see kAudioDeviceCustomPropertyMusicPlayerProcessID in BGM_Types.h.
*/
virtual pid_t GetMusicPlayerProcessID() const;
/*!
Set the value of BGMDevice's property for the selected music player's process ID. Pass zero to
unset the property. Setting this property will unset the bundle ID version of the property.
@throws CAException If the HAL returns an error.
@see kAudioDeviceCustomPropertyMusicPlayerProcessID in BGM_Types.h.
*/
virtual void SetMusicPlayerProcessID(CFNumberRef inProcessID) {
SetPropertyData_CFType(kBGMMusicPlayerProcessIDAddress, inProcessID); }
/*!
@return The value of BGMDevice's property for the selected music player's bundle ID. The empty
string if the property is unset.
@throws CAException If the HAL returns an error or an invalid bundle ID when queried.
@see kAudioDeviceCustomPropertyMusicPlayerBundleID in BGM_Types.h.
*/
virtual CFStringRef GetMusicPlayerBundleID() const;
/*!
Set the value of BGMDevice's property for the selected music player's bundle ID. Pass the empty
string to unset the property. Setting this property will unset the process ID version of the
property.
@throws CAException If the HAL returns an error.
@see kAudioDeviceCustomPropertyMusicPlayerBundleID in BGM_Types.h.
*/
virtual void SetMusicPlayerBundleID(CFStringRef inBundleID) {
SetPropertyData_CFString(kBGMMusicPlayerBundleIDAddress, inBundleID); }
#pragma mark UI Sounds Instance
public:
/*! @return The instance of BGMDevice that handles UI sounds. */
BGMAudioDevice GetUISoundsBGMDeviceInstance() { return mUISoundsBGMDevice; }
private:
/*! The instance of BGMDevice that handles UI sounds. */
BGMAudioDevice mUISoundsBGMDevice;
};
#pragma clang assume_nonnull end
#endif /* BGMApp__BGMBackgroundMusicDevice */
+268 -148
View File
@@ -17,7 +17,7 @@
// BGMDeviceControlSync.cpp
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
@@ -25,13 +25,13 @@
// Local Includes
#include "BGM_Types.h"
#include "BGM_Utils.h"
// PublicUtility Includes
#include "CAPropertyAddress.h"
// System Includes
#include <AudioToolbox/AudioServices.h>
#pragma clang assume_nonnull begin
// AudioObjectPropertyElement docs: "Elements are numbered sequentially where 0 represents the master element."
static const AudioObjectPropertyElement kMasterChannel = 0;
static const AudioObjectPropertyAddress kMutePropertyAddress =
{ kAudioDevicePropertyMute, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMaster };
@@ -41,55 +41,31 @@ static const AudioObjectPropertyAddress kVolumePropertyAddress =
#pragma mark Construction/Destruction
BGMDeviceControlSync::BGMDeviceControlSync(AudioObjectID inBGMDevice,
AudioObjectID inOutputDevice,
CAHALAudioSystemObject inAudioSystem)
BGMDeviceControlSync::BGMDeviceControlSync(CAHALAudioDevice inBGMDevice, CAHALAudioDevice inOutputDevice)
:
mBGMDevice(inBGMDevice),
mOutputDevice(inOutputDevice),
mAudioSystem(inAudioSystem),
mBGMDeviceControlsList(inBGMDevice)
mOutputDevice(inOutputDevice)
{
Activate();
}
BGMDeviceControlSync::~BGMDeviceControlSync()
{
BGMLogAndSwallowExceptions("BGMDeviceControlSync::~BGMDeviceControlSync", [&] {
CAMutex::Locker locker(mMutex);
Deactivate();
});
Deactivate();
}
void BGMDeviceControlSync::Activate()
{
CAMutex::Locker locker(mMutex);
ThrowIf((mBGMDevice.GetObjectID() == kAudioObjectUnknown || mOutputDevice.GetObjectID() == kAudioObjectUnknown),
ThrowIf((mBGMDevice.GetObjectID() == kAudioDeviceUnknown || mOutputDevice.GetObjectID() == kAudioDeviceUnknown),
BGM_DeviceNotSetException(),
"BGMDeviceControlSync::Activate: Both the output device and BGMDevice must be set to start synchronizing their controls");
// Init BGMDevice controls to match output device
CopyVolume(mOutputDevice, mBGMDevice, kAudioObjectPropertyScopeOutput);
CopyMute(mOutputDevice, mBGMDevice, kAudioObjectPropertyScopeOutput);
if(!mActive)
{
DebugMsg("BGMDeviceControlSync::Activate: Activating control sync");
// Disable BGMDevice controls that the output device doesn't have and reenable any that were
// disabled for the previous output device.
//
// Continue anyway if this fails because it's better to have extra/missing controls than to
// be unable to use the device.
BGMLogAndSwallowExceptionsMsg("BGMDeviceControlSync::Activate", "Controls list", [&] {
bool wasUpdated = mBGMDeviceControlsList.MatchControlsListOf(mOutputDevice);
if(wasUpdated)
{
mBGMDeviceControlsList.PropagateControlListChange();
}
});
// Init BGMDevice controls to match output device
mBGMDevice.CopyVolumeFrom(mOutputDevice, kAudioObjectPropertyScopeOutput);
mBGMDevice.CopyMuteFrom(mOutputDevice, kAudioObjectPropertyScopeOutput);
// Register listeners for volume and mute values
mBGMDevice.AddPropertyListener(kVolumePropertyAddress, &BGMDeviceControlSync::BGMDeviceListenerProc, this);
@@ -99,140 +75,284 @@ void BGMDeviceControlSync::Activate()
}
catch(CAException)
{
CATry
mBGMDevice.RemovePropertyListener(kVolumePropertyAddress, &BGMDeviceControlSync::BGMDeviceListenerProc, this);
CACatch
throw;
}
mActive = true;
}
else
{
DebugMsg("BGMDeviceControlSync::Activate: Already active");
}
}
void BGMDeviceControlSync::Deactivate()
{
CAMutex::Locker locker(mMutex);
if(mActive)
if(mActive && mBGMDevice.GetObjectID() != kAudioDeviceUnknown)
{
DebugMsg("BGMDeviceControlSync::Deactivate: Deactivating control sync");
// Deregister listeners
if(mBGMDevice.GetObjectID() != kAudioDeviceUnknown)
{
BGMLogAndSwallowExceptions("BGMDeviceControlSync::Deactivate", [&] {
mBGMDevice.RemovePropertyListener(kVolumePropertyAddress,
&BGMDeviceControlSync::BGMDeviceListenerProc,
this);
});
BGMLogAndSwallowExceptions("BGMDeviceControlSync::Deactivate", [&] {
mBGMDevice.RemovePropertyListener(kMutePropertyAddress,
&BGMDeviceControlSync::BGMDeviceListenerProc,
this);
});
}
mActive = false;
}
else
{
DebugMsg("BGMDeviceControlSync::Deactivate: Not active");
// Unregister listeners
mBGMDevice.RemovePropertyListener(kVolumePropertyAddress, &BGMDeviceControlSync::BGMDeviceListenerProc, this);
mBGMDevice.RemovePropertyListener(kMutePropertyAddress, &BGMDeviceControlSync::BGMDeviceListenerProc, this);
}
}
#pragma mark Accessors
void BGMDeviceControlSync::SetDevices(AudioObjectID inBGMDevice, AudioObjectID inOutputDevice)
void BGMDeviceControlSync::Swap(BGMDeviceControlSync& inDeviceControlSync)
{
CAMutex::Locker locker(mMutex);
bool wasActive = mActive;
Deactivate();
mBGMDevice = inBGMDevice;
mBGMDeviceControlsList.SetBGMDevice(inBGMDevice);
mOutputDevice = inOutputDevice;
if(wasActive)
{
Activate();
}
mBGMDevice = inDeviceControlSync.mBGMDevice;
mOutputDevice = inDeviceControlSync.mOutputDevice;
inDeviceControlSync.Deactivate();
Activate();
}
#pragma mark Listener Procs
#pragma mark Get/Set Control Values
// static
OSStatus BGMDeviceControlSync::BGMDeviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses, void* __nullable inClientData)
void BGMDeviceControlSync::CopyMute(CAHALAudioDevice inFromDevice, CAHALAudioDevice inToDevice, AudioObjectPropertyScope inScope)
{
// refCon (reference context) is the instance that registered this listener proc.
BGMDeviceControlSync* refCon = static_cast<BGMDeviceControlSync*>(inClientData);
auto checkState = [&] {
if(!refCon)
{
LogError("BGMDeviceControlSync::BGMDeviceListenerProc: !refCon");
return false;
}
if(!refCon->mActive ||
(refCon->mBGMDevice.GetObjectID() == kAudioObjectUnknown) ||
(refCon->mOutputDevice.GetObjectID() == kAudioObjectUnknown))
{
return false;
}
if(inObjectID != refCon->mBGMDevice.GetObjectID())
{
LogError("BGMDeviceControlSync::BGMDeviceListenerProc: notified about audio object other than BGMDevice");
return false;
}
return true;
};
for(int i = 0; i < inNumberAddresses; i++)
// TODO: Support for devices that have per-channel mute controls but no master mute control
bool toHasSettableMasterMute = inToDevice.HasMuteControl(inScope, kMasterChannel) && inToDevice.MuteControlIsSettable(inScope, kMasterChannel);
if(toHasSettableMasterMute && inFromDevice.HasMuteControl(inScope, kMasterChannel))
{
AudioObjectPropertyScope scope = inAddresses[i].mScope;
switch(inAddresses[i].mSelector)
{
case kAudioDevicePropertyVolumeScalar:
{
CAMutex::Locker locker(refCon->mMutex);
inToDevice.SetMuteControlValue(inScope,
kMasterChannel,
inFromDevice.GetMuteControlValue(inScope, kMasterChannel));
}
}
// Update the output device's volume.
if(checkState())
{
refCon->mOutputDevice.CopyVolumeFrom(refCon->mBGMDevice, scope);
}
}
break;
case kAudioDevicePropertyMute:
{
CAMutex::Locker locker(refCon->mMutex);
// Update the output device's mute control. Note that this also runs when you
// change the volume (on BGMDevice).
if(checkState())
{
refCon->mOutputDevice.CopyMuteFrom(refCon->mBGMDevice, scope);
}
}
break;
}
// static
void BGMDeviceControlSync::CopyVolume(CAHALAudioDevice inFromDevice, CAHALAudioDevice inToDevice, AudioObjectPropertyScope inScope)
{
// Get the volume of the from device
bool didGetFromVolume = false;
Float32 fromVolume = FLT_MIN;
if(inFromDevice.HasVolumeControl(inScope, kMasterChannel))
{
fromVolume = inFromDevice.GetVolumeControlScalarValue(inScope, kMasterChannel);
didGetFromVolume = true;
}
// "The return value [of an AudioObjectPropertyListenerProc] is currently unused and should always be 0."
// Use the average channel volume of the from device if it has no master volume
if(!didGetFromVolume)
{
UInt32 fromNumChannels = inFromDevice.GetTotalNumberChannels(inScope == kAudioObjectPropertyScopeInput);
fromVolume = 0;
for(UInt32 channel = 1; channel <= fromNumChannels; channel++)
{
if(inFromDevice.HasVolumeControl(inScope, channel))
{
fromVolume += inFromDevice.GetVolumeControlScalarValue(inScope, channel);
didGetFromVolume = true;
}
}
fromVolume /= fromNumChannels;
}
// Set the volume of the to device
if(didGetFromVolume && fromVolume != FLT_MIN)
{
bool didSetVolume = false;
try
{
didSetVolume = SetMasterVolumeScalar(inToDevice, inScope, fromVolume);
}
catch(CAException e)
{
OSStatus err = e.GetError();
char err4CC[5] = CA4CCToCString(err);
CFStringRef uid = inToDevice.CopyDeviceUID();
LogWarning("BGMDeviceControlSync::CopyVolume: CAException '%s' trying to set master volume of %s", err4CC, uid);
CFRelease(uid);
}
if(!didSetVolume)
{
// Couldn't find a master volume control to set, so try to find a virtual one
Float32 fromVirtualMasterVolume;
bool success = GetVirtualMasterVolume(inFromDevice, inScope, fromVirtualMasterVolume);
if(success)
{
didSetVolume = SetVirtualMasterVolume(inToDevice, inScope, fromVirtualMasterVolume);
}
}
if(!didSetVolume)
{
// Couldn't set a master or virtual master volume, so as a fallback try to set each channel individually
UInt32 numChannels = inToDevice.GetTotalNumberChannels(inScope == kAudioObjectPropertyScopeInput);
for(UInt32 channel = 1; channel <= numChannels; channel++)
{
if(inToDevice.HasVolumeControl(inScope, channel) && inToDevice.VolumeControlIsSettable(inScope, channel))
{
inToDevice.SetVolumeControlScalarValue(inScope, channel, fromVolume);
}
}
}
}
}
// static
bool BGMDeviceControlSync::SetMasterVolumeScalar(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32 inVolume)
{
bool hasSettableMasterVolume =
inDevice.HasVolumeControl(inScope, kMasterChannel) && inDevice.VolumeControlIsSettable(inScope, kMasterChannel);
if(hasSettableMasterVolume)
{
inDevice.SetVolumeControlScalarValue(inScope, kMasterChannel, inVolume);
return true;
}
return false;
}
// static
bool BGMDeviceControlSync::GetVirtualMasterVolume(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32& outVirtualMasterVolume)
{
AudioObjectPropertyAddress virtualMasterVolumeAddress =
{ kAudioHardwareServiceDeviceProperty_VirtualMasterVolume, inScope, kAudioObjectPropertyElementMaster };
if(!AudioHardwareServiceHasProperty(inDevice.GetObjectID(), &virtualMasterVolumeAddress))
{
return false;
}
UInt32 virtualMasterVolumePropertySize = sizeof(Float32);
return kAudioServicesNoError == AHSGetPropertyData(inDevice.GetObjectID(),
&virtualMasterVolumeAddress,
&virtualMasterVolumePropertySize,
&outVirtualMasterVolume);
}
// static
bool BGMDeviceControlSync::SetVirtualMasterVolume(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32 inVolume)
{
// TODO: For me, setting the virtual master volume sets all the device's channels to the same volume, meaning you can't
// keep any channels quieter than the others. The expected behaviour is to scale the channel volumes
// proportionally. So to do this properly I think we'd have to store BGMDevice's previous volume and calculate
// each channel's new volume from its current volume and the distance between BGMDevice's old and new volumes.
//
// The docs kAudioHardwareServiceDeviceProperty_VirtualMasterVolume for say
// "If the device has individual channel volume controls, this property will apply to those identified by the
// device's preferred multi-channel layout (or preferred stereo pair if the device is stereo only). Note that
// this control maintains the relative balance between all the channels it affects.
// so I'm not sure why that's not working here. As a workaround we take the to device's (virtual master) balance
// before changing the volume and set it back after, but of course that'll only work for stereo devices.
bool didSetVolume = false;
AudioObjectPropertyAddress virtualMasterVolumeAddress =
{ kAudioHardwareServiceDeviceProperty_VirtualMasterVolume, inScope, kAudioObjectPropertyElementMaster };
bool hasVirtualMasterVolume = AudioHardwareServiceHasProperty(inDevice.GetObjectID(), &virtualMasterVolumeAddress);
Boolean virtualMasterVolumeIsSettable;
OSStatus err = AudioHardwareServiceIsPropertySettable(inDevice.GetObjectID(), &virtualMasterVolumeAddress, &virtualMasterVolumeIsSettable);
virtualMasterVolumeIsSettable &= (err == kAudioServicesNoError);
if(hasVirtualMasterVolume && virtualMasterVolumeIsSettable)
{
// Not sure why, but setting the virtual master volume sets all channels to the same volume. As a workaround, we store
// the current balance here so we can reset it after setting the volume.
Float32 virtualMasterBalance;
bool didGetVirtualMasterBalance = GetVirtualMasterBalance(inDevice, inScope, virtualMasterBalance);
didSetVolume = kAudioServicesNoError == AHSSetPropertyData(inDevice.GetObjectID(), &virtualMasterVolumeAddress, sizeof(Float32), &inVolume);
// Reset the balance
AudioObjectPropertyAddress virtualMasterBalanceAddress =
{ kAudioHardwareServiceDeviceProperty_VirtualMasterBalance, inScope, kAudioObjectPropertyElementMaster };
if(didSetVolume && didGetVirtualMasterBalance && AudioHardwareServiceHasProperty(inDevice.GetObjectID(), &virtualMasterBalanceAddress))
{
Boolean balanceIsSettable;
err = AudioHardwareServiceIsPropertySettable(inDevice.GetObjectID(), &virtualMasterBalanceAddress, &balanceIsSettable);
if(err == kAudioServicesNoError && balanceIsSettable)
{
AHSSetPropertyData(inDevice.GetObjectID(), &virtualMasterBalanceAddress, sizeof(Float32), &virtualMasterBalance);
}
}
}
return didSetVolume;
}
// static
bool BGMDeviceControlSync::GetVirtualMasterBalance(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32& outVirtualMasterBalance)
{
AudioObjectPropertyAddress virtualMasterBalanceAddress =
{ kAudioHardwareServiceDeviceProperty_VirtualMasterBalance, inScope, kAudioObjectPropertyElementMaster };
if(!AudioHardwareServiceHasProperty(inDevice.GetObjectID(), &virtualMasterBalanceAddress))
{
return false;
}
UInt32 virtualMasterVolumePropertySize = sizeof(Float32);
return kAudioServicesNoError == AHSGetPropertyData(inDevice.GetObjectID(),
&virtualMasterBalanceAddress,
&virtualMasterVolumePropertySize,
&outVirtualMasterBalance);
}
// static
OSStatus BGMDeviceControlSync::AHSGetPropertyData(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32* ioDataSize, void* outData)
{
// The docs for AudioHardwareServiceGetPropertyData specifically allow passing NULL for inQualifierData as we do here,
// but it's declared in an assume_nonnull section so we have to disable the warning here. I'm not sure why inQualifierData
// isn't __nullable. I'm assuming it's either a backwards compatibility thing or just a bug.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
// The non-depreciated version of this (and the setter below) doesn't seem to support devices other than the default
return AudioHardwareServiceGetPropertyData(inObjectID, inAddress, 0, NULL, ioDataSize, outData);
#pragma clang diagnostic pop
}
// static
OSStatus BGMDeviceControlSync::AHSSetPropertyData(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inDataSize, const void* inData)
{
// See the explanation about these pragmas in AHSGetPropertyData
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
return AudioHardwareServiceSetPropertyData(inObjectID, inAddress, 0, NULL, inDataSize, inData);
#pragma clang diagnostic pop
}
#pragma mark Listener
// static
OSStatus BGMDeviceControlSync::BGMDeviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress* __nonnull inAddresses, void* __nullable inClientData)
{
// refCon (reference context) is the instance that registered this listener proc
BGMDeviceControlSync* refCon = static_cast<BGMDeviceControlSync*>(inClientData);
if(refCon->mActive)
{
ThrowIf(inObjectID != refCon->mBGMDevice.GetObjectID(),
CAException(kAudioHardwareBadObjectError),
"BGMDeviceControlSync::BGMDeviceListenerProc: notified about audio object other than BGMDevice");
for(int i = 0; i < inNumberAddresses; i++)
{
AudioObjectPropertyScope scope = inAddresses[i].mScope;
switch(inAddresses[i].mSelector)
{
case kAudioDevicePropertyVolumeScalar:
// Update the output device
CopyVolume(refCon->mBGMDevice, refCon->mOutputDevice, scope);
break;
case kAudioDevicePropertyMute:
// Update the output device. Note that this also runs when you change the volume (on BGMDevice)
CopyMute(refCon->mBGMDevice, refCon->mOutputDevice, scope);
break;
default:
break;
}
}
}
return 0;
}
#pragma clang assume_nonnull end
+33 -73
View File
@@ -17,105 +17,65 @@
// BGMDeviceControlSync.h
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Synchronises BGMDevice's controls (just volume and mute currently) with the output device's
// controls. This allows the user to control the output device normally while BGMDevice is set as
// the default device.
//
// BGMDeviceControlSync disables any BGMDevice controls that the output device doesn't also have.
// When the value of one of BGMDevice's controls is changed, BGMDeviceControlSync copies the new
// value to the output device.
//
// Thread safe.
// Listens for notifications that BGMDevice's controls (just volume and mute currently) have changed value, and
// copies the new values to the output device.
//
#ifndef BGMApp__BGMDeviceControlSync
#define BGMApp__BGMDeviceControlSync
// Local Includes
#include "BGMAudioDevice.h"
#include "BGMDeviceControlsList.h"
#ifndef __BGMApp__BGMDeviceControlSync__
#define __BGMApp__BGMDeviceControlSync__
// PublicUtility Includes
#include "CAHALAudioSystemObject.h"
#include "CAMutex.h"
// System Includes
#include <AudioToolbox/AudioServices.h>
#include "CAHALAudioDevice.h"
#pragma clang assume_nonnull begin
class BGMDeviceControlSync
{
#pragma mark Construction/Destruction
public:
BGMDeviceControlSync(AudioObjectID inBGMDevice,
AudioObjectID inOutputDevice,
CAHALAudioSystemObject inAudioSystem
= CAHALAudioSystemObject());
BGMDeviceControlSync(CAHALAudioDevice inBGMDevice, CAHALAudioDevice inOutputDevice);
~BGMDeviceControlSync();
// Disallow copying
BGMDeviceControlSync(const BGMDeviceControlSync&) = delete;
BGMDeviceControlSync& operator=(const BGMDeviceControlSync&) = delete;
// Move constructor/assignment
BGMDeviceControlSync(BGMDeviceControlSync&& inDeviceControlSync) { Swap(inDeviceControlSync); }
BGMDeviceControlSync& operator=(BGMDeviceControlSync&& inDeviceControlSync) { Swap(inDeviceControlSync); return *this; }
#ifdef __OBJC__
// Only intended as a convenience for Objective-C instance vars
BGMDeviceControlSync()
: BGMDeviceControlSync(kAudioObjectUnknown, kAudioObjectUnknown) { };
BGMDeviceControlSync() { };
#endif
/*!
Begin synchronising BGMDevice's controls with the output device's.
@throws BGM_DeviceNotSetException if BGMDevice isn't set.
@throws CAException if the HAL or one of the devices returns an error when this function
registers for device property notifications or when it copies the current
values of the output device's controls to BGMDevice. This
BGMDeviceControlSync will remain inactive if this function throws.
*/
private:
void Activate();
/*! Stop synchronising BGMDevice's controls with the output device's. */
void Deactivate();
#pragma mark Accessors
/*!
Set the IDs of BGMDevice and the output device to synchronise with.
@throws BGM_DeviceNotSetException if BGMDevice isn't set.
@throws CAException if the HAL or one of the new devices returns an error while restarting
synchronisation. This BGMDeviceControlSync will be deactivated if this
function throws, but its devices will still be set.
*/
void SetDevices(AudioObjectID inBGMDevice, AudioObjectID inOutputDevice);
#pragma mark Listener Procs
void Swap(BGMDeviceControlSync& inDeviceControlSync);
static void CopyMute(CAHALAudioDevice inFromDevice, CAHALAudioDevice inToDevice, AudioObjectPropertyScope inScope);
static void CopyVolume(CAHALAudioDevice inFromDevice, CAHALAudioDevice inToDevice, AudioObjectPropertyScope inScope);
static bool SetMasterVolumeScalar(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32 inVolume);
static bool GetVirtualMasterVolume(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32& outVirtualMasterVolume);
static bool SetVirtualMasterVolume(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32 inVolume);
static bool GetVirtualMasterBalance(CAHALAudioDevice inDevice, AudioObjectPropertyScope inScope, Float32& outVirtualMasterBalance);
static OSStatus AHSGetPropertyData(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32* ioDataSize, void* outData);
static OSStatus AHSSetPropertyData(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inDataSize, const void* inData);
static OSStatus BGMDeviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses, void* __nullable inClientData);
private:
/*! Receives HAL notifications about the BGMDevice properties this class listens to. */
static OSStatus BGMDeviceListenerProc(AudioObjectID inObjectID,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void* __nullable inClientData);
private:
CAMutex mMutex { "Device Control Sync" };
bool mActive = false;
CAHALAudioSystemObject mAudioSystem;
BGMAudioDevice mBGMDevice { (AudioObjectID)kAudioObjectUnknown };
BGMAudioDevice mOutputDevice { (AudioObjectID)kAudioObjectUnknown };
BGMDeviceControlsList mBGMDeviceControlsList;
bool mActive = false;
CAHALAudioDevice mBGMDevice { kAudioDeviceUnknown };
CAHALAudioDevice mOutputDevice { kAudioDeviceUnknown };
};
#pragma clang assume_nonnull end
#endif /* BGMApp__BGMDeviceControlSync */
#endif /* __BGMApp__BGMDeviceControlSync__ */
-569
View File
@@ -1,569 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMDeviceControlsList.cpp
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Self Include
#include "BGMDeviceControlsList.h"
// Local Includes
#include "BGM_Types.h"
#include "BGM_Utils.h"
// PublicUtility Includes
#include "CAPropertyAddress.h"
#include "CACFArray.h"
#pragma clang assume_nonnull begin
static const SInt64 kToggleDeviceInitialDelay = 50 * NSEC_PER_MSEC;
static const SInt64 kToggleDeviceBackDelay = 500 * NSEC_PER_MSEC;
static const SInt64 kDisableNullDeviceDelay = 500 * NSEC_PER_MSEC;
static const SInt64 kDisableNullDeviceTimeout = 5000 * NSEC_PER_MSEC;
#pragma mark Construction/Destruction
BGMDeviceControlsList::BGMDeviceControlsList(AudioObjectID inBGMDevice,
CAHALAudioSystemObject inAudioSystem)
:
mBGMDevice(inBGMDevice),
mAudioSystem(inAudioSystem)
{
BGMAssert((mBGMDevice.IsBGMDevice() || mBGMDevice.GetObjectID() == kAudioObjectUnknown),
"BGMDeviceControlsList::BGMDeviceControlsList: Given device is not BGMDevice");
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
mCanToggleDeviceOnSystem = (&dispatch_block_wait &&
&dispatch_block_cancel &&
&dispatch_block_testcancel &&
&dispatch_queue_attr_make_with_qos_class);
#pragma clang diagnostic pop
}
BGMDeviceControlsList::~BGMDeviceControlsList()
{
CAMutex::Locker locker(mMutex);
if(!mDeviceTogglingInitialised)
{
return;
}
if(mListenerQueue && mListenerBlock)
{
BGMLogAndSwallowExceptions("BGMDeviceControlsList::~BGMDeviceControlsList", ([&] {
mAudioSystem.RemovePropertyListenerBlock(
CAPropertyAddress(kAudioHardwarePropertyDevices),
mListenerQueue,
mListenerBlock);
}));
}
// If we're in the middle of toggling the default device, block until we've finished.
if(mDisableNullDeviceBlock && mDeviceToggleState != ToggleState::NotToggling)
{
DebugMsg("BGMDeviceControlsList::~BGMDeviceControlsList: Waiting for device toggle");
// Copy the reference so we can unlock the mutex and allow any remaining blocks to run.
dispatch_block_t disableNullDeviceBlock = mDisableNullDeviceBlock;
CAMutex::Unlocker unlocker(mMutex);
// Note that if mDisableNullDeviceBlock is currently running this will return after it
// finishes and if it's already run this will return immediately. So we don't have to
// worry about ending up waiting for mDisableNullDeviceBlock when it isn't queued.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
long timedOut = dispatch_block_wait(disableNullDeviceBlock, kDisableNullDeviceTimeout);
#pragma clang diagnostic pop
if(timedOut)
{
LogWarning("BGMDeviceControlsList::~BGMDeviceControlsList: Device toggle timed out");
}
}
mDeviceToggleState = ToggleState::NotToggling;
DestroyBlock(mDeviceToggleBlock);
DestroyBlock(mDeviceToggleBackBlock);
DestroyBlock(mDisableNullDeviceBlock);
if(mListenerBlock)
{
Block_release(mListenerBlock);
}
if(mListenerQueue)
{
dispatch_release(BGM_Utils::NN(mListenerQueue));
}
}
#pragma mark Accessors
void BGMDeviceControlsList::SetBGMDevice(AudioObjectID inBGMDeviceID)
{
CAMutex::Locker locker(mMutex);
mBGMDevice = inBGMDeviceID;
BGMAssert(mBGMDevice.IsBGMDevice(),
"BGMDeviceControlsList::SetBGMDevice: Given device is not BGMDevice");
}
#pragma mark Update Controls List
bool BGMDeviceControlsList::MatchControlsListOf(AudioObjectID inDeviceID)
{
CAMutex::Locker locker(mMutex);
if(!mBGMDevice.IsBGMDevice())
{
LogWarning("BGMDeviceControlsList::MatchControlsListOf: BGMDevice ID not set");
return false;
}
// If the output device doesn't have a control that BGMDevice does, disable it on BGMDevice so
// the system's audio UI isn't confusing.
// No need to change input controls.
AudioObjectPropertyScope inScope = kAudioObjectPropertyScopeOutput;
// Check which of BGMDevice's controls are currently enabled. We need to know whether we're
// actually enabling/disabling any controls so we know whether we need to call
// PropagateControlListChange afterward.
CFTypeRef __nullable enabledControlsRef =
mBGMDevice.GetPropertyData_CFType(kBGMEnabledOutputControlsAddress);
ThrowIf(!enabledControlsRef || (CFGetTypeID(enabledControlsRef) != CFArrayGetTypeID()),
CAException(kAudioHardwareIllegalOperationError),
"BGMDeviceControlsList::MatchControlsListOf: Expected a CFArray for "
"kAudioDeviceCustomPropertyEnabledOutputControls");
CACFArray enabledControls(static_cast<CFArrayRef>(enabledControlsRef), true);
BGMAssert(enabledControls.GetNumberItems() == 2,
"BGMDeviceControlsList::MatchControlsListOf: Expected 2 array elements for "
"kAudioDeviceCustomPropertyEnabledOutputControls");
bool volumeEnabled;
bool didGetBool = enabledControls.GetBool(kBGMEnabledOutputControlsIndex_Volume, volumeEnabled);
ThrowIf(!didGetBool,
CAException(kAudioHardwareIllegalOperationError),
"BGMDeviceControlsList::MatchControlsListOf: Expected volume element of "
"kAudioDeviceCustomPropertyEnabledOutputControls to be a CFBoolean");
bool muteEnabled;
didGetBool = enabledControls.GetBool(kBGMEnabledOutputControlsIndex_Mute, muteEnabled);
ThrowIf(!didGetBool,
CAException(kAudioHardwareIllegalOperationError),
"BGMDeviceControlsList::MatchControlsListOf: Expected mute element of "
"kAudioDeviceCustomPropertyEnabledOutputControls to be a CFBoolean");
DebugMsg("BGMDeviceControlsList::MatchControlsListOf: BGMDevice has volume %s, mute %s",
(volumeEnabled ? "enabled" : "disabled"),
(muteEnabled ? "enabled" : "disabled"));
// Check which controls the other device has.
BGMAudioDevice device(inDeviceID);
bool hasMute = device.HasSettableMasterMute(inScope);
bool hasVolume =
device.HasSettableMasterVolume(inScope) || device.HasSettableVirtualMasterVolume(inScope);
if(!hasVolume)
{
// Check for per-channel volume controls.
UInt32 numChannels =
device.GetTotalNumberChannels(inScope == kAudioObjectPropertyScopeInput);
for(UInt32 channel = 1; channel <= numChannels; channel++)
{
BGMLogAndSwallowExceptionsMsg("BGMDeviceControlsList::MatchControlsListOf",
"Checking for channel volume controls",
([&] {
hasVolume =
(device.HasVolumeControl(inScope, channel)
&& device.VolumeControlIsSettable(inScope, channel));
}));
if(hasVolume)
{
break;
}
}
}
// Tell BGMDevice to enable/disable its controls to match the output device.
bool deviceUpdated = false;
CACFArray newEnabledControls;
newEnabledControls.SetCFMutableArrayFromCopy(enabledControls.GetCFArray());
// Update volume.
if(volumeEnabled != hasVolume)
{
DebugMsg("BGMDeviceControlsList::MatchControlsListOf: %s BGMDevice volume control.",
hasVolume ? "Enabling" : "Disabling");
newEnabledControls.SetBool(kBGMEnabledOutputControlsIndex_Volume, hasVolume);
deviceUpdated = true;
}
// Update mute.
if(muteEnabled != hasMute)
{
DebugMsg("BGMDeviceControlsList::MatchControlsListOf: %s BGMDevice mute control.",
hasMute ? "Enabling" : "Disabling");
newEnabledControls.SetBool(kBGMEnabledOutputControlsIndex_Mute, hasMute);
deviceUpdated = true;
}
if(deviceUpdated)
{
mBGMDevice.SetPropertyData_CFType(kBGMEnabledOutputControlsAddress,
newEnabledControls.GetCFMutableArray());
}
return deviceUpdated;
}
void BGMDeviceControlsList::PropagateControlListChange()
{
CAMutex::Locker locker(mMutex);
if((mBGMDevice == kAudioObjectUnknown) || !mCanToggleDeviceOnSystem)
{
return;
}
InitDeviceToggling();
// Leave the default device alone if the user has changed it since launching BGMApp.
bool bgmDeviceIsDefault = true;
BGMLogAndSwallowExceptions("BGMDeviceControlsList::PropagateControlListChange", ([&] {
bgmDeviceIsDefault =
(mBGMDevice.GetObjectID() == mAudioSystem.GetDefaultAudioDevice(false, false));
}));
if(bgmDeviceIsDefault)
{
mDeviceToggleState = ToggleState::SettingNullDeviceAsDefault;
// We'll get a notification from the HAL after the Null Device is enabled. Then we can
// temporarily make it the default device, which gets other programs to notice that
// BGMDevice's controls have changed.
try
{
CAMutex::Unlocker unlocker(mMutex);
SetNullDeviceEnabled(true);
}
catch (...)
{
mDeviceToggleState = ToggleState::NotToggling;
LogError("BGMDeviceControlsList::PropagateControlListChange: Could not enable the Null "
"Device");
throw;
}
}
}
#pragma mark Implementation
void BGMDeviceControlsList::InitDeviceToggling()
{
CAMutex::Locker locker(mMutex);
if(mDeviceTogglingInitialised || !mCanToggleDeviceOnSystem)
{
return;
}
BGMAssert(mBGMDevice.IsBGMDevice(),
"BGMDeviceControlsList::InitDeviceToggling: mBGMDevice device is not set to "
"BGMDevice's ID");
// Register a listener to find out when the Null Device becomes available/unavailable. See
// ToggleDefaultDevice.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
dispatch_queue_attr_t attr =
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0);
#pragma clang diagnostic pop
mListenerQueue = dispatch_queue_create("com.bearisdriving.BGM.BGMDeviceControlsList", attr);
auto listenerBlock = ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses) {
// Ignore the notification if we're not toggling the default device, which would just mean
// the default device has been changed for an unrelated reason.
if(mDeviceToggleState == ToggleState::NotToggling)
{
return;
}
for(int i = 0; i < inNumberAddresses; i++)
{
switch(inAddresses[i].mSelector)
{
case kAudioHardwarePropertyDevices:
{
CAMutex::Locker innerLocker(mMutex);
DebugMsg("BGMDeviceControlsList::InitDeviceToggling: Got "
"kAudioHardwarePropertyDevices");
// Cancel the previous block in case it hasn't run yet.
DestroyBlock(mDeviceToggleBlock);
mDeviceToggleBlock = CreateDeviceToggleBlock();
// Changing the default device too quickly after enabling the Null Device
// seems to cause problems with some programs. Not sure why.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
if(mDeviceToggleBlock)
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
kToggleDeviceInitialDelay),
dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0),
BGM_Utils::NN(mDeviceToggleBlock));
}
#pragma clang diagnostic pop
}
break;
default:
break;
}
}
};
mListenerBlock = Block_copy(listenerBlock);
BGMLogAndSwallowExceptions("BGMDeviceControlsList::InitDeviceToggling", [&] {
mAudioSystem.AddPropertyListenerBlock(CAPropertyAddress(kAudioHardwarePropertyDevices),
mListenerQueue,
mListenerBlock);
});
mDeviceTogglingInitialised = true;
}
void BGMDeviceControlsList::ToggleDefaultDevice()
{
// Set the Null Device as the OS X default device.
AudioObjectID nullDeviceID = mAudioSystem.GetAudioDeviceForUID(CFSTR(kBGMNullDeviceUID));
if(nullDeviceID == kAudioObjectUnknown)
{
// It's unlikely, but we might have been notified about an unrelated device so just log a
// warning.
LogWarning("BGMDeviceControlsList::ToggleDefaultDevice: Null Device not found");
return;
}
DebugMsg("BGMDeviceControlsList::ToggleDefaultDevice: Setting Null Device as default. "
"nullDeviceID = %u", nullDeviceID);
mAudioSystem.SetDefaultAudioDevice(false, false, nullDeviceID);
mDeviceToggleState = ToggleState::SettingBGMDeviceAsDefault;
// A small number of apps (e.g. Firefox) seem to have trouble with the default device being
// changed back immediately, so for now we insert a short delay here and before disabling the
// Null Device.
// Cancel the previous block in case it hasn't run yet.
DestroyBlock(mDeviceToggleBackBlock);
mDeviceToggleBackBlock = CreateDeviceToggleBackBlock();
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
if(mDeviceToggleBackBlock)
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kToggleDeviceBackDelay),
dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0),
BGM_Utils::NN(mDeviceToggleBackBlock));
}
#pragma clang diagnostic pop
}
void BGMDeviceControlsList::SetNullDeviceEnabled(bool inEnabled)
{
DebugMsg("BGMDeviceControlsList::SetNullDeviceEnabled: %s the null device",
inEnabled ? "Enabling" : "Disabling");
// Get the audio object for BGMDriver, which is the object the Null Device belongs to.
AudioObjectID bgmDriverID = mAudioSystem.GetAudioPlugInForBundleID(CFSTR(kBGMDriverBundleID));
if(bgmDriverID == kAudioObjectUnknown)
{
LogError("BGMDeviceControlsList::SetNullDeviceEnabled: BGMDriver plug-in audio object not "
"found");
throw CAException(kAudioHardwareUnspecifiedError);
}
CAHALAudioObject bgmDriver(bgmDriverID);
bgmDriver.SetPropertyData_CFType(CAPropertyAddress(kAudioPlugInCustomPropertyNullDeviceActive),
(inEnabled ? kCFBooleanTrue : kCFBooleanFalse));
}
dispatch_block_t __nullable BGMDeviceControlsList::CreateDeviceToggleBlock()
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
dispatch_block_t __nullable toggleBlock = dispatch_block_create((dispatch_block_flags_t)0, ^{
#pragma clang diagnostic pop
CAMutex::Locker locker(mMutex);
if(mDeviceToggleState == ToggleState::SettingNullDeviceAsDefault)
{
BGMLogAndSwallowExceptions("BGMDeviceControlsList::CreateDeviceToggleBlock",
([&] {
ToggleDefaultDevice();
}));
}
});
if(!toggleBlock)
{
// Pretty sure this should never happen, but the docs aren't completely clear.
LogError("BGMDeviceControlsList::CreateDeviceToggleBlock: !toggleBlock");
}
return toggleBlock;
}
dispatch_block_t __nullable BGMDeviceControlsList::CreateDeviceToggleBackBlock()
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
dispatch_block_t __nullable toggleBackBlock =
dispatch_block_create((dispatch_block_flags_t)0, ^{
#pragma clang diagnostic pop
CAMutex::Locker locker(mMutex);
if(mDeviceToggleState != ToggleState::SettingBGMDeviceAsDefault)
{
return;
}
// Set BGMDevice back as the default device.
DebugMsg("BGMDeviceControlsList::ToggleDefaultDevice: Setting BGMDevice as default");
BGMLogAndSwallowExceptions("BGMDeviceControlsList::CreateDeviceToggleBackBlock", ([&] {
mAudioSystem.SetDefaultAudioDevice(false, false, mBGMDevice.GetObjectID());
}));
mDeviceToggleState = ToggleState::DisablingNullDevice;
// Cancel the previous block in case it hasn't run yet.
DestroyBlock(mDisableNullDeviceBlock);
mDisableNullDeviceBlock = CreateDisableNullDeviceBlock();
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
if(mDisableNullDeviceBlock)
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kDisableNullDeviceDelay),
dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0),
BGM_Utils::NN(mDisableNullDeviceBlock));
}
#pragma clang diagnostic pop
});
if(!toggleBackBlock)
{
// Pretty sure this should never happen, but the docs aren't completely clear.
LogError("BGMDeviceControlsList::CreateDeviceToggleBackBlock: !toggleBackBlock");
}
return toggleBackBlock;
}
dispatch_block_t __nullable BGMDeviceControlsList::CreateDisableNullDeviceBlock()
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
dispatch_block_t __nullable disableNullDeviceBlock =
dispatch_block_create((dispatch_block_flags_t)0, ^{
#pragma clang diagnostic pop
CAMutex::Locker locker(mMutex);
if(mDeviceToggleState != ToggleState::DisablingNullDevice)
{
return;
}
mDeviceToggleState = ToggleState::NotToggling;
BGMLogAndSwallowExceptions("BGMDeviceControlsList::CreateDisableNullDeviceBlock",
([&] {
CAMutex::Unlocker unlocker(mMutex);
// Hide the null device from the user again.
SetNullDeviceEnabled(false);
}));
BGMAssert(mBGMDevice.IsBGMDevice(), "BGMDevice's AudioObjectID changed");
});
if(!disableNullDeviceBlock)
{
// Pretty sure this should never happen, but the docs aren't completely clear.
LogError("BGMDeviceControlsList::CreateDisableNullDeviceBlock: !disableNullDeviceBlock");
}
return disableNullDeviceBlock;
}
void BGMDeviceControlsList::DestroyBlock(dispatch_block_t __nullable & block)
{
if(!block)
{
return;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
dispatch_block_t& blockNN = (dispatch_block_t&)block;
if(!dispatch_block_testcancel(blockNN))
{
// Stop the block from running if it's currently queued.
dispatch_block_cancel(blockNN);
// Make sure the block isn't currently running. That should almost never be the case.
while(!dispatch_block_testcancel(blockNN))
{
CAMutex::Unlocker unlocker(mMutex);
usleep(10);
}
Block_release(block);
block = nullptr;
}
#pragma clang diagnostic pop
}
#pragma clang assume_nonnull end
-138
View File
@@ -1,138 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMDeviceControlsList.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
#ifndef BGMApp__BGMDeviceControlsList
#define BGMApp__BGMDeviceControlsList
// Local Includes
#include "BGMAudioDevice.h"
// PublicUtility Includes
#include "CAHALAudioDevice.h"
#include "CAHALAudioSystemObject.h"
#include "CAMutex.h"
// System Includes
#include <dispatch/dispatch.h>
#include <AudioToolbox/AudioServices.h>
#pragma clang assume_nonnull begin
class BGMDeviceControlsList
{
#pragma mark Construction/Destruction
public:
BGMDeviceControlsList(AudioObjectID inBGMDevice,
CAHALAudioSystemObject inAudioSystem
= CAHALAudioSystemObject());
~BGMDeviceControlsList();
// Disallow copying
BGMDeviceControlsList(const BGMDeviceControlsList&) = delete;
BGMDeviceControlsList& operator=(const BGMDeviceControlsList&) = delete;
#pragma mark Accessors
/*! @param inBGMDeviceID The ID of BGMDevice. */
void SetBGMDevice(AudioObjectID inBGMDeviceID);
#pragma mark Update Controls List
/*!
Enable the BGMDevice controls (volume and mute currently) that can be matched to controls of
the given device, and disable the ones that can't.
@param inDeviceID The ID of the device.
@return True if BGMDevice's list of controls was updated.
@throws CAException if an error is received from either device.
*/
bool MatchControlsListOf(AudioObjectID inDeviceID);
/*!
After updating BGMDevice's controls list, we need to change the default device so programs
(including OS X's audio UI) will update themselves. We could just change to the real output
device and change back, but that could have side effects the user wouldn't expect. For example,
an app the user has muted might be unmuted for a short period.
Instead we tell BGMDriver to enable the Null Device -- a device that does nothing -- so we can
use it to toggle the default device. The Null Device is normally disabled so it can be hidden
from the user. OS X won't let us make a hidden device temporarily visible or set a hidden
device as the default, so we have to completely remove the Null Device from the system while
we're not using it.
@throws CAException if it fails to enable the Null Device.
*/
void PropagateControlListChange();
#pragma mark Implementation
private:
/*! Lazily initialises the fields used to toggle the default device. */
void InitDeviceToggling();
/*! Changes the OS X default audio device to the Null Device and then back to BGMDevice. */
void ToggleDefaultDevice();
/*!
Enable or disable the Null Device. See PropagateControlListChange and BGM_NullDevice in
BGMDriver.
@throws CAException if we can't get the BGMDriver plug-in audio object from the HAL or the HAL
returns an error when setting kAudioPlugInCustomPropertyNullDeviceActive.
*/
void SetNullDeviceEnabled(bool inEnabled);
dispatch_block_t __nullable CreateDeviceToggleBlock();
dispatch_block_t __nullable CreateDeviceToggleBackBlock();
dispatch_block_t __nullable CreateDisableNullDeviceBlock();
void DestroyBlock(dispatch_block_t __nullable & block);
private:
CAMutex mMutex { "Device Controls List" };
bool mDeviceTogglingInitialised = false;
// OS X 10.9 doesn't have the functions we use for PropagateControlListChange.
bool mCanToggleDeviceOnSystem;
BGMAudioDevice mBGMDevice;
CAHALAudioSystemObject mAudioSystem; // Not guarded by the mutex.
enum ToggleState
{
NotToggling, SettingNullDeviceAsDefault, SettingBGMDeviceAsDefault, DisablingNullDevice
};
BGMDeviceControlsList::ToggleState mDeviceToggleState = ToggleState::NotToggling;
dispatch_block_t __nullable mDeviceToggleBlock = nullptr;
dispatch_block_t __nullable mDeviceToggleBackBlock = nullptr;
dispatch_block_t __nullable mDisableNullDeviceBlock = nullptr;
// These will only ever be null after construction on 10.9, since toggling will be disabled.
dispatch_queue_t __nullable mListenerQueue = nullptr;
AudioObjectPropertyListenerBlock __nullable mListenerBlock = nullptr;
};
#pragma clang assume_nonnull end
#endif /* BGMApp__BGMDeviceControlsList */
-48
View File
@@ -1,48 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMOutputVolumeMenuItem.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Local Includes
#import "BGMAudioDeviceManager.h"
// System Includes
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
@interface BGMOutputVolumeMenuItem : NSMenuItem
// A menu item with a slider for controlling the volume of the output device. Similar to the one in
// macOS's Volume menu extra.
//
// view, slider and deviceLabel are the UI elements from MainMenu.xib.
- (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices
view:(NSView*)view
slider:(NSSlider*)slider
deviceLabel:(NSTextField*)label;
- (void) outputDeviceDidChange;
@end
#pragma clang assume_nonnull end
-319
View File
@@ -1,319 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMOutputVolumeMenuItem.mm
// BGMApp
//
// Copyright © 2017, 2018 Kyle Neideck
//
// Self Include
#import "BGMOutputVolumeMenuItem.h"
// Local Includes
#import "BGM_Utils.h"
#import "BGMAudioDevice.h"
// PublicUtility Includes
#import "CAException.h"
#import "CAPropertyAddress.h"
// System Includes
#import <CoreAudio/AudioHardware.h>
#pragma clang assume_nonnull begin
const float kSliderEpsilon = 1e-10f;
const AudioObjectPropertyScope kScope = kAudioDevicePropertyScopeOutput;
NSString* const __nonnull kGenericOutputDeviceName = @"Output Device";
@implementation BGMOutputVolumeMenuItem {
BGMAudioDeviceManager* audioDevices;
NSTextField* deviceLabel;
NSSlider* volumeSlider;
BGMAudioDevice outputDevice;
AudioObjectPropertyListenerBlock updateSliderListenerBlock;
AudioObjectPropertyListenerBlock updateLabelListenerBlock;
}
// TODO: Show the output device's icon next to its name.
// TODO: Should the menu (bgmMenu) hide after you change the output volume slider, like the normal
// menu bar volume slider does?
// TODO: Move the output devices from Preferences to the main menu so they're slightly easier to
// access?
// TODO: Update the screenshot in the README at some point.
- (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices
view:(NSView*)view
slider:(NSSlider*)slider
deviceLabel:(NSTextField*)label {
if ((self = [super initWithTitle:@"" action:nil keyEquivalent:@""])) {
audioDevices = devices;
deviceLabel = label;
volumeSlider = slider;
outputDevice = audioDevices.outputDevice;
// These are initialised in the methods called below.
updateSliderListenerBlock = nil;
updateLabelListenerBlock = nil;
// Apply our custom view from MainMenu.xib.
self.view = view;
// Set up the UI components in the view.
[self initSlider];
[self updateLabelAndToolTip];
// Register a listener so we can update if the output device's data source changes.
[self addOutputDeviceDataSourceListener];
}
return self;
}
// We currently only use one instance of this class and it's never deallocated, but it's probably
// good practice to define dealloc anyway.
- (void) dealloc {
dispatch_sync(dispatch_get_main_queue(), ^{
// Remove the audio property listeners.
[self removeOutputDeviceDataSourceListener];
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::dealloc", ([&] {
audioDevices.bgmDevice.RemovePropertyListenerBlock(
CAPropertyAddress(kAudioDevicePropertyVolumeScalar, kScope),
dispatch_get_main_queue(),
updateSliderListenerBlock);
}));
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::dealloc", ([&] {
audioDevices.bgmDevice.RemovePropertyListenerBlock(
CAPropertyAddress(kAudioDevicePropertyMute, kScope),
dispatch_get_main_queue(),
updateSliderListenerBlock);
}));
});
}
- (void) initSlider {
BGMAssert([NSThread isMainThread],
"initSlider must be called from the main thread because it calls UI functions.");
volumeSlider.target = self;
volumeSlider.action = @selector(sliderChanged:);
// Initialise the slider.
[self updateVolumeSlider];
// Register a listener that will update the slider when the user changes the volume or
// mutes/unmutes their audio.
BGMOutputVolumeMenuItem* __weak weakSelf = self;
updateSliderListenerBlock =
^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses) {
// The docs for AudioObjectPropertyListenerBlock say inAddresses will always contain
// at least one property the block is listening to, so there's no need to check it.
#pragma unused (inNumberAddresses, inAddresses)
[weakSelf updateVolumeSlider];
};
// Instead of swallowing exceptions, we could try again later, but I doubt it would be worth the
// effort. And the documentation doesn't actually explain what could cause this to fail.
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::initSlider", ([&] {
// Register the listener to receive volume notifications.
audioDevices.bgmDevice.AddPropertyListenerBlock(
CAPropertyAddress(kAudioDevicePropertyVolumeScalar, kScope),
dispatch_get_main_queue(),
updateSliderListenerBlock);
}));
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::initSlider", ([&] {
// Register the same listener for mute/unmute notifications.
audioDevices.bgmDevice.AddPropertyListenerBlock(
CAPropertyAddress(kAudioDevicePropertyMute, kScope),
dispatch_get_main_queue(),
updateSliderListenerBlock);
}));
}
// Updates the value of the output volume slider. Should only be called on the main thread because
// it calls UI functions.
- (void) updateVolumeSlider {
BGMAssert([[NSThread currentThread] isMainThread], "updateVolumeSlider on non-main thread.");
BGMAudioDevice bgmDevice = [audioDevices bgmDevice];
// BGMDevice should never return an error for these calls, so we just swallow any exceptions and
// give up. (That said, we do check mute last so that, if it did throw, it wouldn't affect the
// more important calls.)
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::updateVolumeSlider", ([&] {
BOOL hasVolume = bgmDevice.HasSettableMasterVolume(kScope);
// If the device doesn't have a master volume control, we disable the slider and set it to
// full (or to zero, if muted).
volumeSlider.enabled = hasVolume;
if (hasVolume) {
// Set the slider to the current output volume. The slider values and volume values are
// both from 0 to 1, so we can use the volume as is.
volumeSlider.doubleValue =
bgmDevice.GetVolumeControlScalarValue(kScope, kMasterChannel);
} else {
volumeSlider.doubleValue = 1.0;
}
// Set the slider to zero if the device is muted.
if (bgmDevice.HasSettableMasterMute(kScope) &&
bgmDevice.GetMuteControlValue(kScope, kMasterChannel)) {
volumeSlider.doubleValue = 0.0;
}
}));
};
- (void) addOutputDeviceDataSourceListener {
// Create the block that updates deviceLabel when the output device's data source changes, e.g.
// from Internal Speakers to Headphones.
if (!updateLabelListenerBlock) {
BGMOutputVolumeMenuItem* __weak weakSelf = self;
updateLabelListenerBlock =
^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses) {
// The docs for AudioObjectPropertyListenerBlock say inAddresses will always contain
// at least one property the block is listening to, so there's no need to check it.
#pragma unused (inNumberAddresses, inAddresses)
[weakSelf updateLabelAndToolTip];
};
}
// Register the listener.
//
// Instead of swallowing exceptions, we could try again later, but I doubt it would be worth the
// effort. And the documentation doesn't actually explain what could cause this to fail.
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::addOutputDeviceDataSourceListener", ([&] {
outputDevice.AddPropertyListenerBlock(
CAPropertyAddress(kAudioDevicePropertyDataSource, kScope),
dispatch_get_main_queue(),
updateLabelListenerBlock);
}));
}
- (void) removeOutputDeviceDataSourceListener {
BGMLogAndSwallowExceptions("BGMOutputVolumeMenuItem::removeOutputDeviceDataSourceListener",
([&] {
outputDevice.RemovePropertyListenerBlock(
CAPropertyAddress(kAudioDevicePropertyDataSource, kScope),
dispatch_get_main_queue(),
updateLabelListenerBlock);
}));
}
- (void) outputDeviceDidChange {
dispatch_async(dispatch_get_main_queue(), ^{
// Remove the data source listener from the previous output device.
[self removeOutputDeviceDataSourceListener];
// Add it to the new output device.
outputDevice = audioDevices.outputDevice;
[self addOutputDeviceDataSourceListener];
// Update the label to use the name of the new output device.
[self updateLabelAndToolTip];
// Set the slider to the volume of the new device.
[self updateVolumeSlider];
});
}
// Sets the label to the output device's name or, if it has one, its current datasource. If it has a
// datasource, the device's name is set as this menu item's tooltip. Falls back to a generic name if
// the device returns an error when queried.
- (void) updateLabelAndToolTip {
BOOL didSetLabel = NO;
try {
if (outputDevice.HasDataSourceControl(kScope, kMasterChannel)) {
// The device has datasources, so use the current datasource's name like macOS does.
UInt32 dataSourceID = outputDevice.GetCurrentDataSourceID(kScope, kMasterChannel);
deviceLabel.stringValue =
(__bridge_transfer NSString*)outputDevice.CopyDataSourceNameForID(kScope,
kMasterChannel,
dataSourceID);
didSetLabel = YES; // So we know not to change the text if setting the tooltip fails.
// Set the tooltip of the menu item (the container) rather than the label because menu
// items' tooltips will still appear when a different app is focused and, as far as I
// know, BGMApp should never be the foreground app.
self.toolTip = (__bridge_transfer NSString*)outputDevice.CopyName();
} else {
deviceLabel.stringValue = (__bridge_transfer NSString*)outputDevice.CopyName();
self.toolTip = nil;
}
} catch (const CAException& e) {
BGMLogException(e);
// The device returned an error, so set the label to a generic device name, since we don't
// want to leave it set to the previous device's name.
self.toolTip = nil;
if (!didSetLabel) {
deviceLabel.stringValue = kGenericOutputDeviceName;
}
}
DebugMsg("BGMOutputVolumeMenuItem::updateLabelAndToolTip: Label: '%s' Tooltip: '%s'",
deviceLabel.stringValue.UTF8String,
self.toolTip.UTF8String);
// Take the label out of the accessibility hierarchy, which also moves the slider up a level.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 // MAC_OS_X_VERSION_10_10
if ([deviceLabel.cell respondsToSelector:@selector(setAccessibilityElement:)]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
deviceLabel.cell.accessibilityElement = NO;
#pragma clang diagnostic pop
}
#endif
}
// Called when the user slides the slider.
- (IBAction) sliderChanged:(NSSlider*)sender {
float newValue = sender.floatValue;
DebugMsg("BGMOutputVolumeMenuItem::sliderChanged: New value: %f", newValue);
// Update BGMDevice's volume to the new value selected by the user.
try {
// The slider values and volume values are both from 0.0f to 1.0f, so we can use the slider
// value as is.
audioDevices.bgmDevice.SetVolumeControlScalarValue(kScope, kMasterChannel, newValue);
// Mute BGMDevice if they set the slider to zero, and unmute it for non-zero. Muting makes
// sure the audio doesn't play very quietly instead being completely silent. This matches
// the behaviour of the Volume menu built-in to macOS.
if (audioDevices.bgmDevice.HasMuteControl(kScope, kMasterChannel)) {
audioDevices.bgmDevice.SetMuteControlValue(kScope,
kMasterChannel,
(newValue < kSliderEpsilon));
}
} catch (const CAException& e) {
NSLog(@"BGMOutputVolumeMenuItem::sliderChanged: Failed to set volume (%d)", e.GetError());
}
}
@end
#pragma clang assume_nonnull end
File diff suppressed because it is too large Load Diff
+35 -88
View File
@@ -17,7 +17,7 @@
// BGMPlayThrough.h
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Reads audio from an input device and immediately writes it to an output device. We currently use this class with the input
// device always set to BGMDevice and the output device set to the one selected in the preferences menu.
@@ -28,7 +28,7 @@
// sample code from 2004. This class's main addition is pausing playthrough when idle to save CPU.
//
// Playing audio with this class uses more CPU, mostly in the coreaudiod process, than playing audio normally because we need
// an input IOProc as well as an output one, and BGMDriver is running in addition to the output device's driver. For me, it
// an input IO proc as well as an output one, and BGMDriver is running in addition to the output device's driver. For me, it
// usually adds around 1-2% (as a percentage of total usage -- it doesn't seem to be relative to the CPU used when playing
// audio normally).
//
@@ -36,20 +36,14 @@
// a future release.
//
#ifndef BGMApp__BGMPlayThrough
#define BGMApp__BGMPlayThrough
// Local Includes
#include "BGMAudioDevice.h"
#ifndef __BGMApp__BGMPlayThrough__
#define __BGMApp__BGMPlayThrough__
// PublicUtility Includes
#include "CARingBuffer.h"
#include "CAHALAudioDevice.h"
#include "CAMutex.h"
// STL Includes
#include <atomic>
#include <algorithm>
// System Includes
#include <mach/semaphore.h>
@@ -58,79 +52,48 @@
class BGMPlayThrough
{
public:
// Error codes
static const OSStatus kDeviceNotStarting = 100;
public:
BGMPlayThrough(BGMAudioDevice inInputDevice, BGMAudioDevice inOutputDevice);
BGMPlayThrough(CAHALAudioDevice inInputDevice, CAHALAudioDevice inOutputDevice);
~BGMPlayThrough();
// Disallow copying
BGMPlayThrough(const BGMPlayThrough&) = delete;
BGMPlayThrough& operator=(const BGMPlayThrough&) = delete;
// Move constructor/assignment
BGMPlayThrough(BGMPlayThrough&& inPlayThrough) { Swap(inPlayThrough); }
BGMPlayThrough& operator=(BGMPlayThrough&& inPlayThrough) { Swap(inPlayThrough); return *this; }
#ifdef __OBJC__
// Only intended as a convenience (hack) for Objective-C instance vars. Call
// SetDevices to initialise the instance before using it.
// Only intended as a convenience for Objective-C instance vars
BGMPlayThrough() { }
#endif
private:
/*! @throws CAException */
void Init(BGMAudioDevice inInputDevice, BGMAudioDevice inOutputDevice);
public:
/*! @throws CAException */
void Swap(BGMPlayThrough& inPlayThrough);
void Activate();
/*! @throws CAException */
void Deactivate();
private:
void AllocateBuffer();
static bool IsBGMDevice(CAHALAudioDevice inDevice);
/*! @throws CAException */
void CreateIOProcIDs();
/*! @throws CAException */
void DestroyIOProcIDs();
/*!
@return True if both IOProcs are stopped.
@nonthreadsafe
*/
bool CheckIOProcsAreStopped() const noexcept; // TODO: REQUIRES(mStateMutex);
void CreateIOProcs();
void DestroyIOProcs();
public:
/*!
Pass null for either param to only change one of the devices.
@throws CAException
*/
void SetDevices(const BGMAudioDevice* __nullable inInputDevice,
const BGMAudioDevice* __nullable inOutputDevice);
/*! @throws CAException */
void Start();
// Blocks until the output device has started our IOProc. Returns one of the error constants
// from AudioHardwareBase.h (e.g. kAudioHardwareNoError).
OSStatus WaitForOutputDeviceToStart() noexcept;
OSStatus Start();
OSStatus WaitForOutputDeviceToStart();
private:
void ReleaseThreadsWaitingForOutputToStart() const;
public:
OSStatus Stop();
void StopIfIdle();
private:
static OSStatus BGMDeviceListenerProc(AudioObjectID inObjectID,
UInt32 inNumberAddresses,
const AudioObjectPropertyAddress* inAddresses,
void* __nullable inClientData);
static void HandleBGMDeviceIsRunning(BGMPlayThrough* refCon);
static void HandleBGMDeviceIsRunningSomewhereOtherThanBGMApp(BGMPlayThrough* refCon);
static bool IsRunningSomewhereOtherThanBGMApp(const BGMAudioDevice& inBGMDevice);
static bool RunningSomewhereOtherThanBGMApp(const CAHALAudioDevice inBGMDevice);
static OSStatus InputDeviceIOProc(AudioObjectID inDevice,
const AudioTimeStamp* inNow,
@@ -146,22 +109,6 @@ private:
AudioBufferList* outOutputData,
const AudioTimeStamp* inOutputTime,
void* __nullable inClientData);
// The state of an IOProc. Used by the IOProc to tell other threads when it's finished starting. Used by other
// threads to tell the IOProc to stop itself. (Probably used for other things as well.)
enum class IOState
{
Stopped, Starting, Running, Stopping
};
// The IOProcs call this to update their IOState member. Also stops the IOProc if its state has been set to Stopping.
// Returns true if it changes the state.
static bool UpdateIOProcState(const char* __nullable callerName,
std::atomic<IOState>& inState,
AudioDeviceIOProcID __nullable inIOProcID,
BGMAudioDevice& inDevice,
IOState& outNewState);
static void HandleRingBufferError(CARingBufferError err,
const char* methodName,
const char* callReturningErr);
@@ -169,41 +116,41 @@ private:
private:
CARingBuffer mBuffer;
AudioDeviceIOProcID __nullable mInputDeviceIOProcID { nullptr };
AudioDeviceIOProcID __nullable mOutputDeviceIOProcID { nullptr };
AudioDeviceIOProcID mInputDeviceIOProcID;
AudioDeviceIOProcID mOutputDeviceIOProcID;
BGMAudioDevice mInputDevice { kAudioObjectUnknown };
BGMAudioDevice mOutputDevice { kAudioObjectUnknown };
CAHALAudioDevice mInputDevice { kAudioDeviceUnknown };
CAHALAudioDevice mOutputDevice { kAudioDeviceUnknown };
CAMutex mStateMutex { "Playthrough state" };
// Signalled when the output IOProc runs. We use it to tell BGMDriver when the output device is ready to receive audio data.
// Signalled when the output IO proc runs. We use it to tell BGMDriver when the output device is ready to receive audio data.
semaphore_t mOutputDeviceIOProcSemaphore { SEMAPHORE_NULL };
bool mActive = false;
bool mPlayingThrough = false;
UInt64 mLastNotifiedIOStoppedOnBGMDevice { 0 };
std::atomic<IOState> mInputDeviceIOProcState { IOState::Stopped };
std::atomic<IOState> mOutputDeviceIOProcState { IOState::Stopped };
UInt64 mLastNotifiedIOStoppedOnBGMDevice;
bool mInputDeviceIOProcShouldStop = false;
bool mOutputDeviceIOProcShouldStop = false;
// For debug logging.
UInt64 mToldOutputDeviceToStartAt { 0 };
UInt64 mToldOutputDeviceToStartAt;
// IOProc vars. (Should only be used inside IOProcs.)
// IO proc vars. (Should only be used inside IO procs.)
// The earliest/latest sample times seen by the IOProcs since starting playthrough. -1 for unset.
// The earliest/latest sample times seen by the IO procs since starting playthrough. -1 for unset.
Float64 mFirstInputSampleTime = -1;
Float64 mLastInputSampleTime = -1;
Float64 mLastOutputSampleTime = -1;
// Subtract this from the output time to get the input time.
Float64 mInToOutSampleOffset { 0.0 };
Float64 mInToOutSampleOffset;
};
#pragma clang assume_nonnull end
#endif /* BGMApp__BGMPlayThrough */
#endif /* __BGMApp__BGMPlayThrough__ */
-56
View File
@@ -1,56 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMSystemSoundsVolume.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// The menu item with the volume slider that controls system-related sounds. The slider is used to
// set the volume of the instance of BGMDevice that system sounds are played on, i.e. the audio
// device returned by BGMBackgroundMusicDevice::GetUISoundsBGMDeviceInstance.
//
// System sounds are any sounds played using the audio device macOS is set to use as the device
// "for system related sound from the alert sound to digital call progress". See
// kAudioHardwarePropertyDefaultSystemOutputDevice in AudioHardware.h. They can be played by any
// app, though most apps use systemsoundserverd to play their system sounds, which means BGMDriver
// can't tell which app is actually playing the sounds.
//
// Local Includes
#import "BGMAudioDevice.h"
// System Includes
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
@interface BGMSystemSoundsVolume : NSObject
// The volume level of uiSoundsDevice will be used to set the slider's initial position and will be
// updated when the user moves the slider. view and slider are the UI elements from MainMenu.xib.
- (instancetype) initWithUISoundsDevice:(BGMAudioDevice)uiSoundsDevice
view:(NSView*)view
slider:(NSSlider*)slider;
// The menu item with the volume slider for system sounds.
@property (readonly) NSMenuItem* menuItem;
@end
#pragma clang assume_nonnull end
-92
View File
@@ -1,92 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMSystemSoundsVolume.mm
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Self Include
#import "BGMSystemSoundsVolume.h"
// Local Includes
#import "BGM_Types.h"
#import "BGM_Utils.h"
#pragma clang assume_nonnull begin
// TODO: It's a bit confusing that this slider's default position is all the way right, but the App
// Volumes sliders default to 50%. After you move the slider there's no way to tell how to put
// it back to its normal position.
NSString* const kMenuItemToolTip =
@"Alerts, notification sounds, etc. Usually short. Can be played by any app.";
@implementation BGMSystemSoundsVolume {
BGMAudioDevice uiSoundsDevice;
NSSlider* volumeSlider;
}
- (instancetype) initWithUISoundsDevice:(BGMAudioDevice)inUISoundsDevice
view:(NSView*)inView
slider:(NSSlider*)inSlider {
if ((self = [super init])) {
uiSoundsDevice = inUISoundsDevice;
volumeSlider = inSlider;
_menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
_menuItem.toolTip = kMenuItemToolTip;
// Apply our custom view from MainMenu.xib. It's very similar to the one for app volumes.
_menuItem.view = inView;
try {
volumeSlider.floatValue =
uiSoundsDevice.GetVolumeControlScalarValue(kAudioObjectPropertyScopeOutput,
kMasterChannel);
} catch (const CAException& e) {
BGMLogException(e);
volumeSlider.floatValue = 1.0f; // Full volume
}
volumeSlider.target = self;
volumeSlider.action = @selector(systemSoundsSliderChanged:);
}
return self;
}
- (void) systemSoundsSliderChanged:(id)sender {
#pragma unused(sender)
float sliderLevel = volumeSlider.floatValue;
BGMAssert((sliderLevel >= 0.0f) && (sliderLevel <= 1.0f), "Invalid value from slider");
DebugMsg("BGMSystemSoundsVolume::systemSoundsSliderChanged: UI sounds volume: %f", sliderLevel);
BGMLogAndSwallowExceptions("BGMSystemSoundsVolume::systemSoundsSliderChanged", ([&] {
uiSoundsDevice.SetVolumeControlScalarValue(kAudioObjectPropertyScopeOutput,
kMasterChannel,
sliderLevel);
}));
}
@end
#pragma clang assume_nonnull end
-86
View File
@@ -1,86 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMTermination.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Cleans up if BGMApp crashes because of an uncaught C++ or Objective C exception, or is sent
// SIGINT/SIGTERM/SIGQUIT. Currently, it just changes the default output device from BGMDevice to
// the real output device and records debug info for some types of crashes.
//
// BGMXPCHelper also changes the default device if BGMApp disconnects and leaves BGMDevice as the
// default. This handles cases like segfaults where it wouldn't be safe to clean up from the
// crashing process.
//
#ifndef BGMApp__BGMTermination
#define BGMApp__BGMTermination
// Local Includes
#import "BGMAudioDeviceManager.h"
// PublicUtility Includes
#import "CAPThread.h"
// STL Includes
#import <exception>
#pragma clang assume_nonnull begin
class BGMTermination
{
public:
/*!
Starts a thread that will clean up before exiting if BGMApp receives SIGINT, SIGTERM or
SIGQUIT. Sets a similar clean up function to run if BGMApp terminates due to an uncaught
exception.
*/
static void SetUpTerminationCleanUp(BGMAudioDeviceManager* inAudioDevices);
/*! Some commented out ways to have BGMApp crash for testing. Does nothing if unmodified. */
static void TestCrash() __attribute__((noinline));
private:
static void StartExitSignalsThread();
static void CleanUpAudioDevices();
/*! Adds some info about the uncaught exception that caused a crash to the crash report. */
static void AddCurrentExceptionToCrashReport();
/*! The entry point for sExitSignalsThread. */
static void* __nullable ExitSignalsProc(void* __nullable ignored);
/*! The thread that handles SIGQUIT, SIGTERM and SIGINT. Never destroyed. */
static CAPThread* const sExitSignalsThread;
static sigset_t sExitSignals;
/*! The function that handles std::terminate by default. */
static std::terminate_handler sOriginalTerminateHandler;
/*! The audio device manager. (Must be static to be accessed in our std::terminate_handler.) */
static BGMAudioDeviceManager* __nullable sAudioDevices;
};
#pragma clang assume_nonnull end
#endif /* BGMApp__BGMTermination */
-211
View File
@@ -1,211 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMTermination.mm
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Self Include
#import "BGMTermination.h"
// Local Includes
#import "BGM_Utils.h"
// PublicUtility Includes
#import "CADebugMacros.h"
// STL Includes
#import <string>
// System Includes
#import <signal.h>
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
std::terminate_handler BGMTermination::sOriginalTerminateHandler = std::get_terminate();
CAPThread* const BGMTermination::sExitSignalsThread = new CAPThread(ExitSignalsProc, nullptr);
sigset_t BGMTermination::sExitSignals;
BGMAudioDeviceManager* __nullable BGMTermination::sAudioDevices = nullptr;
// If BGMApp crashes, CrashReporter will read this string from our process' memory and include it in
// the crash report.
const char* __nullable __crashreporter_info__ = nullptr;
// Set the REFERENCED_DYNAMICALLY bit so the symbol doesn't get stripped from the binary. See
// <https://developer.apple.com/library/content/documentation/DeveloperTools/Reference/Assembler/040-Assembler_Directives/asm_directives.html>
// and
// <https://github.com/aidansteele/osx-abi-macho-file-format-reference#symbol-table-and-related-data-structures>
// (Ctrl+F "REFERENCED_DYNAMICALLY").
asm(".desc ___crashreporter_info__, 0x10");
// static
void BGMTermination::TestCrash()
{
// To give BGMApp a few seconds to finish launching and then crash:
//
// dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)),
// dispatch_get_main_queue(),
// ^{
// BGMTermination::TestCrash();
// });
// throw CAException(kAudioHardwareBadDeviceError);
// throw BGM_InvalidClientRelativeVolumeException();
// std::string().at(1);
// *reinterpret_cast<int*>(0x1234) = 9;
// [NSException raise:@"ObjC Test Exception" format:@"The description of the test exception."];
}
// static
void BGMTermination::SetUpTerminationCleanUp(BGMAudioDeviceManager* inAudioDevices)
{
sAudioDevices = inAudioDevices;
StartExitSignalsThread();
// Wrap the default handler for std::terminate, which is called if BGMApp crashes because of an
// uncaught C++ or Objective C exception, so we can clean up first.
sOriginalTerminateHandler = std::get_terminate();
std::set_terminate([] {
CleanUpAudioDevices();
AddCurrentExceptionToCrashReport();
// Call the default terminate handler to finish crashing normally.
sOriginalTerminateHandler();
});
}
// static
void BGMTermination::StartExitSignalsThread()
{
// Block the signals the thread will handle, so they can be unblocked for just that thread.
sigemptyset(&sExitSignals);
sigaddset(&sExitSignals, SIGQUIT);
sigaddset(&sExitSignals, SIGTERM);
sigaddset(&sExitSignals, SIGINT);
if(pthread_sigmask(SIG_BLOCK, &sExitSignals, nullptr) != 0)
{
perror("pthread_sigmask");
return; // This would just mean the signals would be handled by the default handlers.
}
// Start the thread.
sExitSignalsThread->Start();
}
// static
void BGMTermination::CleanUpAudioDevices()
{
// BGMXPCHelper would set the output device back if we didn't do it here, but in general
// it's better for things to work even if BGMXPCHelper isn't installed.
if(sAudioDevices)
{
[sAudioDevices unsetBGMDeviceAsOSDefault];
}
}
// static
void BGMTermination::AddCurrentExceptionToCrashReport()
{
std::exception_ptr exceptionPtr = std::current_exception();
if(exceptionPtr)
{
// The message to add to the crash report (and log).
std::string* msg = new std::string("");
// Throw the exception again and catch it so we can get some info if it's a CAException. If
// it's a std::exception, the default terminate handler will do the same thing, so we can
// just ignore it here.
try
{
std::rethrow_exception(exceptionPtr);
}
catch(const CAException& e)
{
OSStatus err = e.GetError();
const char err4CC[5] = CA4CCToCString(err);
msg = new std::string("Uncaught CAException. Error code: '");
msg->append(err4CC);
msg->append("' (");
msg->append(std::to_string(err));
msg->append(").");
}
catch(...)
{
}
// CrashReporter will read the contents of __crashreporter_info__.
__crashreporter_info__ = msg->c_str();
NSLog(@"%s", msg->c_str());
}
}
// The entry point for the thread that handles SIGQUIT, SIGTERM and SIGINT.
// static
void* __nullable BGMTermination::ExitSignalsProc(void* __nullable ignored)
{
#pragma unused (ignored)
DebugMsg("BGMTermination::ExitSignalsProc: Thread started.");
int signal = -1;
// Wait until we receive a signal.
while((signal != SIGINT) && (signal != SIGTERM) && (signal != SIGQUIT))
{
if(sigwait(&sExitSignals, &signal) != 0)
{
perror("sigwait");
return nullptr;
}
}
if(signal == SIGINT)
{
NSLog(@"Interrupted.");
}
else if(signal == SIGTERM)
{
NSLog(@"Exiting.");
}
CleanUpAudioDevices();
// Unblock the signal and resend it to ourselves so it will be handled by the default handler
// and exit BGMApp.
if(pthread_sigmask(SIG_UNBLOCK, &sExitSignals, nullptr) != 0)
{
perror("pthread_sigmask");
abort();
}
raise(signal);
return nullptr;
}
#pragma clang assume_nonnull end
-46
View File
@@ -1,46 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMUserDefaults.h
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
//
// A simple wrapper around our use of NSUserDefaults. Used to store the preferences/state that only
// apply to BGMApp. The others are stored on BGMDriver.
//
// System includes
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
@interface BGMUserDefaults : NSObject
// If inDefaults is nil, settings are not loaded from or saved to disk, which is useful for testing.
- (instancetype) initWithDefaults:(NSUserDefaults* __nullable)inDefaults;
// The musicPlayerID (see BGMMusicPlayer.h), as a string, of the music player selected by the user.
// Must be either null or a string that can be parsed by NSUUID.
@property NSString* __nullable selectedMusicPlayerID;
@property BOOL autoPauseMusicEnabled;
@end
#pragma clang assume_nonnull end
-106
View File
@@ -1,106 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMUserDefaults.m
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
//
// Self include
#import "BGMUserDefaults.h"
#pragma clang assume_nonnull begin
// Keys
static NSString* const BGMDefaults_AutoPauseMusicEnabled = @"AutoPauseMusicEnabled";
static NSString* const BGMDefaults_SelectedMusicPlayerID = @"SelectedMusicPlayerID";
@implementation BGMUserDefaults {
// The defaults object wrapped by this object.
NSUserDefaults* defaults;
// When we're not persisting defaults, settings are stored in this dictionary instead. This
// var should only be accessed if 'defaults' is nil.
NSMutableDictionary<NSString*,id>* transientDefaults;
}
- (instancetype) initWithDefaults:(NSUserDefaults* __nullable)inDefaults {
if ((self = [super init])) {
defaults = inDefaults;
// Register the settings defaults.
//
// iTunes is the default music player, but we don't set BGMDefaults_SelectedMusicPlayerID
// here so we know when it's never been set. (If it hasn't, we try using BGMDevice's
// kAudioDeviceCustomPropertyMusicPlayerBundleID property to tell which music player should
// be selected. See BGMMusicPlayers.)
NSDictionary* defaultsDict = @{ BGMDefaults_AutoPauseMusicEnabled: @YES };
if (defaults) {
[defaults registerDefaults:defaultsDict];
} else {
transientDefaults = [defaultsDict mutableCopy];
}
}
return self;
}
- (NSString* __nullable) selectedMusicPlayerID {
return [self get:BGMDefaults_SelectedMusicPlayerID];
}
- (void) setSelectedMusicPlayerID:(NSString* __nullable)selectedMusicPlayerID {
[self set:BGMDefaults_SelectedMusicPlayerID to:selectedMusicPlayerID];
}
- (BOOL) autoPauseMusicEnabled {
return [self getBool:BGMDefaults_AutoPauseMusicEnabled];
}
- (void) setAutoPauseMusicEnabled:(BOOL)autoPauseMusicEnabled {
[self setBool:BGMDefaults_AutoPauseMusicEnabled to:autoPauseMusicEnabled];
}
- (id __nullable) get:(NSString*)key {
return defaults ? [defaults objectForKey:key] : transientDefaults[key];
}
- (void) set:(NSString*)key to:(NSObject<NSCopying,NSSecureCoding>* __nullable)value {
if (defaults) {
[defaults setObject:value forKey:key];
} else {
transientDefaults[key] = value;
}
}
- (BOOL) getBool:(NSString*)key {
return defaults ? [defaults boolForKey:key] : [transientDefaults[key] boolValue];
}
- (void) setBool:(NSString*)key to:(BOOL)value {
if (defaults) {
[defaults setBool:value forKey:key];
} else {
transientDefaults[key] = [NSNumber numberWithBool:value];
}
}
@end
#pragma clang assume_nonnull end
+4 -34
View File
@@ -17,15 +17,12 @@
// BGMXPCListener.mm
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMXPCListener.h"
// Local Includes
#import "BGMPlayThrough.h" // For kDeviceNotStarting.
#pragma clang assume_nonnull begin
@@ -54,9 +51,6 @@
// Set up the connection to BGMXPCHelper.
[self initHelperConnectionWithErrorHandler:errorHandler];
// Pass the connection to the audio device manager so it can tell BGMXPCHelper the output device's ID.
[audioDevices setBGMXPCHelperConnection:helperConnection];
}
return self;
@@ -147,9 +141,6 @@
retryAfterTimeout(nil);
};
}];
// Pass the new connection to the audio device manager.
[audioDevices setBGMXPCHelperConnection:helperConnection];
}
- (void) dealloc {
@@ -183,27 +174,12 @@
return YES;
}
- (void) startPlayThroughSyncWithReply:(void (^)(NSError*))reply forUISoundsDevice:(BOOL)isUI {
- (void) waitForOutputDeviceToStartWithReply:(void (^)(NSError*))reply {
OSStatus err = [audioDevices waitForOutputDeviceToStart];
NSString* description;
OSStatus err;
try {
err = [audioDevices startPlayThroughSync:isUI];
} catch (CAException e) {
// startPlayThroughSync should never throw a CAException, but check anyway in case we change that at some point.
LogError("BGMXPCListener::startPlayThroughSyncWithReply: Caught CAException (%d). Replying kBGMXPC_HardwareError.",
e.GetError());
err = kBGMXPC_HardwareError;
} catch (...) {
LogError("BGMXPCListener::startPlayThroughSyncWithReply: Caught unknown exception. Replying kBGMXPC_InternalError.");
err = kBGMXPC_InternalError;
#if DEBUG
throw;
#endif
}
switch (err) {
case kAudioHardwareNoError:
case noErr:
description = @"BGMApp started the output device.";
err = kBGMXPC_Success;
break;
@@ -218,12 +194,6 @@
err = kBGMXPC_HardwareError;
break;
case kBGMErrorCode_ReturningEarly:
// We have to send a more specific error in this case because BGMDevice handles this case differently.
description = @"BGMApp could not wait for the output device to be ready for IO.";
err = kBGMXPC_ReturningEarlyError;
break;
default:
description = @"Unknown error while waiting for the output device.";
err = kBGMXPC_InternalError;
+57 -233
View File
@@ -1,10 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14313.18" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="9531" systemVersion="14F1509" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<development version="8000" identifier="xcode"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14313.18"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="9531"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
@@ -14,18 +12,13 @@
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="BGMAppDelegate">
<customObject id="Voe-Tx-rLC" customClass="AppDelegate">
<connections>
<outlet property="aboutPanel" destination="Cf4-3V-gl1" id="cgo-Hw-rE2"/>
<outlet property="aboutPanelLicenseView" destination="LSG-PF-cl8" id="mbu-kv-Jfc"/>
<outlet property="appVolumeView" destination="MWB-XH-kFI" id="eFA-RN-VMC"/>
<outlet property="autoPauseMenuItemUnwrapped" destination="nHv-T8-1nb" id="Lie-Cx-jw6"/>
<outlet property="autoPauseMenuItem" destination="nHv-T8-1nb" id="skN-ap-dre"/>
<outlet property="bgmMenu" destination="8AN-nh-rEe" id="UWn-BX-eLy"/>
<outlet property="outputVolumeLabel" destination="wfC-C6-SLv" id="Nuf-mo-osG"/>
<outlet property="outputVolumeSlider" destination="9Ru-Sc-dqC" id="wv0-Md-BwF"/>
<outlet property="outputVolumeView" destination="JOz-H1-mj9" id="xeJ-fk-NMI"/>
<outlet property="systemSoundsSlider" destination="gyd-WV-2ju" id="NEe-5W-EI5"/>
<outlet property="systemSoundsView" destination="dBD-CE-4dw" id="4SD-Z1-akp"/>
</connections>
</customObject>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
@@ -33,10 +26,12 @@
<items>
<menuItem title="Auto-pause Music" tag="2" id="nHv-T8-1nb">
<modifierMask key="keyEquivalentModifierMask"/>
<accessibility help="Enable to automatically pause your selected music player when a different app starts playing audio." identifier="Auto-pause enabled"/>
<connections>
<action selector="toggleAutoPauseMusic:" target="Voe-Tx-rLC" id="fL3-wA-voV"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="ZGd-Pq-YeA"/>
<menuItem title="Volumes" tag="3" enabled="NO" id="8PP-wA-Pae">
<menuItem title="App Volumes" tag="3" enabled="NO" id="8PP-wA-Pae">
<modifierMask key="keyEquivalentModifierMask"/>
</menuItem>
<menuItem isSeparatorItem="YES" tag="4" id="rkf-nx-H2J"/>
@@ -65,16 +60,14 @@
</connections>
</menuItem>
</items>
<accessibility description="Background Music Main Menu" identifier="MainMenu"/>
<point key="canvasLocation" x="-184" y="-69.5"/>
</menu>
<customView wantsLayer="YES" id="MWB-XH-kFI">
<rect key="frame" x="0.0" y="0.0" width="269" height="47"/>
<customView id="MWB-XH-kFI">
<rect key="frame" x="0.0" y="0.0" width="264" height="20"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<subviews>
<textField identifier="AppName" horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Xmd-bg-huG" customClass="BGMAVM_AppNameLabel">
<rect key="frame" x="42" y="28" width="115" height="14"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textField identifier="AppName" horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Xmd-bg-huG" customClass="BGMAVM_AppNameLabel">
<rect key="frame" x="58" y="4" width="115" height="14"/>
<textFieldCell key="cell" controlSize="small" lineBreakMode="truncatingTail" allowsUndo="NO" sendsActionOnEndEditing="YES" alignment="left" title="App name here" usesSingleLineMode="YES" id="ZHF-ZW-Oqg">
<font key="font" metaFont="smallSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
@@ -82,177 +75,110 @@
</textFieldCell>
</textField>
<imageView identifier="AppIcon" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="W04-iT-IUw" customClass="BGMAVM_AppIcon">
<rect key="frame" x="20" y="27" width="16" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<rect key="frame" x="36" y="3" width="16" height="16"/>
<imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" id="6QQ-oO-HxF"/>
</imageView>
<slider verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="I1l-Ci-4md" customClass="BGMAVM_VolumeSlider">
<rect key="frame" x="163" y="27" width="74" height="15"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<rect key="frame" x="179" y="2" width="74" height="17"/>
<sliderCell key="cell" controlSize="small" continuous="YES" state="on" alignment="left" maxValue="100" doubleValue="50" tickMarkPosition="above" sliderType="linear" id="Jmg-df-9Xl"/>
<accessibility description="Volume"/>
</slider>
<slider toolTip="Pan" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="2mh-uO-kOV" customClass="BGMAVM_PanSlider">
<rect key="frame" x="163" y="7" width="74" height="15"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<sliderCell key="cell" controlSize="mini" continuous="YES" state="on" alignment="left" minValue="-100" maxValue="100" tickMarkPosition="below" numberOfTickMarks="1" sliderType="linear" id="ccM-Mt-93g"/>
<accessibility description="Pan"/>
</slider>
<button verticalHuggingPriority="750" fixedFrame="YES" tag="1" springLoaded="YES" translatesAutoresizingMaskIntoConstraints="NO" id="vTG-n6-GxY" customClass="BGMAVM_ShowMoreControlsButton">
<rect key="frame" x="243" y="27" width="16" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<contentFilters>
<ciFilter name="CIAffineTransform">
<configuration>
<null key="inputImage"/>
<affineTransform key="inputTransform" m11="1" m12="0.0" m21="0.0" m22="1" tX="0.0" tY="2"/>
</configuration>
</ciFilter>
</contentFilters>
<buttonCell key="cell" type="square" title="⌃" bezelStyle="shadowlessSquare" image="buttonCell:IXo-C7-3uE:image" alignment="center" lineBreakMode="truncatingTail" imageScaling="proportionallyDown" inset="2" id="IXo-C7-3uE">
<behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/>
<font key="font" metaFont="system"/>
</buttonCell>
</button>
<textField identifier="PanLeft" toolTip="Pan" horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="9jc-9i-jw2">
<rect key="frame" x="162" y="-1" width="12" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="L" id="hgE-7A-bez">
<font key="font" metaFont="miniSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField identifier="PanRight" toolTip="Pan" horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="1lZ-hX-6Kl">
<rect key="frame" x="228" y="-1" width="12" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="R" id="lzr-NO-0Na">
<font key="font" metaFont="miniSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
<point key="canvasLocation" x="117" y="-45"/>
<point key="canvasLocation" x="81" y="-111"/>
</customView>
<window allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" restorable="NO" hidesOnDeactivate="YES" visibleAtLaunch="NO" animationBehavior="default" id="Cf4-3V-gl1" customClass="NSPanel">
<window allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" restorable="NO" hidesOnDeactivate="YES" oneShot="NO" releasedWhenClosed="NO" showsToolbarButton="NO" visibleAtLaunch="NO" animationBehavior="default" id="Cf4-3V-gl1" customClass="NSPanel">
<windowStyleMask key="styleMask" titled="YES" closable="YES" utility="YES"/>
<windowPositionMask key="initialPositionMask" topStrut="YES"/>
<rect key="contentRect" x="248" y="350" width="1002" height="335"/>
<rect key="screenRect" x="0.0" y="0.0" width="1440" height="877"/>
<rect key="contentRect" x="248" y="350" width="748" height="293"/>
<rect key="screenRect" x="0.0" y="0.0" width="1280" height="777"/>
<view key="contentView" id="HlB-hX-Y0Y">
<rect key="frame" x="0.0" y="0.0" width="1002" height="335"/>
<rect key="frame" x="0.0" y="0.0" width="748" height="293"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="r51-dd-LGP">
<rect key="frame" x="71" y="125" width="240" height="22"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="r51-dd-LGP">
<rect key="frame" x="18" y="78" width="240" height="22"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Background Music" id="Dw2-nu-eBQ">
<font key="font" size="18" name=".HelveticaNeueDeskInterface-Regular"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" tag="1" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="ekc-h0-I43">
<rect key="frame" x="71" y="100" width="240" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Version 0.2.0" id="FDH-7l-wFf">
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" tag="1" translatesAutoresizingMaskIntoConstraints="NO" id="ekc-h0-I43">
<rect key="frame" x="18" y="53" width="240" height="17"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Version 0.1.0" id="FDH-7l-wFf">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="L5P-Lw-aCd">
<rect key="frame" x="413" y="298" width="270" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Licensed under GPL v2 or any later version." id="ETh-En-bzX">
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="L5P-Lw-aCd">
<rect key="frame" x="299" y="256" width="270" height="17"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="left" title="Licensed under GPLv2 or any later version." id="ETh-En-bzX">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<box horizontalHuggingPriority="750" fixedFrame="YES" boxType="separator" translatesAutoresizingMaskIntoConstraints="NO" id="Zc9-gs-X8C">
<rect key="frame" x="383" y="93" width="5" height="150"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<box horizontalHuggingPriority="750" fixedFrame="YES" title="Box" boxType="separator" titlePosition="noTitle" translatesAutoresizingMaskIntoConstraints="NO" id="Zc9-gs-X8C">
<rect key="frame" x="264" y="71" width="5" height="150"/>
<color key="borderColor" white="0.0" alpha="0.41999999999999998" colorSpace="calibratedWhite"/>
<color key="fillColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<font key="titleFont" metaFont="system"/>
</box>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" tag="3" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="nx6-kQ-N8Z" customClass="BGMLinkField">
<rect key="frame" x="36" y="50" width="310" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" tag="3" title="https://github.com/kyleneideck/BackgroundMusic" placeholderString="" id="VOb-5X-o3R">
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" tag="2" translatesAutoresizingMaskIntoConstraints="NO" id="Vy4-dv-jQB">
<rect key="frame" x="18" y="28" width="240" height="17"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Copyright © 2016 Kyle Neideck" placeholderString="" id="ctF-95-uVu">
<font key="font" metaFont="system"/>
<color key="textColor" red="0.20000000000000001" green="0.40000000000000002" blue="0.59999999999999998" alpha="1" colorSpace="calibratedRGB"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<imageView wantsLayer="YES" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Tui-Hf-FLv">
<rect key="frame" x="116" y="155" width="150" height="150"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<rect key="frame" x="63" y="108" width="150" height="150"/>
<shadow key="shadow">
<color key="color" white="0.0" alpha="1" colorSpace="calibratedWhite"/>
</shadow>
<imageCell key="cell" refusesFirstResponder="YES" alignment="left" animates="YES" imageScaling="proportionallyUpOrDown" image="FermataIcon" id="dBU-ZS-ZzA"/>
</imageView>
<imageView wantsLayer="YES" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="R1R-Rd-xPC">
<rect key="frame" x="116" y="155" width="150" height="150"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<rect key="frame" x="63" y="108" width="150" height="150"/>
<shadow key="shadow">
<color key="color" white="0.0" alpha="1" colorSpace="calibratedWhite"/>
</shadow>
<imageCell key="cell" refusesFirstResponder="YES" alignment="left" animates="YES" imageScaling="proportionallyUpOrDown" image="FermataIcon" id="1VP-dU-RCe"/>
</imageView>
<scrollView fixedFrame="YES" horizontalLineScroll="10" horizontalPageScroll="10" verticalLineScroll="10" verticalPageScroll="10" hasHorizontalScroller="NO" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="eqz-ap-PAC">
<rect key="frame" x="415" y="45" width="567" height="245"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<clipView key="contentView" ambiguous="YES" drawsBackground="NO" id="Cdb-RA-YK0">
<rect key="frame" x="1" y="1" width="565" height="243"/>
<autoresizingMask key="autoresizingMask"/>
<rect key="frame" x="301" y="28" width="427" height="220"/>
<clipView key="contentView" ambiguous="YES" id="Cdb-RA-YK0">
<rect key="frame" x="1" y="1" width="425" height="218"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<textView ambiguous="YES" editable="NO" importsGraphics="NO" richText="NO" verticallyResizable="YES" id="LSG-PF-cl8">
<rect key="frame" x="-6" y="0.0" width="577" height="243"/>
<textView ambiguous="YES" editable="NO" importsGraphics="NO" findStyle="panel" continuousSpellChecking="YES" allowsUndo="YES" usesRuler="YES" usesFontPanel="YES" verticallyResizable="YES" allowsNonContiguousLayout="YES" quoteSubstitution="YES" dashSubstitution="YES" smartInsertDelete="YES" id="LSG-PF-cl8">
<rect key="frame" x="0.0" y="0.0" width="425" height="218"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="textColor" name="textColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="textBackgroundColor" catalog="System" colorSpace="catalog"/>
<size key="minSize" width="565" height="243"/>
<size key="maxSize" width="594" height="10000000"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<size key="minSize" width="425" height="218"/>
<size key="maxSize" width="477" height="10000000"/>
<color key="insertionPointColor" name="controlTextColor" catalog="System" colorSpace="catalog"/>
<allowedInputSourceLocales>
<string>NSAllRomanInputSourcesLocaleIdentifier</string>
</allowedInputSourceLocales>
<size key="minSize" width="425" height="218"/>
<size key="maxSize" width="477" height="10000000"/>
</textView>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</clipView>
<scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="3jV-aP-AB7">
<scroller key="horizontalScroller" hidden="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="YES" id="3jV-aP-AB7">
<rect key="frame" x="-100" y="-100" width="87" height="18"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
<scroller key="verticalScroller" wantsLayer="YES" verticalHuggingPriority="750" horizontal="NO" id="qCC-lY-zQ6">
<rect key="frame" x="550" y="1" width="16" height="243"/>
<scroller key="verticalScroller" verticalHuggingPriority="750" horizontal="NO" id="qCC-lY-zQ6">
<rect key="frame" x="410" y="1" width="16" height="218"/>
<autoresizingMask key="autoresizingMask"/>
</scroller>
</scrollView>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" fixedFrame="YES" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="6qu-yI-r00">
<rect key="frame" x="413" y="20" width="203" height="11"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" lineBreakMode="truncatingTail" sendsActionOnEndEditing="YES" title="The AirPlay Logo is a trademark of Apple Inc." id="lx7-k3-q16">
<font key="font" metaFont="miniSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" tag="2" allowsCharacterPickerTouchBarItem="YES" translatesAutoresizingMaskIntoConstraints="NO" id="Vy4-dv-jQB">
<rect key="frame" x="18" y="75" width="346" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" alignment="center" title="Copyright © 2016-2018 Background Music contributors" placeholderString="" id="ctF-95-uVu">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
</view>
<point key="canvasLocation" x="-200" y="232.5"/>
<point key="canvasLocation" x="101" y="211.5"/>
</window>
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" setsMaxLayoutWidthAtFirstLayout="YES" allowsCharacterPickerTouchBarItem="YES" id="IoN-sN-cCx">
<textField verticalHuggingPriority="750" horizontalCompressionResistancePriority="250" setsMaxLayoutWidthAtFirstLayout="YES" id="IoN-sN-cCx">
<rect key="frame" x="0.0" y="0.0" width="471" height="180"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" controlSize="mini" sendsActionOnEndEditing="YES" drawsBackground="YES" id="Ay8-8n-FHi">
@@ -262,112 +188,10 @@
<color key="textColor" red="0.11543657067200695" green="0.4338699494949495" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<color key="backgroundColor" red="0.99215692281723022" green="0.9960784912109375" blue="0.9960784912109375" alpha="1" colorSpace="deviceRGB"/>
</textFieldCell>
<point key="canvasLocation" x="-559" y="-118"/>
<point key="canvasLocation" x="101.5" y="496"/>
</textField>
<customView id="JOz-H1-mj9" userLabel="Output Volume View">
<rect key="frame" x="0.0" y="0.0" width="269" height="47"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<subviews>
<slider identifier="Output Volume" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="9Ru-Sc-dqC" userLabel="Output Volume Slider">
<rect key="frame" x="20" y="4" width="220" height="19"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<sliderCell key="cell" continuous="YES" state="on" alignment="left" maxValue="1" tickMarkPosition="above" sliderType="linear" id="MzM-fe-nKb"/>
<accessibility description="Output Volume" help="Sets the volume of your audio output device." identifier="Output Volume"/>
</slider>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="wfC-C6-SLv">
<rect key="frame" x="20" y="25" width="226" height="17"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Volume" id="60O-ju-B5C">
<font key="font" metaFont="system"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
</subviews>
<point key="canvasLocation" x="117" y="-219"/>
</customView>
<customView id="dBD-CE-4dw" userLabel="Output Volume View">
<rect key="frame" x="0.0" y="0.0" width="269" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<subviews>
<slider identifier="System Sounds Volume" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="gyd-WV-2ju" userLabel="Output Volume Slider">
<rect key="frame" x="163" y="0.0" width="74" height="15"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<sliderCell key="cell" controlSize="small" continuous="YES" state="on" alignment="left" maxValue="1" doubleValue="1" tickMarkPosition="above" sliderType="linear" id="VDn-d8-XK3"/>
<accessibility description="System Sounds Volume" help="Volume of alerts, notification sounds, etc. Usually short. Can be played by any app."/>
</slider>
<textField horizontalHuggingPriority="251" verticalHuggingPriority="750" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="iKs-df-Hp6">
<rect key="frame" x="42" y="1" width="86" height="14"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<textFieldCell key="cell" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="System Sounds" id="ATK-L8-s8z">
<font key="font" metaFont="smallSystem"/>
<color key="textColor" name="labelColor" catalog="System" colorSpace="catalog"/>
<color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/>
</textFieldCell>
</textField>
<imageView identifier="SystemSoundsIcon" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="V2D-eM-8yN">
<rect key="frame" x="20" y="1" width="16" height="16"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMinY="YES"/>
<imageCell key="cell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" image="NSComputer" id="8Xp-9S-hOz"/>
</imageView>
</subviews>
<point key="canvasLocation" x="116.5" y="-133"/>
</customView>
</objects>
<resources>
<image name="FermataIcon" width="284" height="284"/>
<image name="NSComputer" width="128" height="128"/>
<image name="buttonCell:IXo-C7-3uE:image" width="1" height="1">
<mutableData key="keyedArchiveRepresentation">
YnBsaXN0MDDUAQIDBAUGPT5YJHZlcnNpb25YJG9iamVjdHNZJGFyY2hpdmVyVCR0b3ASAAGGoK4HCBMU
GR4fIyQrLjE3OlUkbnVsbNUJCgsMDQ4PEBESVk5TU2l6ZVYkY2xhc3NcTlNJbWFnZUZsYWdzVk5TUmVw
c1dOU0NvbG9ygAKADRIgwwAAgAOAC1Z7MSwgMX3SFQoWGFpOUy5vYmplY3RzoReABIAK0hUKGh2iGxyA
BYAGgAkQANIgCiEiXxAUTlNUSUZGUmVwcmVzZW50YXRpb26AB4AITxEIxE1NACoAAAAKAAAAEAEAAAMA
AAABAAEAAAEBAAMAAAABAAEAAAECAAMAAAACAAgACAEDAAMAAAABAAEAAAEGAAMAAAABAAEAAAEKAAMA
AAABAAEAAAERAAQAAAABAAAACAESAAMAAAABAAEAAAEVAAMAAAABAAIAAAEWAAMAAAABAAEAAAEXAAQA
AAABAAAAAgEcAAMAAAABAAEAAAEoAAMAAAABAAIAAAFSAAMAAAABAAEAAAFTAAMAAAACAAEAAYdzAAcA
AAf0AAAA0AAAAAAAAAf0YXBwbAIgAABtbnRyR1JBWVhZWiAH0AACAA4ADAAAAABhY3NwQVBQTAAAAABu
b25lAAAAAAAAAAAAAAAAAAAAAAAA9tYAAQAAAADTLWFwcGwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVkZXNjAAAAwAAAAG9kc2NtAAABMAAABmZjcHJ0AAAHmAAAADh3
dHB0AAAH0AAAABRrVFJDAAAH5AAAAA5kZXNjAAAAAAAAABVHZW5lcmljIEdyYXkgUHJvZmlsZQAAAAAA
AAAAAAAAFUdlbmVyaWMgR3JheSBQcm9maWxlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAbWx1YwAAAAAAAAAfAAAADHNrU0sAAAAqAAABhGVuVVMAAAAoAAABrmNhRVMA
AAAsAAAB1nZpVk4AAAAsAAACAnB0QlIAAAAqAAACLnVrVUEAAAAsAAACWGZyRlUAAAAqAAAChGh1SFUA
AAAuAAACrnpoVFcAAAAQAAAC3G5iTk8AAAAsAAAC7GtvS1IAAAAYAAADGGNzQ1oAAAAkAAADMGhlSUwA
AAAgAAADVHJvUk8AAAAkAAADdGRlREUAAAA6AAADmGl0SVQAAAAuAAAD0nN2U0UAAAAuAAAEAHpoQ04A
AAAQAAAELmphSlAAAAAWAAAEPmVsR1IAAAAkAAAEVHB0UE8AAAA4AAAEeG5sTkwAAAAqAAAEsGVzRVMA
AAAoAAAE2nRoVEgAAAAkAAAFAnRyVFIAAAAiAAAFJmZpRkkAAAAsAAAFSGhySFIAAAA6AAAFdHBsUEwA
AAA2AAAFrnJ1UlUAAAAmAAAF5GFyRUcAAAAoAAAGCmRhREsAAAA0AAAGMgBWAWEAZQBvAGIAZQBjAG4A
/QAgAHMAaQB2AP0AIABwAHIAbwBmAGkAbABHAGUAbgBlAHIAaQBjACAARwByAGEAeQAgAFAAcgBvAGYA
aQBsAGUAUABlAHIAZgBpAGwAIABkAGUAIABnAHIAaQBzACAAZwBlAG4A6AByAGkAYwBDHqUAdQAgAGgA
7ABuAGgAIABNAOAAdQAgAHgA4QBtACAAQwBoAHUAbgBnAFAAZQByAGYAaQBsACAAQwBpAG4AegBhACAA
RwBlAG4A6QByAGkAYwBvBBcEMAQzBDAEOwRMBD0EOAQ5ACAEPwRABD4ERAQwBDkEOwAgAEcAcgBhAHkA
UAByAG8AZgBpAGwAIABnAOkAbgDpAHIAaQBxAHUAZQAgAGcAcgBpAHMAwQBsAHQAYQBsAOEAbgBvAHMA
IABzAHoA/AByAGsAZQAgAHAAcgBvAGYAaQBskBp1KHBwlo6Ccl9pY8+P8ABHAGUAbgBlAHIAaQBzAGsA
IABnAHIA5QB0AG8AbgBlAHAAcgBvAGYAaQBsx3y8GAAgAEcAcgBhAHkAINUEuFzTDMd8AE8AYgBlAGMA
bgD9ACABYQBlAGQA/QAgAHAAcgBvAGYAaQBsBeQF6AXVBeQF2QXcACAARwByAGEAeQAgBdsF3AXcBdkA
UAByAG8AZgBpAGwAIABnAHIAaQAgAGcAZQBuAGUAcgBpAGMAQQBsAGwAZwBlAG0AZQBpAG4AZQBzACAA
RwByAGEAdQBzAHQAdQBmAGUAbgAtAFAAcgBvAGYAaQBsAFAAcgBvAGYAaQBsAG8AIABnAHIAaQBnAGkA
bwAgAGcAZQBuAGUAcgBpAGMAbwBHAGUAbgBlAHIAaQBzAGsAIABnAHIA5QBzAGsAYQBsAGUAcAByAG8A
ZgBpAGxmbpAacHBepmPPj/Blh072TgCCLDCwMOwwpDDXMO0w1TChMKQw6wOTA7UDvQO5A7oDzAAgA8AD
wQO/A8YDrwO7ACADswO6A8EDuQBQAGUAcgBmAGkAbAAgAGcAZQBuAOkAcgBpAGMAbwAgAGQAZQAgAGMA
aQBuAHoAZQBuAHQAbwBzAEEAbABnAGUAbQBlAGUAbgAgAGcAcgBpAGoAcwBwAHIAbwBmAGkAZQBsAFAA
ZQByAGYAaQBsACAAZwByAGkAcwAgAGcAZQBuAOkAcgBpAGMAbw5CDhsOIw5EDh8OJQ5MDioONQ5ADhcO
Mg4XDjEOSA4nDkQOGwBHAGUAbgBlAGwAIABHAHIAaQAgAFAAcgBvAGYAaQBsAGkAWQBsAGUAaQBuAGUA
bgAgAGgAYQByAG0AYQBhAHAAcgBvAGYAaQBpAGwAaQBHAGUAbgBlAHIAaQENAGsAaQAgAHAAcgBvAGYA
aQBsACAAcwBpAHYAaQBoACAAdABvAG4AbwB2AGEAVQBuAGkAdwBlAHIAcwBhAGwAbgB5ACAAcAByAG8A
ZgBpAGwAIABzAHoAYQByAG8BWwBjAGkEHgQxBEkEOAQ5ACAEQQQ1BEAESwQ5ACAEPwRABD4ERAQ4BDsE
TAZFBkQGQQAgBioGOQYxBkoGQQAgAEcAcgBhAHkAIAYnBkQGOQYnBkUARwBlAG4AZQByAGUAbAAgAGcA
cgDlAHQAbwBuAGUAYgBlAHMAawByAGkAdgBlAGwAcwBlAAB0ZXh0AAAAAENvcHlyaWdodCAyMDA3IEFw
cGxlIEluYy4sIGFsbCByaWdodHMgcmVzZXJ2ZWQuAFhZWiAAAAAAAADzUQABAAAAARbMY3VydgAAAAAA
AAABAc0AANIlJicoWiRjbGFzc25hbWVYJGNsYXNzZXNfEBBOU0JpdG1hcEltYWdlUmVwoycpKlpOU0lt
YWdlUmVwWE5TT2JqZWN00iUmLC1XTlNBcnJheaIsKtIlJi8wXk5TTXV0YWJsZUFycmF5oy8sKtMyMwo0
NTZXTlNXaGl0ZVxOU0NvbG9yU3BhY2VEMCAwABADgAzSJSY4OVdOU0NvbG9yojgq0iUmOzxXTlNJbWFn
ZaI7Kl8QD05TS2V5ZWRBcmNoaXZlctE/QFRyb290gAEACAARABoAIwAtADIANwBGAEwAVwBeAGUAcgB5
AIEAgwCFAIoAjACOAJUAmgClAKcAqQCrALAAswC1ALcAuQC7AMAA1wDZANsJowmoCbMJvAnPCdMJ3gnn
CewJ9An3CfwKCwoPChYKHgorCjAKMgo0CjkKQQpECkkKUQpUCmYKaQpuAAAAAAAAAgEAAAAAAAAAQQAA
AAAAAAAAAAAAAAAACnA
</mutableData>
</image>
</resources>
</document>
File diff suppressed because one or more lines are too long
@@ -1,21 +0,0 @@
{
"images" : [
{
"idiom" : "universal",
"filename" : "AirPlay.pdf",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
+2 -14
View File
@@ -17,7 +17,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.2.0</string>
<string>0.1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -28,23 +28,11 @@
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>LSUIElement</key>
<true/>
<key>NSAppleEventsUsageDescription</key>
<string>Background Music needs to control your music player app if you want it to automatically pause your music.</string>
<key>NSAppleScriptEnabled</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2016-2018 Background Music contributors</string>
<string>Copyright © 2016 Kyle Neideck</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSMicrophoneUsageDescription</key>
<string>The "Background Music" virtual audio device sends system audio to Background Music (the app) through a virtual input device.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSServices</key>
<array>
<dict/>
</array>
<key>OSAScriptingDefinition</key>
<string>BGMApp.sdef</string>
</dict>
</plist>
-30
View File
@@ -1,30 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMDecibel.h
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// Superclass/Protocol Import
#import "BGMMusicPlayer.h"
@interface BGMDecibel : BGMMusicPlayerBase<BGMMusicPlayer>
@end
-106
View File
@@ -1,106 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMDecibel.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2016 Tanner Hoke
//
// Self Include
#import "BGMDecibel.h"
// Auto-generated Scripting Bridge header
#import "Decibel.h"
// Local Includes
#import "BGMScriptingBridge.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMDecibel {
BGMScriptingBridge* scriptingBridge;
}
- (instancetype) init {
if ((self = [super initWithMusicPlayerID:[BGMMusicPlayerBase makeID:@"A9790CD5-4886-47C7-9FFC-DD70743CF2BF"]
name:@"Decibel"
bundleID:@"org.sbooth.Decibel"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
return self;
}
- (DecibelApplication* __nullable) decibel {
return (DecibelApplication* __nullable)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
}
- (BOOL) isRunning {
return self.decibel.running;
}
- (BOOL) isPlaying {
return self.running && self.decibel.playing;
}
- (BOOL) isPaused {
// We don't want to return true when Decibel is stopped, rather than paused. At least for me, Decibel
// returns -1 for playbackTime and playbackPosition when it's neither playing nor paused.
BOOL probablyNotStopped =
self.decibel.playbackTime >= 0 || self.decibel.playbackPosition >= 0;
return self.running && !self.decibel.playing && probablyNotStopped;
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = self.playing;
if (wasPlaying) {
DebugMsg("BGMDecibel::pause: Pausing Decibel");
[self.decibel pause];
}
return wasPlaying;
}
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = self.paused;
if (wasPaused) {
DebugMsg("BGMDecibel::unpause: Unpausing Decibel");
[self.decibel play];
}
return wasPaused;
}
@end
#pragma clang assume_nonnull end
-105
View File
@@ -1,105 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMHermes.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
//
// Self Include
#import "BGMHermes.h"
// Auto-generated Scripting Bridge header
#import "Hermes.h"
// Local Includes
#import "BGMScriptingBridge.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMHermes {
BGMScriptingBridge* scriptingBridge;
}
- (instancetype) init {
// If you're copying this class, replace the ID string with a new one generated by uuidgen. (Command line tool.)
if ((self = [super initWithMusicPlayerID:[BGMMusicPlayerBase makeID:@"0CDC67B0-56D3-4D94-BC06-6E380D8F5E34"]
name:@"Hermes"
bundleID:@"com.alexcrichton.Hermes"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
return self;
}
- (HermesApplication* __nullable) hermes {
return (HermesApplication* __nullable)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
}
- (BOOL) isRunning {
// Note that this will return NO if is self.hermes is nil (i.e. Hermes isn't running).
return self.hermes.running;
}
// isPlaying and isPaused check self.running first just in case Hermes is closed but self.hermes hasn't become
// nil yet. In that case, reading self.hermes.playerState could make Scripting Bridge open Hermes.
- (BOOL) isPlaying {
return self.running && (self.hermes.playbackState == HermesPlayerStatesPlaying);
}
- (BOOL) isPaused {
return self.running && (self.hermes.playbackState == HermesPlayerStatesPaused);
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = self.playing;
if (wasPlaying) {
DebugMsg("BGMHermes::pause: Pausing Hermes");
[self.hermes pause];
}
return wasPlaying;
}
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = self.paused;
if (wasPaused) {
DebugMsg("BGMHermes::unpause: Unpausing Hermes");
[self.hermes play];
}
return wasPaused;
}
@end
#pragma clang assume_nonnull end
+55 -90
View File
@@ -17,129 +17,94 @@
// BGMMusicPlayer.h
// BGMApp
//
// Copyright © 2016, 2018 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// The base classes and protocol for objects that represent a music player app.
// The base class and protocol for music player apps. Also holds the state of the currently
// selected music player.
//
// To add support for a music player, create a class that implements the BGMMusicPlayer protocol
// and add it to initWithAudioDevices in BGMMusicPlayers.mm.
// To add support for a music player, create a subclass of BGMMusicPlayerBase that implements
// BGMMusicPlayerProtocol. BGMSpotify will probably be the most useful example.
//
// You'll probably want to subclass BGMMusicPlayerBase and, if the music player supports
// AppleScript, use BGMScriptingBridge. Your class might need to override the icon method if the
// default implementation from BGMMusicPlayerBase doesn't work.
// Include the BGM_MUSIC_PLAYER_DEFAULT_LOAD_METHOD macro somewhere in the @implementation block.
// You might also want to override the icon method if the default implementation from
// BGMMusicPlayerBase doesn't work.
//
// BGMSpotify will probably be the most useful example to follow, but they're all pretty
// similar. The music player classes written so far all use Scripting Bridge to communicate with
// the music player apps (see iTunes.h/Spotify.h) but any other way is fine too.
//
// BGMDriver will use either the music player's bundle ID or PID to match it to the audio it
// plays. (Though using PIDs hasn't been tested yet.)
//
// If you're not sure what bundle ID the music player uses, install a debug build of BGMDriver
// and play something in the music player. The easiest way is to do
// build_and_install.sh -d
// BGMDriver will log the bundle ID to system.log when it becomes aware of the music player.
// The music player classes written so far use Scripting Bridge to communicate with the music
// player apps (see iTunes.h/Spotify.h) but any other way is fine too.
//
// System Includes
#import <Cocoa/Cocoa.h>
#import <Foundation/Foundation.h>
#import <ScriptingBridge/ScriptingBridge.h>
#pragma clang assume_nonnull begin
@protocol BGMMusicPlayer <NSObject>
#define BGM_MUSIC_PLAYER_ADD_SELF_TO_CLASSES_LIST \
[BGMMusicPlayerBase addToMusicPlayerClasses:[self class]];
// Classes return an instance of themselves for each music player app they make available in
// BGMApp. So far that's always been a single instance, and classes haven't needed to override
// the default implementation of createInstances from BGMMusicPlayerBase. But that will probably
// change eventually.
//
// For example, a class for custom music players would probably return an instance for each
// custom player the user has created. (Also note that it could return an empty array.) In that
// case the class would probably restore some state from user defaults in its createInstances.
//
// TODO: I think the return type should actually be NSArray<instancetype>*, but that doesn't seem
// to work. There's a Clang bug about this: https://llvm.org/bugs/show_bug.cgi?id=27323
// (though it hasn't been confirmed yet).
+ (NSArray<id<BGMMusicPlayer>>*) createInstances;
#define BGM_MUSIC_PLAYER_DEFAULT_LOAD_METHOD \
+ (void) load { \
BGM_MUSIC_PLAYER_ADD_SELF_TO_CLASSES_LIST \
}
// We need a unique ID for each music player to store in user defaults. In the most common case,
// classes that provide a static (or at least bounded) number of music players, you can generate
// IDs with uuidgen (the command line tool) and include them in your class as constants. Otherwise,
// you'll probably want to store them in user defaults and retrieve them in your createInstances.
@property (readonly) NSUUID* musicPlayerID;
// Forward declarations (just for the typedef)
@class BGMMusicPlayerBase;
@protocol BGMMusicPlayerProtocol;
// The name and icon of the music player, to be used in the UI.
@property (readonly) NSString* name;
@property (readonly) NSImage* __nullable icon;
typedef BGMMusicPlayerBase<BGMMusicPlayerProtocol> BGMMusicPlayer;
@property (readonly) NSString* __nullable bundleID;
@protocol BGMMusicPlayerProtocol
// Classes will usually ignore this property and leave it nil unless the music player has no
// bundle ID.
//
// TODO: If we ever add a music player class that uses this property, it'll need a way to inform
// BGMDevice of changes. It might be easiest to have BGMMusicPlayers to observe this property,
// on the selected music player, with KVO and update BGMDevice when it changes. Or
// BGMMusicPlayers could pass a pointer to itself to createInstances.
@property NSNumber* __nullable pid;
@optional
// Subclasses usually won't need to implement these unless the music player has no bundle ID.
+ (id) initWithPID:(pid_t)pid;
+ (id) initWithPIDFromNSNumber:(NSNumber*)pid;
+ (id) initWithPIDFromCFNumber:(CFNumberRef)pid;
// The pid of each instance of the music player app currently running
+ (BGMGeneric(NSArray, NSNumber*)*) pidsOfRunningInstances;
// True if this is currently the selected music player.
@property (readonly) BOOL selected;
@required
// The name of the music player, to be used in the UI
+ (NSString*) name;
// The state of the music player.
//
// True if the music player app is open.
@property (readonly, getter=isRunning) BOOL running;
// True if the music player is playing a song or some other user-selected audio file. Note that
// the music player playing audio for UI, notifications, etc. won't make this true (which is why we
// need this property and can't just ask BGMDriver if the music player is playing audio).
@property (readonly, getter=isPlaying) BOOL playing;
// True if the music player has a current/open song (or whatever) and will continue playing it if
// BGMMusicPlayer::unpause is called. Normally because the user was playing a song and they or
// BGMApp paused it.
@property (readonly, getter=isPaused) BOOL paused;
// The refs returned by the bundleID and pid methods don't need to be released by users, but may be
// released by the class/instance at some point (get rule applies).
+ (CFStringRef __nullable) bundleID;
// Subclasses will usually always return NULL unless they implement the optional methods above.
- (CFNumberRef __nullable) pid;
// Called when the user selects this music player.
- (void) onSelect;
// Called when this is the selected music player and the user selects a different one.
- (void) onDeselect;
- (BOOL) isRunning;
// Pause the music player. Does nothing if the music player is already paused or isn't running.
// Returns YES if the music player is paused now but wasn't before, returns NO otherwise.
- (BOOL) pause;
// Unpause the music player. Does nothing if the music player is already playing or isn't running.
// Returns YES if the music player is playing now but wasn't before, returns NO otherwise.
- (BOOL) unpause;
- (BOOL) isPlaying;
- (BOOL) isPaused;
@end
@interface BGMMusicPlayerBase : NSObject <SBApplicationDelegate>
@interface BGMMusicPlayerBase : NSObject
+ (NSArray*) musicPlayerClasses;
+ (void) addToMusicPlayerClasses:(Class)musicPlayerClass;
- (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID
name:(NSString*)name
bundleID:(NSString* __nullable)bundleID;
// The music player currently selected in the preferences menu. (There's no real reason for this to be
// global or in this class. I was just trying it out of curiosity.)
+ (BGMMusicPlayer*) selectedMusicPlayer;
+ (void) setSelectedMusicPlayer:(BGMMusicPlayer*)musicPlayer;
- (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID
name:(NSString*)name
bundleID:(NSString* __nullable)bundleID
pid:(NSNumber* __nullable)pid;
+ (NSImage* __nullable) icon;
// Convenience wrapper around NSUUID's initWithUUIDString. musicPlayerIDString must be a string
// generated by uuidgen (command line tool), e.g. "60BA9739-B6DD-4E6A-8134-51410A45BB84".
+ (NSUUID*) makeID:(NSString*)musicPlayerIDString;
// BGMMusicPlayer default implementations
+ (NSArray<id<BGMMusicPlayer>>*) createInstances;
@property (readonly) NSImage* __nullable icon;
@property (readonly) NSUUID* musicPlayerID;
@property (readonly) NSString* name;
@property (readonly) NSString* __nullable bundleID;
@property NSNumber* __nullable pid;
@property (readonly) BOOL selected;
- (void) onSelect;
- (void) onDeselect;
// If the music player application is running, the scripting bridge object representing it. Otherwise
// nil.
@property (readonly) BGMKindOf(SBApplication*) __nullable sbApplication;
@end
+118 -51
View File
@@ -17,79 +17,146 @@
// BGMMusicPlayer.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMMusicPlayer.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#undef CoreAudio_ThreadStampMessages
#define CoreAudio_ThreadStampMessages 0 // Requires C++
#include "CADebugMacros.h"
// System Includes
#import <Cocoa/Cocoa.h>
#pragma clang assume_nonnull begin
@implementation BGMMusicPlayerBase
@synthesize musicPlayerID = _musicPlayerID;
@synthesize name = _name;
@synthesize bundleID = _bundleID;
@synthesize pid = _pid;
@synthesize selected = _selected;
- (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID
name:(NSString*)name
bundleID:(NSString* __nullable)bundleID {
return [self initWithMusicPlayerID:musicPlayerID name:name bundleID:bundleID pid:nil];
@implementation BGMMusicPlayerBase {
// Tokens for the notification observers. We need these to remove the observers in dealloc.
id didLaunchToken;
id didTerminateToken;
}
- (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID
name:(NSString*)name
bundleID:(NSString* __nullable)bundleID
pid:(NSNumber* __nullable)pid {
if ((self = [super init])) {
NSAssert(musicPlayerID, @"BGMMusicPlayerBase::initWithMusicPlayerID: !musicPlayerID");
NSAssert([self conformsToProtocol:@protocol(BGMMusicPlayer)],
@"BGMMusicPlayerBase::initWithMusicPlayerID: !conformsToProtocol");
_musicPlayerID = musicPlayerID;
_name = name;
_bundleID = bundleID;
_pid = pid;
_selected = NO;
}
@synthesize sbApplication = sbApplication;
// A array of the subclasses of BGMMusicPlayer
static NSArray* sMusicPlayerClasses;
// The user-selected music player. One of BGMMusicPlayer's subclasses declares itself the default music player by
// setting this to an instance of itself in its load method.
static BGMMusicPlayer* sSelectedMusicPlayer;
// Load-time static initializer
+ (void) load {
sMusicPlayerClasses = @[];
}
- (id) init {
if ((self = [super init])) {
NSString* bundleID = (__bridge NSString*)[[self class] bundleID];
void (^createSBApplication)(void) = ^{
sbApplication = [SBApplication applicationWithBundleIdentifier:bundleID];
((SBApplication*)sbApplication).delegate = self;
};
BOOL (^isAboutThisMusicPlayer)(NSNotification*) = ^(NSNotification* note){
return [[note.userInfo[NSWorkspaceApplicationKey] bundleIdentifier] isEqualToString:bundleID];
};
// Add observers that create/destroy the SBApplication when the music player is launched/terminated. We
// only create the SBApplication when the music player is open because, if it isn't, creating the
// SBApplication, or sending it events, could launch the music player. Whether it does or not depends on
// the music player, and possibly the version of the music player, so to be safe we assume they all do.
//
// From the docs for SBApplication's applicationWithBundleIdentifier method:
// "For applications that declare themselves to have a dynamic scripting interface, this method will
// launch the application if it is not already running."
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
#if DEBUG
const char* mpName = [[[self class] name] UTF8String];
#endif
didLaunchToken = [center addObserverForName:NSWorkspaceDidLaunchApplicationNotification
object:nil
queue:nil
usingBlock:^(NSNotification* note) {
if (isAboutThisMusicPlayer(note)) {
DebugMsg("BGMMusicPlayer::init: %s launched", mpName);
createSBApplication();
}
}];
didTerminateToken = [center addObserverForName:NSWorkspaceDidTerminateApplicationNotification
object:nil
queue:nil
usingBlock:^(NSNotification* note) {
if (isAboutThisMusicPlayer(note)) {
DebugMsg("BGMMusicPlayer::init: %s terminated", mpName);
sbApplication = nil;
}
}];
// Create the SBApplication if the music player is already running.
if ([[NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID] count] > 0) {
createSBApplication();
}
}
return self;
}
+ (NSUUID*) makeID:(NSString*)musicPlayerIDString {
NSUUID* __nullable musicPlayerID = [[NSUUID alloc] initWithUUIDString:musicPlayerIDString];
NSAssert(musicPlayerID, @"BGMMusicPlayerBase::makeID: !musicPlayerID");
- (id) eventDidFail:(const AppleEvent*)event withError:(NSError*)error {
// SBApplicationDelegate method. So far, this just logs the error.
return (NSUUID*)musicPlayerID;
}
#pragma mark BGMMusicPlayer default implementations
+ (NSArray<id<BGMMusicPlayer>>*) createInstances {
return @[ [self new] ];
}
- (NSImage* __nullable) icon {
NSString* __nullable bundleID = self.bundleID;
NSString* __nullable bundlePath =
(!bundleID ? nil : [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:(NSString*)bundleID]);
#if DEBUG
NSString* vars = [NSString stringWithFormat:@"event=%@ error=%@ sbApplication=%@", event, error, sbApplication];
DebugMsg("BGMMusicPlayer::eventDidFail: Apple event sent to %s failed. %s",
[[[self class] name] UTF8String],
[vars UTF8String]);
#else
#pragma unused (event, error)
#endif
return (!bundlePath ? nil : [[NSWorkspace sharedWorkspace] iconForFile:(NSString*)bundlePath]);
return nil;
}
- (void) onSelect {
_selected = YES;
- (void) dealloc {
// Remove the application launch/termination observers.
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
if (didLaunchToken) {
[center removeObserver:didLaunchToken];
}
if (didTerminateToken) {
[center removeObserver:didTerminateToken];
}
}
- (void) onDeselect {
_selected = NO;
+ (void) addToMusicPlayerClasses:(Class)musicPlayerClass {
sMusicPlayerClasses = [sMusicPlayerClasses arrayByAddingObject:musicPlayerClass];
}
+ (NSArray*) musicPlayerClasses {
return sMusicPlayerClasses;
}
+ (BGMMusicPlayer*) selectedMusicPlayer {
NSAssert(sSelectedMusicPlayer != nil, @"One of BGMMusicPlayer's subclasses should set itself as the default "
"music player (i.e. set sSelectedMusicPlayer) in its initialize method");
return sSelectedMusicPlayer;
}
+ (void) setSelectedMusicPlayer:(BGMMusicPlayer*)musicPlayer {
sSelectedMusicPlayer = musicPlayer;
}
+ (NSImage* __nullable) icon {
NSString* bundleID = (__bridge NSString*)[(id<BGMMusicPlayerProtocol>)self bundleID];
NSString* bundlePath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:bundleID];
return bundlePath == nil ? nil : [[NSWorkspace sharedWorkspace] iconForFile:bundlePath];
}
@end
@@ -1,62 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMMusicPlayers.h
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// Holds the music players (i.e. BGMMusicPlayer objects) available in BGMApp. Also keeps track of
// which music player is currently selected by the user.
//
// Local Includes
#import "BGMAudioDeviceManager.h"
#import "BGMMusicPlayer.h"
#import "BGMUserDefaults.h"
// System Includes
#import <Foundation/Foundation.h>
#pragma clang assume_nonnull begin
@interface BGMMusicPlayers : NSObject
// Calls initWithAudioDevices:musicPlayers: with sensible defaults.
- (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices
userDefaults:(BGMUserDefaults*)defaults;
// defaultMusicPlayerID is the musicPlayerID (see BGMMusicPlayer.h) of the music player that should be
// selected by default.
//
// The createInstances method of each class in musicPlayerClasses will be called, and the results stored
// in the musicPlayers property.
- (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices
defaultMusicPlayerID:(NSUUID*)defaultMusicPlayerID
musicPlayerClasses:(NSArray<Class<BGMMusicPlayer>>*)musicPlayerClasses
userDefaults:(BGMUserDefaults*)defaults;
@property (readonly) NSArray<id<BGMMusicPlayer>>* musicPlayers;
// The music player currently selected in the preferences menu. BGMDevice is informed when this property
// is changed.
@property id<BGMMusicPlayer> selectedMusicPlayer;
@end
#pragma clang assume_nonnull end
@@ -1,253 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMMusicPlayers.mm
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
//
// Self include
#import "BGMMusicPlayers.h"
// Local includes
#import "BGM_Types.h"
// Music player includes
#import "BGMiTunes.h"
#import "BGMSpotify.h"
#import "BGMVLC.h"
#import "BGMVOX.h"
#import "BGMDecibel.h"
#import "BGMHermes.h"
#import "BGMSwinsian.h"
#pragma clang assume_nonnull begin
@implementation BGMMusicPlayers {
BGMAudioDeviceManager* audioDevices;
BGMUserDefaults* userDefaults;
}
@synthesize selectedMusicPlayer = _selectedMusicPlayer;
- (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices
userDefaults:(BGMUserDefaults*)defaults {
return [self initWithAudioDevices:devices
defaultMusicPlayerID:[BGMiTunes sharedMusicPlayerID]
// If you write a new music player class, add it to this array.
musicPlayerClasses:@[ [BGMVOX class],
[BGMVLC class],
[BGMSpotify class],
[BGMiTunes class],
[BGMDecibel class],
[BGMHermes class],
[BGMSwinsian class] ]
userDefaults:defaults];
}
- (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices
defaultMusicPlayerID:(NSUUID*)defaultMusicPlayerID
musicPlayerClasses:(NSArray<Class<BGMMusicPlayer>>*)musicPlayerClasses
userDefaults:(BGMUserDefaults*)defaults {
if ((self = [super init])) {
audioDevices = devices;
userDefaults = defaults;
// Init _musicPlayers, an array containing one object for each music player in BGMApp.
//
// Each music player class has a factory method, createInstances, that returns all the instances of that
// class BGMApp will use. (Though so far it's always just one instance.)
NSMutableArray* musicPlayers = [NSMutableArray new];
for (Class<BGMMusicPlayer> musicPlayerClass in musicPlayerClasses) {
[musicPlayers addObjectsFromArray:[musicPlayerClass createInstances]];
}
_musicPlayers = [NSArray arrayWithArray:musicPlayers];
// Set _selectedMusicPlayer to its setting from last time BGMApp ran. (Unless this is the first run or
// that music player isn't available this time.)
[self initSelectedMusicPlayerFromUserDefaults];
if (!_selectedMusicPlayer) {
// Couldn't set _selectedMusicPlayer from user defaults, so try BGMDevice's music player property.
[self initSelectedMusicPlayerFromBGMDevice];
}
if (!_selectedMusicPlayer) {
// The user hasn't changed the music player yet, so we set the default music player as selected.
[self setSelectedMusicPlayerByID:defaultMusicPlayerID];
}
NSAssert(_selectedMusicPlayer, @"BGMMusicPlayers::initWithAudioDevices: !_selectedMusicPlayer");
}
return self;
}
- (void) initSelectedMusicPlayerFromUserDefaults {
// Load the selected music player setting from user defaults.
NSString* __nullable selectedMusicPlayerIDStr = userDefaults.selectedMusicPlayerID;
NSUUID* __nullable selectedMusicPlayerID = nil;
if (selectedMusicPlayerIDStr) {
NSString* idStrNN = selectedMusicPlayerIDStr;
selectedMusicPlayerID = [[NSUUID alloc] initWithUUIDString:idStrNN];
NSAssert(selectedMusicPlayerID,
@"BGMMusicPlayers::initSelectedMusicPlayerFromUserDefaults: !selectedMusicPlayerID");
}
if (selectedMusicPlayerID) {
NSUUID* idNN = selectedMusicPlayerID;
BOOL didChangeMusicPlayer = [self setSelectedMusicPlayerByID:idNN];
#if DEBUG
DebugMsg("BGMMusicPlayers::initSelectedMusicPlayerFromUserDefaults: %s selectedMusicPlayerIDStr=%s",
(didChangeMusicPlayer ?
"Selected music player restored from user defaults." :
"The selected music player setting found in user defaults didn't match an available music player."),
selectedMusicPlayerIDStr.UTF8String);
#else
#pragma unused (didChangeMusicPlayer)
#endif
}
}
- (void) initSelectedMusicPlayerFromBGMDevice {
// When the selected music player setting hasn't been stored in user defaults yet, we get the music player
// bundle ID from the driver and look for the music player with that bundle ID. This is mainly done for
// backwards compatability.
NSString* __nullable bundleID =
(__bridge_transfer NSString* __nullable)[audioDevices bgmDevice].GetMusicPlayerBundleID();
DebugMsg("BGMMusicPlayers::initSelectedMusicPlayerFromBGMDevice: "
"Trying to set selected music player by bundle ID (from BGMDriver). bundleID=%s",
(bundleID ? bundleID.UTF8String : "(null)"));
if (bundleID && ![bundleID isEqualToString:@""]) {
// Find any music players with a bundle ID matching the one from BGMDriver.
NSArray<id<BGMMusicPlayer>>* matchingMusicPlayers = @[ ];
for (id<BGMMusicPlayer> musicPlayer in _musicPlayers) {
NSString* bundleIDNN = bundleID;
if ([musicPlayer.bundleID isEqualToString:bundleIDNN]) {
DebugMsg("BGMMusicPlayers::initSelectedMusicPlayerFromBGMDevice: Bundle ID on BGMDevice matches %s",
musicPlayer.name.UTF8String);
matchingMusicPlayers = [matchingMusicPlayers arrayByAddingObject:musicPlayer];
}
}
// Currently, the music players all have different bundle IDs, but that might change at some point. We
// might want to consider some websites as music players, for example. So we don't change the setting
// unless the bundle ID only matches one music player.
if (matchingMusicPlayers.count == 1) {
// (Use setSelectedMusicPlayerImpl to avoid setSelectedMusicPlayer being called in init.)
[self setSelectedMusicPlayerImpl:matchingMusicPlayers[0]];
}
}
}
- (id<BGMMusicPlayer>) selectedMusicPlayer {
return _selectedMusicPlayer;
}
- (void) setSelectedMusicPlayer:(id<BGMMusicPlayer>)newSelectedMusicPlayer {
// Apparently you shouldn't call properties' setter methods in init (KVO notifications might trigger, etc.)
// so the actual work is done in setSelectedMusicPlayerImpl.
[self setSelectedMusicPlayerImpl:newSelectedMusicPlayer];
NSAssert(self.selectedMusicPlayer == newSelectedMusicPlayer,
@"BGMMusicPlayers::setSelectedMusicPlayer: selectedMusicPlayer wasn't set to the object expected");
}
- (BOOL) setSelectedMusicPlayerByID:(NSUUID*)newSelectedMusicPlayerID {
id<BGMMusicPlayer> __nullable newSelectedMusicPlayer = nil;
// Find the music player with the given ID, if there is one.
for (id<BGMMusicPlayer> musicPlayer in _musicPlayers) {
if ([musicPlayer.musicPlayerID isEqual:newSelectedMusicPlayerID]) {
NSAssert(!newSelectedMusicPlayer, @"BGMMusicPlayers::setSelectedMusicPlayerByID: Non-unique musicPlayerID");
newSelectedMusicPlayer = musicPlayer;
}
}
if (newSelectedMusicPlayer) {
// (Use setSelectedMusicPlayerImpl to avoid setSelectedMusicPlayer being called in init.)
id<BGMMusicPlayer> newPlayerNN = newSelectedMusicPlayer;
[self setSelectedMusicPlayerImpl:newPlayerNN];
return YES;
} else {
return NO;
}
}
- (void) setSelectedMusicPlayerImpl:(id<BGMMusicPlayer>)newSelectedMusicPlayer {
NSAssert([_musicPlayers containsObject:newSelectedMusicPlayer],
@"BGMMusicPlayers::setSelectedMusicPlayerImpl: Only the music players in the musicPlayers array can be selected. "
"newSelectedMusicPlayer=%@",
newSelectedMusicPlayer.name);
if (_selectedMusicPlayer == newSelectedMusicPlayer) {
DebugMsg("BGMMusicPlayers::setSelectedMusicPlayerImpl: %s is already the selected music "
"player.",
_selectedMusicPlayer.name.UTF8String);
return;
}
// Tell the current music player (object) a different player has been selected.
[_selectedMusicPlayer onDeselect];
_selectedMusicPlayer = newSelectedMusicPlayer;
DebugMsg("BGMMusicPlayers::setSelectedMusicPlayerImpl: Set selected music player to %s",
_selectedMusicPlayer.name.UTF8String);
// Update the selected music player on the driver.
[self updateBGMDeviceMusicPlayerProperties];
// Save the new setting in user defaults.
userDefaults.selectedMusicPlayerID = _selectedMusicPlayer.musicPlayerID.UUIDString;
// Tell the music player (object) it's been selected.
[_selectedMusicPlayer onSelect];
}
- (void) updateBGMDeviceMusicPlayerProperties {
// Send the music player's PID and/or bundle ID to the driver.
NSAssert(self.selectedMusicPlayer.pid || self.selectedMusicPlayer.bundleID,
@"BGMMusicPlayers::updateBGMDeviceMusicPlayerProperties: Music player has neither bundle ID nor PID");
if (self.selectedMusicPlayer.pid) {
[audioDevices bgmDevice].SetMusicPlayerProcessID((__bridge CFNumberRef)self.selectedMusicPlayer.pid);
}
if (self.selectedMusicPlayer.bundleID) {
[audioDevices bgmDevice].SetMusicPlayerBundleID((__bridge CFStringRef)self.selectedMusicPlayer.bundleID);
}
}
@end
#pragma clang assume_nonnull end
@@ -1,69 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMScriptingBridge.h
// BGMApp
//
// Copyright © 2016, 2018 Kyle Neideck
//
// A wrapper around Scripting Bridge's SBApplication that tries to avoid ever launching the application.
//
// We use Scripting Bridge to communicate with music player apps, which we never want to launch
// ourselves. But creating an SBApplication for an app, or sending messages/events to an existing one,
// can launch the app.
//
// As a workaround, this class has an SBApplication property, application (see below), which is nil
// unless the music player app is running. That way messages sent while the app is closed are ignored.
//
// Local Includes
#import "BGMMusicPlayer.h"
// System Includes
#import <Cocoa/Cocoa.h>
#import <ScriptingBridge/ScriptingBridge.h>
#pragma clang assume_nonnull begin
@interface BGMScriptingBridge : NSObject <SBApplicationDelegate>
// Only keeps a weak ref to musicPlayer.
- (instancetype) initWithMusicPlayer:(id<BGMMusicPlayer>)musicPlayer;
// If the music player application is running, this property is the Scripting Bridge object representing
// it. If not, it's set to nil. Used to send Apple events to the music player app.
@property (readonly) __kindof SBApplication* __nullable application;
// macOS 10.14 requires the user's permission to send Apple Events. If the music player that owns
// this object (i.e. the one passed to initWithMusicPlayer) is currently the selected music player
// and the user hasn't already given us permission to send it Apple Events, this method asks the
// user for permission.
- (void) ensurePermission;
// SBApplicationDelegate
// On 10.11, SBApplicationDelegate.h declares eventDidFail with a non-null return type, but the docs
// specifically say that returning nil is allowed.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability"
- (id __nullable) eventDidFail:(const AppleEvent*)event withError:(NSError*)error;
#pragma clang diagnostic pop
@end
#pragma clang assume_nonnull end
@@ -1,202 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMScriptingBridge.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
//
// Self Include
#import "BGMScriptingBridge.h"
// Local Includes
#import "BGM_Utils.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMScriptingBridge {
id<BGMMusicPlayer> __weak _musicPlayer;
// Tokens for the notification observers. We need these to remove the observers in dealloc.
id _didLaunchToken, _didTerminateToken;
}
@synthesize application = _application;
- (instancetype) initWithMusicPlayer:(id<BGMMusicPlayer>)musicPlayer {
if ((self = [super init])) {
_musicPlayer = musicPlayer;
[self initApplication];
}
return self;
}
- (void) initApplication {
NSString* bundleID = _musicPlayer.bundleID;
BGMAssert(bundleID, "Music players need a bundle ID to use ScriptingBridge");
BGMScriptingBridge* __weak weakSelf = self;
void (^createSBApplication)(void) = ^{
BGMScriptingBridge* __strong strongSelf = weakSelf;
strongSelf->_application = [SBApplication applicationWithBundleIdentifier:bundleID];
// TODO: I think the SBApplication will still keep a strong ref to this object, so we might
// have to make a separate delegate object.
strongSelf->_application.delegate = strongSelf;
};
BOOL (^isAboutThisMusicPlayer)(NSNotification*) = ^(NSNotification* note) {
return [[note.userInfo[NSWorkspaceApplicationKey] bundleIdentifier] isEqualToString:bundleID];
};
// Add observers that create/destroy the SBApplication when the music player is launched/terminated. We
// only create the SBApplication when the music player is open. If it isn't open, creating the
// SBApplication or sending it events could launch the music player. Whether or not it does depends on
// the music player, and possibly the version of the music player, so to be safe we assume they all do.
//
// From the docs for SBApplication's applicationWithBundleIdentifier method:
// "For applications that declare themselves to have a dynamic scripting interface, this method will
// launch the application if it is not already running."
NSNotificationCenter* center = [[NSWorkspace sharedWorkspace] notificationCenter];
_didLaunchToken = [center addObserverForName:NSWorkspaceDidLaunchApplicationNotification
object:nil
queue:nil
usingBlock:^(NSNotification* note)
{
if (isAboutThisMusicPlayer(note)) {
DebugMsg("BGMScriptingBridge::initApplication: %s launched",
bundleID.UTF8String);
createSBApplication();
[weakSelf ensurePermission];
}
}];
_didTerminateToken = [center addObserverForName:NSWorkspaceDidTerminateApplicationNotification
object:nil
queue:nil
usingBlock:^(NSNotification* note)
{
if (isAboutThisMusicPlayer(note)) {
DebugMsg("BGMScriptingBridge::initApplication: %s terminated",
bundleID.UTF8String);
BGMScriptingBridge* __strong strongSelf = weakSelf;
strongSelf->_application = nil;
}
}];
// Create the SBApplication if the music player is already running.
if ([NSRunningApplication runningApplicationsWithBundleIdentifier:bundleID].count > 0) {
createSBApplication();
}
}
- (void) dealloc {
// Remove the application launch/termination observers.
NSNotificationCenter* center = [NSWorkspace sharedWorkspace].notificationCenter;
if (_didLaunchToken) {
[center removeObserver:_didLaunchToken];
}
if (_didTerminateToken) {
[center removeObserver:_didTerminateToken];
}
}
- (void) ensurePermission {
// Skip this check if running on a version of macOS before 10.14. In that case, we don't require
// user permission to send Apple Events. Also skip it if compiling on an earlier version.
#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 // MAC_OS_X_VERSION_10_14
if (@available(macOS 10.14, *)) {
id<BGMMusicPlayer> musicPlayer = _musicPlayer;
if (!musicPlayer.selected) {
DebugMsg("BGMScriptingBridge::ensurePermission: %s not selected. Nothing to do.",
musicPlayer.name.UTF8String);
return;
}
if (!musicPlayer.running) {
DebugMsg("BGMScriptingBridge::ensurePermission: %s not running. Nothing to do.",
musicPlayer.name.UTF8String);
return;
}
// AEDeterminePermissionToAutomateTarget will block if it has to show a dialog to the user
// to ask for permission, so dispatch this to make sure it doesn't run on the main thread.
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
NSAppleEventDescriptor* musicPlayerEventDescriptor =
[NSAppleEventDescriptor
descriptorWithBundleIdentifier:(NSString*)musicPlayer.bundleID];
OSStatus status =
AEDeterminePermissionToAutomateTarget(musicPlayerEventDescriptor.aeDesc,
typeWildCard,
typeWildCard,
true);
DebugMsg("BGMScriptingBridge::ensurePermission: "
"Apple Events permission status for %s: %d",
musicPlayer.name.UTF8String,
status);
if (status != noErr) {
// TODO: If they deny permission, we should grey-out the auto-pause menu item and
// add something to the UI that indicates the problem. Maybe a warning icon
// that shows an explanation when you hover your mouse over it. (We can't just
// ask them again later because the API doesn't support it. They can only fix
// it in System Preferences.)
NSLog(@"BGMScriptingBridge::ensurePermission: Permission denied for %@. status=%d",
musicPlayer.name,
status);
}
});
} else {
DebugMsg("BGMScriptingBridge::ensurePermission: Not macOS 10.14+. Nothing to do.");
}
#endif /* MAC_OS_X_VERSION_MAX_ALLOWED >= 101400 */
}
#pragma mark SBApplicationDelegate
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnullability" // See explanation in the header file.
- (id __nullable) eventDidFail:(const AppleEvent*)event withError:(NSError*)error {
#pragma clang diagnostic pop
// So far, this just logs the error.
#if DEBUG
NSString* vars = [NSString stringWithFormat:@"event='%4.4s' error=%@ application=%@",
(char*)&(event->descriptorType), error, self.application];
DebugMsg("BGMScriptingBridge::eventDidFail: Apple event sent to %s failed. %s",
_musicPlayer.bundleID.UTF8String,
vars.UTF8String);
#else
#pragma unused (event, error)
#endif
return nil;
}
@end
#pragma clang assume_nonnull end
+1 -1
View File
@@ -24,7 +24,7 @@
#import "BGMMusicPlayer.h"
@interface BGMSpotify : BGMMusicPlayerBase<BGMMusicPlayer>
@interface BGMSpotify : BGMMusicPlayer
@end
+27 -40
View File
@@ -17,7 +17,7 @@
// BGMSpotify.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Spotify's AppleScript API looks to have been designed to match iTunes', so this file is basically
// just s/iTunes/Spotify/ on BGMiTunes.m
@@ -29,58 +29,39 @@
// Auto-generated Scripting Bridge header
#import "Spotify.h"
// Local Includes
#import "BGMScriptingBridge.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#undef CoreAudio_ThreadStampMessages
#define CoreAudio_ThreadStampMessages 0 // Requires C++
#include "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMSpotify
@implementation BGMSpotify {
BGMScriptingBridge* scriptingBridge;
BGM_MUSIC_PLAYER_DEFAULT_LOAD_METHOD
+ (NSString*) name {
return @"Spotify";
}
- (instancetype) init {
// If you're copying this class, replace the ID string with a new one generated by uuidgen. (Command line tool.)
if ((self = [super initWithMusicPlayerID:[BGMMusicPlayerBase makeID:@"EC2A907F-8515-4687-9570-1BF63176E6D8"]
name:@"Spotify"
bundleID:@"com.spotify.client"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
return self;
- (CFNumberRef) pid {
return NULL;
}
+ (CFStringRef) bundleID {
return CFSTR("com.spotify.client");
}
- (SpotifyApplication* __nullable) spotify {
return (SpotifyApplication* __nullable)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
return (SpotifyApplication*) self.sbApplication;
}
- (BOOL) isRunning {
// Note that this will return NO if is self.spotify is nil (i.e. Spotify isn't running).
return self.spotify.running;
}
// isPlaying and isPaused check self.running first just in case Spotify is closed but self.spotify hasn't become
// nil yet. In that case, reading self.spotify.playerState could make Scripting Bridge open Spotify.
- (BOOL) isPlaying {
return self.running && (self.spotify.playerState == SpotifyEPlSPlaying);
}
- (BOOL) isPaused {
return self.running && (self.spotify.playerState == SpotifyEPlSPaused);
return self.spotify && [self.spotify isRunning];
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = self.playing;
BOOL wasPlaying = [self isPlaying];
if (wasPlaying) {
DebugMsg("BGMSpotify::pause: Pausing Spotify");
@@ -92,7 +73,7 @@
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = self.paused;
BOOL wasPaused = [self isPaused];
if (wasPaused) {
DebugMsg("BGMSpotify::unpause: Unpausing Spotify");
@@ -102,7 +83,13 @@
return wasPaused;
}
- (BOOL) isPlaying {
return [self isRunning] && [self.spotify playerState] == SpotifyEPlSPlaying;
}
- (BOOL) isPaused {
return [self isRunning] && [self.spotify playerState] == SpotifyEPlSPaused;
}
@end
#pragma clang assume_nonnull end
-34
View File
@@ -1,34 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMSwinsian.h
// BGMApp
//
// Copyright © 2018 Kyle Neideck
//
// Superclass/Protocol Import
#import "BGMMusicPlayer.h"
#pragma clang assume_nonnull begin
@interface BGMSwinsian : BGMMusicPlayerBase<BGMMusicPlayer>
@end
#pragma clang assume_nonnull end
-109
View File
@@ -1,109 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMSwinsian.m
// BGMApp
//
// Copyright © 2018 Kyle Neideck
//
// Self Include
#import "BGMSwinsian.h"
// Auto-generated Scripting Bridge header
#import "Swinsian.h"
// Local Includes
#import "BGMScriptingBridge.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMSwinsian {
BGMScriptingBridge* scriptingBridge;
}
- (instancetype) init {
// If you're copying this class, replace the ID string with a new one generated by uuidgen (the
// command line tool).
NSUUID* musicPlayerID = [BGMMusicPlayerBase makeID:@"B74D18F6-DFF7-4D88-B719-429CFF98CFFA"];
if ((self = [super initWithMusicPlayerID:musicPlayerID
name:@"Swinsian"
bundleID:@"com.swinsian.Swinsian"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
return self;
}
- (SwinsianApplication* __nullable) swinsian {
return (SwinsianApplication* __nullable)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
}
- (BOOL) isRunning {
// Note that this will return NO if is self.swinsian is nil (i.e. Swinsian isn't running).
return self.swinsian.running;
}
// isPlaying and isPaused check self.running first just in case Swinsian is closed but self.swinsian
// hasn't become nil yet. In that case, reading self.swinsian.playerState could make Scripting
// Bridge open Swinsian.
- (BOOL) isPlaying {
return self.running && (self.swinsian.playerState == SwinsianPlayerStatePlaying);
}
- (BOOL) isPaused {
return self.running && (self.swinsian.playerState == SwinsianPlayerStatePaused);
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event.
BOOL wasPlaying = self.playing;
if (wasPlaying) {
DebugMsg("BGMSwinsian::pause: Pausing Swinsian");
[self.swinsian pause];
}
return wasPlaying;
}
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event.
BOOL wasPaused = self.paused;
if (wasPaused) {
DebugMsg("BGMSwinsian::unpause: Unpausing Swinsian");
[self.swinsian play];
}
return wasPaused;
}
@end
#pragma clang assume_nonnull end
+1 -1
View File
@@ -24,7 +24,7 @@
#import "BGMMusicPlayer.h"
@interface BGMVLC : BGMMusicPlayerBase<BGMMusicPlayer>
@interface BGMVLC : BGMMusicPlayer
@end
+38 -44
View File
@@ -17,7 +17,7 @@
// BGMVLC.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2016 Kyle Neideck
// Portions copyright (C) 2012 Peter Ljunglöf. All rights reserved.
//
@@ -25,63 +25,50 @@
#import "BGMVLC.h"
// Auto-generated Scripting Bridge header
#import "VLC.h"
// Local Includes
#import "BGMScriptingBridge.h"
#if __has_feature(objc_generics)
// According to "man sdp", generics is required by headers generated for 10.11+ but not for headers generated for 10.10.
#import "VLC.h"
#else
#import "VLC_10.9.h"
#endif
// PublicUtility Includes
#import "CADebugMacros.h"
#undef CoreAudio_ThreadStampMessages
#define CoreAudio_ThreadStampMessages 0 // Requires C++
#include "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMVLC
@implementation BGMVLC {
BGMScriptingBridge* scriptingBridge;
BGM_MUSIC_PLAYER_DEFAULT_LOAD_METHOD
+ (NSString*) name {
return @"VLC";
}
- (instancetype) init {
if ((self = [super initWithMusicPlayerID:[BGMMusicPlayerBase makeID:@"5226F4B9-C740-4045-A273-4B8EABC0E8FC"]
name:@"VLC"
bundleID:@"org.videolan.vlc"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
return self;
- (CFNumberRef) pid {
return NULL;
}
+ (CFStringRef) bundleID {
return CFSTR("org.videolan.vlc");
}
- (VLCApplication* __nullable) vlc {
return (VLCApplication*)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
return (VLCApplication*) self.sbApplication;
}
- (BOOL) isRunning {
return self.vlc.running;
}
// isPlaying and isPaused check self.running first just in case VLC is closed but self.vlc hasn't become
// nil yet. In that case, reading other properties of self.vlc could make Scripting Bridge open VLC.
- (BOOL) isPlaying {
return self.running && self.vlc.playing;
}
- (BOOL) isPaused {
// VLC is paused if it has a file open but isn't playing it
return self.running && (self.vlc.nameOfCurrentItem != nil) && !self.vlc.playing;
return self.vlc && [self.vlc isRunning];
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = self.playing;
BOOL wasPlaying = [self isPlaying];
if (wasPlaying) {
DebugMsg("BGMVLC::pause: Pausing VLC");
[BGMVLC togglePlay];
[self togglePlay];
}
return wasPlaying;
@@ -89,27 +76,34 @@
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = self.paused;
BOOL wasPaused = [self isPaused];
if (wasPaused) {
DebugMsg("BGMVLC::unpause: Unpausing VLC");
[BGMVLC togglePlay];
[self togglePlay];
}
return wasPaused;
}
- (BOOL) isPlaying {
return [self isRunning] && [self.vlc playing];
}
- (BOOL) isPaused {
// VLC is paused if it has a file open but isn't playing it
return [self isRunning] && [self.vlc nameOfCurrentItem] != nil && ![self.vlc playing];
}
// This is from SubTTS's STVLCPlayer class:
// https://github.com/heatherleaf/subtts-mac/blob/master/SubTTS/STVLCPlayer.m
//
// VLC's Scripting Bridge interface doesn't seem to have a cleaner way to do this.
+ (void) togglePlay {
NSString* src = @"tell application id \"org.videolan.vlc\" to play";
- (void) togglePlay {
NSString* src = @"tell application \"VLC\" to play";
NSAppleScript* script = [[NSAppleScript alloc] initWithSource:src];
[script executeAndReturnError:nil];
}
@end
#pragma clang assume_nonnull end
-105
View File
@@ -1,105 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMVOX.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
//
// Self Include
#import "BGMVOX.h"
// Auto-generated Scripting Bridge header
#import "VOX.h"
// Local Includes
#import "BGMScriptingBridge.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMVOX {
BGMScriptingBridge* scriptingBridge;
}
- (instancetype) init {
if ((self = [super initWithMusicPlayerID:[BGMMusicPlayerBase makeID:@"26498C5D-C18B-4689-8B41-9DA91A78FFAD"]
name:@"VOX"
bundleID:@"com.coppertino.Vox"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
return self;
}
- (VoxApplication* __nullable) vox {
return (VoxApplication*)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
}
- (BOOL) isRunning {
return self.vox.running;
}
// isPlaying and isPaused check self.running first just in case VOX is closed but self.vox hasn't become
// nil yet. In that case, reading self.vox.playerState could make Scripting Bridge open VOX.
//
// VOX's comment for its playerState property says "playing = 1, paused = 0".
- (BOOL) isPlaying {
return self.running && (self.vox.playerState == 1);
}
- (BOOL) isPaused {
return self.running && (self.vox.playerState == 0);
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = self.playing;
if (wasPlaying) {
DebugMsg("BGMVOX::pause: Pausing VOX");
[self.vox pause];
}
return wasPlaying;
}
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = self.paused;
if (wasPaused) {
DebugMsg("BGMVOX::unpause: Unpausing VOX");
[self.vox playpause];
}
return wasPaused;
}
@end
#pragma clang assume_nonnull end
@@ -14,7 +14,7 @@
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMVOX.h
// BGMVox.h
// BGMApp
//
// Copyright © 2016 Kyle Neideck
@@ -24,7 +24,7 @@
#import "BGMMusicPlayer.h"
@interface BGMVOX : BGMMusicPlayerBase<BGMMusicPlayer>
@interface BGMVox : BGMMusicPlayer
@end
+94
View File
@@ -0,0 +1,94 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMVox.m
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMVox.h"
// Auto-generated Scripting Bridge header
#import "Vox.h"
// PublicUtility Includes
#undef CoreAudio_ThreadStampMessages
#define CoreAudio_ThreadStampMessages 0 // Requires C++
#include "CADebugMacros.h"
@implementation BGMVox
BGM_MUSIC_PLAYER_DEFAULT_LOAD_METHOD
+ (NSString*) name {
return @"VOX";
}
- (CFNumberRef) pid {
return NULL;
}
+ (CFStringRef) bundleID {
return CFSTR("com.coppertino.Vox");
}
- (VoxApplication* __nullable) vox {
return (VoxApplication*) self.sbApplication;
}
- (BOOL) isRunning {
return self.vox && [self.vox isRunning];
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = [self isPlaying];
if (wasPlaying) {
DebugMsg("BGMVox::pause: Pausing VOX");
[self.vox pause];
}
return wasPlaying;
}
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = [self isPaused];
if (wasPaused) {
DebugMsg("BGMVox::unpause: Unpausing VOX");
[self.vox playpause];
}
return wasPaused;
}
// Vox's comment for playerState says "playing = 1, paused = 0"
- (BOOL) isPlaying {
return [self isRunning] && [self.vox playerState] == 1;
}
- (BOOL) isPaused {
return [self isRunning] && [self.vox playerState] == 0;
}
@end
+2 -5
View File
@@ -24,11 +24,8 @@
#import "BGMMusicPlayer.h"
@interface BGMiTunes : BGMMusicPlayerBase<BGMMusicPlayer>
// The music player ID (see BGMMusicPlayer.h) used by BGMiTunes instances. (Though BGMApp only ever creates one instance of
// BGMiTunes, sharedMusicPlayerID is exposed so iTunes can be set as the default music player.)
+ (NSUUID*) sharedMusicPlayerID;
@interface BGMiTunes : BGMMusicPlayer
@end
+33 -45
View File
@@ -17,7 +17,7 @@
// BGMiTunes.m
// BGMApp
//
// Copyright © 2016-2018 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
@@ -26,62 +26,44 @@
// Auto-generated Scripting Bridge header
#import "iTunes.h"
// Local Includes
#import "BGMScriptingBridge.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#undef CoreAudio_ThreadStampMessages
#define CoreAudio_ThreadStampMessages 0 // Requires C++
#include "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMiTunes
@implementation BGMiTunes {
BGMScriptingBridge* scriptingBridge;
}
+ (NSUUID*) sharedMusicPlayerID {
NSUUID* __nullable musicPlayerID = [[NSUUID alloc] initWithUUIDString:@"7B62B5BF-CF90-4938-84E3-F16DEDC3F608"];
NSAssert(musicPlayerID, @"BGMiTunes::sharedMusicPlayerID: !musicPlayerID");
return (NSUUID*)musicPlayerID;
}
- (instancetype) init {
if ((self = [super initWithMusicPlayerID:[BGMiTunes sharedMusicPlayerID]
name:@"iTunes"
bundleID:@"com.apple.iTunes"])) {
scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
}
+ (void) load {
BGM_MUSIC_PLAYER_ADD_SELF_TO_CLASSES_LIST
return self;
// iTunes is selected as the music player when the user hasn't changed the setting yet
[self setSelectedMusicPlayer:[BGMiTunes new]];
}
+ (NSString*) name {
return @"iTunes";
}
- (CFNumberRef) pid {
return NULL;
}
+ (CFStringRef) bundleID {
return CFSTR("com.apple.iTunes");
}
- (iTunesApplication* __nullable) iTunes {
return (iTunesApplication*)scriptingBridge.application;
}
- (void) onSelect {
[super onSelect];
[scriptingBridge ensurePermission];
return (iTunesApplication*) self.sbApplication;
}
- (BOOL) isRunning {
return self.iTunes.running;
}
// isPlaying and isPaused check self.running first just in case iTunes is closed but self.iTunes hasn't become
// nil yet. In that case, reading self.iTunes.playerState could make Scripting Bridge open iTunes.
- (BOOL) isPlaying {
return self.running && (self.iTunes.playerState == iTunesEPlSPlaying);
}
- (BOOL) isPaused {
return self.running && (self.iTunes.playerState == iTunesEPlSPaused);
return self.iTunes && [self.iTunes isRunning];
}
- (BOOL) pause {
// isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPlaying = self.playing;
BOOL wasPlaying = [self isPlaying];
if (wasPlaying) {
DebugMsg("BGMiTunes::pause: Pausing iTunes");
@@ -93,7 +75,7 @@
- (BOOL) unpause {
// isPaused checks isRunning, so we don't need to check it here and waste an Apple event
BOOL wasPaused = self.paused;
BOOL wasPaused = [self isPaused];
if (wasPaused) {
DebugMsg("BGMiTunes::unpause: Unpausing iTunes");
@@ -103,7 +85,13 @@
return wasPaused;
}
- (BOOL) isPlaying {
return [self isRunning] && [self.iTunes playerState] == iTunesEPlSPlaying;
}
- (BOOL) isPaused {
return [self isRunning] && [self.iTunes playerState] == iTunesEPlSPaused;
}
@end
#pragma clang assume_nonnull end
-181
View File
@@ -1,181 +0,0 @@
/*
* Decibel.h
*
* Generated with
* sdef /Applications/Decibel.app | sdp -fh --basename Decibel
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class DecibelApplication, DecibelDocument, DecibelWindow, DecibelApplication, DecibelTrack;
enum DecibelSaveOptions {
DecibelSaveOptionsYes = 'yes ' /* Save the file. */,
DecibelSaveOptionsNo = 'no ' /* Do not save the file. */,
DecibelSaveOptionsAsk = 'ask ' /* Ask the user whether or not to save the file. */
};
typedef enum DecibelSaveOptions DecibelSaveOptions;
enum DecibelPrintingErrorHandling {
DecibelPrintingErrorHandlingStandard = 'lwst' /* Standard PostScript error handling */,
DecibelPrintingErrorHandlingDetailed = 'lwdt' /* print a detailed report of PostScript errors */
};
typedef enum DecibelPrintingErrorHandling DecibelPrintingErrorHandling;
enum DecibelShuffleMode {
DecibelShuffleModeOff = 'off ' /* Off */,
DecibelShuffleModeTrack = 'trck' /* Track */,
DecibelShuffleModeAlbum = 'albm' /* Album */,
DecibelShuffleModeArtist = 'arts' /* Artist */
};
typedef enum DecibelShuffleMode DecibelShuffleMode;
enum DecibelRepeatMode {
DecibelRepeatModeOff = 'off ' /* Off */,
DecibelRepeatModeTrack = 'trck' /* Track */,
DecibelRepeatModeAlbum = 'albm' /* Album */,
DecibelRepeatModeArtist = 'arts' /* Artist */,
DecibelRepeatModeAll = 'all ' /* All */
};
typedef enum DecibelRepeatMode DecibelRepeatMode;
@protocol DecibelGenericMethods
- (void) closeSaving:(DecibelSaveOptions)saving savingIn:(NSURL *)savingIn; // Close a document.
- (void) saveIn:(NSURL *)in_ as:(id)as; // Save a document.
- (void) printWithProperties:(NSDictionary *)withProperties printDialog:(BOOL)printDialog; // Print a document.
- (void) delete; // Delete an object.
- (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy an object.
- (void) moveTo:(SBObject *)to; // Move an object to a new location.
@end
/*
* Standard Suite
*/
// The application's top-level scripting object.
@interface DecibelApplication : SBApplication
- (SBElementArray<DecibelDocument *> *) documents;
- (SBElementArray<DecibelWindow *> *) windows;
@property (copy, readonly) NSString *name; // The name of the application.
@property (readonly) BOOL frontmost; // Is this the active application?
@property (copy, readonly) NSString *version; // The version number of the application.
- (id) open:(id)x; // Open a document.
- (void) print:(id)x withProperties:(NSDictionary *)withProperties printDialog:(BOOL)printDialog; // Print a document.
- (void) quitSaving:(DecibelSaveOptions)saving; // Quit the application.
- (BOOL) exists:(id)x; // Verify that an object exists.
- (void) play; // Begin audio playback
- (void) pause; // Suspend audio playback
- (void) stop; // Stop audio playback
- (void) playPause; // Begin or suspend audio playback
- (void) seekForward; // Seek forward three seconds
- (void) seekBackward; // Seek backward three seconds
- (void) playSelection; // Play the selected track, or the first track if more than one are selected
- (void) playPreviousTrack; // Play the previous logical track in the playlist
- (void) playNextTrack; // Play the next logical track in the playlist
- (void) addFile:(NSURL *)x; // Add a file to the playlist
- (void) playFile:(NSURL *)x; // Add a file to the playlist and play it
- (void) playTrackAtIndex:(NSInteger)x; // Play a track in the playlist
- (void) increaseDeviceVolume; // Increase the device volume
- (void) decreaseDeviceVolume; // Decrease the device volume
- (void) increaseDigitalVolume; // Increase the digital volume
- (void) decreaseDigitalVolume; // Decrease the digital volume
- (void) clearPlaylist; // Clear the playlist
- (void) scramblePlaylist; // Scramble the playlist
@end
// A document.
@interface DecibelDocument : SBObject <DecibelGenericMethods>
@property (copy, readonly) NSString *name; // Its name.
@property (readonly) BOOL modified; // Has it been modified since the last save?
@property (copy, readonly) NSURL *file; // Its location on disk, if it has one.
@end
// A window.
@interface DecibelWindow : SBObject <DecibelGenericMethods>
@property (copy, readonly) NSString *name; // The title of the window.
- (NSInteger) id; // The unique identifier of the window.
@property NSInteger index; // The index of the window, ordered front to back.
@property NSRect bounds; // The bounding rectangle of the window.
@property (readonly) BOOL closeable; // Does the window have a close button?
@property (readonly) BOOL miniaturizable; // Does the window have a minimize button?
@property BOOL miniaturized; // Is the window minimized right now?
@property (readonly) BOOL resizable; // Can the window be resized?
@property BOOL visible; // Is the window visible right now?
@property (readonly) BOOL zoomable; // Does the window have a zoom button?
@property BOOL zoomed; // Is the window zoomed right now?
@property (copy, readonly) DecibelDocument *document; // The document whose contents are displayed in the window.
@end
/*
* Decibel Scripting Suite
*/
// The Decibel application class.
@interface DecibelApplication (DecibelScriptingSuite)
- (SBElementArray<DecibelTrack *> *) tracks;
@property (readonly) BOOL playing; // Is the player currently playing?
@property (readonly) BOOL shuffling; // Is the player currently shuffling?
@property (readonly) BOOL repeating; // Is the player currently repeating?
@property (copy, readonly) DecibelTrack *nowPlaying; // The track that is currently playing?
@property double deviceVolume; // The current device volume
@property double digitalVolume; // The current digital volume
@property double playbackPosition; // The current playback position [0, 1]
@property double playbackTime; // The current playback time in seconds
@property (readonly) BOOL canPlay; // Is the player currently playing?
@property (readonly) BOOL canPlayPreviousTrack; // Is the player currently playing?
@property (readonly) BOOL canPlayNextTrack; // Is the player currently playing?
@property (readonly) BOOL canAdjustDeviceVolume; // Can the device volume be adjusted?
@property DecibelShuffleMode shuffleMode; // Player shuffle mode
@property DecibelRepeatMode repeatMode; // Player repeat mode
@property (copy, readonly) SBObject *currentPlaylist; // The current playlist
@end
// A track in the playlist
@interface DecibelTrack : SBObject <DecibelGenericMethods>
- (NSString *) id; // The track's ID
@property (copy, readonly) NSURL *file; // The track's location
@property (readonly) double duration; // The track's duration in seconds
@property (readonly) double sampleRate; // The track's sample rate in Hz
@property (readonly) NSInteger bitDepth; // The bit depth
@property (readonly) NSInteger channels; // The track's channels
@property (copy) NSString *title; // The track's title
@property (copy) NSString *artist; // The track's artist
@property (copy) NSString *albumTitle; // The track's album title
@property (copy) NSString *albumArtist; // The track's album artist
@property NSInteger trackNumber; // The track's track number
@property NSInteger trackTotal; // The total number of tracks on the album
@property NSInteger discNumber; // The disc number containing the track
@property NSInteger discTotal; // The total number of discs (for multidisc albums)
@property BOOL partOfACompilation; // Is the track part of a compilation?
@property (copy) NSString *genre; // The track's genre
@property (copy) NSString *composer; // The track's composer
@property (copy) NSString *releaseDate; // The track's release date
@property (copy) NSString *ISRC; // The track's ISRC
@property (copy) id MCN; // The track's MCN
- (void) playTrack; // Play a track in the playlist
@end
-78
View File
@@ -1,78 +0,0 @@
/*
* Hermes.h
*
* Generated with
* sdef /Applications/Hermes.app | sdp -fh --basename Hermes
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class HermesApplication, HermesSong, HermesStation;
// Legal player states
enum HermesPlayerStates {
HermesPlayerStatesStopped = 'stop' /* Player is stopped */,
HermesPlayerStatesPlaying = 'play' /* Player is playing */,
HermesPlayerStatesPaused = 'paus' /* Player is paused */
};
typedef enum HermesPlayerStates HermesPlayerStates;
/*
* Hermes Suite
*/
// The Pandora player.
@interface HermesApplication : SBApplication
- (SBElementArray<HermesStation *> *) stations;
@property NSInteger playbackVolume; // The current playback volume (0100).
@property HermesPlayerStates playbackState; // The current playback state.
@property (readonly) double playbackPosition; // The current songs playback position, in seconds.
@property (readonly) double currentSongDuration; // The duration (length) of the current song, in seconds.
@property (copy) HermesStation *currentStation; // The currently selected Pandora station.
@property (copy, readonly) HermesSong *currentSong; // The currently playing (or paused) Pandora song (WARNING: This is an invalid reference in current versions of Hermes; you must access the current songs properties individually or as a group directly instead.)
- (void) playpause; // Play the current song if it is paused; pause the current song if it is playing.
- (void) pause; // Pause the currently playing song.
- (void) play; // Resume playing the current song.
- (void) nextSong; // Skip to the next song on the current station.
- (void) thumbsUp; // Tell Pandora you like the current song.
- (void) thumbsDown; // Tell Pandora you dont like the current song.
- (void) tiredOfSong; // Tell Pandora youre tired of the current song.
- (void) increaseVolume; // Increase the playback volume.
- (void) decreaseVolume; // Decrease the playback volume.
- (void) maximizeVolume; // Set the playback volume to its maximum level.
- (void) mute; // Mutes playback, saving the current volume level.
- (void) unmute; // Restores the volume to the level prior to muting.
@end
// A Pandora song (track).
@interface HermesSong : SBObject
@property (copy, readonly) NSString *title; // The songs title.
@property (copy, readonly) NSString *artist; // The songs artist.
@property (copy, readonly) NSString *album; // The songs album.
@property (copy, readonly) NSString *artworkURL; // An image URL for the albums cover artwork.
@property (readonly) NSInteger rating; // The songs numeric rating.
@property (copy, readonly) NSString *albumURL; // A Pandora URL for more information on the album.
@property (copy, readonly) NSString *artistURL; // A Pandora URL for more information on the artist.
@property (copy, readonly) NSString *trackURL; // A Pandora URL for more information on the track.
@end
// A Pandora station.
@interface HermesStation : SBObject
@property (copy, readonly) NSString *name; // The stations name.
@property (copy, readonly) NSString *stationID; // The stations ID.
@end
-252
View File
@@ -1,252 +0,0 @@
/*
* Swinsian.h
*
* Generated with
* sdef /Applications/Swinsian.app | sdp -fh --basename Swinsian
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class SwinsianItem, SwinsianColor, SwinsianWindow, SwinsianApplication, SwinsianPlaylist, SwinsianLibrary, SwinsianTrack, SwinsianLibraryTrack, SwinsianIPodTrack, SwinsianQueue, SwinsianSmartPlaylist, SwinsianNormalPlaylist, SwinsianPlaylistFolder, SwinsianAudioDevice;
enum SwinsianSaveOptions {
SwinsianSaveOptionsYes = 'yes ' /* Save the file. */,
SwinsianSaveOptionsNo = 'no ' /* Do not save the file. */,
SwinsianSaveOptionsAsk = 'ask ' /* Ask the user whether or not to save the file. */
};
typedef enum SwinsianSaveOptions SwinsianSaveOptions;
enum SwinsianPlayerState {
SwinsianPlayerStateStopped = 'kPSS',
SwinsianPlayerStatePlaying = 'kPSP',
SwinsianPlayerStatePaused = 'kPSp'
};
typedef enum SwinsianPlayerState SwinsianPlayerState;
@protocol SwinsianGenericMethods
- (void) closeSaving:(SwinsianSaveOptions)saving savingIn:(NSURL *)savingIn; // Close an object.
- (void) delete; // Delete an object.
- (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location.
- (BOOL) exists; // Verify if an object exists.
- (void) moveTo:(SBObject *)to; // Move object(s) to a new location.
- (void) saveIn:(NSURL *)in_ as:(NSString *)as; // Save an object.
@end
/*
* Standard Suite
*/
// A scriptable object.
@interface SwinsianItem : SBObject <SwinsianGenericMethods>
@property (copy) NSDictionary *properties; // All of the object's properties.
@end
// A color.
@interface SwinsianColor : SBObject <SwinsianGenericMethods>
@end
// A window.
@interface SwinsianWindow : SBObject <SwinsianGenericMethods>
@property (copy) NSString *name; // The full title of the window.
- (NSNumber *) id; // The unique identifier of the window.
@property NSRect bounds; // The bounding rectangle of the window.
@property (readonly) BOOL closeable; // Whether the window has a close box.
@property (readonly) BOOL titled; // Whether the window has a title bar.
@property (copy) NSNumber *index; // The index of the window in the back-to-front window ordering.
@property (readonly) BOOL floating; // Whether the window floats.
@property (readonly) BOOL miniaturizable; // Whether the window can be miniaturized.
@property BOOL miniaturized; // Whether the window is currently miniaturized.
@property (readonly) BOOL modal; // Whether the window is the application's current modal window.
@property (readonly) BOOL resizable; // Whether the window can be resized.
@property BOOL visible; // Whether the window is currently visible.
@property (readonly) BOOL zoomable; // Whether the window can be zoomed.
@property BOOL zoomed; // Whether the window is currently zoomed.
@property (copy, readonly) NSArray<SwinsianTrack *> *selection; // Currently seleted tracks
@end
/*
* Swinsian Suite
*/
// The application
@interface SwinsianApplication : SBApplication
- (SBElementArray<SwinsianWindow *> *) windows;
- (SBElementArray<SwinsianPlaylist *> *) playlists;
- (SBElementArray<SwinsianSmartPlaylist *> *) smartPlaylists;
- (SBElementArray<SwinsianNormalPlaylist *> *) normalPlaylists;
- (SBElementArray<SwinsianLibrary *> *) libraries;
- (SBElementArray<SwinsianTrack *> *) tracks;
- (SBElementArray<SwinsianAudioDevice *> *) audioDevices;
@property (copy, readonly) NSString *name; // The name of the application.
@property (readonly) BOOL frontmost; // Is this the frontmost (active) application?
@property (copy, readonly) NSString *version; // The version of the application.
@property NSInteger playerPosition; // the players position within the currently playing track in seconds.
@property (copy, readonly) SwinsianTrack *currentTrack; // the currently playing track
@property (copy) NSNumber *soundVolume; // the volume. (0 minimum, 100 maximum)
@property (readonly) SwinsianPlayerState playerState; // are we stopped, paused or still playing?
@property (copy, readonly) SwinsianQueue *playbackQueue; // the currently queued tracks
@property (copy) SwinsianAudioDevice *outputDevice; // current audio output device
- (void) open:(NSURL *)x; // Open an object.
- (void) print:(NSURL *)x; // Print an object.
- (void) quitSaving:(SwinsianSaveOptions)saving; // Quit an application.
- (void) play; // begin playing the current playlist
- (void) pause; // pause playback
- (void) nextTrack; // skip to the next track in the current playlist
- (void) stop; // stop playback
- (NSArray<SwinsianTrack *> *) searchPlaylist:(SwinsianPlaylist *)playlist for:(NSString *)for_; // search a playlist for tracks matching a string
- (void) previousTrack; // skip back to the previous track
- (void) playpause; // toggle play/pause
- (void) addTracks:(NSArray<SwinsianTrack *> *)tracks to:(SwinsianNormalPlaylist *)to; // add a track to a playlist
- (void) notify; // show currently playing track notification
- (void) rescanTags:(NSArray<SwinsianTrack *> *)x; // rescan tags on tracks
- (NSArray<SwinsianTrack *> *) findTrack:(NSString *)x; // Finds tracks for the given path
- (void) removeTracks:(NSArray<SwinsianTrack *> *)tracks from:(SwinsianNormalPlaylist *)from; // remove tracks from a playlist
@end
// generic playlist type, subcasses include smart playlist and normal playlist
@interface SwinsianPlaylist : SwinsianItem
- (SBElementArray<SwinsianTrack *> *) tracks;
@property (copy) NSString *name; // the name of the playlist
@property (readonly) BOOL smart; // is this a smart playlist
@end
@interface SwinsianLibrary : SwinsianItem
- (SBElementArray<SwinsianTrack *> *) tracks;
@end
// a music track
@interface SwinsianTrack : SwinsianItem
@property (copy) NSString *album; // the album of the track
@property (copy) NSString *artist; // the artist
@property (copy) NSString *composer; // the composer
@property (copy) NSString *genre; // the genre
@property (copy, readonly) NSString *time; // the length of the track in text format as MM:SS
@property NSInteger year; // the year the track was recorded
@property (copy, readonly) NSDate *dateAdded; // the date the track was added to the library
@property (readonly) double duration; // the length of the track in seconds
@property (copy, readonly) NSString *location; // location on disk
@property (readonly) BOOL iPodTrack; // TRUE if the track is on an iPod
@property (copy) NSString *name; // the title of the track (same as title)
@property (readonly) NSInteger bitRate; // the bitrate of the track
@property (copy, readonly) NSString *kind; // a text description of the type of file the track is
@property (copy) NSNumber *rating; // Track rating. 0-5
@property NSInteger trackNumber; // the Track number
@property (readonly) NSInteger fileSize; // file size in bytes
@property (copy, readonly) NSImage *albumArt; // the album artwork
@property (copy, readonly) NSString *artFormat; // the data format for this piece of artwork. text that will be "PNG" or "JPEG". getting the album art property first will mean this information has been retrieved already, otherwise the tags for the file will have to be re-read
@property (copy) NSNumber *discNumber; // the disc number
@property (copy) NSNumber *discCount; // the total number of discs in the album
- (NSString *) id; // uuid
@property (copy) NSString *albumArtist; // the album artist
@property (copy, readonly) NSString *albumArtistOrArtist; // the album artist of the track, or is none is set, the artist
@property BOOL compilation; // compilation flag
@property (copy) NSString *title; // track title (the same as name)
@property (copy) NSString *comment; // the comment
@property (copy, readonly) NSDate *dateCreated; // the date created
@property (readonly) NSInteger channels; // audio channel count
@property (readonly) NSInteger sampleRate; // audio sample rate
@property (readonly) NSInteger bitDepth; // the audio bit depth
@property (copy) NSDate *lastPlayed; // date track was last played
@property (copy) NSString *lyrics; // track lyrics
@property (copy, readonly) NSString *path; // POSIX style path
@property (copy) NSString *grouping; // grouping
@property (copy) NSString *publisher; // the publisher
@property (copy) NSString *conductor; // the conductor
@property (copy) NSString *objectDescription; // the description
@property (copy, readonly) NSString *encoder; // the encoder
@property (copy, readonly) NSString *copyright; // the copyright
@property (copy) NSString *catalogNumber; // the catalog number
@property (copy, readonly) NSDate *dateModified; // the date modified
@property NSInteger playCount; // the play count
@property (copy) NSNumber *trackCount; // the total number of tracks in the album
@end
@interface SwinsianLibraryTrack : SwinsianTrack
@end
@interface SwinsianIPodTrack : SwinsianTrack
@property (copy, readonly) NSString *iPodName; // the name of the iPod this track is on
@end
// The playback queue
@interface SwinsianQueue : SwinsianItem
- (SBElementArray<SwinsianTrack *> *) tracks;
@end
// a smart playlist
@interface SwinsianSmartPlaylist : SwinsianPlaylist
@end
// a normal, non-smart, playlist
@interface SwinsianNormalPlaylist : SwinsianPlaylist
- (SBElementArray<SwinsianTrack *> *) tracks;
- (NSString *) id; // uuid
@end
// folder of playlists
@interface SwinsianPlaylistFolder : SwinsianPlaylist
- (SBElementArray<SwinsianPlaylist *> *) playlists;
- (NSString *) id; // uuid
@end
// an audio output device
@interface SwinsianAudioDevice : SBObject <SwinsianGenericMethods>
@property (copy, readonly) NSString *name; // device name
- (NSString *) id; // uuid
- (void) setId: (NSString *) id;
@end
+253
View File
@@ -0,0 +1,253 @@
/*
* VLC_10.9.h
*
* Generated with
* sdef /Applications/VLC.app | sdp -fh -V 10.9 --basename VLC
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class VLCItem, VLCApplication, VLCColor, VLCDocument, VLCWindow, VLCAttributeRun, VLCCharacter, VLCParagraph, VLCText, VLCAttachment, VLCWord, VLCPrintSettings;
enum VLCSavo {
VLCSavoAsk = 'ask ' /* Ask the user whether or not to save the file. */,
VLCSavoNo = 'no ' /* Do not save the file. */,
VLCSavoYes = 'yes ' /* Save the file. */
};
typedef enum VLCSavo VLCSavo;
enum VLCEnum {
VLCEnumStandard = 'lwst' /* Standard PostScript error handling */,
VLCEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */
};
typedef enum VLCEnum VLCEnum;
@protocol VLCGenericMethods
- (void) closeSaving:(VLCSavo)saving savingIn:(NSURL *)savingIn; // Close an object.
- (void) delete; // Delete an object.
- (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location.
- (BOOL) exists; // Verify if an object exists.
- (void) moveTo:(SBObject *)to; // Move object(s) to a new location.
- (void) saveAs:(NSString *)as in:(NSURL *)in_; // Save an object.
- (void) fullscreen; // Toggle between fullscreen and windowed mode.
- (void) GetURL; // Get a URL
- (void) mute; // Mute the audio
- (void) next; // Go to the next item in the playlist or the next chapter in the DVD/VCD.
- (void) OpenURL; // Open a URL
- (void) play; // Start playing the current playlistitem or pause it when it is already playing.
- (void) previous; // Go to the previous item in the playlist or the previous chapter in the DVD/VCD.
- (void) stepBackward; // Step the current playlist item backward the specified step width (default is 2) (1=extraShort, 2=short, 3=medium, 4=long).
- (void) stepForward; // Step the current playlist item forward the specified step width (default is 2) (1=extraShort, 2=short, 3=medium, 4=long).
- (void) stop; // Stop playing the current playlistitem
- (void) volumeDown; // Bring the volume down by one step. There are 32 steps from 0 to 400% volume.
- (void) volumeUp; // Bring the volume up by one step. There are 32 steps from 0 to 400% volume.
@end
/*
* Standard Suite
*/
// A scriptable object.
@interface VLCItem : SBObject <VLCGenericMethods>
@property (copy) NSDictionary *properties; // All of the object's properties.
@end
// An application's top level scripting object.
@interface VLCApplication : SBApplication
- (SBElementArray *) documents;
- (SBElementArray *) windows;
@property (readonly) BOOL frontmost; // Is this the frontmost (active) application?
@property (copy, readonly) NSString *name; // The name of the application.
@property (copy, readonly) NSString *version; // The version of the application.
- (VLCDocument *) open:(NSURL *)x; // Open an object.
- (void) print:(NSURL *)x printDialog:(BOOL)printDialog withProperties:(VLCPrintSettings *)withProperties; // Print an object.
- (void) quitSaving:(VLCSavo)saving; // Quit an application.
@end
// A color.
@interface VLCColor : VLCItem
@end
// A document.
@interface VLCDocument : VLCItem
@property (readonly) BOOL modified; // Has the document been modified since the last save?
@property (copy) NSString *name; // The document's name.
@property (copy) NSString *path; // The document's path.
@end
// A window.
@interface VLCWindow : VLCItem
@property NSRect bounds; // The bounding rectangle of the window.
@property (readonly) BOOL closeable; // Whether the window has a close box.
@property (copy, readonly) VLCDocument *document; // The document whose contents are being displayed in the window.
@property (readonly) BOOL floating; // Whether the window floats.
- (NSInteger) id; // The unique identifier of the window.
@property NSInteger index; // The index of the window, ordered front to back.
@property (readonly) BOOL miniaturizable; // Whether the window can be miniaturized.
@property BOOL miniaturized; // Whether the window is currently miniaturized.
@property (readonly) BOOL modal; // Whether the window is the application's current modal window.
@property (copy) NSString *name; // The full title of the window.
@property (readonly) BOOL resizable; // Whether the window can be resized.
@property (readonly) BOOL titled; // Whether the window has a title bar.
@property BOOL visible; // Whether the window is currently visible.
@property (readonly) BOOL zoomable; // Whether the window can be zoomed.
@property BOOL zoomed; // Whether the window is currently zoomed.
@end
/*
* Text Suite
*/
// This subdivides the text into chunks that all have the same attributes.
@interface VLCAttributeRun : VLCItem
- (SBElementArray *) attachments;
- (SBElementArray *) attributeRuns;
- (SBElementArray *) characters;
- (SBElementArray *) paragraphs;
- (SBElementArray *) words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// This subdivides the text into characters.
@interface VLCCharacter : VLCItem
- (SBElementArray *) attachments;
- (SBElementArray *) attributeRuns;
- (SBElementArray *) characters;
- (SBElementArray *) paragraphs;
- (SBElementArray *) words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// This subdivides the text into paragraphs.
@interface VLCParagraph : VLCItem
- (SBElementArray *) attachments;
- (SBElementArray *) attributeRuns;
- (SBElementArray *) characters;
- (SBElementArray *) paragraphs;
- (SBElementArray *) words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// Rich (styled) text
@interface VLCText : VLCItem
- (SBElementArray *) attachments;
- (SBElementArray *) attributeRuns;
- (SBElementArray *) characters;
- (SBElementArray *) paragraphs;
- (SBElementArray *) words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// Represents an inline text attachment. This class is used mainly for make commands.
@interface VLCAttachment : VLCText
@property (copy) NSString *fileName; // The path to the file for the attachment
@end
// This subdivides the text into words.
@interface VLCWord : VLCItem
- (SBElementArray *) attachments;
- (SBElementArray *) attributeRuns;
- (SBElementArray *) characters;
- (SBElementArray *) paragraphs;
- (SBElementArray *) words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
/*
* VLC suite
*/
// VLC's top level scripting object
@interface VLCApplication (VLCSuite)
@property NSInteger audioVolume; // The volume of the current playlist item from 0 to 4, where 4 is 400%
@property NSInteger currentTime; // The current time of the current playlist item in seconds.
@property (readonly) NSInteger durationOfCurrentItem; // The duration of the current playlist item in seconds.
@property BOOL fullscreenMode; // indicates wheter fullscreen is enabled or not
@property (readonly) BOOL muted; // Is VLC currently muted?
@property (copy, readonly) NSString *nameOfCurrentItem; // Name of the current playlist item.
@property (copy, readonly) NSString *pathOfCurrentItem; // Path to the current playlist item.
@property (readonly) BOOL playing; // Is VLC playing an item?
@end
/*
* Type Definitions
*/
@interface VLCPrintSettings : SBObject <VLCGenericMethods>
@property NSInteger copies; // the number of copies of a document to be printed
@property BOOL collating; // Should printed copies be collated?
@property NSInteger startingPage; // the first page of the document to be printed
@property NSInteger endingPage; // the last page of the document to be printed
@property NSInteger pagesAcross; // number of logical pages laid across a physical page
@property NSInteger pagesDown; // number of logical pages laid out down a physical page
@property (copy) NSDate *requestedPrintTime; // the time at which the desktop printer should print the document
@property VLCEnum errorHandling; // how errors are handled
@property (copy) NSString *faxNumber; // for fax number
@property (copy) NSString *targetPrinter; // for target printer
@end
@@ -1,8 +1,8 @@
/*
* VOX.h
* Vox.h
*
* Generated with
* sdef /Applications/VOX.app | sdp -fh --basename VOX
* sdef /Applications/Vox.app | sdp -fh --basename Vox
*/
#import <AppKit/AppKit.h>
-143
View File
@@ -1,143 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAboutPanel.m
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMAboutPanel.h"
// Local Includes
#import "BGM_Types.h"
// PublicUtility Includes
#include "CADebugMacros.h"
NS_ASSUME_NONNULL_BEGIN
static NSInteger const kVersionLabelTag = 1;
static NSInteger const kCopyrightLabelTag = 2;
static NSInteger const kProjectWebsiteLabelTag = 3;
@implementation BGMAboutPanel {
NSPanel* aboutPanel;
NSTextField* versionLabel;
NSTextField* copyrightLabel;
NSTextField* websiteLabel;
NSTextView* licenseView;
}
- (instancetype)initWithPanel:(NSPanel*)inAboutPanel licenseView:(NSTextView*)inLicenseView {
if ((self = [super init])) {
aboutPanel = inAboutPanel;
versionLabel = [[aboutPanel contentView] viewWithTag:kVersionLabelTag];
copyrightLabel = [[aboutPanel contentView] viewWithTag:kCopyrightLabelTag];
websiteLabel = [[aboutPanel contentView] viewWithTag:kProjectWebsiteLabelTag];
licenseView = inLicenseView;
[self initAboutPanel];
}
return self;
}
- (void) initAboutPanel {
// Set up the About Background Music window
NSBundle* bundle = [NSBundle mainBundle];
if (bundle == nil) {
NSLog(@"Background Music: BGMAboutPanel::initAboutPanel: Could not find main bundle");
} else {
// Version number label
NSString* __nullable version =
[[bundle infoDictionary] objectForKey:@"CFBundleShortVersionString"];
if (version) {
versionLabel.stringValue = [NSString stringWithFormat:@"Version %@", version];
}
// Copyright notice label
NSString* __nullable copyrightNotice =
[[bundle infoDictionary] objectForKey:@"NSHumanReadableCopyright"];
if (copyrightNotice) {
copyrightLabel.stringValue = (NSString*)copyrightNotice;
}
// Project website link label
websiteLabel.selectable = YES;
websiteLabel.allowsEditingTextAttributes = YES;
NSString* projectURL = [NSString stringWithUTF8String:kBGMProjectURL];
NSFont* linkFont = websiteLabel.font ? websiteLabel.font : [NSFont labelFontOfSize:0.0];
websiteLabel.attributedStringValue =
[[NSAttributedString alloc] initWithString:projectURL
attributes:@{ NSLinkAttributeName: projectURL,
NSFontAttributeName: linkFont }];
// Load the text of the license into the text view
NSString* __nullable licensePath = [bundle pathForResource:@"LICENSE" ofType:nil];
NSError* err;
NSString* __nullable licenseStr = (!licensePath ? nil :
[NSString stringWithContentsOfFile:(NSString*)licensePath
encoding:NSASCIIStringEncoding
error:&err]);
if (err || !licenseStr || [licenseStr isEqualToString:@""]) {
NSLog(@"Error loading license file: %@", err);
licenseStr = @"Error: could not open license file.";
}
licenseView.string = (NSString*)licenseStr;
NSFont* __nullable font = [NSFont fontWithName:@"Andale Mono" size:0.0];
if (font) {
licenseView.textStorage.font = font;
}
}
}
- (void) show {
DebugMsg("BGMAboutPanel::showAboutPanel: Opening \"About Background Music\" panel");
[NSApp activateIgnoringOtherApps:YES];
[aboutPanel setIsVisible:YES];
[aboutPanel makeKeyAndOrderFront:self];
}
@end
@implementation BGMLinkField
- (void) resetCursorRects {
// Change the mouse cursor when hovering over the link. (It does change by default, but only after
// you've clicked it once.)
[self addCursorRect:self.bounds cursor:[NSCursor pointingHandCursor]];
}
@end
NS_ASSUME_NONNULL_END
@@ -20,23 +20,21 @@
// Copyright © 2016 Kyle Neideck
//
// Local Includes
#import "BGMAudioDeviceManager.h"
#import "BGMMusicPlayers.h"
// PublicUtility Includes
#include "BGMAudioDeviceManager.h"
// System Includes
#import <Cocoa/Cocoa.h>
#import <AppKit/AppKit.h>
#pragma clang assume_nonnull begin
@interface BGMAutoPauseMusicPrefs : NSObject
// Note that toggleAutoPauseMusicMenuItem is the item in the main menu that enables/disables auto-pausing, rather than the
// disabled "Auto-pause" menu item in the preferences menu that acts as a section heading. This class updates the text of
// toggleAutoPauseMusicMenuItem when the user changes the music player.
- (id) initWithPreferencesMenu:(NSMenu*)inPrefsMenu
audioDevices:(BGMAudioDeviceManager*)inAudioDevices
musicPlayers:(BGMMusicPlayers*)inMusicPlayers;
toggleAutoPauseMusicMenuItem:(NSMenuItem*)inToggleAutoPauseMusicMenuItem
audioDevices:(BGMAudioDeviceManager*)inAudioDevices;
@end
#pragma clang assume_nonnull end
@@ -24,94 +24,182 @@
#import "BGMAutoPauseMusicPrefs.h"
// Local Includes
#import "BGM_Types.h"
#include "BGM_Types.h"
#import "BGMMusicPlayer.h"
#pragma clang assume_nonnull begin
static NSString* const kToggleAutoPauseMusicMenuItemTitleFormat = @"Auto-pause %@";
static float const kMenuItemIconScalingFactor = 1.15f;
static NSInteger const kPrefsMenuAutoPauseHeaderTag = 1;
@implementation BGMAutoPauseMusicPrefs {
BGMAudioDeviceManager* audioDevices;
BGMMusicPlayers* musicPlayers;
NSMenuItem* toggleAutoPauseMusicMenuItem;
NSMenu* prefsMenu;
NSArray<NSMenuItem*>* musicPlayerMenuItems;
BGMGeneric(NSArray, NSMenuItem*)* musicPlayerMenuItems;
}
- (id) initWithPreferencesMenu:(NSMenu*)inPrefsMenu
audioDevices:(BGMAudioDeviceManager*)inAudioDevices
musicPlayers:(BGMMusicPlayers*)inMusicPlayers {
toggleAutoPauseMusicMenuItem:(NSMenuItem*)inToggleAutoPauseMusicMenuItem
audioDevices:(BGMAudioDeviceManager*)inAudioDevices {
if ((self = [super init])) {
prefsMenu = inPrefsMenu;
toggleAutoPauseMusicMenuItem = inToggleAutoPauseMusicMenuItem;
audioDevices = inAudioDevices;
musicPlayers = inMusicPlayers;
musicPlayerMenuItems = @[];
[self initPreferencesMenuSection];
[self initSelectedMusicPlayer];
[self initMenuSection];
[self updateMenuItemTitle];
}
return self;
}
- (void) initPreferencesMenuSection {
// Add the menu items related to auto-pausing music to the Preferences submenu
- (void) initSelectedMusicPlayer {
// TODO: It would make more sense to either just save the music player setting in the User Defaults (the same way AppDelegate saves
// whether auto-pause is enabled) or to send a "musicPlayerID" to the driver, which would only be used by BGMApp. If the latter,
// we might as well save the auto-pause setting on the driver as well just so all the settings are saved in the same place.
// Get the currently selected music player from the driver and update the global in BGMMusicPlayerBase
// The bundle ID and PID set on the driver
CFNumberRef selectedPID = static_cast<CFNumberRef>([audioDevices bgmDevice].GetPropertyData_CFType(kBGMMusicPlayerProcessIDAddress));
CFStringRef selectedBundleID = [audioDevices bgmDevice].GetPropertyData_CFString(kBGMMusicPlayerBundleIDAddress);
DebugMsg("BGMAutoPauseMusicPrefs::initSelectedMusicPlayer: Music player on BGMDriver: bundleID=%s PID=%s",
selectedBundleID == NULL ? "null" : CFStringGetCStringPtr(selectedBundleID, kCFStringEncodingUTF8),
selectedPID == NULL ? "null" : [[(__bridge NSNumber*)selectedPID stringValue] UTF8String]);
// If no music player is set on the driver, set it to the one set in the app and return
if ((selectedBundleID == NULL || CFEqual(selectedBundleID, CFSTR(""))) &&
(selectedPID == NULL || [(__bridge NSNumber*)selectedPID intValue] < 1)) {
[self updateBGMDevice];
return;
}
// The IDs set in the app, which will be updated if they don't match the values from the driver
CFNumberRef selectedPIDInBGMApp = [[BGMMusicPlayerBase selectedMusicPlayer] pid];
CFStringRef selectedBundleIDInBGMApp = [[[BGMMusicPlayerBase selectedMusicPlayer] class] bundleID];
// Return early if the music player selected in the app already matches the driver
if ((selectedPID != NULL && selectedPIDInBGMApp != NULL && CFEqual(selectedPID, selectedPIDInBGMApp)) ||
(selectedBundleID != NULL && selectedBundleIDInBGMApp != NULL && CFEqual(selectedBundleID, selectedBundleIDInBGMApp))) {
return;
}
// Check each selectable music player
for (Class mpClass in [BGMMusicPlayerBase musicPlayerClasses]) {
// Look for a running instance of the music player by PID
if (selectedPID != NULL &&
[mpClass respondsToSelector:@selector(pidsOfRunningInstances)] &&
[mpClass respondsToSelector:@selector(initWithPIDFromNSNumber:)]) {
BGMGeneric(NSArray, NSNumber*)* mpPIDs = [mpClass pidsOfRunningInstances];
for (NSNumber* mpPID in mpPIDs) {
if (CFEqual((__bridge CFNumberRef)mpPID, selectedPID)) {
DebugMsg("BGMAutoPauseMusicPrefs::initSelectedMusicPlayer: Selected music player on driver was %s (found by pid)",
[[mpClass name] UTF8String]);
[BGMMusicPlayerBase setSelectedMusicPlayer:[[mpClass alloc] initWithPIDFromNSNumber:mpPID]];
return;
}
}
}
// Check by bundle ID
CFStringRef mpBundleID = [mpClass bundleID];
if (selectedBundleID != NULL &&
mpBundleID != NULL &&
CFEqual(mpBundleID, selectedBundleID)) {
// Found the selected music player. Update the app to match the driver and return.
DebugMsg("BGMAutoPauseMusicPrefs::initSelectedMusicPlayer: Selected music player on driver was %s",
[[mpClass name] UTF8String]);
[BGMMusicPlayerBase setSelectedMusicPlayer:[mpClass new]];
return;
}
}
}
- (void) initMenuSection {
// Add the menu items related to auto-pausing music to the settings submenu
// The index to start inserting music player menu items at
NSInteger musicPlayerItemsIndex = [prefsMenu indexOfItemWithTag:kPrefsMenuAutoPauseHeaderTag] + 1;
// Insert the menu items used to change the music player app.
for (id<BGMMusicPlayer> musicPlayer in musicPlayers.musicPlayers) {
// Create an menu item for this music player.
NSMenuItem* menuItem = [prefsMenu insertItemWithTitle:musicPlayer.name
// Insert the options to change the music player app
for (Class musicPlayerClass in [BGMMusicPlayerBase musicPlayerClasses]) {
NSMenuItem* menuItem = [prefsMenu insertItemWithTitle:[musicPlayerClass name]
action:@selector(handleMusicPlayerChange:)
keyEquivalent:@""
atIndex:musicPlayerItemsIndex];
atIndex:musicPlayerItemsIndex];
musicPlayerMenuItems = [musicPlayerMenuItems arrayByAddingObject:menuItem];
// Associate the music player with the menu item
menuItem.representedObject = musicPlayer;
// Create an instance for this music player and associate it with the menu item
[menuItem setRepresentedObject:[musicPlayerClass new]];
// Show the menu item for the selected music player as selected
if (musicPlayers.selectedMusicPlayer == musicPlayer) {
menuItem.state = NSOnState;
// Show the default music player as selected
if (musicPlayerClass == [[BGMMusicPlayerBase selectedMusicPlayer] class]) {
[menuItem setState:NSOnState];
}
// Set the menu item's icon
NSImage* __nullable icon = musicPlayer.icon;
// Set the item's icon
NSImage* icon = [musicPlayerClass icon];
if (icon == nil) {
// Set a blank icon so the text lines up
icon = [NSImage new];
}
// Size the icon relative to the size of the item's text
CGFloat length = [NSFont menuBarFontOfSize:0].pointSize * kMenuItemIconScalingFactor;
icon.size = NSMakeSize(length, length);
menuItem.image = icon;
CGFloat length = [[NSFont menuBarFontOfSize:0] pointSize] * kMenuItemIconScalingFactor;
[icon setSize:NSMakeSize(length, length)];
[menuItem setImage:icon];
menuItem.target = self;
menuItem.indentationLevel = 1;
[menuItem setTarget:self];
[menuItem setIndentationLevel:1];
}
}
- (void) handleMusicPlayerChange:(NSMenuItem*)sender {
// Set the new music player as the selected music player
id<BGMMusicPlayer> musicPlayer = sender.representedObject;
NSAssert(musicPlayer, @"BGMAutoPauseMusicPrefs::handleMusicPlayerChange: !musicPlayer");
BGMMusicPlayer* musicPlayer = [sender representedObject];
assert(musicPlayer != nil);
[BGMMusicPlayerBase setSelectedMusicPlayer:musicPlayer];
musicPlayers.selectedMusicPlayer = musicPlayer;
// Select/deselect the menu items
// Select/Deselect the menu items
for (NSMenuItem* item in musicPlayerMenuItems) {
BOOL isNewlySelectedMusicPlayer = (item == sender);
item.state = (isNewlySelectedMusicPlayer ? NSOnState : NSOffState);
BOOL isNewlySelectedMusicPlayer = item == sender;
[item setState:(isNewlySelectedMusicPlayer ? NSOnState : NSOffState)];
}
[self updateMenuItemTitle];
[self updateBGMDevice];
}
- (void) updateBGMDevice {
// Send the music player's PID or bundle ID to the driver
DebugMsg("BGMAutoPauseMusicPrefs::updateBGMDevice: Setting the music player to %s on the driver",
[[[[BGMMusicPlayer selectedMusicPlayer] class] name] UTF8String]);
CFNumberRef __nullable pid = [[BGMMusicPlayer selectedMusicPlayer] pid];
if (pid != NULL) {
[audioDevices bgmDevice].SetPropertyData_CFType(kBGMMusicPlayerProcessIDAddress, pid);
} else {
CFStringRef __nullable bundleID = [[[BGMMusicPlayer selectedMusicPlayer] class] bundleID];
if (bundleID != NULL) {
[audioDevices bgmDevice].SetPropertyData_CFString(kBGMMusicPlayerBundleIDAddress, bundleID);
}
}
}
- (void) updateMenuItemTitle {
// Set the title of the Auto-pause Music menu item, including the name of the selected music player
NSString* musicPlayerName = [[[BGMMusicPlayer selectedMusicPlayer] class] name];
NSString* title = [NSString stringWithFormat:kToggleAutoPauseMusicMenuItemTitleFormat, musicPlayerName];
[toggleAutoPauseMusicMenuItem setTitle:title];
}
@end
#pragma clang assume_nonnull end
@@ -27,8 +27,6 @@
#import <AppKit/AppKit.h>
#pragma clang assume_nonnull begin
@interface BGMOutputDevicePrefs : NSObject
- (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices;
@@ -36,5 +34,3 @@
@end
#pragma clang assume_nonnull end
+32 -190
View File
@@ -17,30 +17,23 @@
// BGMOutputDevicePrefs.mm
// BGMApp
//
// Copyright © 2016, 2017 Kyle Neideck
// Copyright © 2016 Kyle Neideck
//
// Self Include
#import "BGMOutputDevicePrefs.h"
// Local Includes
#import "BGM_Utils.h"
#import "BGM_Types.h"
#import "BGMAudioDevice.h"
// PublicUtility Includes
#include "CAHALAudioSystemObject.h"
#include "CAHALAudioDevice.h"
#include "CAAutoDisposer.h"
#pragma clang assume_nonnull begin
static NSInteger const kOutputDeviceMenuItemTag = 2;
@implementation BGMOutputDevicePrefs {
BGMAudioDeviceManager* audioDevices;
NSMutableArray<NSMenuItem*>* outputDeviceMenuItems;
BGMGeneric(NSMutableArray, NSMenuItem*)* outputDeviceMenuItems;
}
- (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices {
@@ -57,209 +50,58 @@ static NSInteger const kOutputDeviceMenuItemTag = 2;
for (NSMenuItem* item in outputDeviceMenuItems) {
[prefsMenu removeItem:item];
}
[outputDeviceMenuItems removeAllObjects];
// Insert menu items after the item for the "Output Device" heading
const NSInteger menuItemsIdx = [prefsMenu indexOfItemWithTag:kOutputDeviceMenuItemTag] + 1;
// Add a menu item for each output device
CAHALAudioSystemObject audioSystem;
UInt32 numDevices = audioSystem.GetNumberAudioDevices();
if (numDevices > 0) {
CAAutoArrayDelete<AudioObjectID> devices(numDevices);
audioSystem.GetAudioDevices(numDevices, devices);
for (UInt32 i = 0; i < numDevices; i++) {
[self insertMenuItemsForDevice:devices[i] preferencesMenu:prefsMenu];
}
}
}
- (void) insertMenuItemsForDevice:(BGMAudioDevice)device preferencesMenu:(NSMenu*)prefsMenu {
// Insert menu items after the item for the "Output Device" heading.
const NSInteger menuItemsIdx = [prefsMenu indexOfItemWithTag:kOutputDeviceMenuItemTag] + 1;
BOOL canBeOutputDevice = YES;
BGMLogAndSwallowExceptions("BGMOutputDevicePrefs::insertMenuItemsForDevice", ([&] {
canBeOutputDevice = device.CanBeOutputDeviceInBGMApp();
}));
if (canBeOutputDevice) {
for (NSMenuItem* item : [self createMenuItemsForDevice:device]) {
[prefsMenu insertItem:item atIndex:menuItemsIdx];
[outputDeviceMenuItems addObject:item];
}
}
}
- (NSArray<NSMenuItem*>*) createMenuItemsForDevice:(CAHALAudioDevice)device {
// We fill this array with a menu item for each output device (or each data source for each device) on
// the system.
NSMutableArray<NSMenuItem*>* items = [NSMutableArray new];
AudioObjectPropertyScope scope = kAudioObjectPropertyScopeOutput;
UInt32 channel = 0; // 0 is the master channel.
// If the device has data sources, create a menu item for each. Otherwise, create a single menu item
// for the device. This way the menu items' titles will be, for example, "Internal Speakers" rather
// than "Built-in Output".
//
// TODO: Handle data destinations as well? I don't have (or know of) any hardware with them.
// TODO: Use the current data source's name when the control isn't settable, but only add one menu item.
UInt32 numDataSources = 0;
BGMLogAndSwallowExceptions("BGMOutputDevicePrefs::createMenuItemsForDevice", [&] {
if (device.HasDataSourceControl(scope, channel) &&
device.DataSourceControlIsSettable(scope, channel)) {
numDataSources = device.GetNumberAvailableDataSources(scope, channel);
}
});
if (numDataSources > 0) {
UInt32 dataSourceIDs[numDataSources];
// This call updates numDataSources to the real number of IDs it added to our array.
device.GetAvailableDataSources(scope, channel, numDataSources, dataSourceIDs);
for (UInt32 i = 0; i < numDataSources; i++) {
DebugMsg("BGMOutputDevicePrefs::createMenuItemsForDevice: Creating item. %s%u %s%u",
"Device ID:", device.GetObjectID(),
", Data source ID:", dataSourceIDs[i]);
CAHALAudioDevice device(devices[i]);
BOOL hasOutputChannels = device.GetTotalNumberChannels(/* inIsInput = */ false) > 0;
BGMLogAndSwallowExceptionsMsg("BGMOutputDevicePrefs::createMenuItemsForDevice", "(DS)", [&]() {
NSNumber* dataSourceID = [NSNumber numberWithUnsignedInt:dataSourceIDs[i]];
NSString* dataSourceName =
CFBridgingRelease(device.CopyDataSourceNameForID(scope, channel, dataSourceIDs[i]));
if (device.GetObjectID() != [audioDevices bgmDevice].GetObjectID() && hasOutputChannels) {
NSString* deviceName = CFBridgingRelease(device.CopyName());
NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:deviceName
action:@selector(outputDeviceWasChanged:)
keyEquivalent:@""];
[items addObject:[self createMenuItemForDevice:device
dataSourceID:dataSourceID
title:dataSourceName
toolTip:deviceName]];
});
BOOL isSelected = [audioDevices isOutputDevice:device.GetObjectID()];
[item setState:(isSelected ? NSOnState : NSOffState)];
[item setTarget:self];
[item setIndentationLevel:1];
[item setRepresentedObject:[NSNumber numberWithUnsignedInt:device.GetObjectID()]];
[prefsMenu insertItem:item atIndex:menuItemsIdx];
[outputDeviceMenuItems addObject:item];
}
}
} else {
DebugMsg("BGMOutputDevicePrefs::createMenuItemsForDevice: Creating item. %s%u",
"Device ID:", device.GetObjectID());
BGMLogAndSwallowExceptions("BGMOutputDevicePrefs::createMenuItemsForDevice", ([&] {
[items addObject:[self createMenuItemForDevice:device
dataSourceID:nil
title:CFBridgingRelease(device.CopyName())
toolTip:nil]];
}));
}
return items;
}
- (NSMenuItem*) createMenuItemForDevice:(CAHALAudioDevice)device
dataSourceID:(NSNumber* __nullable)dataSourceID
title:(NSString* __nullable)title
toolTip:(NSString* __nullable)toolTip {
// If we don't have a title, use the tool-tip text instead.
if (!title) {
title = (toolTip ? toolTip : @"");
}
NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:BGMNN(title)
action:@selector(outputDeviceWasChanged:)
keyEquivalent:@""];
// Add the AirPlay icon to the labels of AirPlay devices.
//
// TODO: Test this with real hardware that supports AirPlay. (I don't have any.)
BGMLogAndSwallowExceptions("BGMOutputDevicePrefs::createMenuItemForDevice", [&] {
if (device.GetTransportType() == kAudioDeviceTransportTypeAirPlay) {
item.image = [NSImage imageNamed:@"AirPlayIcon"];
// Make the icon a "template image" so it gets drawn colour-inverted when it's highlighted or
// OS X is in dark mode.
[item.image setTemplate:YES];
}
});
// The menu item should be selected if it's the menu item for the current output device. If the device
// has data sources, only the menu item for the current data source should be selected.
BOOL isSelected =
[audioDevices isOutputDevice:device.GetObjectID()] &&
(!dataSourceID || [audioDevices isOutputDataSource:[dataSourceID unsignedIntValue]]);
item.state = (isSelected ? NSOnState : NSOffState);
item.toolTip = toolTip;
item.target = self;
item.indentationLevel = 1;
item.representedObject = @{ @"deviceID": @(device.GetObjectID()),
@"dataSourceID": dataSourceID ? BGMNN(dataSourceID) : [NSNull null] };
return item;
}
- (void) outputDeviceWasChanged:(NSMenuItem*)menuItem {
DebugMsg("BGMOutputDevicePrefs::outputDeviceWasChanged: '%s' menu item selected",
[menuItem.title UTF8String]);
BOOL success = [audioDevices setOutputDeviceWithID:[[menuItem representedObject] unsignedIntValue] revertOnFailure:YES];
// Make sure the menu item is actually for an output device.
if (![outputDeviceMenuItems containsObject:menuItem]) {
return;
}
// Change to the new output device.
AudioDeviceID newDeviceID = [[menuItem representedObject][@"deviceID"] unsignedIntValue];
id newDataSourceID = [menuItem representedObject][@"dataSourceID"];
BOOL changingDevice = ![audioDevices isOutputDevice:newDeviceID];
BOOL changingDataSource =
(newDataSourceID != [NSNull null]) &&
![audioDevices isOutputDataSource:[newDataSourceID unsignedIntValue]];
if (changingDevice || changingDataSource) {
NSString* deviceName =
menuItem.toolTip ?
[NSString stringWithFormat:@"%@ (%@)", menuItem.title, menuItem.toolTip] :
menuItem.title;
// Dispatched because it usually blocks. (Note that we're using
// DISPATCH_QUEUE_PRIORITY_HIGH, which is the second highest priority.)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self changeToOutputDevice:newDeviceID
newDataSource:newDataSourceID
deviceName:deviceName];
});
}
}
- (void) changeToOutputDevice:(AudioDeviceID)deviceID
newDataSource:(id)dataSourceID
deviceName:(NSString*)deviceName {
NSError* __nullable error;
if (dataSourceID == [NSNull null]) {
error = [audioDevices setOutputDeviceWithID:deviceID revertOnFailure:YES];
} else {
error = [audioDevices setOutputDeviceWithID:deviceID
dataSourceID:[dataSourceID unsignedIntValue]
revertOnFailure:YES];
}
if (error) {
// Couldn't change the output device, so show a warning. (No need to change the menu
// selection back because it gets repopulated every time it's opened.)
if (!success) {
// Couldn't change the output device, so show a warning and change the menu selection back
NSAlert* alert = [NSAlert new];
NSString* deviceName = [menuItem title];
[alert setMessageText:[NSString stringWithFormat:@"Failed to set %@ as the output device", deviceName]];
[alert setInformativeText:@"This is probably a bug. Feel free to report it."];
[alert runModal];
// NSAlerts should only be shown on the main thread.
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Failed to set output device: %@", deviceName);
NSAlert* alert = [NSAlert new];
alert.messageText =
[NSString stringWithFormat:@"Failed to set %@ as the output device.", deviceName];
alert.informativeText = @"This is probably a bug. Feel free to report it.";
[alert runModal];
});
[menuItem setState:NSOffState];
// TODO: Reselect previous menu item
}
}
@end
#pragma clang assume_nonnull end
@@ -25,23 +25,21 @@
// Local Includes
#import "BGMAudioDeviceManager.h"
#import "BGMMusicPlayers.h"
// System Includes
#import <Cocoa/Cocoa.h>
NS_ASSUME_NONNULL_BEGIN
#pragma clang assume_nonnull begin
@interface BGMPreferencesMenu : NSObject <NSMenuDelegate>
- (id) initWithBGMMenu:(NSMenu*)inBGMMenu
- (id) initWithbgmMenu:(NSMenu*)inBGMMenu
audioDevices:(BGMAudioDeviceManager*)inAudioDevices
musicPlayers:(BGMMusicPlayers*)inMusicPlayers
aboutPanel:(NSPanel*)inAboutPanel
aboutPanelLicenseView:(NSTextView*)inAboutPanelLicenseView;
@end
NS_ASSUME_NONNULL_END
#pragma clang assume_nonnull end
+64 -15
View File
@@ -26,57 +26,106 @@
// Local Includes
#import "BGMAutoPauseMusicPrefs.h"
#import "BGMOutputDevicePrefs.h"
#import "BGMAboutPanel.h"
NS_ASSUME_NONNULL_BEGIN
#pragma clang assume_nonnull begin
// Interface Builder tags
static NSInteger const kToggleAutoPauseMusicMenuItemTag = 2;
static NSInteger const kPreferencesMenuItemTag = 1;
static NSInteger const kAboutPanelMenuItemTag = 3;
static NSInteger const kAboutPanelVersionLabelTag = 1;
static NSInteger const kAboutPanelCopyrightLabelTag = 2;
@implementation BGMPreferencesMenu {
BGMAudioDeviceManager* audioDevices;
// Menu sections
BGMAutoPauseMusicPrefs* autoPauseMusicPrefs;
BGMOutputDevicePrefs* outputDevicePrefs;
// The About Background Music window
BGMAboutPanel* aboutPanel;
// About Background Music window
NSPanel* aboutPanel;
NSTextField* aboutPanelVersionLabel;
NSTextField* aboutPanelCopyrightLabel;
NSTextView* aboutPanelLicenceView;
}
- (id) initWithBGMMenu:(NSMenu*)inBGMMenu
- (id) initWithbgmMenu:(NSMenu*)inBGMMenu
audioDevices:(BGMAudioDeviceManager*)inAudioDevices
musicPlayers:(BGMMusicPlayers*)inMusicPlayers
aboutPanel:(NSPanel*)inAboutPanel
aboutPanelLicenseView:(NSTextView*)inAboutPanelLicenseView {
if ((self = [super init])) {
audioDevices = inAudioDevices;
aboutPanel = inAboutPanel;
aboutPanelVersionLabel = [[aboutPanel contentView] viewWithTag:kAboutPanelVersionLabelTag];
aboutPanelCopyrightLabel = [[aboutPanel contentView] viewWithTag:kAboutPanelCopyrightLabelTag];
aboutPanelLicenceView = inAboutPanelLicenseView;
NSMenu* prefsMenu = [[inBGMMenu itemWithTag:kPreferencesMenuItemTag] submenu];
[prefsMenu setDelegate:self];
NSMenuItem* toggleAutoPauseMusicMenuItem = [inBGMMenu itemWithTag:kToggleAutoPauseMusicMenuItemTag];
autoPauseMusicPrefs = [[BGMAutoPauseMusicPrefs alloc] initWithPreferencesMenu:prefsMenu
audioDevices:inAudioDevices
musicPlayers:inMusicPlayers];
toggleAutoPauseMusicMenuItem:toggleAutoPauseMusicMenuItem
audioDevices:audioDevices];
outputDevicePrefs = [[BGMOutputDevicePrefs alloc] initWithAudioDevices:inAudioDevices];
aboutPanel = [[BGMAboutPanel alloc] initWithPanel:inAboutPanel licenseView:inAboutPanelLicenseView];
outputDevicePrefs = [[BGMOutputDevicePrefs alloc] initWithAudioDevices:audioDevices];
// Set up the "About Background Music" menu item
NSMenuItem* aboutMenuItem = [prefsMenu itemWithTag:kAboutPanelMenuItemTag];
[aboutMenuItem setTarget:aboutPanel];
[aboutMenuItem setAction:@selector(show)];
[aboutMenuItem setTarget:self];
[aboutMenuItem setAction:@selector(showAboutPanel)];
[self initAboutPanel];
}
return self;
}
#pragma mark NSMenuDelegate
- (void) initAboutPanel {
// Set up the About Background Music window
NSBundle* bundle = [NSBundle mainBundle];
if (bundle == nil) {
LogWarning("Background Music: BGMPreferencesMenu::initAboutPanel: Could not find main bundle");
} else {
// Version number label
NSString* version = [[bundle infoDictionary] objectForKey:@"CFBundleShortVersionString"];
[aboutPanelVersionLabel setStringValue:[NSString stringWithFormat:@"Version %@", version]];
// Copyright notice label
NSString* copyrightNotice = [[bundle infoDictionary] objectForKey:@"NSHumanReadableCopyright"];
[aboutPanelCopyrightLabel setStringValue:copyrightNotice];
// Load the text of the license into the text view
NSString* licensePath = [bundle pathForResource:@"LICENSE" ofType:nil];
NSError* err;
NSString* licenseStr = [NSString stringWithContentsOfFile:licensePath encoding:NSASCIIStringEncoding error:&err];
if (err != nil || [licenseStr isEqualToString:@""]) {
NSLog(@"Error loading license file: %@", err);
licenseStr = @"Error: could not open license file.";
}
[aboutPanelLicenceView setString:licenseStr];
}
}
- (void) menuNeedsUpdate:(NSMenu*)menu {
[outputDevicePrefs populatePreferencesMenu:menu];
}
- (void) showAboutPanel {
DebugMsg("BGMPreferencesMenu::showAboutPanel: Opening \"About Background Music\" panel");
[NSApp activateIgnoringOtherApps:YES];
[aboutPanel setIsVisible:YES];
[aboutPanel makeKeyAndOrderFront:self];
}
@end
NS_ASSUME_NONNULL_END
#pragma clang assume_nonnull end
@@ -1,46 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMASOutputDevice.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// An AppleScript class for the output devices that can be selected in the preferences menu.
//
// Local Includes
#import "BGMAudioDeviceManager.h"
// System Includes
#import <Foundation/Foundation.h>
#pragma clang assume_nonnull begin
@interface BGMASOutputDevice : NSObject
- (instancetype) initWithAudioObjectID:(AudioObjectID)objID
audioDevices:(BGMAudioDeviceManager*)devices
parentSpecifier:(NSScriptObjectSpecifier* __nullable)parentSpecifier;
@property (readonly) NSString* name;
@property BOOL selected; // is this the device to be used for audio output?
@end
#pragma clang assume_nonnull end
@@ -1,83 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMASOutputDevice.mm
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Self Include
#import "BGMASOutputDevice.h"
// Local Includes
#import "BGMAudioDevice.h"
// PublicUtility Includes
#import "CADebugMacros.h"
#pragma clang assume_nonnull begin
@implementation BGMASOutputDevice {
NSScriptObjectSpecifier* parentSpecifier;
BGMAudioDevice device;
BGMAudioDeviceManager* audioDevices;
}
- (instancetype) initWithAudioObjectID:(AudioObjectID)objID
audioDevices:(BGMAudioDeviceManager*)devices
parentSpecifier:(NSScriptObjectSpecifier* __nullable)parent {
if ((self = [super init])) {
parentSpecifier = parent;
device = objID;
audioDevices = devices;
}
return self;
}
- (NSString*) name {
return (NSString*)CFBridgingRelease(device.CopyName());
}
- (BOOL) selected {
return [audioDevices isOutputDevice:device];
}
- (void) setSelected:(BOOL)selected {
if (selected && ![self selected]) {
DebugMsg("BGMASOutputDevice::setSelected: A script is setting output device to %s",
[[self name] UTF8String]);
NSError* err = [audioDevices setOutputDeviceWithID:device revertOnFailure:YES];
(void)err; // TODO: Return an error to the script somehow if this isn't nil. Also, should
// we return an error if the script tries to set this property to false?
}
}
- (NSScriptObjectSpecifier* __nullable) objectSpecifier {
NSScriptClassDescription* parentClassDescription = [parentSpecifier keyClassDescription];
return [[NSNameSpecifier alloc] initWithContainerClassDescription:parentClassDescription
containerSpecifier:parentSpecifier
key:@"output devices"
name:self.name];
}
@end
#pragma clang assume_nonnull end
-59
View File
@@ -1,59 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
<dictionary>
<suite name="Background Music" code="BGMs" description="Background Music specific classes">
<!-- TODO: Figure out why Script Editor returns output device objects as
«class» "Built-in Output" of application "Background Music"
instead of
device "Built-in Output" of application "Background Music" -->
<class name="output device"
code="aDev"
description="A hardware device that can play audio"
plural="output devices"
inherits="item">
<synonym name="audio device"/>
<cocoa class="BGMASOutputDevice"/>
<property name="name"
code="pnam"
description="The name of the output device."
type="text"
access="r"/>
<property name="selected"
code="Slcd"
type="boolean"
access="rw"
description="Is this the device to be used for audio output?">
<synonym name="default"/>
</property>
</class>
<class name="application"
code="capp"
description="The application program">
<cocoa class="NSApplication"/>
<!-- We have a class called "output device", so we have to call this class something
else. -->
<property name="selected output device"
type="output device"
code="selO"
access="rw"
description="The device to be used for audio output">
<synonym name="selected device"/>
<synonym name="default device"/>
<synonym name="default output device"/>
<cocoa key="selectedOutputDevice"/>
</property>
<!-- Unintuitively, this is for the array of output devices. -->
<element type="output device" access="r">
<cocoa key="outputDevices"/>
</element>
</class>
</suite>
</dictionary>
@@ -1,44 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppDelegate+AppleScript.h
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
#import "BGMAppDelegate.h"
// Local Includes
#import "BGMASOutputDevice.h"
// System Includes
#import <Foundation/Foundation.h>
#pragma clang assume_nonnull begin
@interface BGMAppDelegate (AppleScript)
- (BOOL) application:(NSApplication*)sender delegateHandlesKey:(NSString*)key;
@property BGMASOutputDevice* selectedOutputDevice;
@property (readonly) NSArray<BGMASOutputDevice*>* outputDevices;
@end
#pragma clang assume_nonnull end
@@ -1,89 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppDelegate+AppleScript.mm
// BGMApp
//
// Copyright © 2017 Kyle Neideck
//
// Self Include
#import "BGMAppDelegate+AppleScript.h"
// Local Includes
#import "BGMAudioDevice.h"
// PublicUtility Includes
#import "CAHALAudioSystemObject.h"
#import "CAAutoDisposer.h"
#pragma clang assume_nonnull begin
@implementation BGMAppDelegate (AppleScript)
- (BOOL) application:(NSApplication*)sender delegateHandlesKey:(NSString*)key {
#pragma unused (sender)
if (![key isEqual:@"_keyWindow"]) {
DebugMsg("BGMAppDelegate:application:delegateHandlesKey: Key queried: '%s'",
[key UTF8String]);
}
return [@[@"selectedOutputDevice", @"outputDevices"] containsObject:key];
}
- (BGMASOutputDevice*) selectedOutputDevice {
AudioObjectID outputDeviceID = [self.audioDevices outputDevice].GetObjectID();
return [[BGMASOutputDevice alloc] initWithAudioObjectID:outputDeviceID
audioDevices:self.audioDevices
parentSpecifier:[self objectSpecifier]];
}
- (void) setSelectedOutputDevice:(BGMASOutputDevice*)device {
[device setSelected:YES];
}
- (NSArray<BGMASOutputDevice*>*) outputDevices {
UInt32 numDevices = CAHALAudioSystemObject().GetNumberAudioDevices();
CAAutoArrayDelete<AudioObjectID> devices(numDevices);
CAHALAudioSystemObject().GetAudioDevices(numDevices, devices);
NSMutableArray<BGMASOutputDevice*>* outputDevices =
[NSMutableArray arrayWithCapacity:numDevices];
for (UInt32 i = 0; i < numDevices; i++) {
BGMAudioDevice device(devices[i]);
if (device.CanBeOutputDeviceInBGMApp()) {
BGMASOutputDevice* outputDevice =
[[BGMASOutputDevice alloc] initWithAudioObjectID:device.GetObjectID()
audioDevices:self.audioDevices
parentSpecifier:[self objectSpecifier]];
[outputDevices addObject:outputDevice];
}
}
return outputDevices;
}
@end
#pragma clang assume_nonnull end
-258
View File
@@ -1,258 +0,0 @@
/*
* SystemPreferences.h
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class SystemPreferencesItem, SystemPreferencesApplication, SystemPreferencesColor, SystemPreferencesDocument, SystemPreferencesWindow, SystemPreferencesAttributeRun, SystemPreferencesCharacter, SystemPreferencesParagraph, SystemPreferencesText, SystemPreferencesAttachment, SystemPreferencesWord, SystemPreferencesAnchor, SystemPreferencesPane, SystemPreferencesPrintSettings;
enum SystemPreferencesSavo {
SystemPreferencesSavoAsk = 'ask ' /* Ask the user whether or not to save the file. */,
SystemPreferencesSavoNo = 'no ' /* Do not save the file. */,
SystemPreferencesSavoYes = 'yes ' /* Save the file. */
};
typedef enum SystemPreferencesSavo SystemPreferencesSavo;
enum SystemPreferencesEnum {
SystemPreferencesEnumStandard = 'lwst' /* Standard PostScript error handling */,
SystemPreferencesEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */
};
typedef enum SystemPreferencesEnum SystemPreferencesEnum;
/*
* Standard Suite
*/
// A scriptable object.
@interface SystemPreferencesItem : SBObject
@property (copy) NSDictionary *properties; // All of the object's properties.
- (void)closeSaving:(SystemPreferencesSavo) saving savingIn:(NSURL *)savingIn; // Close an object.
- (void)delete; // Delete an object.
- (void)duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location.
- (BOOL)exists; // Verify if an object exists.
- (void)moveTo:(SBObject *)to; // Move object(s) to a new location.
- (void)saveAs:(NSString *)as in:(NSURL *)in_; // Save an object.
@end
// An application's top level scripting object.
@interface SystemPreferencesApplication : SBApplication
- (SBElementArray *)documents;
- (SBElementArray *)windows;
@property (readonly) BOOL frontmost; // Is this the frontmost (active) application?
@property (copy, readonly) NSString *name; // The name of the application.
@property (copy, readonly) NSString *version; // The version of the application.
- (SystemPreferencesDocument *)open:(NSURL *)x; // Open an object.
- (void)print:(NSURL *)x printDialog:(BOOL) printDialog withProperties:(SystemPreferencesPrintSettings *)withProperties; // Print an object.
- (void)quitSaving:(SystemPreferencesSavo)saving; // Quit an application.
@end
// A color.
@interface SystemPreferencesColor : SystemPreferencesItem
@end
// A document.
@interface SystemPreferencesDocument : SystemPreferencesItem
@property (readonly) BOOL modified; // Has the document been modified since the last save?
@property (copy) NSString *name; // The document's name.
@property (copy) NSString *path; // The document's path.
@end
// A window.
@interface SystemPreferencesWindow : SystemPreferencesItem
@property NSRect bounds; // The bounding rectangle of the window.
@property (readonly) BOOL closeable; // Whether the window has a close box.
@property (copy, readonly) SystemPreferencesDocument *document; // The document whose contents are being displayed in the window.
@property (readonly) BOOL floating; // Whether the window floats.
- (NSInteger)id; // The unique identifier of the window.
@property NSInteger index; // The index of the window, ordered front to back.
@property (readonly) BOOL miniaturizable; // Whether the window can be miniaturized.
@property BOOL miniaturized; // Whether the window is currently miniaturized.
@property (readonly) BOOL modal; // Whether the window is the application's current modal window.
@property (copy) NSString *name; // The full title of the window.
@property (readonly) BOOL resizable; // Whether the window can be resized.
@property (readonly) BOOL titled; // Whether the window has a title bar.
@property BOOL visible; // Whether the window is currently visible.
@property (readonly) BOOL zoomable; // Whether the window can be zoomed.
@property BOOL zoomed; // Whether the window is currently zoomed.
@end
/*
* Text Suite
*/
// This subdivides the text into chunks that all have the same attributes.
@interface SystemPreferencesAttributeRun : SystemPreferencesItem
- (SBElementArray *)attachments;
- (SBElementArray *)attributeRuns;
- (SBElementArray *)characters;
- (SBElementArray *)paragraphs;
- (SBElementArray *)words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// This subdivides the text into characters.
@interface SystemPreferencesCharacter : SystemPreferencesItem
- (SBElementArray *)attachments;
- (SBElementArray *)attributeRuns;
- (SBElementArray *)characters;
- (SBElementArray *)paragraphs;
- (SBElementArray *)words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// This subdivides the text into paragraphs.
@interface SystemPreferencesParagraph : SystemPreferencesItem
- (SBElementArray *)attachments;
- (SBElementArray *)attributeRuns;
- (SBElementArray *)characters;
- (SBElementArray *)paragraphs;
- (SBElementArray *)words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// Rich (styled) text
@interface SystemPreferencesText : SystemPreferencesItem
- (SBElementArray *)attachments;
- (SBElementArray *)attributeRuns;
- (SBElementArray *)characters;
- (SBElementArray *)paragraphs;
- (SBElementArray *)words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
// Represents an inline text attachment. This class is used mainly for make commands.
@interface SystemPreferencesAttachment : SystemPreferencesText
@property (copy) NSString *fileName; // The path to the file for the attachment
@end
// This subdivides the text into words.
@interface SystemPreferencesWord : SystemPreferencesItem
- (SBElementArray *)attachments;
- (SBElementArray *)attributeRuns;
- (SBElementArray *)characters;
- (SBElementArray *)paragraphs;
- (SBElementArray *)words;
@property (copy) NSColor *color; // The color of the first character.
@property (copy) NSString *font; // The name of the font of the first character.
@property NSInteger size; // The size in points of the first character.
@end
/*
* System Preferences
*/
// an anchor within a preference pane
@interface SystemPreferencesAnchor : SystemPreferencesItem
@property (copy, readonly) NSString *name; // name of the anchor within a preference pane
- (SystemPreferencesAnchor *)reveal; // Reveals an anchor within a preference pane or preference pane itself
@end
// System Preferences top level scripting object
@interface SystemPreferencesApplication (SystemPreferences)
- (SBElementArray *)panes;
@property (copy) SystemPreferencesPane *currentPane; // the currently selected pane
@property (copy, readonly) SystemPreferencesWindow *preferencesWindow; // the main preferences window
@property BOOL showAll; // Is SystemPrefs in show all view. (Setting to false will do nothing)
@end
// a preference pane
@interface SystemPreferencesPane : SystemPreferencesItem
- (SBElementArray *)anchors;
- (NSString *)id; // locale independent name of the preference pane; can refer to a pane using the expression: pane id "<name>"
@property (copy, readonly) NSString *localizedName; // localized name of the preference pane
@property (copy, readonly) NSString *name; // name of the preference pane as it appears in the title bar; can refer to a pane using the expression: pane "<name>"
- (NSInteger)timedLoad; // This command does xxxx.
@end
/*
* Type Definitions
*/
@interface SystemPreferencesPrintSettings : SBObject
@property NSInteger copies; // the number of copies of a document to be printed
@property BOOL collating; // Should printed copies be collated?
@property NSInteger startingPage; // the first page of the document to be printed
@property NSInteger endingPage; // the last page of the document to be printed
@property NSInteger pagesAcross; // number of logical pages laid across a physical page
@property NSInteger pagesDown; // number of logical pages laid out down a physical page
@property (copy) NSDate *requestedPrintTime; // the time at which the desktop printer should print the document
@property SystemPreferencesEnum errorHandling; // how errors are handled
@property (copy) NSString *faxNumber; // for fax number
@property (copy) NSString *targetPrinter; // for target printer
- (void)closeSaving:(SystemPreferencesSavo) saving savingIn:(NSURL *)savingIn; // Close an object.
- (void)delete; // Delete an object.
- (void)duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location.
- (BOOL)exists; // Verify if an object exists.
- (void)moveTo:(SBObject *)to; // Move object(s) to a new location.
- (void)saveAs:(NSString *)as in:(NSURL *)in_; // Save an object.
@end
-156
View File
@@ -1,156 +0,0 @@
#!/bin/bash
# vim: tw=120:
# This file is part of Background Music.
#
# Background Music is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.
#
# Background Music is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Background Music. If not, see <http://www.gnu.org/licenses/>.
#
# _uninstall-non-interactive.sh
#
# Copyright © 2016 Nick Jacques
# Copyright © 2016, 2017 Kyle Neideck
#
# Removes BGMApp, BGMDriver and BGMXPCHelper from the system immediately. Run by uninstall.sh and the Homebrew formula.
#
# TODO: Log commands and their output to uninstall.log, like build_and_install.sh does, rather than just sending
# everything to /dev/null.
# TODO: Show a custom error message if the script fails, like build_and_install.sh.
# Halt on errors.
set -e
PATH=/bin:/sbin:/usr/bin:/usr/sbin; export PATH
bold=$(tput bold)
normal=$(tput sgr0)
app_path="/Applications/Background Music.app"
driver_path="/Library/Audio/Plug-Ins/HAL/Background Music Device.driver"
xpc_path1="/usr/local/libexec/BGMXPCHelper.xpc"
xpc_path2="/Library/Application Support/Background Music/BGMXPCHelper.xpc"
# Check that files/directories are at most this big before we delete them, just to be safe.
max_size_mb_for_rm=15
file_paths=("${app_path}" "${driver_path}" "${xpc_path1}" "${xpc_path2}")
bgmapp_process_name="Background Music"
launchd_plist_label="com.bearisdriving.BGM.XPCHelper"
launchd_plist="/Library/LaunchDaemons/${launchd_plist_label}.plist"
coreaudiod_plist="/System/Library/LaunchDaemons/com.apple.audio.coreaudiod.plist"
user_group_name="_BGMXPCHelper"
# We move files to this temp directory and then move the directory to the user's trash at the end of the script.
# Unfortunately, this means that if the user tries to use the "put back" feature the files will just go back to the
# temp directory.
trash_dir="$(mktemp -d -t UninstalledBackgroundMusicFiles)/"
# Takes a path to a file or directory and returns false if the file/directory is larger than $max_size_mb_for_rm.
function size_check {
local size="$(du -sm "$1" 2>/dev/null | awk '{ print $1 }')"
[[ "${size}" =~ ^[0-9]+$ ]] && [[ "${size}" -le ${max_size_mb_for_rm} ]]
}
# Ensure that the user can use sudo. (But not if this is a Travis CI build, because then it would fail.)
if ([[ -z ${TRAVIS:-} ]] || [[ "${TRAVIS}" != true ]]) && ! sudo -v; then
echo "ERROR: This script must be run by a user with administrator (sudo) privileges." >&2
exit 1
fi
# Try to kill Background Music.app, in case it's running.
killall "${bgmapp_process_name}" &>/dev/null || true
# TODO: Use
# mdfind kMDItemCFBundleIdentifier = "com.bearisdriving.BGM.App"
# to offer alternatives if Background Music.app isn't installed to /Applications. Or we could open it with
# open -b "com.bearisdriving.BGM.App" -- delete-yourself
# and have Background Music.app delete itself and close when it gets the "delete-yourself" argument. Though
# that wouldn't be backwards compatible.
# Remove the files defined in file_paths
for path in "${file_paths[@]}"; do
if [ -e "${path}" ]; then
if size_check "${path}"; then
echo "Moving \"${path}\" to the trash."
sudo mv -f "${path}" "${trash_dir}" &>/dev/null
else
echo "Error: Refusing to delete \"${path}\" because it was much larger than expected." >&2
fi
fi
done
echo "Removing Background Music launchd service."
sudo launchctl list | grep "${launchd_plist_label}" >/dev/null && \
(sudo launchctl bootout system "${launchd_plist}" &>/dev/null || \
# Try older versions of the command in case the user has an old version of launchctl.
sudo launchctl unbootstrap system "${launchd_plist}" &>/dev/null || \
sudo launchctl unload "${launchd_plist}" >/dev/null) || \
echo " Service does not exist."
echo "Removing Background Music launchd service configuration file."
if [ -e "${launchd_plist}" ]; then
sudo mv -f "${launchd_plist}" "${trash_dir}"
fi
# Be paranoid about user_group_name because we really don't want to delete every user account.
if ! [[ -z ${user_group_name} ]] && [[ "${user_group_name}" != "" ]]; then
echo "Removing Background Music user."
dscl . -read /Users/"${user_group_name}" &>/dev/null && \
sudo dscl . -delete /Users/"${user_group_name}" 1>/dev/null || \
echo " User does not exist."
echo "Removing Background Music group."
dscl . -read /Groups/"${user_group_name}" &>/dev/null && \
sudo dscl . -delete /Groups/"${user_group_name}" 1>/dev/null || \
echo " Group does not exist."
else
echo "Warning: could not delete the Background Music user/group due to an internal error in $0." >&2
fi
# We're done removing files, so now actually move trash_dir into the trash. And if that fails, just delete it normally.
osascript -e 'tell application id "com.apple.finder"
move the POSIX file "'"${trash_dir}"'" to trash
end tell' >/dev/null 2>&1 \
|| rm -rf "${trash_dir}" \
|| true
echo "Restarting Core Audio."
# Wait a little because moving files to the trash plays a short sound.
sleep 2
# The extra or-clauses are fallback versions of the command that restarts coreaudiod. Apparently some of these commands
# don't work with older versions of launchctl, so I figure there's no harm in trying a bunch of different ways until
# one works.
(sudo launchctl kill SIGTERM system/com.apple.audio.coreaudiod &>/dev/null || \
sudo launchctl kill TERM system/com.apple.audio.coreaudiod &>/dev/null || \
sudo launchctl kill 15 system/com.apple.audio.coreaudiod &>/dev/null || \
sudo launchctl kill -15 system/com.apple.audio.coreaudiod &>/dev/null || \
(sudo launchctl unload "${coreaudiod_plist}" &>/dev/null && \
sudo launchctl load "${coreaudiod_plist}" &>/dev/null) || \
sudo killall coreaudiod &>/dev/null)
echo "..."
sleep 3
# TODO: What if they only have one audio device?
echo ""
echo "${bold}Done! Toggle your audio output device in the Sound section of System Preferences to finish" \
"uninstalling. (Or just restart your computer.)${normal}"
-2
View File
@@ -20,12 +20,10 @@
// Copyright © 2016 Kyle Neideck
//
// System Includes
#import <Cocoa/Cocoa.h>
int main(int argc, const char * argv[]) {
// Start BGMApp.
return NSApplicationMain(argc, argv);
}
@@ -14,35 +14,45 @@
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAutoPauseMenuItem.h
// BGMApp
// BGMAppTests.m
// BGMAppTests
//
// Copyright © 2016 Kyle Neideck
//
// Local Includes
#import "BGMAutoPauseMusic.h"
#import "BGMMusicPlayers.h"
#import "BGMUserDefaults.h"
// System Includes
#import <Cocoa/Cocoa.h>
#import <XCTest/XCTest.h>
#pragma clang assume_nonnull begin
@interface BGMAutoPauseMenuItem : NSObject
- (instancetype) initWithMenuItem:(NSMenuItem*)item
autoPauseMusic:(BGMAutoPauseMusic*)autoPause
musicPlayers:(BGMMusicPlayers*)players
userDefaults:(BGMUserDefaults*)defaults;
// Handle events passed along by the delegate (NSMenuDelegate) of the menu containing this menu item.
- (void) parentMenuNeedsUpdate;
- (void) parentMenuItemWillHighlight:(NSMenuItem* __nullable)item;
@interface BGMAppTests : XCTestCase
@end
#pragma clang assume_nonnull end
@implementation BGMAppTests
// TODO: More than no tests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
[super tearDown];
}
- (void)testExample {
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
}
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
@end
@@ -16,6 +16,8 @@
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
@@ -15,7 +15,7 @@
//
// BGMXPCHelperTests.m
// BGMXPCHelperTests
// BGMApp
//
// Copyright © 2016 Kyle Neideck
//
@@ -57,20 +57,19 @@
- (void) testStartOutputDeviceWithoutBGMAppConnected {
dispatch_semaphore_t replySemaphore = dispatch_semaphore_create(0);
// Unregister BGMXPCHelper's connection to BGMApp in case BGMApp didn't shutdown cleanly the last time it ran.
[[connection remoteObjectProxy] unregisterAsBGMApp];
[[connection remoteObjectProxy] startBGMAppPlayThroughSyncWithReply:^(NSError* reply) {
[[connection remoteObjectProxy] waitForBGMAppToStartOutputDeviceWithReply:^(NSError* reply) {
XCTAssertEqual([reply code],
kBGMXPC_MessageFailure,
@"Check that BGMApp isn't running, which would cause this failure");
dispatch_semaphore_signal(replySemaphore);
} forUISoundsDevice:NO];
// Very long timeout to make it less likely to fail on Travis CI when there's high contention.
if (0 != dispatch_semaphore_wait(replySemaphore, dispatch_time(DISPATCH_TIME_NOW, 5 * 60 * NSEC_PER_SEC))) {
}];
if (0 != dispatch_semaphore_wait(replySemaphore, dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC))) {
XCTFail(@"Timed out waiting for BGMXPCHelper");
}
}
@@ -1,754 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
2D46CA7B17D6ADCA00049D4A /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 2D46CA7817D6AD8A00049D4A /* Localizable.strings */; };
2D46CA7D17D6AF4200049D4A /* DeviceIcon.icns in Resources */ = {isa = PBXBuildFile; fileRef = 2D46CA7C17D6AF4200049D4A /* DeviceIcon.icns */; };
2D47CAA415FEC82B002AAFB5 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 2D47CAA215FEC82B002AAFB5 /* Localizable.strings */; };
2D4DE41415EDF8D500E96F0D /* CAVolumeCurve.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2D4DE41215EDF8D500E96F0D /* CAVolumeCurve.cpp */; };
2D4DE41515EDF8D500E96F0D /* CAVolumeCurve.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D4DE41315EDF8D500E96F0D /* CAVolumeCurve.h */; };
2D616EF415B8C82500D598BD /* NullAudio.c in Sources */ = {isa = PBXBuildFile; fileRef = 2D616EF215B8C82500D598BD /* NullAudio.c */; };
2D7477AD1578168D00412279 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D7477AC1578168D00412279 /* CoreFoundation.framework */; };
2D76D96115E48B2000FF0F33 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D7477AC1578168D00412279 /* CoreFoundation.framework */; };
2D76D97615E48B6400FF0F33 /* SA_PlugIn.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2D76D97415E48B6400FF0F33 /* SA_PlugIn.cpp */; };
2D76D97715E48B6400FF0F33 /* SA_PlugIn.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D76D97515E48B6400FF0F33 /* SA_PlugIn.h */; };
2D76D97A15E498EB00FF0F33 /* SA_Object.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2D76D97815E498EB00FF0F33 /* SA_Object.cpp */; };
2D76D97B15E498EB00FF0F33 /* SA_Object.h in Headers */ = {isa = PBXBuildFile; fileRef = 2D76D97915E498EB00FF0F33 /* SA_Object.h */; };
2DD7AA0A15EACDE000C67AE1 /* SA_IOKit.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA0815EACDDF00C67AE1 /* SA_IOKit.cpp */; };
2DD7AA0B15EACDE000C67AE1 /* SA_IOKit.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA0915EACDDF00C67AE1 /* SA_IOKit.h */; };
2DD7AA2315EAFD5100C67AE1 /* CACFArray.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA0E15EAFD3300C67AE1 /* CACFArray.cpp */; };
2DD7AA2415EAFD5100C67AE1 /* CACFArray.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA0F15EAFD3300C67AE1 /* CACFArray.h */; };
2DD7AA2515EAFD5100C67AE1 /* CACFDictionary.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1015EAFD3300C67AE1 /* CACFDictionary.cpp */; };
2DD7AA2615EAFD5100C67AE1 /* CACFDictionary.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1115EAFD3300C67AE1 /* CACFDictionary.h */; };
2DD7AA2715EAFD5100C67AE1 /* CACFNumber.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1215EAFD3300C67AE1 /* CACFNumber.cpp */; };
2DD7AA2815EAFD5100C67AE1 /* CACFNumber.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1315EAFD3300C67AE1 /* CACFNumber.h */; };
2DD7AA2915EAFD5100C67AE1 /* CACFString.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1415EAFD3300C67AE1 /* CACFString.cpp */; };
2DD7AA2A15EAFD5100C67AE1 /* CACFString.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1515EAFD3300C67AE1 /* CACFString.h */; };
2DD7AA2B15EAFD5100C67AE1 /* CADebugger.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1615EAFD3300C67AE1 /* CADebugger.cpp */; };
2DD7AA2C15EAFD5100C67AE1 /* CADebugger.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1715EAFD3300C67AE1 /* CADebugger.h */; };
2DD7AA2D15EAFD5100C67AE1 /* CADebugMacros.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1815EAFD3300C67AE1 /* CADebugMacros.cpp */; };
2DD7AA2E15EAFD5100C67AE1 /* CADebugMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1915EAFD3300C67AE1 /* CADebugMacros.h */; };
2DD7AA2F15EAFD5100C67AE1 /* CADebugPrintf.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1A15EAFD3300C67AE1 /* CADebugPrintf.cpp */; };
2DD7AA3015EAFD5100C67AE1 /* CADebugPrintf.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1B15EAFD3300C67AE1 /* CADebugPrintf.h */; };
2DD7AA3115EAFD5100C67AE1 /* CAException.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1C15EAFD3300C67AE1 /* CAException.h */; };
2DD7AA3215EAFD5100C67AE1 /* CAGuard.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1D15EAFD3300C67AE1 /* CAGuard.cpp */; };
2DD7AA3315EAFD5100C67AE1 /* CAGuard.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA1E15EAFD3300C67AE1 /* CAGuard.h */; };
2DD7AA3415EAFD5100C67AE1 /* CAHostTimeBase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA1F15EAFD3300C67AE1 /* CAHostTimeBase.cpp */; };
2DD7AA3515EAFD5100C67AE1 /* CAHostTimeBase.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA2015EAFD3300C67AE1 /* CAHostTimeBase.h */; };
2DD7AA3615EAFD5100C67AE1 /* CAMutex.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA2115EAFD3300C67AE1 /* CAMutex.cpp */; };
2DD7AA3715EAFD5100C67AE1 /* CAMutex.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA2215EAFD3300C67AE1 /* CAMutex.h */; };
2DD7AA7D15EC20FD00C67AE1 /* CADispatchQueue.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA7B15EC20FD00C67AE1 /* CADispatchQueue.cpp */; };
2DD7AA7E15EC20FD00C67AE1 /* CADispatchQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA7C15EC20FD00C67AE1 /* CADispatchQueue.h */; };
2DD7AA8015EC3DB800C67AE1 /* CACFObject.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA7F15EC3DB800C67AE1 /* CACFObject.h */; };
2DD7AA9715EC551600C67AE1 /* SA_Device.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DD7AA9515EC551500C67AE1 /* SA_Device.cpp */; };
2DD7AA9815EC551600C67AE1 /* SA_Device.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DD7AA9615EC551600C67AE1 /* SA_Device.h */; };
2DD7AA9A15EC572000C67AE1 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2DD7AA9915EC572000C67AE1 /* IOKit.framework */; };
2DED184915C359AC0091BE97 /* SimpleAudioDriver.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DED182515C356BA0091BE97 /* SimpleAudioDriver.cpp */; };
2DED184A15C359AC0091BE97 /* SimpleAudioDriver.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DED182615C356BA0091BE97 /* SimpleAudioDriver.h */; };
2DED184B15C359AC0091BE97 /* SimpleAudioDriverUserClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 2DED182915C356BA0091BE97 /* SimpleAudioDriverUserClient.cpp */; };
2DED184C15C359AC0091BE97 /* SimpleAudioDriverUserClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DED182A15C356BA0091BE97 /* SimpleAudioDriverUserClient.h */; };
2DED184D15C359AC0091BE97 /* SimpleAudioDriverTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DED182B15C356BA0091BE97 /* SimpleAudioDriverTypes.h */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
2D46CA7917D6AD8A00049D4A /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/Localizable.strings; sourceTree = "<group>"; };
2D46CA7C17D6AF4200049D4A /* DeviceIcon.icns */ = {isa = PBXFileReference; lastKnownFileType = image.icns; path = DeviceIcon.icns; sourceTree = "<group>"; };
2D47CAA315FEC82B002AAFB5 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/Localizable.strings; sourceTree = "<group>"; };
2D4DE41215EDF8D500E96F0D /* CAVolumeCurve.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CAVolumeCurve.cpp; sourceTree = "<group>"; };
2D4DE41315EDF8D500E96F0D /* CAVolumeCurve.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CAVolumeCurve.h; sourceTree = "<group>"; };
2D616EF115B8C82500D598BD /* NullAudio-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "NullAudio-Info.plist"; sourceTree = "<group>"; };
2D616EF215B8C82500D598BD /* NullAudio.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = NullAudio.c; sourceTree = "<group>"; };
2D7477A91578168D00412279 /* NullAudio.driver */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NullAudio.driver; sourceTree = BUILT_PRODUCTS_DIR; };
2D7477AC1578168D00412279 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };
2D7477EC157823CF00412279 /* CoreAudio.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreAudio.framework; path = System/Library/Frameworks/CoreAudio.framework; sourceTree = SDKROOT; };
2D76D96015E48B2000FF0F33 /* SimpleAudioPlugIn.driver */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SimpleAudioPlugIn.driver; sourceTree = BUILT_PRODUCTS_DIR; };
2D76D97415E48B6400FF0F33 /* SA_PlugIn.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SA_PlugIn.cpp; sourceTree = "<group>"; };
2D76D97515E48B6400FF0F33 /* SA_PlugIn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SA_PlugIn.h; sourceTree = "<group>"; };
2D76D97815E498EB00FF0F33 /* SA_Object.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SA_Object.cpp; sourceTree = "<group>"; };
2D76D97915E498EB00FF0F33 /* SA_Object.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SA_Object.h; sourceTree = "<group>"; };
2D76D98B15E56E4E00FF0F33 /* SA_PlugIn-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "SA_PlugIn-Info.plist"; sourceTree = "<group>"; };
2DA8FA1515FEAAB000F04B50 /* ReadMe.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = ReadMe.txt; sourceTree = "<group>"; };
2DD7AA0815EACDDF00C67AE1 /* SA_IOKit.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SA_IOKit.cpp; sourceTree = "<group>"; };
2DD7AA0915EACDDF00C67AE1 /* SA_IOKit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SA_IOKit.h; sourceTree = "<group>"; };
2DD7AA0E15EAFD3300C67AE1 /* CACFArray.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CACFArray.cpp; sourceTree = "<group>"; };
2DD7AA0F15EAFD3300C67AE1 /* CACFArray.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CACFArray.h; sourceTree = "<group>"; };
2DD7AA1015EAFD3300C67AE1 /* CACFDictionary.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CACFDictionary.cpp; sourceTree = "<group>"; };
2DD7AA1115EAFD3300C67AE1 /* CACFDictionary.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CACFDictionary.h; sourceTree = "<group>"; };
2DD7AA1215EAFD3300C67AE1 /* CACFNumber.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CACFNumber.cpp; sourceTree = "<group>"; };
2DD7AA1315EAFD3300C67AE1 /* CACFNumber.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CACFNumber.h; sourceTree = "<group>"; };
2DD7AA1415EAFD3300C67AE1 /* CACFString.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CACFString.cpp; sourceTree = "<group>"; };
2DD7AA1515EAFD3300C67AE1 /* CACFString.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CACFString.h; sourceTree = "<group>"; };
2DD7AA1615EAFD3300C67AE1 /* CADebugger.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CADebugger.cpp; sourceTree = "<group>"; };
2DD7AA1715EAFD3300C67AE1 /* CADebugger.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CADebugger.h; sourceTree = "<group>"; };
2DD7AA1815EAFD3300C67AE1 /* CADebugMacros.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CADebugMacros.cpp; sourceTree = "<group>"; };
2DD7AA1915EAFD3300C67AE1 /* CADebugMacros.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CADebugMacros.h; sourceTree = "<group>"; };
2DD7AA1A15EAFD3300C67AE1 /* CADebugPrintf.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CADebugPrintf.cpp; sourceTree = "<group>"; };
2DD7AA1B15EAFD3300C67AE1 /* CADebugPrintf.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CADebugPrintf.h; sourceTree = "<group>"; };
2DD7AA1C15EAFD3300C67AE1 /* CAException.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CAException.h; sourceTree = "<group>"; };
2DD7AA1D15EAFD3300C67AE1 /* CAGuard.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CAGuard.cpp; sourceTree = "<group>"; };
2DD7AA1E15EAFD3300C67AE1 /* CAGuard.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CAGuard.h; sourceTree = "<group>"; };
2DD7AA1F15EAFD3300C67AE1 /* CAHostTimeBase.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CAHostTimeBase.cpp; sourceTree = "<group>"; };
2DD7AA2015EAFD3300C67AE1 /* CAHostTimeBase.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CAHostTimeBase.h; sourceTree = "<group>"; };
2DD7AA2115EAFD3300C67AE1 /* CAMutex.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = CAMutex.cpp; sourceTree = "<group>"; };
2DD7AA2215EAFD3300C67AE1 /* CAMutex.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CAMutex.h; sourceTree = "<group>"; };
2DD7AA7B15EC20FD00C67AE1 /* CADispatchQueue.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CADispatchQueue.cpp; sourceTree = "<group>"; };
2DD7AA7C15EC20FD00C67AE1 /* CADispatchQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CADispatchQueue.h; sourceTree = "<group>"; };
2DD7AA7F15EC3DB800C67AE1 /* CACFObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CACFObject.h; sourceTree = "<group>"; };
2DD7AA9515EC551500C67AE1 /* SA_Device.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SA_Device.cpp; sourceTree = "<group>"; };
2DD7AA9615EC551600C67AE1 /* SA_Device.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SA_Device.h; sourceTree = "<group>"; };
2DD7AA9915EC572000C67AE1 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
2DED182415C356BA0091BE97 /* SimpleAudioDriver-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "SimpleAudioDriver-Info.plist"; sourceTree = "<group>"; };
2DED182515C356BA0091BE97 /* SimpleAudioDriver.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SimpleAudioDriver.cpp; sourceTree = "<group>"; };
2DED182615C356BA0091BE97 /* SimpleAudioDriver.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SimpleAudioDriver.h; sourceTree = "<group>"; };
2DED182915C356BA0091BE97 /* SimpleAudioDriverUserClient.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = SimpleAudioDriverUserClient.cpp; sourceTree = "<group>"; };
2DED182A15C356BA0091BE97 /* SimpleAudioDriverUserClient.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SimpleAudioDriverUserClient.h; sourceTree = "<group>"; };
2DED182B15C356BA0091BE97 /* SimpleAudioDriverTypes.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SimpleAudioDriverTypes.h; sourceTree = "<group>"; };
2DED183815C357180091BE97 /* SimpleAudioDriver.kext */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SimpleAudioDriver.kext; sourceTree = BUILT_PRODUCTS_DIR; };
2DED183A15C357180091BE97 /* Kernel.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Kernel.framework; path = System/Library/Frameworks/Kernel.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
2D7477A61578168D00412279 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2D7477AD1578168D00412279 /* CoreFoundation.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D76D95D15E48B2000FF0F33 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
2D76D96115E48B2000FF0F33 /* CoreFoundation.framework in Frameworks */,
2DD7AA9A15EC572000C67AE1 /* IOKit.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2DED183315C357180091BE97 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
2D616EF015B8C82500D598BD /* NullAudio */ = {
isa = PBXGroup;
children = (
2D46CA7C17D6AF4200049D4A /* DeviceIcon.icns */,
2D46CA7817D6AD8A00049D4A /* Localizable.strings */,
2D616EF115B8C82500D598BD /* NullAudio-Info.plist */,
2D616EF215B8C82500D598BD /* NullAudio.c */,
);
path = NullAudio;
sourceTree = "<group>";
};
2D74779B1578162B00412279 = {
isa = PBXGroup;
children = (
2DA8FA1515FEAAB000F04B50 /* ReadMe.txt */,
2D616EF015B8C82500D598BD /* NullAudio */,
2DED182215C356BA0091BE97 /* SimpleAudio */,
2DD7AA0D15EAFD3300C67AE1 /* PublicUtility */,
2D7477AB1578168D00412279 /* Frameworks */,
2D7477AA1578168D00412279 /* Products */,
);
sourceTree = "<group>";
};
2D7477AA1578168D00412279 /* Products */ = {
isa = PBXGroup;
children = (
2D7477A91578168D00412279 /* NullAudio.driver */,
2DED183815C357180091BE97 /* SimpleAudioDriver.kext */,
2D76D96015E48B2000FF0F33 /* SimpleAudioPlugIn.driver */,
);
name = Products;
sourceTree = "<group>";
};
2D7477AB1578168D00412279 /* Frameworks */ = {
isa = PBXGroup;
children = (
2D7477EC157823CF00412279 /* CoreAudio.framework */,
2D7477AC1578168D00412279 /* CoreFoundation.framework */,
2DD7AA9915EC572000C67AE1 /* IOKit.framework */,
2DED183A15C357180091BE97 /* Kernel.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
2DA8FA7E15FEC6B500F04B50 /* Resources */ = {
isa = PBXGroup;
children = (
2D47CAA215FEC82B002AAFB5 /* Localizable.strings */,
);
path = Resources;
sourceTree = "<group>";
};
2DD7AA0D15EAFD3300C67AE1 /* PublicUtility */ = {
isa = PBXGroup;
children = (
2DD7AA0E15EAFD3300C67AE1 /* CACFArray.cpp */,
2DD7AA0F15EAFD3300C67AE1 /* CACFArray.h */,
2DD7AA1015EAFD3300C67AE1 /* CACFDictionary.cpp */,
2DD7AA1115EAFD3300C67AE1 /* CACFDictionary.h */,
2DD7AA1215EAFD3300C67AE1 /* CACFNumber.cpp */,
2DD7AA1315EAFD3300C67AE1 /* CACFNumber.h */,
2DD7AA7F15EC3DB800C67AE1 /* CACFObject.h */,
2DD7AA1415EAFD3300C67AE1 /* CACFString.cpp */,
2DD7AA1515EAFD3300C67AE1 /* CACFString.h */,
2DD7AA1615EAFD3300C67AE1 /* CADebugger.cpp */,
2DD7AA1715EAFD3300C67AE1 /* CADebugger.h */,
2DD7AA1815EAFD3300C67AE1 /* CADebugMacros.cpp */,
2DD7AA1915EAFD3300C67AE1 /* CADebugMacros.h */,
2DD7AA1A15EAFD3300C67AE1 /* CADebugPrintf.cpp */,
2DD7AA1B15EAFD3300C67AE1 /* CADebugPrintf.h */,
2DD7AA7B15EC20FD00C67AE1 /* CADispatchQueue.cpp */,
2DD7AA7C15EC20FD00C67AE1 /* CADispatchQueue.h */,
2DD7AA1C15EAFD3300C67AE1 /* CAException.h */,
2DD7AA1D15EAFD3300C67AE1 /* CAGuard.cpp */,
2DD7AA1E15EAFD3300C67AE1 /* CAGuard.h */,
2DD7AA1F15EAFD3300C67AE1 /* CAHostTimeBase.cpp */,
2DD7AA2015EAFD3300C67AE1 /* CAHostTimeBase.h */,
2DD7AA2115EAFD3300C67AE1 /* CAMutex.cpp */,
2DD7AA2215EAFD3300C67AE1 /* CAMutex.h */,
2D4DE41215EDF8D500E96F0D /* CAVolumeCurve.cpp */,
2D4DE41315EDF8D500E96F0D /* CAVolumeCurve.h */,
);
path = PublicUtility;
sourceTree = "<group>";
};
2DED182215C356BA0091BE97 /* SimpleAudio */ = {
isa = PBXGroup;
children = (
2DED182315C356BA0091BE97 /* Driver */,
2DED182C15C356BA0091BE97 /* Plug-In */,
);
path = SimpleAudio;
sourceTree = "<group>";
};
2DED182315C356BA0091BE97 /* Driver */ = {
isa = PBXGroup;
children = (
2DED182415C356BA0091BE97 /* SimpleAudioDriver-Info.plist */,
2DED182515C356BA0091BE97 /* SimpleAudioDriver.cpp */,
2DED182615C356BA0091BE97 /* SimpleAudioDriver.h */,
2DED182915C356BA0091BE97 /* SimpleAudioDriverUserClient.cpp */,
2DED182A15C356BA0091BE97 /* SimpleAudioDriverUserClient.h */,
2DED182B15C356BA0091BE97 /* SimpleAudioDriverTypes.h */,
);
path = Driver;
sourceTree = "<group>";
};
2DED182C15C356BA0091BE97 /* Plug-In */ = {
isa = PBXGroup;
children = (
2DD7AA9515EC551500C67AE1 /* SA_Device.cpp */,
2DD7AA9615EC551600C67AE1 /* SA_Device.h */,
2DD7AA0815EACDDF00C67AE1 /* SA_IOKit.cpp */,
2DD7AA0915EACDDF00C67AE1 /* SA_IOKit.h */,
2D76D97815E498EB00FF0F33 /* SA_Object.cpp */,
2D76D97915E498EB00FF0F33 /* SA_Object.h */,
2D76D98B15E56E4E00FF0F33 /* SA_PlugIn-Info.plist */,
2D76D97415E48B6400FF0F33 /* SA_PlugIn.cpp */,
2D76D97515E48B6400FF0F33 /* SA_PlugIn.h */,
2DA8FA7E15FEC6B500F04B50 /* Resources */,
);
path = "Plug-In";
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
2D76D95E15E48B2000FF0F33 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2D76D97715E48B6400FF0F33 /* SA_PlugIn.h in Headers */,
2D76D97B15E498EB00FF0F33 /* SA_Object.h in Headers */,
2DD7AA0B15EACDE000C67AE1 /* SA_IOKit.h in Headers */,
2DD7AA2415EAFD5100C67AE1 /* CACFArray.h in Headers */,
2DD7AA2615EAFD5100C67AE1 /* CACFDictionary.h in Headers */,
2DD7AA2815EAFD5100C67AE1 /* CACFNumber.h in Headers */,
2DD7AA2A15EAFD5100C67AE1 /* CACFString.h in Headers */,
2DD7AA2C15EAFD5100C67AE1 /* CADebugger.h in Headers */,
2DD7AA2E15EAFD5100C67AE1 /* CADebugMacros.h in Headers */,
2DD7AA3015EAFD5100C67AE1 /* CADebugPrintf.h in Headers */,
2DD7AA3115EAFD5100C67AE1 /* CAException.h in Headers */,
2DD7AA3315EAFD5100C67AE1 /* CAGuard.h in Headers */,
2DD7AA3515EAFD5100C67AE1 /* CAHostTimeBase.h in Headers */,
2DD7AA3715EAFD5100C67AE1 /* CAMutex.h in Headers */,
2DD7AA7E15EC20FD00C67AE1 /* CADispatchQueue.h in Headers */,
2DD7AA8015EC3DB800C67AE1 /* CACFObject.h in Headers */,
2DD7AA9815EC551600C67AE1 /* SA_Device.h in Headers */,
2D4DE41515EDF8D500E96F0D /* CAVolumeCurve.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2DED183415C357180091BE97 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
2DED184A15C359AC0091BE97 /* SimpleAudioDriver.h in Headers */,
2DED184C15C359AC0091BE97 /* SimpleAudioDriverUserClient.h in Headers */,
2DED184D15C359AC0091BE97 /* SimpleAudioDriverTypes.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
2D7477A81578168D00412279 /* NullAudio */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2D7477B51578168D00412279 /* Build configuration list for PBXNativeTarget "NullAudio" */;
buildPhases = (
2D7477A51578168D00412279 /* Sources */,
2D7477A61578168D00412279 /* Frameworks */,
2D46CA7A17D6ADC500049D4A /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = NullAudio;
productName = AudioNULLDriver;
productReference = 2D7477A91578168D00412279 /* NullAudio.driver */;
productType = "com.apple.product-type.bundle";
};
2D76D95F15E48B2000FF0F33 /* SimpleAudioPlugIn */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2D76D97215E48B2000FF0F33 /* Build configuration list for PBXNativeTarget "SimpleAudioPlugIn" */;
buildPhases = (
2D76D95E15E48B2000FF0F33 /* Headers */,
2D76D95C15E48B2000FF0F33 /* Sources */,
2D76D95D15E48B2000FF0F33 /* Frameworks */,
2DA8FA4B15FEABE000F04B50 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = SimpleAudioPlugIn;
productName = SimpleAudioPlugIn;
productReference = 2D76D96015E48B2000FF0F33 /* SimpleAudioPlugIn.driver */;
productType = "com.apple.product-type.bundle";
};
2DED183715C357180091BE97 /* SimpleAudioDriver */ = {
isa = PBXNativeTarget;
buildConfigurationList = 2DED184515C357180091BE97 /* Build configuration list for PBXNativeTarget "SimpleAudioDriver" */;
buildPhases = (
2DED183415C357180091BE97 /* Headers */,
2DED183215C357180091BE97 /* Sources */,
2DED183315C357180091BE97 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = SimpleAudioDriver;
productName = SimpleAudioDriver;
productReference = 2DED183815C357180091BE97 /* SimpleAudioDriver.kext */;
productType = "com.apple.product-type.kernel-extension";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
2D74779D1578162B00412279 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0500;
};
buildConfigurationList = 2D7477A01578162B00412279 /* Build configuration list for PBXProject "AudioDriverExamples" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
English,
);
mainGroup = 2D74779B1578162B00412279;
productRefGroup = 2D7477AA1578168D00412279 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
2D7477A81578168D00412279 /* NullAudio */,
2DED183715C357180091BE97 /* SimpleAudioDriver */,
2D76D95F15E48B2000FF0F33 /* SimpleAudioPlugIn */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
2D46CA7A17D6ADC500049D4A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D46CA7B17D6ADCA00049D4A /* Localizable.strings in Resources */,
2D46CA7D17D6AF4200049D4A /* DeviceIcon.icns in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2DA8FA4B15FEABE000F04B50 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D47CAA415FEC82B002AAFB5 /* Localizable.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
2D7477A51578168D00412279 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D616EF415B8C82500D598BD /* NullAudio.c in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2D76D95C15E48B2000FF0F33 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2D76D97615E48B6400FF0F33 /* SA_PlugIn.cpp in Sources */,
2D76D97A15E498EB00FF0F33 /* SA_Object.cpp in Sources */,
2DD7AA0A15EACDE000C67AE1 /* SA_IOKit.cpp in Sources */,
2DD7AA2315EAFD5100C67AE1 /* CACFArray.cpp in Sources */,
2DD7AA2515EAFD5100C67AE1 /* CACFDictionary.cpp in Sources */,
2DD7AA2715EAFD5100C67AE1 /* CACFNumber.cpp in Sources */,
2DD7AA2915EAFD5100C67AE1 /* CACFString.cpp in Sources */,
2DD7AA2B15EAFD5100C67AE1 /* CADebugger.cpp in Sources */,
2DD7AA2D15EAFD5100C67AE1 /* CADebugMacros.cpp in Sources */,
2DD7AA2F15EAFD5100C67AE1 /* CADebugPrintf.cpp in Sources */,
2DD7AA3215EAFD5100C67AE1 /* CAGuard.cpp in Sources */,
2DD7AA3415EAFD5100C67AE1 /* CAHostTimeBase.cpp in Sources */,
2DD7AA3615EAFD5100C67AE1 /* CAMutex.cpp in Sources */,
2DD7AA7D15EC20FD00C67AE1 /* CADispatchQueue.cpp in Sources */,
2DD7AA9715EC551600C67AE1 /* SA_Device.cpp in Sources */,
2D4DE41415EDF8D500E96F0D /* CAVolumeCurve.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
2DED183215C357180091BE97 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
2DED184915C359AC0091BE97 /* SimpleAudioDriver.cpp in Sources */,
2DED184B15C359AC0091BE97 /* SimpleAudioDriverUserClient.cpp in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
2D46CA7817D6AD8A00049D4A /* Localizable.strings */ = {
isa = PBXVariantGroup;
children = (
2D46CA7917D6AD8A00049D4A /* English */,
);
name = Localizable.strings;
sourceTree = "<group>";
};
2D47CAA215FEC82B002AAFB5 /* Localizable.strings */ = {
isa = PBXVariantGroup;
children = (
2D47CAA315FEC82B002AAFB5 /* English */,
);
name = Localizable.strings;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
2D7477A21578162B00412279 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "c++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_OPTIMIZATION_LEVEL = s;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
GCC_WARN_SHADOW = YES;
GCC_WARN_SIGN_COMPARE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNKNOWN_PRAGMAS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_LABEL = YES;
GCC_WARN_UNUSED_PARAMETER = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
SDKROOT = macosx;
};
name = Release;
};
2D7477A31578162B00412279 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "c++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_OPTIMIZATION_LEVEL = 0;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
GCC_WARN_SHADOW = YES;
GCC_WARN_SIGN_COMPARE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNKNOWN_PRAGMAS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_LABEL = YES;
GCC_WARN_UNUSED_PARAMETER = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
SDKROOT = macosx;
};
name = Debug;
};
2D7477A41578164E00412279 /* Debug-Opt */ = {
isa = XCBuildConfiguration;
buildSettings = {
ARCHS = "$(ARCHS_STANDARD_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "c++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_IMPLICIT_SIGN_CONVERSION = NO;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
GCC_OPTIMIZATION_LEVEL = s;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES;
GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES;
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES;
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES;
GCC_WARN_SHADOW = YES;
GCC_WARN_SIGN_COMPARE = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES;
GCC_WARN_UNKNOWN_PRAGMAS = YES;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_LABEL = YES;
GCC_WARN_UNUSED_PARAMETER = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
SDKROOT = macosx;
};
name = "Debug-Opt";
};
2D7477B61578168D00412279 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"DEBUG=0",
);
INFOPLIST_FILE = "NullAudio/NullAudio-Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Audio/Plug-Ins/HAL";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = driver;
};
name = Release;
};
2D7477B71578168D00412279 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"DEBUG=1",
);
INFOPLIST_FILE = "NullAudio/NullAudio-Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Audio/Plug-Ins/HAL";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = driver;
};
name = Debug;
};
2D7477B81578168D00412279 /* Debug-Opt */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"DEBUG=1",
);
INFOPLIST_FILE = "NullAudio/NullAudio-Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Audio/Plug-Ins/HAL";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = driver;
};
name = "Debug-Opt";
};
2D76D96F15E48B2000FF0F33 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_ENABLE_CPP_RTTI = NO;
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"CoreAudio_Debug=0",
"CoreAudio_UseSysLog=1",
);
INFOPLIST_FILE = "SimpleAudio/Plug-In/SA_PlugIn-Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Audio/Plug-Ins/HAL";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = driver;
};
name = Release;
};
2D76D97015E48B2000FF0F33 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_ENABLE_CPP_RTTI = NO;
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"CoreAudio_Debug=1",
"CoreAudio_UseSysLog=1",
);
INFOPLIST_FILE = "SimpleAudio/Plug-In/SA_PlugIn-Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Audio/Plug-Ins/HAL";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = driver;
};
name = Debug;
};
2D76D97115E48B2000FF0F33 /* Debug-Opt */ = {
isa = XCBuildConfiguration;
buildSettings = {
GCC_ENABLE_CPP_RTTI = NO;
GCC_PREPROCESSOR_DEFINITIONS = (
"$(inherited)",
"CoreAudio_Debug=1",
"CoreAudio_UseSysLog=1",
);
INFOPLIST_FILE = "SimpleAudio/Plug-In/SA_PlugIn-Info.plist";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Audio/Plug-Ins/HAL";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = driver;
};
name = "Debug-Opt";
};
2DED184615C357180091BE97 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN__EXIT_TIME_DESTRUCTORS = NO;
GCC_PREPROCESSOR_DEFINITIONS = "";
INFOPLIST_FILE = "SimpleAudio/Driver/SimpleAudioDriver-Info.plist";
INSTALL_PATH = "$(SYSTEM_LIBRARY_DIR)/Extensions";
MODULE_NAME = com.apple.audio.SimpleAudioDriver;
MODULE_VERSION = 1.0;
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = kext;
};
name = Release;
};
2DED184715C357180091BE97 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN__EXIT_TIME_DESTRUCTORS = NO;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1";
INFOPLIST_FILE = "SimpleAudio/Driver/SimpleAudioDriver-Info.plist";
INSTALL_PATH = "$(SYSTEM_LIBRARY_DIR)/Extensions";
MODULE_NAME = com.apple.audio.SimpleAudioDriver;
MODULE_VERSION = 1.0;
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = kext;
};
name = Debug;
};
2DED184815C357180091BE97 /* Debug-Opt */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_WARN__EXIT_TIME_DESTRUCTORS = NO;
GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1";
INFOPLIST_FILE = "SimpleAudio/Driver/SimpleAudioDriver-Info.plist";
INSTALL_PATH = "$(SYSTEM_LIBRARY_DIR)/Extensions";
MODULE_NAME = com.apple.audio.SimpleAudioDriver;
MODULE_VERSION = 1.0;
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = kext;
};
name = "Debug-Opt";
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
2D7477A01578162B00412279 /* Build configuration list for PBXProject "AudioDriverExamples" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D7477A21578162B00412279 /* Release */,
2D7477A31578162B00412279 /* Debug */,
2D7477A41578164E00412279 /* Debug-Opt */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2D7477B51578168D00412279 /* Build configuration list for PBXNativeTarget "NullAudio" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D7477B61578168D00412279 /* Release */,
2D7477B71578168D00412279 /* Debug */,
2D7477B81578168D00412279 /* Debug-Opt */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2D76D97215E48B2000FF0F33 /* Build configuration list for PBXNativeTarget "SimpleAudioPlugIn" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2D76D96F15E48B2000FF0F33 /* Release */,
2D76D97015E48B2000FF0F33 /* Debug */,
2D76D97115E48B2000FF0F33 /* Debug-Opt */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
2DED184515C357180091BE97 /* Build configuration list for PBXNativeTarget "SimpleAudioDriver" */ = {
isa = XCConfigurationList;
buildConfigurations = (
2DED184615C357180091BE97 /* Release */,
2DED184715C357180091BE97 /* Debug */,
2DED184815C357180091BE97 /* Debug-Opt */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 2D74779D1578162B00412279 /* Project object */;
}
@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
@@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>com.apple.audio.${PRODUCT_NAME:rfc1034identifier}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${PRODUCT_NAME}</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>CFPlugInFactories</key>
<dict>
<key>99A15A8B-DA3C-42C3-BD5D-D035A0C2377A</key>
<string>NullAudio_Create</string>
</dict>
<key>CFPlugInTypes</key>
<dict>
<key>443ABAB8-E7B3-491A-B985-BEB9187030DB</key>
<array>
<string>99A15A8B-DA3C-42C3-BD5D-D035A0C2377A</string>
</array>
</dict>
</dict>
</plist>
File diff suppressed because it is too large Load Diff
-6
View File
@@ -1,6 +0,0 @@
TravisCI's OS X VMs don't have any audio devices installed by default, so we
install Apple's NullAudio sample driver before the tests run. Otherwise the
tests would fail because BGMApp currently crashes on launch if you don't have
any audio devices.
-31
View File
@@ -1,31 +0,0 @@
/*
* BGMApp.h
*/
#import <AppKit/AppKit.h>
#import <ScriptingBridge/ScriptingBridge.h>
@class BGMAppOutputDevice, BGMAppApplication;
/*
* Background Music
*/
// an output audio device
@interface BGMAppOutputDevice : SBObject
@property (copy, readonly) NSString *name;
@property BOOL selected; // is this the device to be used for audio output?
@end
// The application program
@interface BGMAppApplication : SBApplication
- (SBElementArray<BGMAppOutputDevice *> *) outputDevices;
@end
-236
View File
@@ -1,236 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMAppUITests.mm
// BGMAppUITests
//
// Copyright © 2017 Kyle Neideck
//
// You might want to use Xcode's UI test recording feature if you add new tests.
//
// Local Includes
#import "BGM_TestUtils.h"
#import "BGM_Types.h"
#import "BGMBackgroundMusicDevice.h"
// Scripting Bridge Includes
#import "BGMApp.h"
// TODO: Skip these tests if macOS SDK 10.11 or higher isn't available.
// TODO: Mock BGMDevice and music players.
@interface BGMAppUITests : XCTestCase
@end
@implementation BGMAppUITests {
// The BGMApp instance.
XCUIApplication* app;
// Convenience vars.
//
// The menu bar icon. (Called the status bar icon in some places.)
XCUIElement* icon;
// The menu items in the main menu.
XCUIElementQuery* menuItems;
// The Preferences menu item.
XCUIElement* prefs;
}
- (void) setUp {
[super setUp];
// In UI tests it is usually best to stop immediately when a failure occurs.
self.continueAfterFailure = NO;
// Set up the app object and some convenience vars.
app = [[XCUIApplication alloc] init];
menuItems = app.menuBars.menuItems;
icon = [app.menuBars childrenMatchingType:XCUIElementTypeMenuBarItem].element;
prefs = menuItems[@"Preferences"];
// TODO: Make sure BGMDevice isn't set as the OS X default device before launching BGMApp.
// Tell BGMApp not to load/store user defaults (settings) and to use
// NSApplicationActivationPolicyRegular. If it used the "accessory" policy as usual, the tests
// would fail to start because of a bug in Xcode.
app.launchArguments = @[ @"--no-persistent-data", @"--show-dock-icon" ];
// Launch BGMApp.
[app launch];
}
- (void) tearDown {
// Click the quit menu item.
if (!menuItems.count) {
[icon click];
}
[menuItems[@"Quit Background Music"] click];
// BGMApp should quit.
XCTAssert(!app.exists);
[super tearDown];
}
- (void) testCycleOutputDevices {
const int NUM_CYCLES = 2;
// Get the list of output devices from the preferences menu.
[icon click];
[prefs hover];
NSArray<XCUIElement*>* outputDeviceMenuItems = [self outputDeviceMenuItems];
// For debugging certain issues, it can be useful to repeatedly switch between two
// devices:
// outputDeviceMenuItems = [outputDeviceMenuItems subarrayWithRange:NSMakeRange(0,2)];
XCTAssertGreaterThan(outputDeviceMenuItems.count, 0);
// Click the last device to close the menu again.
[outputDeviceMenuItems.lastObject click];
BGMAppApplication* sbApp = [SBApplication applicationWithBundleIdentifier:@kBGMAppBundleID];
for (int i = 0; i < NUM_CYCLES; i++) {
// Select each output device.
for (XCUIElement* item in outputDeviceMenuItems) {
[icon click];
[prefs hover];
[item click];
// Assert that the device we clicked is the selected device now.
for (BGMAppOutputDevice* device in [sbApp outputDevices]) {
// TODO: This seems a bit fragile. Would it still work with long device names?
if ([device.name isEqualToString:[item title]]) {
XCTAssert(device.selected);
} else {
XCTAssertFalse(device.selected);
}
}
}
}
}
// Find the menu items for the output devices in the preferences menu.
- (NSArray<XCUIElement*>*) outputDeviceMenuItems {
NSArray<XCUIElement*>* items = @[];
BOOL inOutputDeviceSection = NO;
for (int i = 0; i < prefs.menuItems.count; i++) {
XCUIElement* menuItem = [prefs.menuItems elementBoundByIndex:i];
if ([menuItem.title isEqual:@"Output Device"]) {
inOutputDeviceSection = YES;
} else if (inOutputDeviceSection) {
// Assume that finding a separator menu item means we've reached the end of the section.
if (((NSMenuItem*)menuItem.value).separatorItem || [menuItem.title isEqual:@""]) {
break;
}
items = [items arrayByAddingObject:menuItem];
}
}
return items;
}
- (void) testSelectMusicPlayer {
// Select VLC as the music player.
[icon click];
[prefs hover];
[prefs.menuItems[@"VLC"] click];
// The name of the Auto-pause menu item should change. Also check the accessibility identifier.
[icon click];
XCTAssertEqualObjects(menuItems[@"Auto-pause VLC"].identifier, @"Auto-pause enabled");
// Select iTunes as the music player.
[prefs hover];
[prefs.menuItems[@"iTunes"] click];
// The name of the Auto-pause menu item should change back.
[icon click];
XCTAssert(menuItems[@"Auto-pause iTunes"].exists);
}
- (void) testOutputVolumeSlider {
const AudioObjectPropertyScope scope = kAudioDevicePropertyScopeOutput;
const UInt32 channel = kMasterChannel;
[icon click];
XCUIElement* slider = menuItems.sliders[@"Output Volume"];
// Try to slide the slider all the way to the right.
[slider adjustToNormalizedSliderPosition:1.0f];
// For whatever reason, XCTest usually doesn't quite make it to the position you ask for. So
// just check that it got close enough.
XCTAssertGreaterThan(slider.normalizedSliderPosition, 0.9f);
// BGMDevice's volume should be set to its max, or as close as XCTest was able to get the
// slider. Probably shouldn't be comparing floats for equality like this, but it's working fine
// so far.
BGMBackgroundMusicDevice bgmDevice;
XCTAssertEqual(slider.normalizedSliderPosition,
bgmDevice.GetVolumeControlScalarValue(scope, channel));
// Try to slide the slider all the way to the left.
[slider adjustToNormalizedSliderPosition:0.0f];
// BGMDevice's volume should be set to the new value of the slider.
XCTAssertLessThan(slider.normalizedSliderPosition, 0.1f);
XCTAssertEqual(slider.normalizedSliderPosition,
bgmDevice.GetVolumeControlScalarValue(scope, channel));
// Try to slide the slider to 75%.
[slider adjustToNormalizedSliderPosition:0.75f];
// BGMDevice's volume should be set to the new value of the slider, about 75% of its max.
XCTAssertEqual(slider.normalizedSliderPosition,
bgmDevice.GetVolumeControlScalarValue(scope, channel));
// BGMDevice should be unmuted.
XCTAssertEqual(false, bgmDevice.GetMuteControlValue(scope, channel));
// Set BGMDevice's volume to its min.
bgmDevice.SetVolumeControlScalarValue(scope, channel, 0.0f);
// The slider should be set to its min value. Use a wait for this check because the change
// happens asynchronously.
[self expectationForPredicate:[NSPredicate predicateWithFormat:@"normalizedSliderPosition == 0"]
evaluatedWithObject:slider
handler:nil];
[self waitForExpectationsWithTimeout:10.0 handler:nil];
XCTAssertEqual(0.0f, slider.normalizedSliderPosition);
// Click the slider without changing it to simulate the user setting the slider to zero.
[slider adjustToNormalizedSliderPosition:0.0f];
// BGMDevice's volume should still be set to its min.
XCTAssertEqual(0.0f, bgmDevice.GetVolumeControlScalarValue(scope, channel));
// BGMDevice should now be muted.
XCTAssertEqual(true, bgmDevice.GetMuteControlValue(scope, channel));
}
@end
-49
View File
@@ -1,49 +0,0 @@
#!/usr/bin/python2.7
# This file is part of Background Music.
#
# Background Music is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.
#
# Background Music is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Background Music. If not, see <http://www.gnu.org/licenses/>.
#
# travis-skip.py
# BGMAppUITests
#
# Copyright (c) 2017 Kyle Neideck
#
# Skip the UI tests in Travis builds because they aren't supported.
#
# We can't run the tests on Travis because Xcode needs permission to use the Accessibility API
# to control BGMApp. There's no way to set that up programmatically without disabling SIP and
# Travis doesn't support that.
#
# See https://github.com/travis-ci/travis-ci/issues/5819
#
# TODO: Figure out a better way to do this.
#
import xml.etree.ElementTree as ET
SCHEME_FILE = "BGMApp/BGMApp.xcodeproj/xcshareddata/xcschemes/Background Music.xcscheme"
UI_REF_XPATH = ".//BuildableReference[@BlueprintName='BGMAppUITests']/.."
# Parse the Xcode scheme.
tree = ET.parse(SCHEME_FILE)
# Set the TestableReference for the UI tests to skipped.
tree.getroot().findall(UI_REF_XPATH)[0].set("skipped", "YES")
# Save the scheme.
tree.write(SCHEME_FILE)
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -1,235 +0,0 @@
// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.
//
// BGMMusicPlayersUnitTests.mm
// BGMAppUnitTests
//
// Copyright © 2016-2018 Kyle Neideck
//
// Unit include
#import "BGMMusicPlayers.h"
// Local includes
#import "BGM_TestUtils.h"
#import "BGM_Types.h"
#import "BGMAudioDeviceManager.h"
#import "BGMiTunes.h"
#import "BGMVLC.h"
#import "BGMDecibel.h"
#import "BGMSpotify.h"
// System includes
#import <Foundation/Foundation.h>
// Note that the PublicUtility classes that we use to communicate with the HAL, CAHALAudioObject and
// CAHALAudioSystemObject, are also mocked. The unit tests are compiled with mock implementations:
// Mock_CAHALAudioObject.cpp and Mock_CAHALAudioSystemObject.cpp.
@interface BGMMockUserDefaults : BGMUserDefaults
@property NSUUID* selectedPlayerID;
@end
@implementation BGMMockUserDefaults
- (void) registerDefaults {
}
- (NSString* __nullable) selectedMusicPlayerID {
return [self.selectedPlayerID UUIDString];
}
- (void) setSelectedMusicPlayerID:(NSString* __nullable)selectedMusicPlayerID {
#pragma unused (selectedMusicPlayerID)
}
- (BOOL) autoPauseMusicEnabled {
return YES;
}
- (void) setAutoPauseMusicEnabled:(BOOL)autoPauseMusicEnabled {
#pragma unused (autoPauseMusicEnabled)
}
@end
// -------------------------------------------------------------------------------------------------
class BGMMockBackgroundMusicDevice
:
public BGMBackgroundMusicDevice
{
public:
CFStringRef GetMusicPlayerBundleID() const;
void SetMusicPlayerBundleID(CFStringRef inBundleID);
private:
CFStringRef mMusicPlayerBundleID = CFSTR("");
};
CFStringRef BGMMockBackgroundMusicDevice::GetMusicPlayerBundleID() const
{
return mMusicPlayerBundleID;
}
void BGMMockBackgroundMusicDevice::SetMusicPlayerBundleID(CFStringRef inBundleID)
{
mMusicPlayerBundleID = inBundleID;
}
// -------------------------------------------------------------------------------------------------
@interface BGMMockAudioDeviceManager : BGMAudioDeviceManager
@end
@implementation BGMMockAudioDeviceManager {
BGMBackgroundMusicDevice bgmDevice;
}
- (BGMBackgroundMusicDevice) bgmDevice {
return bgmDevice;
}
@end
// -------------------------------------------------------------------------------------------------
@interface BGMMusicPlayersUnitTests : XCTestCase
@end
@implementation BGMMusicPlayersUnitTests {
BGMAudioDeviceManager* devices;
BGMMockUserDefaults* defaults;
NSUUID* spotifyID;
NSUUID* vlcID;
}
- (void) setUp {
[super setUp];
devices = [BGMMockAudioDeviceManager new];
defaults = [BGMMockUserDefaults new];
// These are the IDs hardcoded in BGMSpotify and BGMVLC.
spotifyID = [[NSUUID alloc] initWithUUIDString:@"EC2A907F-8515-4687-9570-1BF63176E6D8"];
vlcID = [[NSUUID alloc] initWithUUIDString:@"5226F4B9-C740-4045-A273-4B8EABC0E8FC"];
}
- (void) tearDown {
[super tearDown];
}
- (void) testNoSelectedMusicPlayerStored {
// Test the case where the user has never changed the music player preference.
// Test with iTunes as the default.
BGMMusicPlayers* players = [[BGMMusicPlayers alloc] initWithAudioDevices:devices
defaultMusicPlayerID:[BGMiTunes sharedMusicPlayerID]
musicPlayerClasses:@[ BGMiTunes.class, BGMVLC.class ]
userDefaults:defaults];
XCTAssertEqual(players.musicPlayers.count, 2);
for (id<BGMMusicPlayer> player in players.musicPlayers) {
XCTAssertTrue([player isKindOfClass:BGMiTunes.class] || [player isKindOfClass:BGMVLC.class]);
}
XCTAssertEqualObjects(players.selectedMusicPlayer.musicPlayerID, [BGMiTunes sharedMusicPlayerID]);
XCTAssertEqualObjects(players.selectedMusicPlayer.name, @"iTunes");
[self resetDevice];
// Test with VLC as the default.
players = [[BGMMusicPlayers alloc] initWithAudioDevices:devices
defaultMusicPlayerID:vlcID
musicPlayerClasses:@[ BGMiTunes.class,
BGMVLC.class,
BGMDecibel.class ]
userDefaults:defaults];
XCTAssertEqual(players.musicPlayers.count, 3);
for (id<BGMMusicPlayer> player in players.musicPlayers) {
XCTAssertTrue([player isKindOfClass:BGMiTunes.class] ||
[player isKindOfClass:BGMVLC.class] ||
[player isKindOfClass:BGMDecibel.class]);
}
XCTAssertEqualObjects(players.selectedMusicPlayer.musicPlayerID, vlcID);
XCTAssertEqualObjects(players.selectedMusicPlayer.name, @"VLC");
}
- (void) testSelectedMusicPlayerInUserDefaults {
defaults.selectedPlayerID = spotifyID;
BGMMusicPlayers* players = [[BGMMusicPlayers alloc] initWithAudioDevices:devices
defaultMusicPlayerID:[BGMiTunes sharedMusicPlayerID]
musicPlayerClasses:@[ BGMiTunes.class,
BGMVLC.class,
BGMSpotify.class ]
userDefaults:defaults];
XCTAssertEqual(players.musicPlayers.count, 3);
XCTAssertEqualObjects(players.selectedMusicPlayer.musicPlayerID, spotifyID);
XCTAssertEqualObjects(players.selectedMusicPlayer.name, @"Spotify");
[self resetDevice];
// If there's an unrecognized ID in user defaults, the default music player should be selected.
defaults.selectedPlayerID = [[NSUUID alloc] initWithUUIDString:@"11111111-1111-1111-0000-000000000000"];
// This initializer sets iTunes as the default music player and adds all the other music players.
players = [[BGMMusicPlayers alloc] initWithAudioDevices:devices
userDefaults:defaults];
XCTAssert(players.musicPlayers.count >= 6);
XCTAssertEqualObjects(players.selectedMusicPlayer.musicPlayerID, [BGMiTunes sharedMusicPlayerID]);
XCTAssertEqualObjects(players.selectedMusicPlayer.name, @"iTunes");
}
- (void) testSelectedMusicPlayerInBGMDeviceProperties {
// When it doesn't find a selected music player in user defaults, it should check BGMDevice's music
// player properties.
[devices bgmDevice].SetMusicPlayerBundleID(CFSTR("org.videolan.vlc"));
BGMMusicPlayers* players = [[BGMMusicPlayers alloc] initWithAudioDevices:devices
userDefaults:defaults];
XCTAssert(players.musicPlayers.count >= 6);
XCTAssertEqualObjects(players.selectedMusicPlayer.musicPlayerID, vlcID);
XCTAssertEqualObjects(players.selectedMusicPlayer.name, @"VLC");
}
// TODO: Test setting the selectedMusicPlayer property
- (void) resetDevice {
// Reset the mock BGMDevice.
[devices bgmDevice].SetMusicPlayerBundleID(CFSTR(""));
}
@end

Some files were not shown because too many files have changed in this diff Show More