mirror of
https://github.com/Toxblh/MTMR.git
synced 2026-10-31 10:28:36 +00:00
Compare commits
291
Commits
v0.6
..
small-fixes
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1f764d539a | ||
|
|
e95c707009 | ||
|
|
1914dbb08f | ||
|
|
34074a1b9b | ||
|
|
e07ee1e263 | ||
|
|
9228eaffc8 | ||
|
|
f89871d294 | ||
|
|
8e35d38b59 | ||
|
|
17e023d2d2 | ||
|
|
dc94857ac4 | ||
|
|
ec228fddde | ||
|
|
958f93f440 | ||
|
|
d03b16eb89 | ||
|
|
ea573882a0 | ||
|
|
7fb936bd1d | ||
|
|
f97a3be6d3 | ||
|
|
3bc26eae82 | ||
|
|
f84463dbb2 | ||
|
|
46c86a71de | ||
|
|
ad70c034da | ||
|
|
221565f604 | ||
|
|
6ca7f11a2b | ||
|
|
63795b3d41 | ||
|
|
8a7de99bce | ||
|
|
7f13422805 | ||
|
|
56d64155ae | ||
|
|
088f141da3 | ||
|
|
091208e536 | ||
|
|
c6f6fbc5cd | ||
|
|
3cdf44903b | ||
|
|
e13e8598a7 | ||
|
|
d82c837902 | ||
|
|
d5483cdd03 | ||
|
|
9f2dd277fb | ||
|
|
e7c949209d | ||
|
|
42d3d29e0d | ||
|
|
6674b5aef7 | ||
|
|
f83f331a99 | ||
|
|
cd16c09dbd | ||
|
|
4ba9d11494 | ||
|
|
62a2aa14e1 | ||
|
|
1c0a2f064a | ||
|
|
23357816b3 | ||
|
|
877dca7587 | ||
|
|
fd537bcdfe | ||
|
|
e852ab58f8 | ||
|
|
5c7be625b6 | ||
|
|
475b66c956 | ||
|
|
19f7ff0103 | ||
|
|
3bc75b54c0 | ||
|
|
3c072923d2 | ||
|
|
b29c74ccca | ||
|
|
bbea465500 | ||
|
|
f7eb49e5de | ||
|
|
e9c69f6461 | ||
|
|
9e1fcb9a35 | ||
|
|
7523605d7a | ||
|
|
b73f8865a9 | ||
|
|
852df9d6b6 | ||
|
|
57e8af90dd | ||
|
|
0e48566c74 | ||
|
|
55177a7f90 | ||
|
|
d46827832e | ||
|
|
9e10b2d3d1 | ||
|
|
33efbbebaa | ||
|
|
d048ec851e | ||
|
|
42ebb91e6b | ||
|
|
1da4e2795f | ||
|
|
21bc525a04 | ||
|
|
b9ef3cdc35 | ||
|
|
9a34d5bca0 | ||
|
|
4c9820a390 | ||
|
|
634beeae8b | ||
|
|
3ec2422181 | ||
|
|
a3c7fa7464 | ||
|
|
20ed827750 | ||
|
|
85aa2c4f2b | ||
|
|
b761551384 | ||
|
|
3854b455a6 | ||
|
|
9c803e85cc | ||
|
|
651258b01f | ||
|
|
02baef80db | ||
|
|
cd75be6c26 | ||
|
|
7646c6e89d | ||
|
|
9c970aff63 | ||
|
|
49d7333d5e | ||
|
|
cd69bc341c | ||
|
|
453895f395 | ||
|
|
12796d6387 | ||
|
|
f65e72faed | ||
|
|
df535b2893 | ||
|
|
574ca0fb84 | ||
|
|
4a03ba79ec | ||
|
|
907b79965d | ||
|
|
fbec803d47 | ||
|
|
3f9574245a | ||
|
|
2bf6b90b04 | ||
|
|
9d596c6adc | ||
|
|
175e9edb8c | ||
|
|
8e58bb179a | ||
|
|
d37d9607d3 | ||
|
|
6b553c4d0d | ||
|
|
788927edb3 | ||
|
|
9013779f71 | ||
|
|
a85507c544 | ||
|
|
59aa113995 | ||
|
|
9c5a19925b | ||
|
|
2aa602d77d | ||
|
|
a1b3f13902 | ||
|
|
60384561d2 | ||
|
|
77938340d6 | ||
|
|
93d2f496d0 | ||
|
|
0808f0617a | ||
|
|
966a924183 | ||
|
|
a648402d04 | ||
|
|
207af6468e | ||
|
|
6609a7c806 | ||
|
|
479190d12b | ||
|
|
5ed1790601 | ||
|
|
b95f5af95f | ||
|
|
c76027ca9d | ||
|
|
55dc551516 | ||
|
|
cf5d8bf546 | ||
|
|
8031108fc9 | ||
|
|
d1a577868b | ||
|
|
5f02bb2962 | ||
|
|
cc1332dd02 | ||
|
|
a0dbfca828 | ||
|
|
76bdf12745 | ||
|
|
e1268d0d65 | ||
|
|
9c1e5f5032 | ||
|
|
88cde9256a | ||
|
|
d974f92e3d | ||
|
|
4b8ef1cd96 | ||
|
|
e65c57dbaa | ||
|
|
babc8451e0 | ||
|
|
7698ea1c8e | ||
|
|
aa95d1a1bd | ||
|
|
3fe6c22068 | ||
|
|
5ab19ee27b | ||
|
|
ae4b0aa870 | ||
|
|
1e2043ebda | ||
|
|
409b8d8b46 | ||
|
|
8bccbf3834 | ||
|
|
1b5ae00493 | ||
|
|
22c315d631 | ||
|
|
ffbbafa9d9 | ||
|
|
719a212913 | ||
|
|
651d883672 | ||
|
|
9853e0448f | ||
|
|
0f41638d0f | ||
|
|
f6e5b3ca09 | ||
|
|
04b821510b | ||
|
|
d632bd3ee7 | ||
|
|
aa341b818f | ||
|
|
a513c0083a | ||
|
|
683cc4c9f4 | ||
|
|
3c171b449a | ||
|
|
b4f62f6be1 | ||
|
|
8a9b40a030 | ||
|
|
3375308386 | ||
|
|
2fc9dbccd8 | ||
|
|
051a303f96 | ||
|
|
41a859aea3 | ||
|
|
bb978f2de5 | ||
|
|
9bf42dfb79 | ||
|
|
641eb18b89 | ||
|
|
d76e16b9e6 | ||
|
|
9abb17ee76 | ||
|
|
4b39b000e0 | ||
|
|
9b86ed1dee | ||
|
|
7874433d9b | ||
|
|
d4108d848e | ||
|
|
f78f82893a | ||
|
|
05eabdbd0a | ||
|
|
4109f6efd4 | ||
|
|
bbbbf5b5a4 | ||
|
|
8513ed0fa3 | ||
|
|
0e2a958b5c | ||
|
|
ac234aa4bf | ||
|
|
e6d84888ba | ||
|
|
2aecb2ffb3 | ||
|
|
cd8b595552 | ||
|
|
76934e6ff0 | ||
|
|
3e35e03bfb | ||
|
|
6f3425f4c3 | ||
|
|
0c007b7940 | ||
|
|
a7060b74e4 | ||
|
|
92c4eed4ed | ||
|
|
94d519cd65 | ||
|
|
7341136897 | ||
|
|
4459a95691 | ||
|
|
7bc8458d8b | ||
|
|
bfc4dcf22c | ||
|
|
4eb14ea166 | ||
|
|
c15488b61f | ||
|
|
33bb3b8d65 | ||
|
|
c5a7a3142b | ||
|
|
5b08861dec | ||
|
|
82f192a5c0 | ||
|
|
9230b1c3e6 | ||
|
|
647e0accea | ||
|
|
0ce6648bf9 | ||
|
|
fe3e647b56 | ||
|
|
fe07ea3b46 | ||
|
|
4b22514969 | ||
|
|
03bcafd5ff | ||
|
|
fdd30413c4 | ||
|
|
3a57269510 | ||
|
|
e9de35ee37 | ||
|
|
e027c640f7 | ||
|
|
242e2d3c22 | ||
|
|
b3500684d4 | ||
|
|
42c1ff27c4 | ||
|
|
4c16321a4a | ||
|
|
adaed36fbd | ||
|
|
f724a0d355 | ||
|
|
6b2e06b967 | ||
|
|
4663eb9b27 | ||
|
|
7774b1fa5e | ||
|
|
71ea94590b | ||
|
|
20699e9de7 | ||
|
|
893e9f6982 | ||
|
|
7a3c4811ac | ||
|
|
0ce5a49172 | ||
|
|
9db9df5641 | ||
|
|
69b3f9d238 | ||
|
|
3d7bcd2d47 | ||
|
|
a37bc94588 | ||
|
|
91ceea564e | ||
|
|
ee49e94c73 | ||
|
|
2f796cc07a | ||
|
|
b2b495b551 | ||
|
|
818c32b0ed | ||
|
|
d15764d41d | ||
|
|
9d343a31d3 | ||
|
|
0956b4ebcd | ||
|
|
9ff68a6948 | ||
|
|
ac8a05d2e5 | ||
|
|
75ea408370 | ||
|
|
8760185ae7 | ||
|
|
bd0ffbefe7 | ||
|
|
783ed34c0f | ||
|
|
37c2e8523c | ||
|
|
3f2dad52ee | ||
|
|
d6b0c0313b | ||
|
|
78509fb84d | ||
|
|
877c4268fd | ||
|
|
0e07f71458 | ||
|
|
7100a6e6b8 | ||
|
|
347bad8058 | ||
|
|
d72fb0ef7a | ||
|
|
ccc3a2269b | ||
|
|
6d6048c49c | ||
|
|
055c5d77ef | ||
|
|
f64c705c0d | ||
|
|
ca2ae30873 | ||
|
|
00fae08da0 | ||
|
|
f09b9155c4 | ||
|
|
9ef185d214 | ||
|
|
12f9220e34 | ||
|
|
ba753ff331 | ||
|
|
aba1aea334 | ||
|
|
849b5b6db0 | ||
|
|
621cb3242b | ||
|
|
dd0ecf047d | ||
|
|
bbc3d9dcfe | ||
|
|
85785018f4 | ||
|
|
7b9f894bf3 | ||
|
|
3a57293206 | ||
|
|
9afa9d7470 | ||
|
|
a86f7eb304 | ||
|
|
5013262740 | ||
|
|
106f297f57 | ||
|
|
115ea1372c | ||
|
|
f45aad4fad | ||
|
|
e131f92fb5 | ||
|
|
69a8d81bce | ||
|
|
7789407766 | ||
|
|
6c331619d0 | ||
|
|
9393a4e484 | ||
|
|
4b480dddc3 | ||
|
|
a6f27a1fef | ||
|
|
79eba1a281 | ||
|
|
2ad89bd8c8 | ||
|
|
ec990e8147 | ||
|
|
16d8380830 | ||
|
|
9e43a3b561 | ||
|
|
080bc67c54 | ||
|
|
81131ec390 | ||
|
|
cd6054af03 |
@@ -1,3 +1,5 @@
|
||||
|
||||
.DS_Store
|
||||
# Xcode
|
||||
#
|
||||
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
|
||||
@@ -5,6 +7,7 @@
|
||||
## Build generated
|
||||
build/
|
||||
DerivedData/
|
||||
Release/
|
||||
|
||||
## Various settings
|
||||
*.pbxuser
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
language: swift
|
||||
xcode_project: MTMR.xcodeproj
|
||||
xcode_scheme: UnitTests
|
||||
osx_image: xcode9.3
|
||||
install: gem install xcpretty
|
||||
script: "xcodebuild test -project MTMR.xcodeproj -scheme 'UnitTests' | xcpretty -c && exit ${PIPESTATUS[0]}"
|
||||
@@ -7,12 +7,30 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
36300E83209F040900B31C71 /* SupportHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0008E542080286C003AD4DD /* SupportHelpers.swift */; };
|
||||
36300E8F20A2CF3400B31C71 /* AppleScriptDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36300E8E20A2CF3400B31C71 /* AppleScriptDefinitionTests.swift */; };
|
||||
36300E9120A2D2B200B31C71 /* BackgroundColorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36300E9020A2D2B200B31C71 /* BackgroundColorTests.swift */; };
|
||||
368EDDE720812A1D00E10953 /* ScrollViewItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 368EDDE620812A1D00E10953 /* ScrollViewItem.swift */; };
|
||||
36A778BE20A6C27100B38714 /* GeneralExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36A778BD20A6C27100B38714 /* GeneralExtensions.swift */; };
|
||||
36C2ECD7207B6DAE003CDA33 /* TimeTouchBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C2ECD6207B6DAE003CDA33 /* TimeTouchBarItem.swift */; };
|
||||
36C2ECD9207B74B4003CDA33 /* AppleScriptTouchBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C2ECD8207B74B4003CDA33 /* AppleScriptTouchBarItem.swift */; };
|
||||
36C2ECDB207C3FE7003CDA33 /* ItemsParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C2ECDA207C3FE7003CDA33 /* ItemsParsing.swift */; };
|
||||
36C2ECDD207C723B003CDA33 /* ParseConfigTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C2ECDC207C723B003CDA33 /* ParseConfigTests.swift */; };
|
||||
36C2ECDE207C82DE003CDA33 /* ItemsParsing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36C2ECDA207C3FE7003CDA33 /* ItemsParsing.swift */; };
|
||||
36C2ECE0207CB1B0003CDA33 /* defaultPreset.json in Resources */ = {isa = PBXBuildFile; fileRef = 36C2ECDF207CB1B0003CDA33 /* defaultPreset.json */; };
|
||||
60173D3E20C0031B002C305F /* LaunchAtLoginController.m in Sources */ = {isa = PBXBuildFile; fileRef = 60173D3D20C0031B002C305F /* LaunchAtLoginController.m */; };
|
||||
6027D1B92080E52A004FFDC7 /* BrightnessViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6027D1B72080E52A004FFDC7 /* BrightnessViewController.swift */; };
|
||||
6027D1BA2080E52A004FFDC7 /* VolumeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6027D1B82080E52A004FFDC7 /* VolumeViewController.swift */; };
|
||||
6042B6A72083E03A00C525C8 /* AppScrubberTouchBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6042B6A62083E03A00C525C8 /* AppScrubberTouchBarItem.swift */; };
|
||||
6042B6AA2083E27000C525C8 /* DeprecatedCarbonAPI.c in Sources */ = {isa = PBXBuildFile; fileRef = 6042B6A92083E27000C525C8 /* DeprecatedCarbonAPI.c */; };
|
||||
60669B4320AD8FA80074E817 /* GroupBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60669B4220AD8FA80074E817 /* GroupBarItem.swift */; };
|
||||
607EEA4B2087835F009DA5F0 /* WeatherBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 607EEA4A2087835F009DA5F0 /* WeatherBarItem.swift */; };
|
||||
607EEA4D2087A8DA009DA5F0 /* CurrencyBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 607EEA4C2087A8DA009DA5F0 /* CurrencyBarItem.swift */; };
|
||||
60C44AFD20A373A100C0EC91 /* MusicBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60C44AFC20A373A100C0EC91 /* MusicBarItem.swift */; };
|
||||
60F7D454208CC31400ABF5D2 /* InputSourceBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60F7D453208CC31400ABF5D2 /* InputSourceBarItem.swift */; };
|
||||
B0008E552080286C003AD4DD /* SupportHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0008E542080286C003AD4DD /* SupportHelpers.swift */; };
|
||||
B04B7BB72087398C00C835D0 /* BatteryBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = B04B7BB62087398C00C835D0 /* BatteryBarItem.swift */; };
|
||||
B05600D32083E9BB00EB218D /* CustomSlider.swift in Sources */ = {isa = PBXBuildFile; fileRef = B05600D22083E9BB00EB218D /* CustomSlider.swift */; };
|
||||
B059D622205E03F5006E6B86 /* TouchBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B059D621205E03F5006E6B86 /* TouchBarController.swift */; };
|
||||
B059D624205E04F3006E6B86 /* CustomButtonTouchBarItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = B059D623205E04F3006E6B86 /* CustomButtonTouchBarItem.swift */; };
|
||||
B059D62D205F11E8006E6B86 /* DFRFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B059D62C205F11E8006E6B86 /* DFRFoundation.framework */; };
|
||||
@@ -32,20 +50,16 @@
|
||||
B0B17438207D6B590004B740 /* Vox.next.scpt in Resources */ = {isa = PBXBuildFile; fileRef = B0B1742E207D6B590004B740 /* Vox.next.scpt */; };
|
||||
B0B17439207D6B590004B740 /* Vox.nowPlaying.scpt in Resources */ = {isa = PBXBuildFile; fileRef = B0B1742F207D6B590004B740 /* Vox.nowPlaying.scpt */; };
|
||||
B0B1743A207D6B590004B740 /* iTunes.nowPlaying.scpt in Resources */ = {isa = PBXBuildFile; fileRef = B0B17430207D6B590004B740 /* iTunes.nowPlaying.scpt */; };
|
||||
B0F3112520C9E35F0076BB88 /* SupportNSTouchBar.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0F3112420C9E35F0076BB88 /* SupportNSTouchBar.swift */; };
|
||||
B0F8771A207AC1EA00D6E430 /* TouchBarSupport.m in Sources */ = {isa = PBXBuildFile; fileRef = B0F87719207AC1EA00D6E430 /* TouchBarSupport.m */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
B082B262205C7D8000BC04DC /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = B082B247205C7D8000BC04DC /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = B082B24E205C7D8000BC04DC;
|
||||
remoteInfo = MTMR;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
36300E85209FD16700B31C71 /* .travis.yml */ = {isa = PBXFileReference; lastKnownFileType = text; path = .travis.yml; sourceTree = SOURCE_ROOT; };
|
||||
36300E8E20A2CF3400B31C71 /* AppleScriptDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleScriptDefinitionTests.swift; sourceTree = "<group>"; };
|
||||
36300E9020A2D2B200B31C71 /* BackgroundColorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackgroundColorTests.swift; sourceTree = "<group>"; };
|
||||
368EDDE620812A1D00E10953 /* ScrollViewItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScrollViewItem.swift; sourceTree = "<group>"; };
|
||||
36A778BD20A6C27100B38714 /* GeneralExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GeneralExtensions.swift; sourceTree = "<group>"; };
|
||||
36BDC22F207CDA8600FCFEBE /* TECHNICAL_DEBT.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = TECHNICAL_DEBT.md; sourceTree = "<group>"; };
|
||||
36C2ECD2207B3B1D003CDA33 /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
|
||||
36C2ECD6207B6DAE003CDA33 /* TimeTouchBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TimeTouchBarItem.swift; sourceTree = "<group>"; };
|
||||
@@ -53,6 +67,21 @@
|
||||
36C2ECDA207C3FE7003CDA33 /* ItemsParsing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ItemsParsing.swift; sourceTree = "<group>"; };
|
||||
36C2ECDC207C723B003CDA33 /* ParseConfigTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ParseConfigTests.swift; sourceTree = "<group>"; };
|
||||
36C2ECDF207CB1B0003CDA33 /* defaultPreset.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = defaultPreset.json; sourceTree = "<group>"; };
|
||||
60173D3C20C0031B002C305F /* LaunchAtLoginController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LaunchAtLoginController.h; sourceTree = "<group>"; };
|
||||
60173D3D20C0031B002C305F /* LaunchAtLoginController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = LaunchAtLoginController.m; sourceTree = "<group>"; };
|
||||
6027D1B72080E52A004FFDC7 /* BrightnessViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BrightnessViewController.swift; sourceTree = "<group>"; };
|
||||
6027D1B82080E52A004FFDC7 /* VolumeViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VolumeViewController.swift; sourceTree = "<group>"; };
|
||||
6042B6A62083E03A00C525C8 /* AppScrubberTouchBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppScrubberTouchBarItem.swift; sourceTree = "<group>"; };
|
||||
6042B6A82083E1F500C525C8 /* DeprecatedCarbonAPI.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = DeprecatedCarbonAPI.h; sourceTree = "<group>"; };
|
||||
6042B6A92083E27000C525C8 /* DeprecatedCarbonAPI.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = DeprecatedCarbonAPI.c; sourceTree = "<group>"; };
|
||||
60669B4220AD8FA80074E817 /* GroupBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GroupBarItem.swift; sourceTree = "<group>"; };
|
||||
607EEA4A2087835F009DA5F0 /* WeatherBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeatherBarItem.swift; sourceTree = "<group>"; };
|
||||
607EEA4C2087A8DA009DA5F0 /* CurrencyBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CurrencyBarItem.swift; sourceTree = "<group>"; };
|
||||
60C44AFC20A373A100C0EC91 /* MusicBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MusicBarItem.swift; sourceTree = "<group>"; };
|
||||
60F7D453208CC31400ABF5D2 /* InputSourceBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InputSourceBarItem.swift; sourceTree = "<group>"; };
|
||||
B0008E542080286C003AD4DD /* SupportHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SupportHelpers.swift; sourceTree = "<group>"; };
|
||||
B04B7BB62087398C00C835D0 /* BatteryBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BatteryBarItem.swift; sourceTree = "<group>"; };
|
||||
B05600D22083E9BB00EB218D /* CustomSlider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomSlider.swift; sourceTree = "<group>"; };
|
||||
B059D621205E03F5006E6B86 /* TouchBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TouchBarController.swift; sourceTree = "<group>"; };
|
||||
B059D623205E04F3006E6B86 /* CustomButtonTouchBarItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomButtonTouchBarItem.swift; sourceTree = "<group>"; };
|
||||
B059D629205E13E5006E6B86 /* TouchBarPrivateApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TouchBarPrivateApi.h; sourceTree = "<group>"; };
|
||||
@@ -79,6 +108,7 @@
|
||||
B0B1742E207D6B590004B740 /* Vox.next.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Vox.next.scpt; sourceTree = "<group>"; };
|
||||
B0B1742F207D6B590004B740 /* Vox.nowPlaying.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = Vox.nowPlaying.scpt; sourceTree = "<group>"; };
|
||||
B0B17430207D6B590004B740 /* iTunes.nowPlaying.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = iTunes.nowPlaying.scpt; sourceTree = "<group>"; };
|
||||
B0F3112420C9E35F0076BB88 /* SupportNSTouchBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SupportNSTouchBar.swift; sourceTree = "<group>"; };
|
||||
B0F87719207AC1EA00D6E430 /* TouchBarSupport.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = TouchBarSupport.m; sourceTree = "<group>"; };
|
||||
B0F8771B207AC92700D6E430 /* TouchBarSupport.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TouchBarSupport.h; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
@@ -136,21 +166,26 @@
|
||||
B082B251205C7D8000BC04DC /* MTMR */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
B0B88A07208CD12000A2C160 /* Widgets */,
|
||||
B0B1743B207D6ED40004B740 /* CBridge */,
|
||||
B0B17426207D6AFE0004B740 /* AppleScripts */,
|
||||
B082B252205C7D8000BC04DC /* AppDelegate.swift */,
|
||||
B082B256205C7D8000BC04DC /* Assets.xcassets */,
|
||||
B0A7E9A9205D6AA400EEF070 /* KeyPress.swift */,
|
||||
B059D623205E04F3006E6B86 /* CustomButtonTouchBarItem.swift */,
|
||||
36C2ECD8207B74B4003CDA33 /* AppleScriptTouchBarItem.swift */,
|
||||
36C2ECD6207B6DAE003CDA33 /* TimeTouchBarItem.swift */,
|
||||
B059D621205E03F5006E6B86 /* TouchBarController.swift */,
|
||||
36C2ECDA207C3FE7003CDA33 /* ItemsParsing.swift */,
|
||||
B082B258205C7D8000BC04DC /* Main.storyboard */,
|
||||
B082B25B205C7D8000BC04DC /* Info.plist */,
|
||||
B082B25C205C7D8000BC04DC /* MTMR.entitlements */,
|
||||
B09EB1E3207C082000D5C1E0 /* HapticFeedback.swift */,
|
||||
36C2ECDF207CB1B0003CDA33 /* defaultPreset.json */,
|
||||
B082B252205C7D8000BC04DC /* AppDelegate.swift */,
|
||||
B0A7E9A9205D6AA400EEF070 /* KeyPress.swift */,
|
||||
B059D623205E04F3006E6B86 /* CustomButtonTouchBarItem.swift */,
|
||||
36C2ECD8207B74B4003CDA33 /* AppleScriptTouchBarItem.swift */,
|
||||
B059D621205E03F5006E6B86 /* TouchBarController.swift */,
|
||||
36C2ECDA207C3FE7003CDA33 /* ItemsParsing.swift */,
|
||||
B0008E542080286C003AD4DD /* SupportHelpers.swift */,
|
||||
B09EB1E3207C082000D5C1E0 /* HapticFeedback.swift */,
|
||||
368EDDE620812A1D00E10953 /* ScrollViewItem.swift */,
|
||||
B05600D22083E9BB00EB218D /* CustomSlider.swift */,
|
||||
36A778BD20A6C27100B38714 /* GeneralExtensions.swift */,
|
||||
B0F3112420C9E35F0076BB88 /* SupportNSTouchBar.swift */,
|
||||
);
|
||||
path = MTMR;
|
||||
sourceTree = "<group>";
|
||||
@@ -158,8 +193,11 @@
|
||||
B082B264205C7D8000BC04DC /* MTMRTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
36300E85209FD16700B31C71 /* .travis.yml */,
|
||||
36C2ECDC207C723B003CDA33 /* ParseConfigTests.swift */,
|
||||
B082B267205C7D8000BC04DC /* Info.plist */,
|
||||
36300E8E20A2CF3400B31C71 /* AppleScriptDefinitionTests.swift */,
|
||||
36300E9020A2D2B200B31C71 /* BackgroundColorTests.swift */,
|
||||
);
|
||||
path = MTMRTests;
|
||||
sourceTree = "<group>";
|
||||
@@ -188,10 +226,31 @@
|
||||
B059D62A205F0E7D006E6B86 /* TouchBarPrivateApi-Bridging.h */,
|
||||
B0F87719207AC1EA00D6E430 /* TouchBarSupport.m */,
|
||||
B0F8771B207AC92700D6E430 /* TouchBarSupport.h */,
|
||||
6042B6A82083E1F500C525C8 /* DeprecatedCarbonAPI.h */,
|
||||
6042B6A92083E27000C525C8 /* DeprecatedCarbonAPI.c */,
|
||||
60173D3C20C0031B002C305F /* LaunchAtLoginController.h */,
|
||||
60173D3D20C0031B002C305F /* LaunchAtLoginController.m */,
|
||||
);
|
||||
path = CBridge;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
B0B88A07208CD12000A2C160 /* Widgets */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
36C2ECD6207B6DAE003CDA33 /* TimeTouchBarItem.swift */,
|
||||
6027D1B72080E52A004FFDC7 /* BrightnessViewController.swift */,
|
||||
6027D1B82080E52A004FFDC7 /* VolumeViewController.swift */,
|
||||
B04B7BB62087398C00C835D0 /* BatteryBarItem.swift */,
|
||||
607EEA4A2087835F009DA5F0 /* WeatherBarItem.swift */,
|
||||
607EEA4C2087A8DA009DA5F0 /* CurrencyBarItem.swift */,
|
||||
6042B6A62083E03A00C525C8 /* AppScrubberTouchBarItem.swift */,
|
||||
60F7D453208CC31400ABF5D2 /* InputSourceBarItem.swift */,
|
||||
60C44AFC20A373A100C0EC91 /* MusicBarItem.swift */,
|
||||
60669B4220AD8FA80074E817 /* GroupBarItem.swift */,
|
||||
);
|
||||
path = Widgets;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -223,7 +282,6 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
B082B263205C7D8000BC04DC /* PBXTargetDependency */,
|
||||
);
|
||||
name = MTMRTests;
|
||||
productName = MTMRTests;
|
||||
@@ -309,14 +367,30 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
B059D622205E03F5006E6B86 /* TouchBarController.swift in Sources */,
|
||||
B05600D32083E9BB00EB218D /* CustomSlider.swift in Sources */,
|
||||
36C2ECD9207B74B4003CDA33 /* AppleScriptTouchBarItem.swift in Sources */,
|
||||
B0F8771A207AC1EA00D6E430 /* TouchBarSupport.m in Sources */,
|
||||
B0008E552080286C003AD4DD /* SupportHelpers.swift in Sources */,
|
||||
6042B6A72083E03A00C525C8 /* AppScrubberTouchBarItem.swift in Sources */,
|
||||
B082B253205C7D8000BC04DC /* AppDelegate.swift in Sources */,
|
||||
60C44AFD20A373A100C0EC91 /* MusicBarItem.swift in Sources */,
|
||||
B059D624205E04F3006E6B86 /* CustomButtonTouchBarItem.swift in Sources */,
|
||||
60173D3E20C0031B002C305F /* LaunchAtLoginController.m in Sources */,
|
||||
6027D1BA2080E52A004FFDC7 /* VolumeViewController.swift in Sources */,
|
||||
607EEA4B2087835F009DA5F0 /* WeatherBarItem.swift in Sources */,
|
||||
B0F3112520C9E35F0076BB88 /* SupportNSTouchBar.swift in Sources */,
|
||||
6042B6AA2083E27000C525C8 /* DeprecatedCarbonAPI.c in Sources */,
|
||||
B09EB1E4207C082000D5C1E0 /* HapticFeedback.swift in Sources */,
|
||||
60F7D454208CC31400ABF5D2 /* InputSourceBarItem.swift in Sources */,
|
||||
36A778BE20A6C27100B38714 /* GeneralExtensions.swift in Sources */,
|
||||
60669B4320AD8FA80074E817 /* GroupBarItem.swift in Sources */,
|
||||
36C2ECDB207C3FE7003CDA33 /* ItemsParsing.swift in Sources */,
|
||||
B0A7E9AA205D6AA400EEF070 /* KeyPress.swift in Sources */,
|
||||
36C2ECD7207B6DAE003CDA33 /* TimeTouchBarItem.swift in Sources */,
|
||||
607EEA4D2087A8DA009DA5F0 /* CurrencyBarItem.swift in Sources */,
|
||||
6027D1B92080E52A004FFDC7 /* BrightnessViewController.swift in Sources */,
|
||||
368EDDE720812A1D00E10953 /* ScrollViewItem.swift in Sources */,
|
||||
B04B7BB72087398C00C835D0 /* BatteryBarItem.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -324,21 +398,16 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
36300E9120A2D2B200B31C71 /* BackgroundColorTests.swift in Sources */,
|
||||
36300E8F20A2CF3400B31C71 /* AppleScriptDefinitionTests.swift in Sources */,
|
||||
36C2ECDD207C723B003CDA33 /* ParseConfigTests.swift in Sources */,
|
||||
36300E83209F040900B31C71 /* SupportHelpers.swift in Sources */,
|
||||
36C2ECDE207C82DE003CDA33 /* ItemsParsing.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
B082B263205C7D8000BC04DC /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = B082B24E205C7D8000BC04DC /* MTMR */;
|
||||
targetProxy = B082B262205C7D8000BC04DC /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
B082B258205C7D8000BC04DC /* Main.storyboard */ = {
|
||||
isa = PBXVariantGroup;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?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>BuildSystemType</key>
|
||||
<string>Latest</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,103 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0920"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "B082B24E205C7D8000BC04DC"
|
||||
BuildableName = "MTMR.app"
|
||||
BlueprintName = "MTMR"
|
||||
ReferencedContainer = "container:MTMR.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "B082B260205C7D8000BC04DC"
|
||||
BuildableName = "MTMRTests.xctest"
|
||||
BlueprintName = "MTMRTests"
|
||||
ReferencedContainer = "container:MTMR.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "B082B24E205C7D8000BC04DC"
|
||||
BuildableName = "MTMR.app"
|
||||
BlueprintName = "MTMR"
|
||||
ReferencedContainer = "container:MTMR.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "B082B24E205C7D8000BC04DC"
|
||||
BuildableName = "MTMR.app"
|
||||
BlueprintName = "MTMR"
|
||||
ReferencedContainer = "container:MTMR.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "B082B24E205C7D8000BC04DC"
|
||||
BuildableName = "MTMR.app"
|
||||
BlueprintName = "MTMR"
|
||||
ReferencedContainer = "container:MTMR.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0920"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "B082B260205C7D8000BC04DC"
|
||||
BuildableName = "MTMRTests.xctest"
|
||||
BlueprintName = "MTMRTests"
|
||||
ReferencedContainer = "container:MTMR.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
+94
-6
@@ -11,33 +11,121 @@ import Cocoa
|
||||
@NSApplicationMain
|
||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)
|
||||
private var fileSystemSource: DispatchSourceFileSystemObject?
|
||||
|
||||
func applicationDidFinishLaunching(_ aNotification: Notification) {
|
||||
// Insert code here to initialize your application
|
||||
let _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeRetainedValue() as NSString: true] as NSDictionary)
|
||||
|
||||
TouchBarController.shared.setupControlStripPresence()
|
||||
|
||||
if let button = statusItem.button {
|
||||
button.image = #imageLiteral(resourceName: "StatusImage")
|
||||
}
|
||||
createMenu()
|
||||
|
||||
reloadOnDefaultConfigChanged()
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ aNotification: Notification) {
|
||||
// Insert code here to tear down your application
|
||||
|
||||
}
|
||||
|
||||
@objc func testFn(_ sender: Any?) {
|
||||
let quoteText = "You click on menu"
|
||||
print(quoteText)
|
||||
@objc func openPreferences(_ sender: Any?) {
|
||||
let task = Process()
|
||||
let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR")
|
||||
let presetPath = appSupportDirectory.appending("/items.json")
|
||||
task.launchPath = "/usr/bin/open"
|
||||
task.arguments = [presetPath]
|
||||
task.launch()
|
||||
}
|
||||
|
||||
@objc func toggleControlStrip(_ sender: Any?) {
|
||||
TouchBarController.shared.controlStripState = !TouchBarController.shared.controlStripState
|
||||
createMenu()
|
||||
TouchBarController.shared.resetControlStrip()
|
||||
}
|
||||
|
||||
@objc func toggleBlackListedApp(_ sender: Any?) {
|
||||
let appIdentifier = TouchBarController.shared.frontmostApplicationIdentifier
|
||||
if appIdentifier != nil {
|
||||
if let index = TouchBarController.shared.blacklistAppIdentifiers.index(of: appIdentifier!) {
|
||||
TouchBarController.shared.blacklistAppIdentifiers.remove(at: index)
|
||||
} else {
|
||||
TouchBarController.shared.blacklistAppIdentifiers.append(appIdentifier!)
|
||||
}
|
||||
|
||||
UserDefaults.standard.set(TouchBarController.shared.blacklistAppIdentifiers, forKey: "com.toxblh.mtmr.blackListedApps")
|
||||
UserDefaults.standard.synchronize()
|
||||
|
||||
TouchBarController.shared.updateActiveApp()
|
||||
}
|
||||
}
|
||||
|
||||
@objc func openPreset(_ sender: Any?) {
|
||||
let dialog = NSOpenPanel();
|
||||
|
||||
dialog.title = "Choose a items.json file"
|
||||
dialog.showsResizeIndicator = true
|
||||
dialog.showsHiddenFiles = true
|
||||
dialog.canChooseDirectories = false
|
||||
dialog.canCreateDirectories = false
|
||||
dialog.allowsMultipleSelection = false
|
||||
dialog.allowedFileTypes = ["json"]
|
||||
dialog.directoryURL = NSURL.fileURL(withPath: NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR"), isDirectory: true)
|
||||
|
||||
if dialog.runModal() == .OK, let path = dialog.url?.path {
|
||||
TouchBarController.shared.reloadPreset(path: path)
|
||||
}
|
||||
}
|
||||
|
||||
@objc func toggleStartAtLogin(_ sender: Any?) {
|
||||
LaunchAtLoginController().setLaunchAtLogin(!LaunchAtLoginController().launchAtLogin, for: NSURL.fileURL(withPath: Bundle.main.bundlePath))
|
||||
createMenu()
|
||||
}
|
||||
|
||||
func createMenu() {
|
||||
let menu = NSMenu()
|
||||
menu.addItem(withTitle: "Preferences", action: #selector(testFn(_:)), keyEquivalent: ",")
|
||||
|
||||
let startAtLogin = NSMenuItem(title: "Start at login", action: #selector(toggleStartAtLogin(_:)), keyEquivalent: "L")
|
||||
startAtLogin.state = LaunchAtLoginController().launchAtLogin ? .on : .off
|
||||
|
||||
let hideControlStrip = NSMenuItem(title: "Hide Control Strip", action: #selector(toggleControlStrip(_:)), keyEquivalent: "T")
|
||||
hideControlStrip.state = TouchBarController.shared.controlStripState ? .on : .off
|
||||
|
||||
let settingSeparator = NSMenuItem(title: "Settings", action: nil, keyEquivalent: "")
|
||||
settingSeparator.isEnabled = false
|
||||
|
||||
menu.addItem(withTitle: "Preferences", action: #selector(openPreferences(_:)), keyEquivalent: ",")
|
||||
menu.addItem(withTitle: "Open preset", action: #selector(openPreset(_:)), keyEquivalent: "O")
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(settingSeparator)
|
||||
menu.addItem(hideControlStrip)
|
||||
menu.addItem(withTitle: "Toggle current app in blacklist" , action: #selector(toggleBlackListedApp(_:)), keyEquivalent: "B")
|
||||
menu.addItem(startAtLogin)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
|
||||
statusItem.menu = menu
|
||||
}
|
||||
|
||||
func reloadOnDefaultConfigChanged() {
|
||||
let file = NSURL.fileURL(withPath: standardConfigPath)
|
||||
|
||||
let fd = open(file.path, O_EVTONLY)
|
||||
|
||||
self.fileSystemSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: .write, queue: DispatchQueue(label: "DefaultConfigChanged"))
|
||||
|
||||
self.fileSystemSource?.setEventHandler(handler: {
|
||||
print("Config changed, reloading...")
|
||||
DispatchQueue.main.async {
|
||||
TouchBarController.shared.reloadPreset(path: file.path)
|
||||
}
|
||||
})
|
||||
|
||||
self.fileSystemSource?.setCancelHandler(handler: {
|
||||
close(fd)
|
||||
})
|
||||
|
||||
self.fileSystemSource?.resume()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,22 +5,24 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
||||
private let interval: TimeInterval
|
||||
private var forceHideConstraint: NSLayoutConstraint!
|
||||
|
||||
init?(identifier: NSTouchBarItem.Identifier, source: Source, interval: TimeInterval, onTap: @escaping ()->()) {
|
||||
init?(identifier: NSTouchBarItem.Identifier, source: SourceProtocol, interval: TimeInterval) {
|
||||
self.interval = interval
|
||||
super.init(identifier: identifier, title: "compile", onTap: onTap)
|
||||
super.init(identifier: identifier, title: "⏳")
|
||||
self.forceHideConstraint = self.view.widthAnchor.constraint(equalToConstant: 0)
|
||||
guard let script = source.appleScript else {
|
||||
button.title = "no script"
|
||||
self.title = "no script"
|
||||
return
|
||||
}
|
||||
self.script = script
|
||||
button.bezelColor = .clear
|
||||
DispatchQueue.main.async {
|
||||
self.isBordered = false
|
||||
DispatchQueue.appleScriptQueue.async {
|
||||
var error: NSDictionary?
|
||||
guard script.compileAndReturnError(&error) else {
|
||||
print(error?.description ?? "unknown error")
|
||||
#if DEBUG
|
||||
print(error?.description ?? "unknown error")
|
||||
#endif
|
||||
DispatchQueue.main.async {
|
||||
self.button.title = "compile error"
|
||||
self.title = "error"
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -33,13 +35,18 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
||||
}
|
||||
|
||||
func refreshAndSchedule() {
|
||||
print("refresh happened")
|
||||
#if DEBUG
|
||||
print("refresh happened (interval \(self.interval)), self \(self.identifier.rawValue))")
|
||||
#endif
|
||||
let scriptResult = self.execute()
|
||||
DispatchQueue.main.async {
|
||||
self.button.title = scriptResult
|
||||
self.title = scriptResult
|
||||
self.forceHideConstraint.isActive = scriptResult == ""
|
||||
#if DEBUG
|
||||
print("did set new script result title \(scriptResult)")
|
||||
#endif
|
||||
}
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + self.interval) { [weak self] in
|
||||
DispatchQueue.appleScriptQueue.asyncAfter(deadline: .now() + self.interval) { [weak self] in
|
||||
self?.refreshAndSchedule()
|
||||
}
|
||||
}
|
||||
@@ -56,9 +63,6 @@ class AppleScriptTouchBarItem: CustomButtonTouchBarItem {
|
||||
|
||||
}
|
||||
|
||||
extension Source {
|
||||
var appleScript: NSAppleScript? {
|
||||
guard let source = self.string else { return nil }
|
||||
return NSAppleScript(source: source)
|
||||
}
|
||||
extension DispatchQueue {
|
||||
static let appleScriptQueue = DispatchQueue(label: "mtmr.applescript")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"filename" : "brightnessDown.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
},
|
||||
"properties" : {
|
||||
"template-rendering-intent" : "template"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"filename" : "brightnessUp.png",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"scale" : "3x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"version" : 1,
|
||||
"author" : "xcode"
|
||||
},
|
||||
"properties" : {
|
||||
"template-rendering-intent" : "template"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.2 KiB |
@@ -0,0 +1,45 @@
|
||||
//
|
||||
// DeprecatedCarbonAPI.c
|
||||
//
|
||||
// This file is part of TouchDock
|
||||
// Copyright (C) 2017 Xander Deng
|
||||
//
|
||||
// This program 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 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
#include "DeprecatedCarbonAPI.h"
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
|
||||
|
||||
CFStringRef kPidKey = CFSTR("pid");
|
||||
|
||||
pid_t pidFromASN(void const *asn) {
|
||||
pid_t pid = -1;
|
||||
ProcessSerialNumber psn = {kNoProcess, kNoProcess};
|
||||
if (CFGetTypeID(asn) == _LSASNGetTypeID()) {
|
||||
_LSASNExtractHighAndLowParts(asn, &psn.highLongOfPSN, &psn.lowLongOfPSN);
|
||||
CFDictionaryRef processInfo = ProcessInformationCopyDictionary(&psn, kProcessDictionaryIncludeAllInformationMask);
|
||||
if (processInfo) {
|
||||
CFNumberRef pidNumber = CFDictionaryGetValue(processInfo, kPidKey);
|
||||
if (pidNumber) {
|
||||
CFNumberGetValue(pidNumber, kCFNumberSInt32Type, &pid);
|
||||
}
|
||||
CFRelease(processInfo);
|
||||
}
|
||||
}
|
||||
return pid;
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -0,0 +1,27 @@
|
||||
//
|
||||
// DeprecatedCarbonAPI.h
|
||||
//
|
||||
// This file is part of TouchDock
|
||||
// Copyright (C) 2017 Xander Deng
|
||||
//
|
||||
// This program 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 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
//
|
||||
|
||||
#import <Carbon/Carbon.h>
|
||||
|
||||
extern CFArrayRef _LSCopyApplicationArrayInFrontToBackOrder(uint32_t sessionID);
|
||||
extern void _LSASNExtractHighAndLowParts(void const* asn, UInt32* psnHigh, UInt32* psnLow);
|
||||
extern CFTypeID _LSASNGetTypeID(void);
|
||||
|
||||
pid_t pidFromASN(void const *asn);
|
||||
@@ -0,0 +1,35 @@
|
||||
//
|
||||
// LaunchAtLoginController.h
|
||||
//
|
||||
// Copyright 2011 Tomáš Znamenáček
|
||||
// Copyright 2010 Ben Clark-Robinson
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining
|
||||
// a copy of this software and associated documentation files (the ‘Software’),
|
||||
// to deal in the Software without restriction, including without limitation
|
||||
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
// and/or sell copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
@import Foundation;
|
||||
@import CoreServices;
|
||||
|
||||
@interface LaunchAtLoginController : NSObject {}
|
||||
|
||||
@property(assign) BOOL launchAtLogin;
|
||||
|
||||
- (BOOL) willLaunchAtLogin: (NSURL*) itemURL;
|
||||
- (void) setLaunchAtLogin: (BOOL) enabled forURL: (NSURL*) itemURL;
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,128 @@
|
||||
//
|
||||
// LaunchAtLoginController.m
|
||||
//
|
||||
// Copyright 2011 Tomáš Znamenáček
|
||||
// Copyright 2010 Ben Clark-Robinson
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining
|
||||
// a copy of this software and associated documentation files (the ‘Software’),
|
||||
// to deal in the Software without restriction, including without limitation
|
||||
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
// and/or sell copies of the Software, and to permit persons to whom the
|
||||
// Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be
|
||||
// included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND,
|
||||
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
||||
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
#import "LaunchAtLoginController.h"
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
|
||||
static NSString *const StartAtLoginKey = @"launchAtLogin";
|
||||
|
||||
@interface LaunchAtLoginController ()
|
||||
@property(assign) LSSharedFileListRef loginItems;
|
||||
@end
|
||||
|
||||
@implementation LaunchAtLoginController
|
||||
@synthesize loginItems;
|
||||
|
||||
#pragma mark Change Observing
|
||||
|
||||
void sharedFileListDidChange(LSSharedFileListRef inList, void *context)
|
||||
{
|
||||
LaunchAtLoginController *self = (__bridge id) context;
|
||||
[self willChangeValueForKey:StartAtLoginKey];
|
||||
[self didChangeValueForKey:StartAtLoginKey];
|
||||
}
|
||||
|
||||
#pragma mark Initialization
|
||||
|
||||
- (id) init
|
||||
{
|
||||
self = [super init];
|
||||
loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
|
||||
LSSharedFileListAddObserver(loginItems, CFRunLoopGetMain(),
|
||||
(CFStringRef)NSDefaultRunLoopMode, sharedFileListDidChange, (voidPtr)CFBridgingRetain(self));
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void) dealloc
|
||||
{
|
||||
LSSharedFileListRemoveObserver(loginItems, CFRunLoopGetMain(),
|
||||
(CFStringRef)NSDefaultRunLoopMode, sharedFileListDidChange, (__bridge void *)(self));
|
||||
CFRelease(loginItems);
|
||||
}
|
||||
|
||||
#pragma mark Launch List Control
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
LSSharedFileListItemRef copyItemWithURLinFileList(NSURL* wantedURL, LSSharedFileListRef fileList) {
|
||||
if (wantedURL == NULL || fileList == NULL)
|
||||
return NULL;
|
||||
|
||||
NSArray *listSnapshot = (__bridge_transfer NSArray *)LSSharedFileListCopySnapshot(fileList, NULL);
|
||||
for(NSUInteger i = 0; i< [listSnapshot count]; i++) {
|
||||
LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)[listSnapshot objectAtIndex:i];
|
||||
UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes;
|
||||
CFURLRef currentItemURL = NULL;
|
||||
LSSharedFileListItemResolve(item, resolutionFlags, ¤tItemURL, NULL);
|
||||
if (currentItemURL && [(__bridge_transfer NSURL*)currentItemURL isEqual:wantedURL]) {
|
||||
CFRetain(item);
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
return NULL;
|
||||
}
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
- (BOOL) willLaunchAtLogin: (NSURL*) itemURL
|
||||
{
|
||||
return !!copyItemWithURLinFileList(itemURL, loginItems);
|
||||
}
|
||||
|
||||
- (void) setLaunchAtLogin: (BOOL) enabled forURL: (NSURL*) itemURL
|
||||
{
|
||||
LSSharedFileListItemRef appItem = copyItemWithURLinFileList(itemURL, loginItems);
|
||||
if (enabled && !appItem) {
|
||||
LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst,
|
||||
NULL, NULL, (__bridge CFURLRef)itemURL, NULL, NULL);
|
||||
} else if (!enabled && appItem) {
|
||||
LSSharedFileListItemRemove(loginItems, appItem);
|
||||
}
|
||||
if (appItem) {
|
||||
CFRelease(appItem);
|
||||
}
|
||||
}
|
||||
|
||||
#pragma mark Basic Interface
|
||||
|
||||
- (NSURL*) appURL
|
||||
{
|
||||
return [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];
|
||||
}
|
||||
|
||||
- (void) setLaunchAtLogin: (BOOL) enabled
|
||||
{
|
||||
[self willChangeValueForKey:StartAtLoginKey];
|
||||
[self setLaunchAtLogin:enabled forURL:[self appURL]];
|
||||
[self didChangeValueForKey:StartAtLoginKey];
|
||||
}
|
||||
|
||||
- (BOOL) launchAtLogin
|
||||
{
|
||||
return [self willLaunchAtLogin:[self appURL]];
|
||||
}
|
||||
|
||||
@end
|
||||
#pragma clang diagnostic pop
|
||||
@@ -8,6 +8,8 @@
|
||||
|
||||
#import "TouchBarPrivateApi.h"
|
||||
#import "TouchBarSupport.h"
|
||||
#import "DeprecatedCarbonAPI.h"
|
||||
#include "LaunchAtLoginController.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
|
||||
@@ -17,13 +17,16 @@ extern void DFRSystemModalShowsCloseBoxWhenFrontMost(BOOL);
|
||||
|
||||
@interface NSTouchBar (PrivateMethods)
|
||||
|
||||
// presentSystemModalFunctionBar:placement:systemTrayItemIdentifier:
|
||||
// macOS 10.14
|
||||
+ (void)presentSystemModalTouchBar:(NSTouchBar *)touchBar placement:(long long)placement systemTrayItemIdentifier:(NSTouchBarItemIdentifier)identifier;
|
||||
+ (void)presentSystemModalTouchBar:(NSTouchBar *)touchBar systemTrayItemIdentifier:(NSTouchBarItemIdentifier)identifier;
|
||||
+ (void)dismissSystemModalTouchBar:(NSTouchBar *)touchBar;
|
||||
+ (void)minimizeSystemModalTouchBar:(NSTouchBar *)touchBar;
|
||||
|
||||
// macOS 10.13
|
||||
+ (void)presentSystemModalFunctionBar:(NSTouchBar *)touchBar placement:(long long)placement systemTrayItemIdentifier:(NSTouchBarItemIdentifier)identifier;
|
||||
|
||||
+ (void)presentSystemModalFunctionBar:(NSTouchBar *)touchBar systemTrayItemIdentifier:(NSTouchBarItemIdentifier)identifier;
|
||||
|
||||
+ (void)dismissSystemModalFunctionBar:(NSTouchBar *)touchBar;
|
||||
|
||||
+ (void)minimizeSystemModalFunctionBar:(NSTouchBar *)touchBar;
|
||||
|
||||
@end
|
||||
|
||||
@@ -10,8 +10,6 @@
|
||||
|
||||
@interface MediaKeys : NSObject
|
||||
|
||||
+ (void)decreaseVolume;
|
||||
+ (void)increaseVolume;
|
||||
+ (void)muteVolume;
|
||||
+ (void)HIDPostAuxKey:(UInt8)keyCode;
|
||||
|
||||
@end
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//
|
||||
|
||||
#import "TouchBarSupport.h"
|
||||
#import <IOKit/hidsystem/ev_keymap.h>
|
||||
|
||||
@implementation MediaKeys
|
||||
|
||||
@@ -30,7 +31,7 @@ static io_connect_t get_event_driver(void)
|
||||
}
|
||||
|
||||
|
||||
static void HIDPostAuxKey( const UInt8 auxKeyCode )
|
||||
static void HIDReleaseAuxKey( const UInt8 auxKeyCode )
|
||||
{
|
||||
NXEventData event;
|
||||
kern_return_t kr;
|
||||
@@ -51,16 +52,8 @@ static void HIDPostAuxKey( const UInt8 auxKeyCode )
|
||||
kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
|
||||
}
|
||||
|
||||
+ (void)decreaseVolume {
|
||||
HIDPostAuxKey(NX_KEYTYPE_SOUND_DOWN);
|
||||
}
|
||||
|
||||
+ (void)increaseVolume {
|
||||
HIDPostAuxKey(NX_KEYTYPE_SOUND_UP);
|
||||
}
|
||||
|
||||
+ (void)muteVolume {
|
||||
HIDPostAuxKey(NX_KEYTYPE_MUTE);
|
||||
+ (void)HIDPostAuxKey: (UInt8)keyCode {
|
||||
HIDReleaseAuxKey(keyCode);
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@@ -8,30 +8,179 @@
|
||||
|
||||
import Cocoa
|
||||
|
||||
class CustomButtonTouchBarItem: NSCustomTouchBarItem {
|
||||
let tapClosure: () -> ()
|
||||
private(set) var button: NSButton!
|
||||
class CustomButtonTouchBarItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
||||
var tapClosure: (() -> ())?
|
||||
var longTapClosure: (() -> ())?
|
||||
private var button: NSButton!
|
||||
|
||||
private var singleClick: NSClickGestureRecognizer!
|
||||
private var longClick: NSPressGestureRecognizer!
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, title: String, onTap callback: @escaping () -> (), image: NSImage? = nil) {
|
||||
self.tapClosure = callback
|
||||
init(identifier: NSTouchBarItem.Identifier, title: String) {
|
||||
self.attributedTitle = title.defaultTouchbarAttributedString
|
||||
|
||||
super.init(identifier: identifier)
|
||||
if let image = image {
|
||||
button = NSButton(title: title, image: image, target: self, action: #selector(didTapped))
|
||||
button.bezelColor = .clear
|
||||
} else {
|
||||
button = NSButton(title: title, target: self, action: #selector(didTapped))
|
||||
}
|
||||
self.view = button
|
||||
button = CustomHeightButton(title: title, target: nil, action: nil)
|
||||
|
||||
longClick = NSPressGestureRecognizer(target: self, action: #selector(handleGestureLong))
|
||||
longClick.allowedTouchTypes = .direct
|
||||
longClick.delegate = self
|
||||
|
||||
singleClick = NSClickGestureRecognizer(target: self, action: #selector(handleGestureSingle))
|
||||
singleClick.allowedTouchTypes = .direct
|
||||
singleClick.delegate = self
|
||||
|
||||
reinstallButton()
|
||||
button.attributedTitle = attributedTitle
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
var isBordered: Bool = true {
|
||||
didSet {
|
||||
reinstallButton()
|
||||
}
|
||||
}
|
||||
|
||||
var backgroundColor: NSColor? {
|
||||
didSet {
|
||||
reinstallButton()
|
||||
}
|
||||
}
|
||||
|
||||
var title: String {
|
||||
get {
|
||||
return self.attributedTitle.string
|
||||
}
|
||||
set {
|
||||
self.attributedTitle = newValue.defaultTouchbarAttributedString
|
||||
}
|
||||
}
|
||||
|
||||
var attributedTitle: NSAttributedString {
|
||||
didSet {
|
||||
self.button?.imagePosition = attributedTitle.length > 0 ? .imageLeading : .imageOnly
|
||||
self.button?.attributedTitle = attributedTitle
|
||||
}
|
||||
}
|
||||
|
||||
var image: NSImage? {
|
||||
didSet {
|
||||
button.image = image
|
||||
}
|
||||
}
|
||||
|
||||
private func reinstallButton() {
|
||||
let title = button.attributedTitle
|
||||
let image = button.image
|
||||
let cell = CustomButtonCell(parentItem: self)
|
||||
button.cell = cell
|
||||
if let color = backgroundColor {
|
||||
cell.isBordered = true
|
||||
button.bezelColor = color
|
||||
cell.backgroundColor = color
|
||||
} else {
|
||||
button.isBordered = isBordered
|
||||
button.bezelStyle = isBordered ? .rounded : .inline
|
||||
}
|
||||
button.imageScaling = .scaleProportionallyDown
|
||||
button.imageHugsTitle = true
|
||||
button.attributedTitle = title
|
||||
self.button?.imagePosition = title.length > 0 ? .imageLeading : .imageOnly
|
||||
button.image = image
|
||||
self.view = button
|
||||
|
||||
self.view.addGestureRecognizer(longClick)
|
||||
self.view.addGestureRecognizer(singleClick)
|
||||
}
|
||||
|
||||
@objc func didTapped() {
|
||||
self.tapClosure()
|
||||
func gestureRecognizer(_ gestureRecognizer: NSGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: NSGestureRecognizer) -> Bool {
|
||||
if gestureRecognizer == singleClick && otherGestureRecognizer == longClick {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@objc func handleGestureSingle(gr: NSClickGestureRecognizer) {
|
||||
let hf: HapticFeedback = HapticFeedback()
|
||||
hf.tap(strong: 6)
|
||||
switch gr.state {
|
||||
case .ended:
|
||||
hf.tap(strong: 2)
|
||||
self.tapClosure?()
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@objc func handleGestureLong(gr: NSPressGestureRecognizer) {
|
||||
let hf: HapticFeedback = HapticFeedback()
|
||||
switch gr.state {
|
||||
case .began:
|
||||
if let closure = self.longTapClosure {
|
||||
hf.tap(strong: 2)
|
||||
closure()
|
||||
} else if let closure = self.tapClosure {
|
||||
hf.tap(strong: 6)
|
||||
closure()
|
||||
print("long click")
|
||||
}
|
||||
break
|
||||
default:
|
||||
break
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class CustomHeightButton : NSButton {
|
||||
|
||||
override var intrinsicContentSize: NSSize {
|
||||
var size = super.intrinsicContentSize
|
||||
size.height = 30
|
||||
return size
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class CustomButtonCell: NSButtonCell {
|
||||
weak var parentItem: CustomButtonTouchBarItem?
|
||||
|
||||
init(parentItem: CustomButtonTouchBarItem) {
|
||||
super.init(textCell: "")
|
||||
self.parentItem = parentItem
|
||||
}
|
||||
|
||||
override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) {
|
||||
super.highlight(flag, withFrame: cellFrame, in: controlView)
|
||||
if !self.isBordered {
|
||||
if flag {
|
||||
self.setAttributedTitle(self.attributedTitle, withColor: .lightGray)
|
||||
} else if let parentItem = self.parentItem {
|
||||
self.attributedTitle = parentItem.attributedTitle
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
func setAttributedTitle(_ title: NSAttributedString, withColor color: NSColor) {
|
||||
let attrTitle = NSMutableAttributedString(attributedString: title)
|
||||
attrTitle.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attrTitle.length))
|
||||
self.attributedTitle = attrTitle
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension String {
|
||||
var defaultTouchbarAttributedString: NSAttributedString {
|
||||
let attrTitle = NSMutableAttributedString(string: self, attributes: [.foregroundColor: NSColor.white, .font: NSFont.systemFont(ofSize: 15, weight: .regular), .baselineOffset: 1])
|
||||
attrTitle.setAlignment(.center, range: NSRange(location: 0, length: self.count))
|
||||
return attrTitle
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//
|
||||
// CustomSlider.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Anton Palgunov on 15/04/2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
class CustomSliderCell: NSSliderCell {
|
||||
var knobImage:NSImage!
|
||||
private var _currentKnobRect:NSRect!
|
||||
private var _barRect:NSRect!
|
||||
|
||||
required init(coder aDecoder: NSCoder) {
|
||||
super.init(coder: aDecoder)
|
||||
}
|
||||
|
||||
override init() {
|
||||
super.init()
|
||||
}
|
||||
|
||||
init(knob:NSImage?) {
|
||||
knobImage = knob;
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func drawKnob(_ knobRect: NSRect) {
|
||||
if (knobImage == nil) {
|
||||
super.drawKnob(knobRect)
|
||||
return;
|
||||
}
|
||||
|
||||
_currentKnobRect = knobRect;
|
||||
drawBar(inside: _barRect, flipped: true)
|
||||
|
||||
let x = (knobRect.origin.x * (_barRect.size.width - (knobImage.size.width - knobRect.size.width)) / _barRect.size.width)+1;
|
||||
let y = knobRect.origin.y+3
|
||||
|
||||
knobImage.draw(
|
||||
at: NSPoint(x: x, y: y),
|
||||
from: NSZeroRect,
|
||||
operation: NSCompositingOperation.sourceOver,
|
||||
fraction: 1
|
||||
)
|
||||
}
|
||||
|
||||
override func drawBar(inside aRect: NSRect, flipped: Bool) {
|
||||
_barRect = aRect
|
||||
|
||||
let barRadius = CGFloat(2)
|
||||
|
||||
var bgRect = aRect
|
||||
bgRect.size.height = CGFloat(4)
|
||||
|
||||
let bg = NSBezierPath(roundedRect: bgRect, xRadius: barRadius, yRadius: barRadius)
|
||||
NSColor.lightGray.setFill()
|
||||
bg.fill()
|
||||
|
||||
var activeRect = bgRect
|
||||
|
||||
activeRect.size.width = CGFloat((Double(bgRect.size.width) / (self.maxValue - self.minValue)) * self.doubleValue)
|
||||
let active = NSBezierPath(roundedRect: activeRect, xRadius: barRadius, yRadius: barRadius)
|
||||
NSColor.darkGray.setFill()
|
||||
active.fill()
|
||||
}
|
||||
}
|
||||
|
||||
class CustomSlider:NSSlider {
|
||||
|
||||
var currentValue:CGFloat = 0
|
||||
|
||||
override func setNeedsDisplay(_ invalidRect: NSRect) {
|
||||
super.setNeedsDisplay(invalidRect)
|
||||
}
|
||||
|
||||
override func awakeFromNib() {
|
||||
super.awakeFromNib()
|
||||
if ((self.cell?.isKind(of: CustomSliderCell.self)) == false) {
|
||||
let cell:CustomSliderCell = CustomSliderCell()
|
||||
self.cell = cell
|
||||
}
|
||||
}
|
||||
|
||||
convenience init(knob:NSImage) {
|
||||
self.init()
|
||||
self.cell = CustomSliderCell(knob: knob)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
super.init(coder: coder)
|
||||
}
|
||||
|
||||
override init(frame frameRect: NSRect) {
|
||||
super.init(frame: frameRect)
|
||||
}
|
||||
|
||||
func knobImage() -> NSImage {
|
||||
let cell = self.cell as! CustomSliderCell
|
||||
return cell.knobImage
|
||||
}
|
||||
|
||||
func setKnobImage(image:NSImage) {
|
||||
let cell = self.cell as! CustomSliderCell
|
||||
cell.knobImage = image
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import Foundation
|
||||
|
||||
#if swift(>=4.1)
|
||||
// compactMap supported
|
||||
#else
|
||||
extension Sequence {
|
||||
func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
|
||||
return try flatMap(transform)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension String {
|
||||
|
||||
var ifNotEmpty: String? {
|
||||
return self.count > 0 ? self : nil
|
||||
}
|
||||
|
||||
}
|
||||
@@ -25,27 +25,26 @@ class HapticFeedback {
|
||||
// you can get a plist `otool -s __TEXT __tpad_act_plist /System/Library/PrivateFrameworks/MultitouchSupport.framework/Versions/Current/MultitouchSupport|tail -n +3|awk -F'\t' '{print $2}'|xxd -r -p`
|
||||
|
||||
func tap(strong:Int32) -> Void {
|
||||
let actuatorRef = MTActuatorCreateFromDeviceID(deviceID).takeRetainedValue()
|
||||
actuatorRef = MTActuatorCreateFromDeviceID(deviceID).takeRetainedValue()
|
||||
|
||||
// TODO: Need to fix warning
|
||||
guard actuatorRef != nil else {
|
||||
print("guard actuatorRef == nil")
|
||||
return
|
||||
}
|
||||
|
||||
error = MTActuatorOpen(actuatorRef)
|
||||
error = MTActuatorOpen(actuatorRef!)
|
||||
guard error == kIOReturnSuccess else {
|
||||
print("guard MTActuatorOpen")
|
||||
return
|
||||
}
|
||||
|
||||
error = MTActuatorActuate(actuatorRef, strong, 0, 0.0, 0.0)
|
||||
error = MTActuatorActuate(actuatorRef!, strong, 0, 0.0, 0.0)
|
||||
guard error == kIOReturnSuccess else {
|
||||
print("guard MTActuatorActuate")
|
||||
return
|
||||
}
|
||||
|
||||
error = MTActuatorClose(actuatorRef)
|
||||
error = MTActuatorClose(actuatorRef!)
|
||||
guard error == kIOReturnSuccess else {
|
||||
print("guard MTActuatorClose")
|
||||
return
|
||||
|
||||
+7
-1
@@ -17,7 +17,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.6</string>
|
||||
<string>0.16.2</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
@@ -26,6 +26,12 @@
|
||||
<true/>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2018 Anton Palgunov. All rights reserved.</string>
|
||||
<key>NSLocationAlwaysUsageDescription</key>
|
||||
<string>Weather widget need your location for correct work</string>
|
||||
<key>NSLocationUsageDescription</key>
|
||||
<string>Weather widget need your location for correct work</string>
|
||||
<key>NSLocationWhenInUseUsageDescription</key>
|
||||
<string>Weather widget need your location for correct work</string>
|
||||
<key>NSMainStoryboardFile</key>
|
||||
<string>Main</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
|
||||
+415
-120
@@ -1,280 +1,575 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
extension Data {
|
||||
|
||||
func barItemDefinitions() -> [BarItemDefinition]? {
|
||||
return try? JSONDecoder().decode([BarItemDefinition].self, from: self)
|
||||
return try? JSONDecoder().decode([BarItemDefinition].self, from: self.utf8string!.stripComments().data(using: .utf8)!)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct BarItemDefinition: Decodable {
|
||||
let type: ItemType
|
||||
let action: ActionType
|
||||
let additionalParameters: [GeneralParameter]
|
||||
|
||||
let longAction: LongActionType
|
||||
let additionalParameters: [GeneralParameters.CodingKeys: GeneralParameter]
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case type
|
||||
}
|
||||
|
||||
init(type: ItemType, action: ActionType, additionalParameters: [GeneralParameter]) {
|
||||
|
||||
init(type: ItemType, action: ActionType, longAction: LongActionType, additionalParameters: [GeneralParameters.CodingKeys:GeneralParameter]) {
|
||||
self.type = type
|
||||
self.action = action
|
||||
self.longAction = longAction
|
||||
self.additionalParameters = additionalParameters
|
||||
}
|
||||
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let type = try container.decode(String.self, forKey: .type)
|
||||
let parametersDecoder = SupportedTypesHolder.sharedInstance.lookup(by: type)
|
||||
let additionalParameters = try GeneralParameters(from: decoder).parameters
|
||||
var additionalParameters = try GeneralParameters(from: decoder).parameters
|
||||
|
||||
if let result = try? parametersDecoder(decoder),
|
||||
case let (itemType, action) = result {
|
||||
self.init(type: itemType, action: action, additionalParameters: additionalParameters)
|
||||
case let (itemType, action, longAction, parameters) = result {
|
||||
parameters.forEach { additionalParameters[$0] = $1 }
|
||||
self.init(type: itemType, action: action, longAction: longAction, additionalParameters: additionalParameters)
|
||||
} else {
|
||||
self.init(type: .staticButton(title: "unknown"), action: .none, additionalParameters: additionalParameters)
|
||||
self.init(type: .staticButton(title: "unknown"), action: .none, longAction: .none, additionalParameters: additionalParameters)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
class SupportedTypesHolder {
|
||||
typealias ParametersDecoder = (Decoder) throws ->(item: ItemType, action: ActionType)
|
||||
typealias ParametersDecoder = (Decoder) throws ->(item: ItemType, action: ActionType, longAction: LongActionType, parameters: [GeneralParameters.CodingKeys: GeneralParameter])
|
||||
private var supportedTypes: [String: ParametersDecoder] = [
|
||||
"escape": { _ in return (item: .staticButton(title: "esc"), action: .keyPress(keycode: 53)) },
|
||||
"brightnessUp": { _ in return (item: .staticButton(title: "🔆"), action: .keyPress(keycode: 113)) },
|
||||
"brightnessDown": { _ in return (item: .staticButton(title: "🔅"), action: .keyPress(keycode: 107)) },
|
||||
"volumeDown": { _ in return (item: .staticImageButton(title: "", image: NSImage(named: .touchBarVolumeDownTemplate)!), action: .hidKey(keycode: NX_KEYTYPE_SOUND_DOWN)) },
|
||||
"volumeUp": { _ in return (item: .staticImageButton(title: "", image: NSImage(named: .touchBarVolumeUpTemplate)!), action: .hidKey(keycode: NX_KEYTYPE_SOUND_UP)) },
|
||||
"previous": { _ in return (item: .staticImageButton(title: "", image: NSImage(named: .touchBarRewindTemplate)!), action: .hidKey(keycode: NX_KEYTYPE_PREVIOUS)) },
|
||||
"play": { _ in return (item: .staticImageButton(title: "", image: NSImage(named: .touchBarPlayPauseTemplate)!), action: .hidKey(keycode: NX_KEYTYPE_PLAY)) },
|
||||
"next": { _ in return (item: .staticImageButton(title: "", image: NSImage(named: .touchBarFastForwardTemplate)!), action: .hidKey(keycode: NX_KEYTYPE_NEXT)) },
|
||||
"escape": { _ in return (item: .staticButton(title: "esc"), action: .keyPress(keycode: 53), longAction: .none, parameters: [.align: .align(.left)]) },
|
||||
|
||||
"delete": { _ in return (item: .staticButton(title: "del"), action: .keyPress(keycode: 117), longAction: .none, parameters: [:])},
|
||||
|
||||
"brightnessUp": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "brightnessUp"))
|
||||
return (item: .staticButton(title: ""), action: .keyPress(keycode: 144), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"brightnessDown": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: #imageLiteral(resourceName: "brightnessDown"))
|
||||
return (item: .staticButton(title: ""), action: .keyPress(keycode: 145), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"volumeDown": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: NSImage(named: .touchBarVolumeDownTemplate)!)
|
||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_SOUND_DOWN), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"volumeUp": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: NSImage(named: .touchBarVolumeUpTemplate)!)
|
||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_SOUND_UP), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"mute": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: NSImage(named: .touchBarAudioOutputMuteTemplate)!)
|
||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_MUTE), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"previous": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: NSImage(named: .touchBarRewindTemplate)!)
|
||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_PREVIOUS), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"play": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: NSImage(named: .touchBarPlayPauseTemplate)!)
|
||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_PLAY), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"next": { _ in
|
||||
let imageParameter = GeneralParameter.image(source: NSImage(named: .touchBarFastForwardTemplate)!)
|
||||
return (item: .staticButton(title: ""), action: .hidKey(keycode: NX_KEYTYPE_NEXT), longAction: .none, parameters: [.image: imageParameter])
|
||||
},
|
||||
|
||||
"weather": { decoder in
|
||||
enum CodingKeys: String, CodingKey { case refreshInterval; case units; case api_key ; case icon_type }
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
||||
let units = try container.decodeIfPresent(String.self, forKey: .units)
|
||||
let api_key = try container.decodeIfPresent(String.self, forKey: .api_key)
|
||||
let icon_type = try container.decodeIfPresent(String.self, forKey: .icon_type)
|
||||
let action = try ActionType(from: decoder)
|
||||
let longAction = try LongActionType(from: decoder)
|
||||
return (item: .weather(interval: interval ?? 1800.00, units: units ?? "metric", api_key: api_key ?? "32c4256d09a4c52b38aecddba7a078f6", icon_type: icon_type ?? "text"), action: action, longAction: longAction, parameters: [:])
|
||||
},
|
||||
|
||||
"currency": { decoder in
|
||||
enum CodingKeys: String, CodingKey { case refreshInterval; case from; case to }
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
||||
let from = try container.decodeIfPresent(String.self, forKey: .from)
|
||||
let to = try container.decodeIfPresent(String.self, forKey: .to)
|
||||
let action = try ActionType(from: decoder)
|
||||
let longAction = try LongActionType(from: decoder)
|
||||
return (item: .currency(interval: interval ?? 600.00, from: from ?? "RUB", to: to ?? "USD"), action: action, longAction: longAction, parameters: [:])
|
||||
},
|
||||
|
||||
"dock": { decoder in
|
||||
return (item: .dock(), action: .none, longAction: .none, parameters: [:])
|
||||
},
|
||||
|
||||
"inputsource": { decoder in
|
||||
return (item: .inputsource(), action: .none, longAction: .none, parameters: [:])
|
||||
},
|
||||
|
||||
"volume": { decoder in
|
||||
enum CodingKeys: String, CodingKey { case image }
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
if var img = try container.decodeIfPresent(Source.self, forKey: .image) {
|
||||
return (item: .volume(), action: .none, longAction: .none, parameters: [.image: .image(source: img)])
|
||||
} else {
|
||||
return (item: .volume(), action: .none, longAction: .none, parameters: [:])
|
||||
}
|
||||
},
|
||||
|
||||
"brightness": { decoder in
|
||||
enum CodingKeys: String, CodingKey { case refreshInterval; case image }
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
||||
if var img = try container.decodeIfPresent(Source.self, forKey: .image) {
|
||||
return (item: .brightness(refreshInterval: interval ?? 0.5), action: .none, longAction: .none, parameters: [.image: .image(source: img)])
|
||||
} else {
|
||||
return (item: .brightness(refreshInterval: interval ?? 0.5), action: .none, longAction: .none, parameters: [:])
|
||||
}
|
||||
},
|
||||
|
||||
"sleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["sleepnow"]), longAction: .none, parameters: [:]) },
|
||||
|
||||
"displaySleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["displaysleepnow"]), longAction: .none, parameters: [:])},
|
||||
|
||||
"music": { decoder in
|
||||
enum CodingKeys: String, CodingKey { case refreshInterval }
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
||||
let scriptPath = Bundle.main.path(forResource: "Weather", ofType: "scpt")!
|
||||
let item = ItemType.appleScriptTitledButton(source: Source(filePath: scriptPath), refreshInterval: interval ?? 1800.0)
|
||||
return (item: item, action: .none)
|
||||
return (
|
||||
item: .music(interval: interval ?? 1800.00),
|
||||
action: .none,
|
||||
longAction: .none,
|
||||
parameters: [:]
|
||||
)
|
||||
},
|
||||
"battery": { decoder in
|
||||
enum CodingKeys: String, CodingKey { case refreshInterval }
|
||||
|
||||
"group": { decoder in
|
||||
enum CodingKeys: CodingKey { case items }
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval)
|
||||
let scriptPath = Bundle.main.path(forResource: "Battery", ofType: "scpt")!
|
||||
let item = ItemType.appleScriptTitledButton(source: Source(filePath: scriptPath), refreshInterval: interval ?? 1800.0)
|
||||
return (item: item, action: .none)
|
||||
let items = try container.decode([BarItemDefinition].self, forKey: .items)
|
||||
return (
|
||||
item: .groupBar(items: items),
|
||||
action: .none,
|
||||
longAction: .none,
|
||||
parameters: [:]
|
||||
)
|
||||
},
|
||||
"sleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["sleepnow"]) ) },
|
||||
"displaySleep": { _ in return (item: .staticButton(title: "☕️"), action: .shellScript(executable: "/usr/bin/pmset", parameters: ["displaysleepnow"]) ) },
|
||||
]
|
||||
|
||||
]
|
||||
|
||||
static let sharedInstance = SupportedTypesHolder()
|
||||
|
||||
|
||||
func lookup(by type: String) -> ParametersDecoder {
|
||||
return supportedTypes[type] ?? { decoder in
|
||||
return (item: try ItemType(from: decoder), action: try ActionType(from: decoder))
|
||||
return (item: try ItemType(from: decoder), action: try ActionType(from: decoder), longAction: try LongActionType(from: decoder), parameters: [:])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func register(typename: String, decoder: @escaping ParametersDecoder) {
|
||||
supportedTypes[typename] = decoder
|
||||
}
|
||||
|
||||
func register(typename: String, item: ItemType, action: ActionType) {
|
||||
|
||||
func register(typename: String, item: ItemType, action: ActionType, longAction: LongActionType) {
|
||||
register(typename: typename) { _ in
|
||||
return (item: item, action: action)
|
||||
return (item: item, action: action, longAction: longAction, parameters: [:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ItemType: Decodable {
|
||||
case staticButton(title: String)
|
||||
case staticImageButton(title: String, image: NSImage)
|
||||
case appleScriptTitledButton(source: Source, refreshInterval: Double)
|
||||
case appleScriptTitledButton(source: SourceProtocol, refreshInterval: Double)
|
||||
case timeButton(formatTemplate: String)
|
||||
case flexSpace()
|
||||
|
||||
case battery()
|
||||
case dock()
|
||||
case volume()
|
||||
case brightness(refreshInterval: Double)
|
||||
case weather(interval: Double, units: String, api_key: String, icon_type: String)
|
||||
case currency(interval: Double, from: String, to: String)
|
||||
case inputsource()
|
||||
case music(interval: Double)
|
||||
case groupBar(items: [BarItemDefinition])
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case type
|
||||
case title
|
||||
case source
|
||||
case refreshInterval
|
||||
case from
|
||||
case to
|
||||
case units
|
||||
case api_key
|
||||
case icon_type
|
||||
case formatTemplate
|
||||
case image
|
||||
case url
|
||||
case longUrl
|
||||
case items
|
||||
}
|
||||
|
||||
|
||||
enum ItemTypeRaw: String, Decodable {
|
||||
case staticButton
|
||||
case staticImageButton
|
||||
case appleScriptTitledButton
|
||||
case timeButton
|
||||
case flexSpace
|
||||
case battery
|
||||
case dock
|
||||
case volume
|
||||
case brightness
|
||||
case weather
|
||||
case currency
|
||||
case inputsource
|
||||
case music
|
||||
case groupBar
|
||||
}
|
||||
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let type = try container.decode(ItemTypeRaw.self, forKey: .type)
|
||||
switch type {
|
||||
|
||||
case .appleScriptTitledButton:
|
||||
let source = try container.decode(Source.self, forKey: .source)
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 1800.0
|
||||
self = .appleScriptTitledButton(source: source, refreshInterval: interval)
|
||||
case .staticImageButton:
|
||||
let title = try container.decode(String.self, forKey: .title)
|
||||
let imageRaw = try container.decode(String.self, forKey: .image)
|
||||
if let decodedImageData = Data(base64Encoded: imageRaw, options: .ignoreUnknownCharacters) {
|
||||
let decImage = NSImage(data: decodedImageData)!
|
||||
self = .staticImageButton(title: title, image: decImage)
|
||||
} else {
|
||||
self = .staticButton(title: title)
|
||||
}
|
||||
|
||||
case .staticButton:
|
||||
let title = try container.decode(String.self, forKey: .title)
|
||||
self = .staticButton(title: title)
|
||||
|
||||
case .timeButton:
|
||||
let template = try container.decodeIfPresent(String.self, forKey: .formatTemplate) ?? "HH:mm"
|
||||
self = .timeButton(formatTemplate: template)
|
||||
case .flexSpace:
|
||||
self = .flexSpace()
|
||||
|
||||
case .battery:
|
||||
self = .battery()
|
||||
|
||||
case .dock:
|
||||
self = .dock()
|
||||
|
||||
case .volume:
|
||||
self = .volume()
|
||||
|
||||
case .brightness:
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 0.5
|
||||
self = .brightness(refreshInterval: interval)
|
||||
|
||||
case .weather:
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 1800.0
|
||||
let units = try container.decodeIfPresent(String.self, forKey: .units) ?? "metric"
|
||||
let api_key = try container.decodeIfPresent(String.self, forKey: .api_key) ?? "32c4256d09a4c52b38aecddba7a078f6"
|
||||
let icon_type = try container.decodeIfPresent(String.self, forKey: .icon_type) ?? "text"
|
||||
self = .weather(interval: interval, units: units, api_key: api_key, icon_type: icon_type)
|
||||
|
||||
case .currency:
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 600.0
|
||||
let from = try container.decodeIfPresent(String.self, forKey: .from) ?? "RUB"
|
||||
let to = try container.decodeIfPresent(String.self, forKey: .to) ?? "USD"
|
||||
self = .currency(interval: interval, from: from, to: to)
|
||||
|
||||
case .inputsource:
|
||||
self = .inputsource()
|
||||
|
||||
case .music:
|
||||
let interval = try container.decodeIfPresent(Double.self, forKey: .refreshInterval) ?? 1800.0
|
||||
self = .music(interval: interval)
|
||||
|
||||
case .groupBar:
|
||||
let items = try container.decode([BarItemDefinition].self, forKey: .items)
|
||||
self = .groupBar(items: items)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum ActionType: Decodable {
|
||||
case none
|
||||
case hidKey(keycode: Int)
|
||||
case hidKey(keycode: Int32)
|
||||
case keyPress(keycode: Int)
|
||||
case appleSctipt(source: Source)
|
||||
case appleScript(source: SourceProtocol)
|
||||
case shellScript(executable: String, parameters: [String])
|
||||
case custom(closure: ()->())
|
||||
|
||||
case openUrl(url: String)
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case action
|
||||
case keycode
|
||||
case actionAppleScript
|
||||
case executablePath
|
||||
case shellArguments
|
||||
case url
|
||||
}
|
||||
|
||||
|
||||
private enum ActionTypeRaw: String, Decodable {
|
||||
case hidKey
|
||||
case keyPress
|
||||
case appleScript
|
||||
case shellScript
|
||||
case openUrl
|
||||
}
|
||||
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let type = try container.decodeIfPresent(ActionTypeRaw.self, forKey: .action)
|
||||
|
||||
switch type {
|
||||
case .some(.hidKey):
|
||||
let keycode = try container.decode(Int.self, forKey: .keycode)
|
||||
self = .hidKey(keycode: keycode)
|
||||
case .some(.keyPress):
|
||||
let keycode = try container.decode(Int.self, forKey: .keycode)
|
||||
self = .keyPress(keycode: keycode)
|
||||
case .some(.appleScript):
|
||||
let source = try container.decode(Source.self, forKey: .actionAppleScript)
|
||||
self = .appleSctipt(source: source)
|
||||
case .some(.shellScript):
|
||||
let executable = try container.decode(String.self, forKey: .executablePath)
|
||||
let parameters = try container.decodeIfPresent([String].self, forKey: .shellArguments) ?? []
|
||||
self = .shellScript(executable: executable, parameters: parameters)
|
||||
case .none:
|
||||
self = .none
|
||||
case .some(.hidKey):
|
||||
let keycode = try container.decode(Int32.self, forKey: .keycode)
|
||||
self = .hidKey(keycode: keycode)
|
||||
|
||||
case .some(.keyPress):
|
||||
let keycode = try container.decode(Int.self, forKey: .keycode)
|
||||
self = .keyPress(keycode: keycode)
|
||||
|
||||
case .some(.appleScript):
|
||||
let source = try container.decode(Source.self, forKey: .actionAppleScript)
|
||||
self = .appleScript(source: source)
|
||||
|
||||
case .some(.shellScript):
|
||||
let executable = try container.decode(String.self, forKey: .executablePath)
|
||||
let parameters = try container.decodeIfPresent([String].self, forKey: .shellArguments) ?? []
|
||||
self = .shellScript(executable: executable, parameters: parameters)
|
||||
|
||||
case .some(.openUrl):
|
||||
let url = try container.decode(String.self, forKey: .url)
|
||||
self = .openUrl(url: url)
|
||||
|
||||
case .none:
|
||||
self = .none
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ItemType: Equatable {}
|
||||
func ==(lhs: ItemType, rhs: ItemType) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case let (.staticButton(a), .staticButton(b)):
|
||||
return a == b
|
||||
case let (.flexSpace(a), .flexSpace(b)):
|
||||
return a == b
|
||||
case let (.appleScriptTitledButton(a, b), .appleScriptTitledButton(c, d)):
|
||||
return a == c && b == d
|
||||
|
||||
default:
|
||||
return false
|
||||
enum LongActionType: Decodable {
|
||||
case none
|
||||
case hidKey(keycode: Int32)
|
||||
case keyPress(keycode: Int)
|
||||
case appleScript(source: SourceProtocol)
|
||||
case shellScript(executable: String, parameters: [String])
|
||||
case custom(closure: ()->())
|
||||
case openUrl(url: String)
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case longAction
|
||||
case longKeycode
|
||||
case longActionAppleScript
|
||||
case longExecutablePath
|
||||
case longShellArguments
|
||||
case longUrl
|
||||
}
|
||||
|
||||
private enum LongActionTypeRaw: String, Decodable {
|
||||
case hidKey
|
||||
case keyPress
|
||||
case appleScript
|
||||
case shellScript
|
||||
case openUrl
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let longType = try container.decodeIfPresent(LongActionTypeRaw.self, forKey: .longAction)
|
||||
|
||||
switch longType {
|
||||
case .some(.hidKey):
|
||||
let keycode = try container.decode(Int32.self, forKey: .longKeycode)
|
||||
self = .hidKey(keycode: keycode)
|
||||
|
||||
case .some(.keyPress):
|
||||
let keycode = try container.decode(Int.self, forKey: .longKeycode)
|
||||
self = .keyPress(keycode: keycode)
|
||||
|
||||
case .some(.appleScript):
|
||||
let source = try container.decode(Source.self, forKey: .longActionAppleScript)
|
||||
self = .appleScript(source: source)
|
||||
|
||||
case .some(.shellScript):
|
||||
let executable = try container.decode(String.self, forKey: .longExecutablePath)
|
||||
let parameters = try container.decodeIfPresent([String].self, forKey: .longShellArguments) ?? []
|
||||
self = .shellScript(executable: executable, parameters: parameters)
|
||||
|
||||
case .some(.openUrl):
|
||||
let longUrl = try container.decode(String.self, forKey: .longUrl)
|
||||
self = .openUrl(url: longUrl)
|
||||
|
||||
case .none:
|
||||
self = .none
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ActionType: Equatable {}
|
||||
func ==(lhs: ActionType, rhs: ActionType) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.none, .none):
|
||||
return true
|
||||
case let (.hidKey(a), .hidKey(b)),
|
||||
let (.keyPress(a), .keyPress(b)):
|
||||
return a == b
|
||||
case let (.appleSctipt(a), .appleSctipt(b)):
|
||||
return a == b
|
||||
case let (.shellScript(a, b), .shellScript(c, d)):
|
||||
return a == c && b == d
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
enum GeneralParameter {
|
||||
case width(_: CGFloat)
|
||||
case image(source: SourceProtocol)
|
||||
case align(_: Align)
|
||||
case bordered(_: Bool)
|
||||
case background(_:NSColor)
|
||||
case title(_:String)
|
||||
}
|
||||
|
||||
struct GeneralParameters: Decodable {
|
||||
let parameters: [GeneralParameter]
|
||||
|
||||
fileprivate enum CodingKeys: String, CodingKey {
|
||||
let parameters: [GeneralParameters.CodingKeys: GeneralParameter]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case width
|
||||
case image
|
||||
case align
|
||||
case bordered
|
||||
case background
|
||||
case title
|
||||
}
|
||||
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
var result: [GeneralParameter] = []
|
||||
var result: [GeneralParameters.CodingKeys: GeneralParameter] = [:]
|
||||
|
||||
if let value = try container.decodeIfPresent(CGFloat.self, forKey: .width) {
|
||||
result.append(.width(value))
|
||||
result[.width] = .width(value)
|
||||
}
|
||||
|
||||
if let imageSource = try container.decodeIfPresent(Source.self, forKey: .image) {
|
||||
result[.image] = .image(source: imageSource)
|
||||
}
|
||||
|
||||
let align = try container.decodeIfPresent(Align.self, forKey: .align) ?? .center
|
||||
result[.align] = .align(align)
|
||||
|
||||
if let borderedFlag = try container.decodeIfPresent(Bool.self, forKey: .bordered) {
|
||||
result[.bordered] = .bordered(borderedFlag)
|
||||
}
|
||||
|
||||
if let backgroundColor = try container.decodeIfPresent(String.self, forKey: .background)?.hexColor {
|
||||
result[.background] = .background(backgroundColor)
|
||||
}
|
||||
|
||||
if let title = try container.decodeIfPresent(String.self, forKey: .title) {
|
||||
result[.title] = .title(title)
|
||||
}
|
||||
|
||||
parameters = result
|
||||
}
|
||||
}
|
||||
|
||||
struct Source: Decodable {
|
||||
protocol SourceProtocol {
|
||||
var data: Data? { get }
|
||||
var string: String? { get }
|
||||
var image: NSImage? { get }
|
||||
var appleScript: NSAppleScript? { get }
|
||||
}
|
||||
|
||||
struct Source: Decodable, SourceProtocol {
|
||||
let filePath: String?
|
||||
let base64: String?
|
||||
let inline: String?
|
||||
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case filePath
|
||||
case base64
|
||||
case inline
|
||||
}
|
||||
|
||||
var data: Data? {
|
||||
return base64?.base64Data ?? inline?.data(using: .utf8) ?? filePath?.fileData
|
||||
}
|
||||
|
||||
var string: String? {
|
||||
return inline ?? self.data?.base64Content
|
||||
return inline ?? filePath?.fileString
|
||||
}
|
||||
|
||||
|
||||
var image: NSImage? {
|
||||
return data?.image
|
||||
}
|
||||
|
||||
var appleScript: NSAppleScript? {
|
||||
return filePath?.fileURL.appleScript ?? self.string?.appleScript
|
||||
}
|
||||
|
||||
private init(filePath: String?, base64: String?, inline: String?) {
|
||||
self.filePath = filePath
|
||||
self.base64 = base64
|
||||
self.inline = inline
|
||||
}
|
||||
|
||||
init(filePath: String) {
|
||||
self.init(filePath: filePath, base64: nil, inline: nil)
|
||||
}
|
||||
}
|
||||
extension Source: Equatable {}
|
||||
func ==(left: Source, right: Source) -> Bool {
|
||||
return left.data == right.data
|
||||
|
||||
extension NSImage: SourceProtocol {
|
||||
var data: Data? {
|
||||
return nil
|
||||
}
|
||||
|
||||
var string: String? {
|
||||
return nil
|
||||
}
|
||||
|
||||
var image: NSImage? {
|
||||
return self
|
||||
}
|
||||
|
||||
var appleScript: NSAppleScript? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
var base64Data: Data? {
|
||||
return Data(base64Encoded: self)
|
||||
}
|
||||
|
||||
var fileData: Data? {
|
||||
return try? Data(contentsOf: URL(fileURLWithPath: self))
|
||||
}
|
||||
|
||||
var fileString: String? {
|
||||
var encoding: String.Encoding = .utf8
|
||||
return try? String(contentsOfFile: self, usedEncoding: &encoding)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension Data {
|
||||
var base64Content: String? {
|
||||
var utf8string: String? {
|
||||
return String(data: self, encoding: .utf8)
|
||||
}
|
||||
|
||||
var image: NSImage? {
|
||||
return NSImage(data: self)?.resize(maxSize: NSSize(width: 24, height: 24))
|
||||
}
|
||||
}
|
||||
|
||||
enum Align: String, Decodable {
|
||||
case left
|
||||
case center
|
||||
case right
|
||||
}
|
||||
|
||||
extension String {
|
||||
var fileURL: URL {
|
||||
return URL(fileURLWithPath: self)
|
||||
}
|
||||
|
||||
var appleScript: NSAppleScript? {
|
||||
return NSAppleScript(source: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension URL {
|
||||
var appleScript: NSAppleScript? {
|
||||
guard FileManager.default.fileExists(atPath: self.path) else { return nil }
|
||||
return NSAppleScript(contentsOf: self, error: nil)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-39
@@ -29,43 +29,7 @@ extension KeyPress {
|
||||
}
|
||||
}
|
||||
|
||||
func doKey(_ key: Int, down: Bool) {
|
||||
let flags = NSEvent.ModifierFlags(rawValue: down ? 0xa00 : 0xb00)
|
||||
let data1 = (key << 16) | ((down ? 0xa : 0xb) << 8)
|
||||
|
||||
let ev = NSEvent.otherEvent(
|
||||
with: NSEvent.EventType.systemDefined,
|
||||
location: NSPoint(x:0.0, y:0.0),
|
||||
modifierFlags: flags,
|
||||
timestamp: TimeInterval(0),
|
||||
windowNumber: 0,
|
||||
context: nil,
|
||||
// context: 0,
|
||||
subtype: 8,
|
||||
data1: data1,
|
||||
data2: -1
|
||||
)
|
||||
let cev = ev!.cgEvent!
|
||||
cev.post(tap: CGEventTapLocation(rawValue: 0)!)
|
||||
func HIDPostAuxKey(_ key: Int32) {
|
||||
let key = UInt8(key)
|
||||
MediaKeys.hidPostAuxKey(key)
|
||||
}
|
||||
|
||||
func HIDPostAuxKey(_ key: Int) {
|
||||
doKey(key, down: true)
|
||||
doKey(key, down: false)
|
||||
}
|
||||
|
||||
|
||||
// hidsystem/ev_keymap.h
|
||||
let NX_KEYTYPE_SOUND_UP = 0
|
||||
let NX_KEYTYPE_SOUND_DOWN = 1
|
||||
|
||||
let NX_KEYTYPE_BRIGHTNESS_UP = 2
|
||||
let NX_KEYTYPE_BRIGHTNESS_DOWN = 3
|
||||
|
||||
let NX_KEYTYPE_PLAY = 16
|
||||
let NX_KEYTYPE_NEXT = 17
|
||||
let NX_KEYTYPE_PREVIOUS = 18
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import Foundation
|
||||
|
||||
class ScrollViewItem: NSCustomTouchBarItem, NSGestureRecognizerDelegate {
|
||||
var twofingersPrev: CGFloat = 0.0
|
||||
var threefingersPrev: CGFloat = 0.0
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, items: [NSTouchBarItem]) {
|
||||
super.init(identifier: identifier)
|
||||
let views = items.compactMap { $0.view }
|
||||
let stackView = NSStackView(views: views)
|
||||
stackView.spacing = 1
|
||||
stackView.orientation = .horizontal
|
||||
let scrollView = NSScrollView(frame: CGRect(origin: .zero, size: stackView.fittingSize))
|
||||
scrollView.documentView = stackView
|
||||
self.view = scrollView
|
||||
|
||||
let twofingers = NSPanGestureRecognizer(target: self, action: #selector(twofingersHandler(_:)))
|
||||
twofingers.allowedTouchTypes = .direct
|
||||
twofingers.numberOfTouchesRequired = 2
|
||||
self.view.addGestureRecognizer(twofingers)
|
||||
|
||||
let threefingers = NSPanGestureRecognizer(target: self, action: #selector(threefingersHandler(_:)))
|
||||
threefingers.allowedTouchTypes = .direct
|
||||
threefingers.numberOfTouchesRequired = 3
|
||||
self.view.addGestureRecognizer(threefingers)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
@objc func twofingersHandler(_ sender: NSGestureRecognizer?) { // Volume
|
||||
let position = (sender?.location(in: sender?.view).x)!
|
||||
|
||||
switch sender!.state {
|
||||
case .began:
|
||||
twofingersPrev = position
|
||||
case .changed:
|
||||
if (((position-twofingersPrev) > 10) || ((twofingersPrev-position) > 10)) {
|
||||
if position > twofingersPrev {
|
||||
HIDPostAuxKey(NX_KEYTYPE_SOUND_UP)
|
||||
} else if position < twofingersPrev {
|
||||
HIDPostAuxKey(NX_KEYTYPE_SOUND_DOWN)
|
||||
}
|
||||
twofingersPrev = position
|
||||
}
|
||||
case .ended:
|
||||
twofingersPrev = 0.0
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@objc func threefingersHandler(_ sender: NSGestureRecognizer?) { // Brightness
|
||||
let position = (sender?.location(in: sender?.view).x)!
|
||||
|
||||
switch sender!.state {
|
||||
case .began:
|
||||
threefingersPrev = position
|
||||
case .changed:
|
||||
if (((position-threefingersPrev) > 15) || ((threefingersPrev-position) > 15)) {
|
||||
if position > threefingersPrev {
|
||||
GenericKeyPress(keyCode: CGKeyCode(144)).send()
|
||||
} else if position < threefingersPrev {
|
||||
GenericKeyPress(keyCode: CGKeyCode(145)).send()
|
||||
}
|
||||
threefingersPrev = position
|
||||
}
|
||||
case .ended:
|
||||
threefingersPrev = 0.0
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//
|
||||
// SupportHelpers.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Anton Palgunov on 13/04/2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
extension String {
|
||||
func trim() -> String {
|
||||
return self.trimmingCharacters(in: NSCharacterSet.whitespaces)
|
||||
}
|
||||
|
||||
func stripComments() -> String {
|
||||
// ((\s|,)\/\*[\s\S]*?\*\/)|(( |, ")\/\/.*)
|
||||
return self.replacingOccurrences(of: "((\\s|,)\\/\\*[\\s\\S]*?\\*\\/)|(( |, \\\")\\/\\/.*)", with: "", options: .regularExpression)
|
||||
}
|
||||
|
||||
var hexColor: NSColor? {
|
||||
let hex = trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
|
||||
var int = UInt32()
|
||||
Scanner(string: hex).scanHexInt32(&int)
|
||||
let a, r, g, b: UInt32
|
||||
switch hex.count {
|
||||
case 3: // RGB (12-bit)
|
||||
(r, g, b, a) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17, 255)
|
||||
case 6: // RGB (24-bit)
|
||||
(r, g, b, a) = (int >> 16, int >> 8 & 0xFF, int & 0xFF, 255)
|
||||
case 8: // ARGB (32-bit)
|
||||
(r, g, b, a) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return NSColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
|
||||
}
|
||||
}
|
||||
|
||||
extension NSImage {
|
||||
func resize(maxSize:NSSize) -> NSImage {
|
||||
var ratio:Float = 0.0
|
||||
let imageWidth = Float(self.size.width)
|
||||
let imageHeight = Float(self.size.height)
|
||||
let maxWidth = Float(maxSize.width)
|
||||
let maxHeight = Float(maxSize.height)
|
||||
|
||||
// Get ratio (landscape or portrait)
|
||||
if (imageWidth > imageHeight) {
|
||||
// Landscape
|
||||
ratio = maxWidth / imageWidth;
|
||||
}
|
||||
else {
|
||||
// Portrait
|
||||
ratio = maxHeight / imageHeight;
|
||||
}
|
||||
|
||||
// Calculate new size based on the ratio
|
||||
let newWidth = imageWidth * ratio
|
||||
let newHeight = imageHeight * ratio
|
||||
|
||||
// Create a new NSSize object with the newly calculated size
|
||||
let newSize:NSSize = NSSize(width: Int(newWidth), height: Int(newHeight))
|
||||
|
||||
// Cast the NSImage to a CGImage
|
||||
var imageRect:NSRect = NSMakeRect(0, 0, self.size.width, self.size.height)
|
||||
let imageRef = self.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
|
||||
|
||||
// Create NSImage from the CGImage using the new size
|
||||
let imageWithNewSize = NSImage(cgImage: imageRef!, size: newSize)
|
||||
|
||||
// Return the new image
|
||||
return imageWithNewSize
|
||||
}
|
||||
|
||||
func rotateByDegreess(degrees:CGFloat) -> NSImage {
|
||||
|
||||
var imageBounds = NSZeroRect ; imageBounds.size = self.size
|
||||
let pathBounds = NSBezierPath(rect: imageBounds)
|
||||
var transform = NSAffineTransform()
|
||||
transform.rotate(byDegrees: degrees)
|
||||
pathBounds.transform(using: transform as AffineTransform)
|
||||
let rotatedBounds:NSRect = NSMakeRect(NSZeroPoint.x, NSZeroPoint.y , self.size.width, self.size.height )
|
||||
let rotatedImage = NSImage(size: rotatedBounds.size)
|
||||
|
||||
//Center the image within the rotated bounds
|
||||
imageBounds.origin.x = NSMidX(rotatedBounds) - (NSWidth(imageBounds) / 2)
|
||||
imageBounds.origin.y = NSMidY(rotatedBounds) - (NSHeight(imageBounds) / 2)
|
||||
|
||||
// Start a new transform
|
||||
transform = NSAffineTransform()
|
||||
// Move coordinate system to the center (since we want to rotate around the center)
|
||||
transform.translateX(by: +(NSWidth(rotatedBounds) / 2 ), yBy: +(NSHeight(rotatedBounds) / 2))
|
||||
transform.rotate(byDegrees: degrees)
|
||||
// Move the coordinate system bak to normal
|
||||
transform.translateX(by: -(NSWidth(rotatedBounds) / 2 ), yBy: -(NSHeight(rotatedBounds) / 2))
|
||||
// Draw the original image, rotated, into the new image
|
||||
rotatedImage.lockFocus()
|
||||
transform.concat()
|
||||
self.draw(in: imageBounds, from: NSZeroRect, operation: NSCompositingOperation.copy, fraction: 1.0)
|
||||
rotatedImage.unlockFocus()
|
||||
|
||||
return rotatedImage
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// ExtendNSTouchBar.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Anton Palgunov on 07/06/2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
func presentSystemModal(_ touchBar: NSTouchBar!, systemTrayItemIdentifier identifier: NSTouchBarItem.Identifier!) -> Void {
|
||||
if #available(OSX 10.14, *) {
|
||||
NSTouchBar.presentSystemModalTouchBar(touchBar, systemTrayItemIdentifier: identifier)
|
||||
} else {
|
||||
NSTouchBar.presentSystemModalFunctionBar(touchBar, systemTrayItemIdentifier: identifier)
|
||||
}
|
||||
}
|
||||
|
||||
func presentSystemModal(_ touchBar: NSTouchBar!, placement: Int64, systemTrayItemIdentifier identifier: NSTouchBarItem.Identifier!) -> Void {
|
||||
if #available(OSX 10.14, *) {
|
||||
NSTouchBar.presentSystemModalTouchBar(touchBar, placement: placement, systemTrayItemIdentifier: identifier)
|
||||
} else {
|
||||
NSTouchBar.presentSystemModalFunctionBar(touchBar, placement: placement, systemTrayItemIdentifier: identifier)
|
||||
}
|
||||
}
|
||||
|
||||
func minimizeSystemModal(_ touchBar: NSTouchBar!) -> Void {
|
||||
if #available(OSX 10.14, *) {
|
||||
NSTouchBar.minimizeSystemModalTouchBar(touchBar)
|
||||
} else {
|
||||
NSTouchBar.minimizeSystemModalFunctionBar(touchBar)
|
||||
}
|
||||
}
|
||||
+297
-50
@@ -13,23 +13,40 @@ struct ExactItem {
|
||||
let presetItem: BarItemDefinition
|
||||
}
|
||||
|
||||
let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR")
|
||||
let standardConfigPath = appSupportDirectory.appending("/items.json")
|
||||
|
||||
extension ItemType {
|
||||
|
||||
|
||||
var identifierBase: String {
|
||||
switch self {
|
||||
case .staticButton(title: _):
|
||||
return "com.toxblh.mtmr.staticButton."
|
||||
case .staticImageButton(title: _):
|
||||
return "com.toxblh.mtmr.staticImageButton."
|
||||
case .appleScriptTitledButton(source: _):
|
||||
return "com.toxblh.mtmr.appleScriptButton."
|
||||
case .timeButton(formatTemplate: _):
|
||||
return "com.toxblh.mtmr.timeButton."
|
||||
case .flexSpace():
|
||||
return "NSTouchBarItem.Identifier.flexibleSpace"
|
||||
case .battery():
|
||||
return "com.toxblh.mtmr.battery."
|
||||
case .dock():
|
||||
return "com.toxblh.mtmr.dock"
|
||||
case .volume():
|
||||
return "com.toxblh.mtmr.volume"
|
||||
case .brightness(refreshInterval: _):
|
||||
return "com.toxblh.mtmr.brightness"
|
||||
case .weather(interval: _, units: _, api_key: _, icon_type: _):
|
||||
return "com.toxblh.mtmr.weather"
|
||||
case .currency(interval: _, from: _, to: _):
|
||||
return "com.toxblh.mtmr.currency"
|
||||
case .inputsource():
|
||||
return "com.toxblh.mtmr.inputsource."
|
||||
case .music(interval: _):
|
||||
return "com.toxblh.mtmr.music."
|
||||
case .groupBar(items: _):
|
||||
return "com.toxblh.mtmr.groupBar."
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension NSTouchBarItem.Identifier {
|
||||
@@ -39,98 +56,311 @@ extension NSTouchBarItem.Identifier {
|
||||
class TouchBarController: NSObject, NSTouchBarDelegate {
|
||||
|
||||
static let shared = TouchBarController()
|
||||
|
||||
var touchBar: NSTouchBar!
|
||||
|
||||
fileprivate var lastPresetPath = ""
|
||||
var jsonItems: [BarItemDefinition] = []
|
||||
var itemDefinitions: [NSTouchBarItem.Identifier: BarItemDefinition] = [:]
|
||||
var items: [NSTouchBarItem.Identifier: NSTouchBarItem] = [:]
|
||||
var leftIdentifiers: [NSTouchBarItem.Identifier] = []
|
||||
var centerIdentifiers: [NSTouchBarItem.Identifier] = []
|
||||
var centerItems: [NSTouchBarItem] = []
|
||||
var rightIdentifiers: [NSTouchBarItem.Identifier] = []
|
||||
var scrollArea: NSCustomTouchBarItem?
|
||||
var centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
|
||||
|
||||
var controlStripState: Bool {
|
||||
get {
|
||||
return UserDefaults.standard.bool(forKey: "com.toxblh.mtmr.settings.showControlStrip")
|
||||
}
|
||||
set {
|
||||
UserDefaults.standard.set(!controlStripState, forKey: "com.toxblh.mtmr.settings.showControlStrip")
|
||||
}
|
||||
}
|
||||
|
||||
let touchBar = NSTouchBar()
|
||||
var touchbarNeedRefresh: Bool = true
|
||||
|
||||
var items: [NSTouchBarItem.Identifier: BarItemDefinition] = [:]
|
||||
var blacklistAppIdentifiers: [String] = []
|
||||
var frontmostApplicationIdentifier: String? {
|
||||
get {
|
||||
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
|
||||
return frontmostId
|
||||
}
|
||||
}
|
||||
|
||||
private override init() {
|
||||
super.init()
|
||||
SupportedTypesHolder.sharedInstance.register(typename: "exitTouchbar", item: .staticButton(title: "exit"), action: .custom(closure: { [weak self] in
|
||||
self?.dismissTouchBar()
|
||||
}))
|
||||
SupportedTypesHolder.sharedInstance.register(typename: "exitTouchbar", item: .staticButton(title: "exit"), action: .custom(closure: { [weak self] in self?.dismissTouchBar()}), longAction: .none)
|
||||
|
||||
loadItems()
|
||||
SupportedTypesHolder.sharedInstance.register(typename: "close") { _ in
|
||||
return (item: .staticButton(title: ""), action: .custom(closure: { [weak self] in
|
||||
guard let `self` = self else { return }
|
||||
self.reloadPreset(path: self.lastPresetPath)
|
||||
}), longAction: .none, parameters: [.width: .width(30), .image: .image(source: (NSImage(named: .stopProgressFreestandingTemplate))!)])
|
||||
}
|
||||
|
||||
if let blackListed = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.blackListedApps") {
|
||||
self.blacklistAppIdentifiers = blackListed
|
||||
}
|
||||
|
||||
touchBar.delegate = self
|
||||
self.presentTouchBar()
|
||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didLaunchApplicationNotification, object: nil)
|
||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didTerminateApplicationNotification, object: nil)
|
||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didActivateApplicationNotification, object: nil)
|
||||
|
||||
reloadStandardConfig()
|
||||
}
|
||||
|
||||
func loadItems() {
|
||||
let appSupportDirectory = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!.appending("/MTMR")
|
||||
let presetPath = appSupportDirectory.appending("/items.json")
|
||||
func createAndUpdatePreset(newJsonItems: [BarItemDefinition]) {
|
||||
if let oldBar = self.touchBar {
|
||||
minimizeSystemModal(oldBar)
|
||||
}
|
||||
self.touchBar = NSTouchBar()
|
||||
self.jsonItems = newJsonItems
|
||||
self.itemDefinitions = [:]
|
||||
self.items = [:]
|
||||
self.leftIdentifiers = []
|
||||
self.centerItems = []
|
||||
self.rightIdentifiers = []
|
||||
|
||||
loadItemDefinitions(jsonItems: self.jsonItems)
|
||||
createItems()
|
||||
|
||||
centerItems = centerIdentifiers.compactMap({ (identifier) -> NSTouchBarItem? in
|
||||
return items[identifier]
|
||||
})
|
||||
|
||||
self.centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
|
||||
self.scrollArea = ScrollViewItem(identifier: centerScrollArea, items: centerItems)
|
||||
|
||||
touchBar.delegate = self
|
||||
touchBar.defaultItemIdentifiers = []
|
||||
touchBar.defaultItemIdentifiers = self.leftIdentifiers + [centerScrollArea] + self.rightIdentifiers
|
||||
|
||||
self.updateActiveApp()
|
||||
}
|
||||
|
||||
@objc func activeApplicationChanged(_ n: Notification) {
|
||||
updateActiveApp()
|
||||
}
|
||||
|
||||
func updateActiveApp() {
|
||||
if self.blacklistAppIdentifiers.index(of: self.frontmostApplicationIdentifier!) != nil {
|
||||
DFRElementSetControlStripPresenceForIdentifier(.controlStripItem, false)
|
||||
self.touchbarNeedRefresh = true
|
||||
} else {
|
||||
presentTouchBar()
|
||||
self.touchbarNeedRefresh = false
|
||||
}
|
||||
}
|
||||
|
||||
func reloadStandardConfig() {
|
||||
let presetPath = standardConfigPath
|
||||
if !FileManager.default.fileExists(atPath: presetPath),
|
||||
let defaultPreset = Bundle.main.path(forResource: "defaultPreset", ofType: "json") {
|
||||
try? FileManager.default.createDirectory(atPath: appSupportDirectory, withIntermediateDirectories: true, attributes: nil)
|
||||
try? FileManager.default.copyItem(atPath: defaultPreset, toPath: presetPath)
|
||||
}
|
||||
let jsonData = presetPath.fileData
|
||||
let jsonItems = jsonData?.barItemDefinitions() ?? [BarItemDefinition(type: .staticButton(title: "bad preset"), action: .none, additionalParameters: [])]
|
||||
|
||||
reloadPreset(path: presetPath)
|
||||
}
|
||||
|
||||
func reloadPreset(path: String) {
|
||||
lastPresetPath = path
|
||||
let items = path.fileData?.barItemDefinitions() ?? [BarItemDefinition(type: .staticButton(title: "bad preset"), action: .none, longAction: .none, additionalParameters: [:])]
|
||||
touchbarNeedRefresh = true
|
||||
createAndUpdatePreset(newJsonItems: items)
|
||||
}
|
||||
|
||||
func loadItemDefinitions(jsonItems: [BarItemDefinition]) {
|
||||
let dateFormatter = DateFormatter()
|
||||
dateFormatter.dateFormat = "HH-mm-ss"
|
||||
let time = dateFormatter.string(from: Date())
|
||||
for item in jsonItems {
|
||||
let identifierString = item.type.identifierBase.appending(UUID().uuidString)
|
||||
let identifier = item.type == ItemType.flexSpace()
|
||||
? NSTouchBarItem.Identifier.flexibleSpace
|
||||
: NSTouchBarItem.Identifier(identifierString)
|
||||
items[identifier] = item
|
||||
touchBar.defaultItemIdentifiers += [identifier]
|
||||
let identifierString = item.type.identifierBase.appending(time + "--" + UUID().uuidString)
|
||||
let identifier = NSTouchBarItem.Identifier(identifierString)
|
||||
itemDefinitions[identifier] = item
|
||||
if item.align == .left {
|
||||
leftIdentifiers.append(identifier)
|
||||
}
|
||||
if item.align == .right {
|
||||
rightIdentifiers.append(identifier)
|
||||
}
|
||||
if item.align == .center {
|
||||
centerIdentifiers.append(identifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setupControlStripPresence() {
|
||||
|
||||
func createItems() {
|
||||
for (identifier, definition) in self.itemDefinitions {
|
||||
self.items[identifier] = self.createItem(forIdentifier: identifier, definition: definition)
|
||||
}
|
||||
}
|
||||
|
||||
@objc func setupControlStripPresence() {
|
||||
DFRSystemModalShowsCloseBoxWhenFrontMost(false)
|
||||
let item = NSCustomTouchBarItem(identifier: .controlStripItem)
|
||||
item.view = NSButton(image: #imageLiteral(resourceName: "Strip"), target: self, action: #selector(presentTouchBar))
|
||||
item.view = NSButton(image: #imageLiteral(resourceName: "StatusImage"), target: self, action: #selector(presentTouchBar))
|
||||
NSTouchBarItem.addSystemTrayItem(item)
|
||||
DFRElementSetControlStripPresenceForIdentifier(.controlStripItem, true)
|
||||
}
|
||||
|
||||
|
||||
func updateControlStripPresence() {
|
||||
DFRElementSetControlStripPresenceForIdentifier(.controlStripItem, true)
|
||||
}
|
||||
|
||||
|
||||
@objc private func presentTouchBar() {
|
||||
NSTouchBar.presentSystemModalFunctionBar(touchBar, placement: 1, systemTrayItemIdentifier: .controlStripItem)
|
||||
if touchbarNeedRefresh {
|
||||
if self.controlStripState {
|
||||
presentSystemModal(touchBar, systemTrayItemIdentifier: .controlStripItem)
|
||||
} else {
|
||||
presentSystemModal(touchBar, placement: 1, systemTrayItemIdentifier: .controlStripItem)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@objc private func dismissTouchBar() {
|
||||
NSTouchBar.minimizeSystemModalFunctionBar(touchBar)
|
||||
self.touchbarNeedRefresh = true
|
||||
minimizeSystemModal(touchBar)
|
||||
}
|
||||
|
||||
@objc func resetControlStrip() {
|
||||
dismissTouchBar()
|
||||
presentTouchBar()
|
||||
}
|
||||
|
||||
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
|
||||
guard let item = self.items[identifier] else {
|
||||
if identifier == centerScrollArea {
|
||||
return self.scrollArea
|
||||
}
|
||||
|
||||
guard let item = self.items[identifier],
|
||||
let definition = self.itemDefinitions[identifier],
|
||||
definition.align != .center else {
|
||||
return nil
|
||||
}
|
||||
let action = self.action(forItem: item)
|
||||
return item
|
||||
}
|
||||
|
||||
func createItem(forIdentifier identifier: NSTouchBarItem.Identifier, definition item: BarItemDefinition) -> NSTouchBarItem? {
|
||||
|
||||
var barItem: NSTouchBarItem!
|
||||
switch item.type {
|
||||
case .staticButton(title: let title):
|
||||
barItem = CustomButtonTouchBarItem(identifier: identifier, title: title, onTap: action)
|
||||
case .staticImageButton(title: let title, image: let image):
|
||||
barItem = CustomButtonTouchBarItem(identifier: identifier, title: title, onTap: action, image: image)
|
||||
barItem = CustomButtonTouchBarItem(identifier: identifier, title: title)
|
||||
case .appleScriptTitledButton(source: let source, refreshInterval: let interval):
|
||||
barItem = AppleScriptTouchBarItem(identifier: identifier, source: source, interval: interval, onTap: action)
|
||||
barItem = AppleScriptTouchBarItem(identifier: identifier, source: source, interval: interval)
|
||||
case .timeButton(formatTemplate: let template):
|
||||
barItem = TimeTouchBarItem(identifier: identifier, formatTemplate: template)
|
||||
case .flexSpace:
|
||||
barItem = nil
|
||||
case .battery():
|
||||
barItem = BatteryBarItem(identifier: identifier)
|
||||
case .dock:
|
||||
barItem = AppScrubberTouchBarItem(identifier: identifier)
|
||||
case .volume:
|
||||
if case .image(let source)? = item.additionalParameters[.image] {
|
||||
barItem = VolumeViewController(identifier: identifier, image: source.image)
|
||||
} else {
|
||||
barItem = VolumeViewController(identifier: identifier)
|
||||
}
|
||||
case .brightness(refreshInterval: let interval):
|
||||
if case .image(let source)? = item.additionalParameters[.image] {
|
||||
barItem = BrightnessViewController(identifier: identifier, refreshInterval: interval, image: source.image)
|
||||
} else {
|
||||
barItem = BrightnessViewController(identifier: identifier, refreshInterval: interval)
|
||||
}
|
||||
case .weather(interval: let interval, units: let units, api_key: let api_key, icon_type: let icon_type):
|
||||
barItem = WeatherBarItem(identifier: identifier, interval: interval, units: units, api_key: api_key, icon_type: icon_type)
|
||||
case .currency(interval: let interval, from: let from, to: let to):
|
||||
barItem = CurrencyBarItem(identifier: identifier, interval: interval, from: from, to: to)
|
||||
case .inputsource():
|
||||
barItem = InputSourceBarItem(identifier: identifier)
|
||||
case .music(interval: let interval):
|
||||
barItem = MusicBarItem(identifier: identifier, interval: interval)
|
||||
case .groupBar(items: let items):
|
||||
barItem = GroupBarItem(identifier: identifier, items: items)
|
||||
}
|
||||
for parameter in item.additionalParameters {
|
||||
if case .width(let value) = parameter, let widthBarItem = barItem as? CanSetWidth {
|
||||
widthBarItem.setWidth(value: value)
|
||||
|
||||
if let action = self.action(forItem: item), let item = barItem as? CustomButtonTouchBarItem {
|
||||
item.tapClosure = action
|
||||
}
|
||||
if let longAction = self.longAction(forItem: item), let item = barItem as? CustomButtonTouchBarItem {
|
||||
item.longTapClosure = longAction
|
||||
}
|
||||
if case .bordered(let bordered)? = item.additionalParameters[.bordered], let item = barItem as? CustomButtonTouchBarItem {
|
||||
item.isBordered = bordered
|
||||
}
|
||||
if case .background(let color)? = item.additionalParameters[.background], let item = barItem as? CustomButtonTouchBarItem {
|
||||
item.backgroundColor = color
|
||||
}
|
||||
if case .width(let value)? = item.additionalParameters[.width], let widthBarItem = barItem as? CanSetWidth {
|
||||
widthBarItem.setWidth(value: value)
|
||||
}
|
||||
if case .image(let source)? = item.additionalParameters[.image], let item = barItem as? CustomButtonTouchBarItem {
|
||||
item.image = source.image
|
||||
}
|
||||
if case .title(let value)? = item.additionalParameters[.title] {
|
||||
if let item = barItem as? GroupBarItem {
|
||||
item.collapsedRepresentationLabel = value
|
||||
} else if let item = barItem as? CustomButtonTouchBarItem {
|
||||
item.title = value
|
||||
}
|
||||
}
|
||||
return barItem
|
||||
}
|
||||
|
||||
|
||||
func action(forItem item: BarItemDefinition) -> ()->() {
|
||||
|
||||
func action(forItem item: BarItemDefinition) -> (()->())? {
|
||||
switch item.action {
|
||||
case .hidKey(keycode: let keycode):
|
||||
return { HIDPostAuxKey(keycode) }
|
||||
case .keyPress(keycode: let keycode):
|
||||
return { GenericKeyPress(keyCode: CGKeyCode(keycode)).send() }
|
||||
case .appleSctipt(source: let source):
|
||||
case .appleScript(source: let source):
|
||||
guard let appleScript = source.appleScript else {
|
||||
print("cannot create apple script for item \(item)")
|
||||
return {}
|
||||
}
|
||||
return {
|
||||
DispatchQueue.appleScriptQueue.async {
|
||||
var error: NSDictionary?
|
||||
appleScript.executeAndReturnError(&error)
|
||||
if let error = error {
|
||||
print("error \(error) when handling \(item) ")
|
||||
}
|
||||
}
|
||||
}
|
||||
case .shellScript(executable: let executable, parameters: let parameters):
|
||||
return {
|
||||
let task = Process()
|
||||
task.launchPath = executable
|
||||
task.arguments = parameters
|
||||
task.launch()
|
||||
}
|
||||
case .openUrl(url: let url):
|
||||
return {
|
||||
if let url = URL(string: url), NSWorkspace.shared.open(url) {
|
||||
#if DEBUG
|
||||
print("URL was successfully opened")
|
||||
#endif
|
||||
} else {
|
||||
print("error", url)
|
||||
}
|
||||
}
|
||||
case .custom(closure: let closure):
|
||||
return closure
|
||||
case .none:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func longAction(forItem item: BarItemDefinition) -> (()->())? {
|
||||
switch item.longAction {
|
||||
case .hidKey(keycode: let keycode):
|
||||
return { HIDPostAuxKey(keycode) }
|
||||
case .keyPress(keycode: let keycode):
|
||||
return { GenericKeyPress(keyCode: CGKeyCode(keycode)).send() }
|
||||
case .appleScript(source: let source):
|
||||
guard let appleScript = source.appleScript else {
|
||||
print("cannot create apple script for item \(item)")
|
||||
return {}
|
||||
@@ -149,13 +379,22 @@ class TouchBarController: NSObject, NSTouchBarDelegate {
|
||||
task.arguments = parameters
|
||||
task.launch()
|
||||
}
|
||||
case .openUrl(url: let url):
|
||||
return {
|
||||
if let url = URL(string: url), NSWorkspace.shared.open(url) {
|
||||
#if DEBUG
|
||||
print("URL was successfully opened")
|
||||
#endif
|
||||
} else {
|
||||
print("error", url)
|
||||
}
|
||||
}
|
||||
case .custom(closure: let closure):
|
||||
return closure
|
||||
case .none:
|
||||
return {}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protocol CanSetWidth {
|
||||
@@ -168,3 +407,11 @@ extension NSCustomTouchBarItem: CanSetWidth {
|
||||
}
|
||||
}
|
||||
|
||||
extension BarItemDefinition {
|
||||
var align: Align {
|
||||
if case .align(let result)? = self.additionalParameters[.align] {
|
||||
return result
|
||||
}
|
||||
return .center
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
//
|
||||
// AppScrubberTouchBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Daniel Apatin on 18.04.2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
|
||||
import Cocoa
|
||||
|
||||
class AppScrubberTouchBarItem: NSCustomTouchBarItem, NSScrubberDelegate, NSScrubberDataSource {
|
||||
|
||||
private var scrubber: NSScrubber!
|
||||
|
||||
private let hf: HapticFeedback = HapticFeedback()
|
||||
|
||||
private var timer: Timer!
|
||||
private var ticks: Int = 0
|
||||
private let minTicks: Int = 5
|
||||
private let maxTicks: Int = 20
|
||||
private var lastSelected: Int = 0
|
||||
|
||||
private var persistentAppIdentifiers: [String] = []
|
||||
private var runningAppsIdentifiers: [String] = []
|
||||
|
||||
private var frontmostApplicationIdentifier: String? {
|
||||
get {
|
||||
guard let frontmostId = NSWorkspace.shared.frontmostApplication?.bundleIdentifier else { return nil }
|
||||
return frontmostId
|
||||
}
|
||||
}
|
||||
|
||||
private var applications: [DockItem] = []
|
||||
|
||||
override init(identifier: NSTouchBarItem.Identifier) {
|
||||
super.init(identifier: identifier)
|
||||
|
||||
scrubber = NSScrubber();
|
||||
scrubber.delegate = self
|
||||
scrubber.dataSource = self
|
||||
scrubber.mode = .free // .fixed
|
||||
let layout = NSScrubberFlowLayout();
|
||||
layout.itemSize = NSSize(width: 36, height: 32)
|
||||
layout.itemSpacing = 2
|
||||
scrubber.scrubberLayout = layout
|
||||
scrubber.selectionBackgroundStyle = .roundedBackground
|
||||
scrubber.showsAdditionalContentIndicators = true
|
||||
|
||||
view = scrubber
|
||||
|
||||
scrubber.register(NSScrubberImageItemView.self, forItemIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ScrubberApplicationsItemReuseIdentifier"))
|
||||
|
||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didLaunchApplicationNotification, object: nil)
|
||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didTerminateApplicationNotification, object: nil)
|
||||
NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(activeApplicationChanged), name: NSWorkspace.didActivateApplicationNotification, object: nil)
|
||||
|
||||
if let persistent = UserDefaults.standard.stringArray(forKey: "com.toxblh.mtmr.dock.persistent") {
|
||||
self.persistentAppIdentifiers = persistent
|
||||
}
|
||||
|
||||
updateRunningApplication()
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
@objc func activeApplicationChanged(n: Notification) {
|
||||
updateRunningApplication()
|
||||
}
|
||||
|
||||
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
|
||||
updateRunningApplication()
|
||||
}
|
||||
|
||||
func updateRunningApplication() {
|
||||
let newApplications = launchedApplications()
|
||||
|
||||
let index = newApplications.index {
|
||||
$0.bundleIdentifier == frontmostApplicationIdentifier
|
||||
}
|
||||
|
||||
applications = newApplications
|
||||
applications += getDockPersistentAppsList()
|
||||
scrubber.reloadData()
|
||||
|
||||
scrubber.selectedIndex = index ?? 0
|
||||
}
|
||||
|
||||
public func numberOfItems(for scrubber: NSScrubber) -> Int {
|
||||
return applications.count
|
||||
}
|
||||
|
||||
public func scrubber(_ scrubber: NSScrubber, viewForItemAt index: Int) -> NSScrubberItemView {
|
||||
let item = scrubber.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ScrubberApplicationsItemReuseIdentifier"), owner: self) as? NSScrubberImageItemView ?? NSScrubberImageItemView()
|
||||
item.imageView.imageScaling = .scaleProportionallyDown
|
||||
|
||||
let app = applications[index]
|
||||
|
||||
if let icon = app.icon {
|
||||
item.image = icon
|
||||
item.image.size = NSSize(width: 26, height: 26)
|
||||
}
|
||||
|
||||
item.removeFromSuperview()
|
||||
|
||||
let dotView = NSView(frame: .zero)
|
||||
dotView.wantsLayer = true
|
||||
if self.runningAppsIdentifiers.contains(app.bundleIdentifier!) {
|
||||
dotView.layer?.backgroundColor = NSColor.white.cgColor
|
||||
} else {
|
||||
dotView.layer?.backgroundColor = NSColor.black.cgColor
|
||||
}
|
||||
dotView.layer?.cornerRadius = 1.5
|
||||
dotView.setFrameOrigin(NSPoint(x: 17, y: 1))
|
||||
dotView.frame.size = NSSize(width: 3, height: 3)
|
||||
item.addSubview(dotView)
|
||||
|
||||
return item
|
||||
}
|
||||
|
||||
public func didBeginInteracting(with scrubber: NSScrubber) {
|
||||
stopTimer()
|
||||
self.ticks = 0
|
||||
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(checkTimer), userInfo: nil, repeats: true)
|
||||
}
|
||||
|
||||
@objc private func checkTimer() {
|
||||
self.ticks += 1
|
||||
|
||||
if (self.ticks == minTicks) {
|
||||
hf.tap(strong: 2)
|
||||
}
|
||||
|
||||
if (self.ticks > maxTicks) {
|
||||
stopTimer()
|
||||
hf.tap(strong: 6)
|
||||
}
|
||||
}
|
||||
|
||||
private func stopTimer() {
|
||||
self.timer?.invalidate()
|
||||
self.timer = nil
|
||||
self.lastSelected = 0
|
||||
}
|
||||
|
||||
public func didCancelInteracting(with scrubber: NSScrubber) {
|
||||
stopTimer()
|
||||
}
|
||||
|
||||
public func didFinishInteracting(with scrubber: NSScrubber) {
|
||||
stopTimer()
|
||||
|
||||
if (ticks == 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (self.ticks >= minTicks && scrubber.selectedIndex > 0) {
|
||||
self.longPress(selected: scrubber.selectedIndex)
|
||||
return
|
||||
}
|
||||
|
||||
let bundleIdentifier = applications[scrubber.selectedIndex].bundleIdentifier
|
||||
if bundleIdentifier!.contains("file://") {
|
||||
NSWorkspace.shared.openFile(bundleIdentifier!.replacingOccurrences(of: "file://", with: ""))
|
||||
} else {
|
||||
NSWorkspace.shared.launchApplication(withBundleIdentifier: bundleIdentifier!, options: [.default], additionalEventParamDescriptor: nil, launchIdentifier: nil)
|
||||
hf.tap(strong: 6)
|
||||
}
|
||||
updateRunningApplication()
|
||||
|
||||
// NB: if you can't open app which on another space, try to check mark
|
||||
// "When switching to an application, switch to a Space with open windows for the application"
|
||||
// in Mission control settings
|
||||
}
|
||||
|
||||
private func longPress(selected: Int) {
|
||||
let bundleIdentifier = applications[selected].bundleIdentifier
|
||||
|
||||
if (self.ticks > maxTicks) {
|
||||
if let processIdentifier = applications[selected].pid {
|
||||
if !(NSRunningApplication(processIdentifier: processIdentifier)?.terminate())! {
|
||||
NSRunningApplication(processIdentifier: processIdentifier)?.forceTerminate()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hf.tap(strong: 6)
|
||||
if let index = self.persistentAppIdentifiers.index(of: bundleIdentifier!) {
|
||||
self.persistentAppIdentifiers.remove(at: index)
|
||||
} else {
|
||||
self.persistentAppIdentifiers.append(bundleIdentifier!)
|
||||
}
|
||||
|
||||
UserDefaults.standard.set(self.persistentAppIdentifiers, forKey: "com.toxblh.mtmr.dock.persistent")
|
||||
UserDefaults.standard.synchronize()
|
||||
}
|
||||
self.ticks = 0
|
||||
updateRunningApplication()
|
||||
}
|
||||
|
||||
private func launchedApplications() -> [DockItem] {
|
||||
self.runningAppsIdentifiers = []
|
||||
var returnable: [DockItem] = []
|
||||
for app in NSWorkspace.shared.runningApplications {
|
||||
guard app.activationPolicy == NSApplication.ActivationPolicy.regular else { continue }
|
||||
guard let bundleIdentifier = app.bundleIdentifier else { continue }
|
||||
|
||||
self.runningAppsIdentifiers.append(bundleIdentifier)
|
||||
|
||||
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier), pid: app.processIdentifier)
|
||||
returnable.append(dockItem)
|
||||
}
|
||||
return returnable
|
||||
}
|
||||
|
||||
public func getIcon(forBundleIdentifier bundleIdentifier: String? = nil, orPath path: String? = nil, orType type: String? = nil) -> NSImage {
|
||||
if bundleIdentifier != nil {
|
||||
if let appPath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: bundleIdentifier!) {
|
||||
return NSWorkspace.shared.icon(forFile: appPath)
|
||||
}
|
||||
}
|
||||
|
||||
if path != nil {
|
||||
return NSWorkspace.shared.icon(forFile: path!)
|
||||
}
|
||||
|
||||
let genericIcon = NSImage(contentsOfFile: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns")
|
||||
return genericIcon ?? NSImage(size: .zero)
|
||||
}
|
||||
|
||||
|
||||
public func getDockPersistentAppsList() -> [DockItem] {
|
||||
var returnable: [DockItem] = []
|
||||
|
||||
for bundleIdentifier in persistentAppIdentifiers {
|
||||
if !self.runningAppsIdentifiers.contains(bundleIdentifier) {
|
||||
let dockItem = DockItem(bundleIdentifier: bundleIdentifier, icon: getIcon(forBundleIdentifier: bundleIdentifier))
|
||||
returnable.append(dockItem)
|
||||
}
|
||||
}
|
||||
|
||||
return returnable
|
||||
}
|
||||
}
|
||||
|
||||
public class DockItem: NSObject {
|
||||
var bundleIdentifier: String!, icon: NSImage!, pid: Int32!
|
||||
|
||||
convenience init(bundleIdentifier: String, icon: NSImage, pid: Int32? = nil) {
|
||||
self.init()
|
||||
self.bundleIdentifier = bundleIdentifier
|
||||
self.icon = icon
|
||||
self.pid = pid
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//
|
||||
// BatteryBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Anton Palgunov on 18/04/2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import IOKit.ps
|
||||
import Foundation
|
||||
|
||||
class BatteryBarItem: CustomButtonTouchBarItem {
|
||||
private let batteryInfo = BatteryInfo()
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier) {
|
||||
super.init(identifier: identifier, title: " ")
|
||||
|
||||
batteryInfo.start { [weak self] in
|
||||
self?.refresh()
|
||||
}
|
||||
self.refresh()
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
self.attributedTitle = self.batteryInfo.formattedInfo()
|
||||
}
|
||||
|
||||
deinit {
|
||||
batteryInfo.stop()
|
||||
}
|
||||
}
|
||||
|
||||
class BatteryInfo: NSObject {
|
||||
var current: Int = 0
|
||||
var timeToEmpty: Int = 0
|
||||
var timeToFull: Int = 0
|
||||
var isCharged: Bool = false
|
||||
var isCharging: Bool = false
|
||||
var ACPower: String = ""
|
||||
var timeRemaining: String = ""
|
||||
var notifyBlock: ()->() = {}
|
||||
var loop:CFRunLoopSource?
|
||||
|
||||
func start(notifyBlock: @escaping ()->()) {
|
||||
self.notifyBlock = notifyBlock
|
||||
let opaque = Unmanaged.passRetained(self).toOpaque()
|
||||
let context = UnsafeMutableRawPointer(opaque)
|
||||
loop = IOPSNotificationCreateRunLoopSource({ (context) in
|
||||
guard let ctx = context else {
|
||||
return
|
||||
}
|
||||
|
||||
let watcher = Unmanaged<BatteryInfo>.fromOpaque(ctx).takeUnretainedValue()
|
||||
watcher.notifyBlock()
|
||||
}, context).takeRetainedValue() as CFRunLoopSource
|
||||
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
|
||||
}
|
||||
|
||||
func stop() {
|
||||
self.notifyBlock = {}
|
||||
guard let loop = self.loop else {
|
||||
return
|
||||
}
|
||||
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), loop, CFRunLoopMode.defaultMode)
|
||||
self.loop = nil
|
||||
}
|
||||
|
||||
func getPSInfo() {
|
||||
let psInfo = IOPSCopyPowerSourcesInfo().takeRetainedValue()
|
||||
let psList = IOPSCopyPowerSourcesList(psInfo).takeRetainedValue() as [CFTypeRef]
|
||||
|
||||
for ps in psList {
|
||||
if let psDesc = IOPSGetPowerSourceDescription(psInfo, ps).takeUnretainedValue() as? [String: Any] {
|
||||
let current = psDesc[kIOPSCurrentCapacityKey]
|
||||
if (current != nil) {
|
||||
self.current = current as! Int
|
||||
}
|
||||
|
||||
let timeToEmpty = psDesc[kIOPSTimeToEmptyKey]
|
||||
if (timeToEmpty != nil) {
|
||||
self.timeToEmpty = timeToEmpty as! Int
|
||||
}
|
||||
|
||||
let timeToFull = psDesc[kIOPSTimeToFullChargeKey]
|
||||
if (timeToFull != nil) {
|
||||
self.timeToFull = timeToFull as! Int
|
||||
}
|
||||
|
||||
let isCharged = psDesc[kIOPSIsChargedKey]
|
||||
if (isCharged != nil) {
|
||||
self.isCharged = isCharged as! Bool
|
||||
}
|
||||
|
||||
let isCharging = psDesc[kIOPSIsChargingKey]
|
||||
if (isCharging != nil) {
|
||||
self.isCharging = isCharging as! Bool
|
||||
}
|
||||
|
||||
let ACPower = psDesc[kIOPSPowerSourceStateKey]
|
||||
if (ACPower != nil) {
|
||||
self.ACPower = ACPower as! String
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getFormattedTime(time: Int) -> String {
|
||||
if (time > 0) {
|
||||
let timeFormatted = NSString(format: " %d:%02d", time / 60, time % 60) as String
|
||||
return timeFormatted
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
public func formattedInfo() -> NSAttributedString {
|
||||
var title = ""
|
||||
self.getPSInfo()
|
||||
|
||||
if ACPower == "AC Power" {
|
||||
if current < 100 {
|
||||
title += "⚡️"
|
||||
}
|
||||
timeRemaining = getFormattedTime(time: timeToFull)
|
||||
} else {
|
||||
timeRemaining = getFormattedTime(time: timeToEmpty)
|
||||
}
|
||||
|
||||
title += String(current) + "%"
|
||||
|
||||
var color = NSColor.white
|
||||
if current <= 10 && ACPower != "AC Power" {
|
||||
color = NSColor.red
|
||||
}
|
||||
|
||||
let newTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: NSFont.systemFont(ofSize: 15), .baselineOffset: 1])
|
||||
let newTitleSecond = NSMutableAttributedString(string: timeRemaining as String, attributes: [NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.font: NSFont.systemFont(ofSize: 8, weight: .regular), NSAttributedStringKey.baselineOffset: 7])
|
||||
newTitle.append(newTitleSecond)
|
||||
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
|
||||
return newTitle
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import Cocoa
|
||||
import AppKit
|
||||
import AVFoundation
|
||||
import CoreAudio
|
||||
|
||||
class BrightnessViewController: NSCustomTouchBarItem {
|
||||
private(set) var sliderItem: CustomSlider!
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, refreshInterval: Double, image: NSImage? = nil) {
|
||||
super.init(identifier: identifier)
|
||||
|
||||
if (image == nil) {
|
||||
sliderItem = CustomSlider()
|
||||
} else {
|
||||
sliderItem = CustomSlider(knob: image!)
|
||||
}
|
||||
sliderItem.target = self
|
||||
sliderItem.action = #selector(BrightnessViewController.sliderValueChanged(_:))
|
||||
sliderItem.minValue = 0.0
|
||||
sliderItem.maxValue = 100.0
|
||||
sliderItem.floatValue = getBrightness()*100
|
||||
|
||||
self.view = sliderItem
|
||||
|
||||
let timer = Timer.scheduledTimer(timeInterval: refreshInterval, target: self, selector: #selector(BrightnessViewController.updateBrightnessSlider), userInfo: nil, repeats: true)
|
||||
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
deinit {
|
||||
sliderItem.unbind(NSBindingName.value)
|
||||
}
|
||||
|
||||
@objc func updateBrightnessSlider() {
|
||||
DispatchQueue.main.async {
|
||||
self.sliderItem.floatValue = self.getBrightness() * 100
|
||||
}
|
||||
}
|
||||
|
||||
@objc func sliderValueChanged(_ sender: Any) {
|
||||
if let sliderItem = sender as? NSSlider {
|
||||
setBrightness(level: Float32(sliderItem.intValue)/100.0)
|
||||
}
|
||||
}
|
||||
|
||||
private func getBrightness() -> Float32 {
|
||||
var level: Float32 = 0.5
|
||||
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
|
||||
|
||||
IODisplayGetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, &level)
|
||||
return level
|
||||
}
|
||||
|
||||
private func setBrightness(level: Float) {
|
||||
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
|
||||
|
||||
IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, level)
|
||||
IOObjectRelease(service)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//
|
||||
// CurrencyBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Daniel Apatin on 18.04.2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import CoreLocation
|
||||
|
||||
class CurrencyBarItem: CustomButtonTouchBarItem {
|
||||
private let activity: NSBackgroundActivityScheduler
|
||||
private var prefix: String
|
||||
private var from: String
|
||||
private var to: String
|
||||
private var oldValue: Float32!
|
||||
|
||||
private let currencies = [
|
||||
"USD": "$",
|
||||
"EUR": "€",
|
||||
"RUB": "₽",
|
||||
"JPY": "¥",
|
||||
"GBP": "₤",
|
||||
"CAD": "$",
|
||||
"KRW": "₩",
|
||||
"CNY": "¥",
|
||||
"AUD": "$",
|
||||
"BRL": "R$",
|
||||
"IDR": "Rp",
|
||||
"MXN": "$",
|
||||
"SGD": "$",
|
||||
"CHF": "Fr.",
|
||||
"BTC": "฿",
|
||||
"LTC": "Ł",
|
||||
"ETH": "Ξ",
|
||||
]
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval, from: String, to: String) {
|
||||
activity = NSBackgroundActivityScheduler(identifier: "\(identifier.rawValue).updatecheck")
|
||||
activity.interval = interval
|
||||
self.from = from
|
||||
self.to = to
|
||||
|
||||
if let prefix = currencies[from] {
|
||||
self.prefix = prefix
|
||||
} else {
|
||||
self.prefix = from
|
||||
}
|
||||
|
||||
super.init(identifier: identifier, title: "⏳")
|
||||
|
||||
activity.repeats = true
|
||||
activity.qualityOfService = .utility
|
||||
activity.schedule { (completion: NSBackgroundActivityScheduler.CompletionHandler) in
|
||||
self.updateCurrency()
|
||||
completion(NSBackgroundActivityScheduler.Result.finished)
|
||||
}
|
||||
updateCurrency()
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
@objc func updateCurrency() {
|
||||
let urlRequest = URLRequest(url: URL(string: "https://api.coinbase.com/v2/exchange-rates?currency=\(from)")!)
|
||||
|
||||
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
|
||||
if error == nil {
|
||||
do {
|
||||
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
|
||||
var value: Float32!
|
||||
|
||||
if let data_array = json["data"] as? [String : AnyObject] {
|
||||
if let rates = data_array["rates"] as? [String : AnyObject] {
|
||||
if let item = rates["\(self.to)"] as? String {
|
||||
value = Float32(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
if value != nil {
|
||||
DispatchQueue.main.async {
|
||||
self.setCurrency(value: value!)
|
||||
}
|
||||
}
|
||||
} catch let jsonError {
|
||||
print(jsonError.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task.resume()
|
||||
}
|
||||
|
||||
func setCurrency(value: Float32) {
|
||||
var color = NSColor.white
|
||||
|
||||
if let oldValue = self.oldValue {
|
||||
if oldValue < value {
|
||||
color = NSColor.green
|
||||
} else if oldValue > value {
|
||||
color = NSColor.red
|
||||
}
|
||||
}
|
||||
self.oldValue = value
|
||||
|
||||
let title = String(format: "%@%.2f", self.prefix, value)
|
||||
|
||||
let regularFont = self.attributedTitle.attribute(.font, at: 0, effectiveRange: nil) as? NSFont ?? NSFont.systemFont(ofSize: 15)
|
||||
let newTitle = NSMutableAttributedString(string: title as String, attributes: [.foregroundColor: color, .font: regularFont])
|
||||
newTitle.setAlignment(.center, range: NSRange(location: 0, length: title.count))
|
||||
self.attributedTitle = newTitle
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//
|
||||
// GroupBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Daniel Apatin on 11.05.2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
import Cocoa
|
||||
|
||||
class GroupBarItem: NSPopoverTouchBarItem, NSTouchBarDelegate {
|
||||
|
||||
var jsonItems: [BarItemDefinition]
|
||||
|
||||
var itemDefinitions: [NSTouchBarItem.Identifier: BarItemDefinition] = [:]
|
||||
var items: [NSTouchBarItem.Identifier: NSTouchBarItem] = [:]
|
||||
var leftIdentifiers: [NSTouchBarItem.Identifier] = []
|
||||
var centerIdentifiers: [NSTouchBarItem.Identifier] = []
|
||||
var centerItems: [NSTouchBarItem] = []
|
||||
var rightIdentifiers: [NSTouchBarItem.Identifier] = []
|
||||
var scrollArea: NSCustomTouchBarItem?
|
||||
var centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, items: [BarItemDefinition]) {
|
||||
jsonItems = items
|
||||
super.init(identifier: identifier)
|
||||
self.popoverTouchBar.delegate = self
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
}
|
||||
|
||||
@objc override func showPopover(_ sender: Any?) {
|
||||
self.itemDefinitions = [:]
|
||||
self.items = [:]
|
||||
self.leftIdentifiers = []
|
||||
self.centerItems = []
|
||||
self.rightIdentifiers = []
|
||||
|
||||
self.loadItemDefinitions(jsonItems: jsonItems)
|
||||
self.createItems()
|
||||
|
||||
centerItems = centerIdentifiers.compactMap({ (identifier) -> NSTouchBarItem? in
|
||||
return items[identifier]
|
||||
})
|
||||
|
||||
self.centerScrollArea = NSTouchBarItem.Identifier("com.toxblh.mtmr.scrollArea.".appending(UUID().uuidString))
|
||||
self.scrollArea = ScrollViewItem(identifier: centerScrollArea, items: centerItems)
|
||||
|
||||
TouchBarController.shared.touchBar.delegate = self
|
||||
TouchBarController.shared.touchBar.defaultItemIdentifiers = []
|
||||
TouchBarController.shared.touchBar.defaultItemIdentifiers = self.leftIdentifiers + [centerScrollArea] + self.rightIdentifiers
|
||||
|
||||
if TouchBarController.shared.controlStripState {
|
||||
presentSystemModal(TouchBarController.shared.touchBar, systemTrayItemIdentifier: .controlStripItem)
|
||||
} else {
|
||||
presentSystemModal(TouchBarController.shared.touchBar, placement: 1, systemTrayItemIdentifier: .controlStripItem)
|
||||
}
|
||||
}
|
||||
|
||||
func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
|
||||
if identifier == centerScrollArea {
|
||||
return self.scrollArea
|
||||
}
|
||||
|
||||
guard let item = self.items[identifier],
|
||||
let definition = self.itemDefinitions[identifier],
|
||||
definition.align != .center else {
|
||||
return nil
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
func loadItemDefinitions(jsonItems: [BarItemDefinition]) {
|
||||
let dateFormatter = DateFormatter()
|
||||
dateFormatter.dateFormat = "HH-mm-ss"
|
||||
let time = dateFormatter.string(from: Date())
|
||||
for item in jsonItems {
|
||||
let identifierString = item.type.identifierBase.appending(time + "--" + UUID().uuidString)
|
||||
let identifier = NSTouchBarItem.Identifier(identifierString)
|
||||
itemDefinitions[identifier] = item
|
||||
if item.align == .left {
|
||||
leftIdentifiers.append(identifier)
|
||||
}
|
||||
if item.align == .right {
|
||||
rightIdentifiers.append(identifier)
|
||||
}
|
||||
if item.align == .center {
|
||||
centerIdentifiers.append(identifier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createItems() {
|
||||
for (identifier, definition) in self.itemDefinitions {
|
||||
self.items[identifier] = TouchBarController.shared.createItem(forIdentifier: identifier, definition: definition)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//
|
||||
// InputSourceBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Daniel Apatin on 22.04.2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
|
||||
class InputSourceBarItem: CustomButtonTouchBarItem {
|
||||
|
||||
fileprivate var notificationCenter: CFNotificationCenter
|
||||
let buttonSize = NSSize(width: 21, height: 21)
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier) {
|
||||
notificationCenter = CFNotificationCenterGetDistributedCenter();
|
||||
super.init(identifier: identifier, title: "⏳")
|
||||
|
||||
observeIputSourceChangedNotification();
|
||||
textInputSourceDidChange()
|
||||
self.tapClosure = { [weak self] in
|
||||
self?.switchInputSource()
|
||||
}
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
deinit {
|
||||
CFNotificationCenterRemoveEveryObserver(notificationCenter, UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()));
|
||||
}
|
||||
|
||||
@objc public func textInputSourceDidChange() {
|
||||
let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()
|
||||
|
||||
var iconImage: NSImage? = nil
|
||||
|
||||
if let imageURL = currentSource.iconImageURL,
|
||||
let image = NSImage(contentsOf: imageURL) {
|
||||
iconImage = image
|
||||
} else if let iconRef = currentSource.iconRef {
|
||||
iconImage = NSImage(iconRef: iconRef)
|
||||
}
|
||||
|
||||
if let iconImage = iconImage {
|
||||
iconImage.size = buttonSize
|
||||
self.image = iconImage
|
||||
self.title = ""
|
||||
} else {
|
||||
self.title = currentSource.name
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func switchInputSource() {
|
||||
var inputSources: [TISInputSource] = []
|
||||
|
||||
let currentSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()
|
||||
let inputSourceNSArray = TISCreateInputSourceList(nil, false).takeRetainedValue() as NSArray
|
||||
let elements = inputSourceNSArray as! [TISInputSource]
|
||||
|
||||
inputSources = elements.filter({
|
||||
$0.category == TISInputSource.Category.keyboardInputSource && $0.isSelectable
|
||||
})
|
||||
|
||||
for item in inputSources {
|
||||
if (item.id != currentSource.id) {
|
||||
TISSelectInputSource(item)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc public func observeIputSourceChangedNotification(){
|
||||
let callback: CFNotificationCallback = { center, observer, name, object, info in
|
||||
let mySelf = Unmanaged<InputSourceBarItem>.fromOpaque(observer!).takeUnretainedValue()
|
||||
mySelf.textInputSourceDidChange()
|
||||
}
|
||||
|
||||
CFNotificationCenterAddObserver(notificationCenter,
|
||||
UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()),
|
||||
callback,
|
||||
kTISNotifySelectedKeyboardInputSourceChanged,
|
||||
nil,
|
||||
.deliverImmediately)
|
||||
}
|
||||
}
|
||||
|
||||
extension TISInputSource {
|
||||
enum Category {
|
||||
static var keyboardInputSource: String {
|
||||
return kTISCategoryKeyboardInputSource as String
|
||||
}
|
||||
}
|
||||
|
||||
private func getProperty(_ key: CFString) -> AnyObject? {
|
||||
let cfType = TISGetInputSourceProperty(self, key)
|
||||
if (cfType != nil) {
|
||||
return Unmanaged<AnyObject>.fromOpaque(cfType!).takeUnretainedValue()
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var id: String {
|
||||
return getProperty(kTISPropertyInputSourceID) as! String
|
||||
}
|
||||
|
||||
var name: String {
|
||||
return getProperty(kTISPropertyLocalizedName) as! String
|
||||
}
|
||||
|
||||
var category: String {
|
||||
return getProperty(kTISPropertyInputSourceCategory) as! String
|
||||
}
|
||||
|
||||
var isSelectable: Bool {
|
||||
return getProperty(kTISPropertyInputSourceIsSelectCapable) as! Bool
|
||||
}
|
||||
|
||||
var sourceLanguages: [String] {
|
||||
return getProperty(kTISPropertyInputSourceLanguages) as! [String]
|
||||
}
|
||||
|
||||
var iconImageURL: URL? {
|
||||
return getProperty(kTISPropertyIconImageURL) as! URL?
|
||||
}
|
||||
|
||||
var iconRef: IconRef? {
|
||||
return OpaquePointer(TISGetInputSourceProperty(self, kTISPropertyIconRef)) as IconRef?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
//
|
||||
// MusicBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Daniel Apatin on 05.05.2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import ScriptingBridge
|
||||
|
||||
class MusicBarItem: CustomButtonTouchBarItem {
|
||||
private let interval: TimeInterval
|
||||
private var songTitle: String?
|
||||
private var timer: Timer?
|
||||
let buttonSize = NSSize(width: 21, height: 21)
|
||||
|
||||
let playerBundleIdentifiers = [
|
||||
"com.apple.iTunes",
|
||||
"com.spotify.client",
|
||||
"com.coppertino.Vox",
|
||||
"com.google.Chrome",
|
||||
"com.apple.Safari"
|
||||
]
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval) {
|
||||
self.interval = interval
|
||||
|
||||
super.init(identifier: identifier, title: "⏳")
|
||||
self.isBordered = false
|
||||
|
||||
self.tapClosure = { [weak self] in self?.playPause() }
|
||||
self.longTapClosure = { [weak self] in self?.nextTrack() }
|
||||
|
||||
self.refreshAndSchedule()
|
||||
}
|
||||
|
||||
@objc func marquee(){
|
||||
let str = self.title
|
||||
if (str.count > 10) {
|
||||
let indexFirst = str.index(str.startIndex, offsetBy: 0)
|
||||
let indexSecond = str.index(str.startIndex, offsetBy: 1)
|
||||
self.title = String(str.suffix(from: indexSecond)) + String(str[indexFirst])
|
||||
}
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
@objc func playPause() {
|
||||
for ident in playerBundleIdentifiers {
|
||||
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
||||
if (musicPlayer.isRunning) {
|
||||
if (musicPlayer.className == "SpotifyApplication") {
|
||||
let mp = (musicPlayer as SpotifyApplication)
|
||||
mp.playpause!()
|
||||
return
|
||||
} else if (musicPlayer.className == "ITunesApplication") {
|
||||
let mp = (musicPlayer as iTunesApplication)
|
||||
mp.playpause!()
|
||||
return
|
||||
} else if (musicPlayer.className == "VOXApplication") {
|
||||
let mp = (musicPlayer as VoxApplication)
|
||||
mp.playpause!()
|
||||
return
|
||||
} else if (musicPlayer.className == "SafariApplication") {
|
||||
// You must enable the 'Allow JavaScript from Apple Events' option in Safari's Develop menu to use 'do JavaScript'.
|
||||
let safariApplication = musicPlayer as SafariApplication
|
||||
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
||||
for window in safariWindows! {
|
||||
for tab in window.tabs!() {
|
||||
let tab = tab as! SafariTab
|
||||
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_play')[0].click()", in: tab)
|
||||
return
|
||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('audio_page_player_play')[0].click()", in: tab)
|
||||
return
|
||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||
_ = safariApplication.doJavaScript!("document.getElementById('movie_player').click()", in: tab)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// else if (musicPlayer.className == "GoogleChromeApplication") {
|
||||
// let chromeApplication = musicPlayer as GoogleChromeApplication
|
||||
// let chromeWindows = chromeApplication.windows?().compactMap({ $0 as? GoogleChromeWindow })
|
||||
// for window in chromeWindows! {
|
||||
// for tab in window.tabs!() {
|
||||
// let tab = tab as! GoogleChromeTab
|
||||
// if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||
// chromeApplication.executeJavaScript!(javascript: "document.getElementsByClassName('player-controls__btn_play')[0].click()")
|
||||
// break
|
||||
// } else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
||||
// chromeApplication.executeJavaScript!(javascript: "document.getElementsByClassName('audio_page_player_ctrl')[0].click()")
|
||||
// break
|
||||
// } else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||
// chromeApplication.executeJavaScript!(javascript: "alert(document.title)") // , id: tab
|
||||
// break // document.getElementById('movie_player').click()
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc func nextTrack() {
|
||||
for ident in playerBundleIdentifiers {
|
||||
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
||||
if (musicPlayer.isRunning) {
|
||||
if (musicPlayer.className == "SpotifyApplication") {
|
||||
let mp = (musicPlayer as SpotifyApplication)
|
||||
mp.nextTrack!()
|
||||
updatePlayer()
|
||||
return
|
||||
} else if (musicPlayer.className == "ITunesApplication") {
|
||||
let mp = (musicPlayer as iTunesApplication)
|
||||
mp.nextTrack!()
|
||||
updatePlayer()
|
||||
return
|
||||
} else if (musicPlayer.className == "VOXApplication") {
|
||||
let mp = (musicPlayer as VoxApplication)
|
||||
mp.next!()
|
||||
updatePlayer()
|
||||
return
|
||||
} else if (musicPlayer.className == "SafariApplication") {
|
||||
// You must enable the 'Allow JavaScript from Apple Events' option in Safari's Develop menu to use 'do JavaScript'.
|
||||
let safariApplication = musicPlayer as SafariApplication
|
||||
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
||||
for window in safariWindows! {
|
||||
for tab in window.tabs!() {
|
||||
let tab = tab as! SafariTab
|
||||
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('player-controls__btn_next')[0].click()", in: tab)
|
||||
updatePlayer()
|
||||
return
|
||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('audio_page_player_next')[0].click()", in: tab)
|
||||
updatePlayer()
|
||||
return
|
||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||
_ = safariApplication.doJavaScript!("document.getElementsByClassName('ytp-next-button')[0].click()", in: tab)
|
||||
updatePlayer()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func refreshAndSchedule() {
|
||||
DispatchQueue.main.async {
|
||||
self.updatePlayer()
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + self.interval) { [weak self] in
|
||||
self?.refreshAndSchedule()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func updatePlayer() {
|
||||
var iconUpdated = false
|
||||
var titleUpdated = false
|
||||
|
||||
for var ident in playerBundleIdentifiers {
|
||||
if let musicPlayer = SBApplication(bundleIdentifier: ident) {
|
||||
if (musicPlayer.isRunning) {
|
||||
var tempTitle = ""
|
||||
if (musicPlayer.className == "SpotifyApplication") {
|
||||
tempTitle = (musicPlayer as SpotifyApplication).title
|
||||
} else if (musicPlayer.className == "ITunesApplication") {
|
||||
tempTitle = (musicPlayer as iTunesApplication).title
|
||||
} else if (musicPlayer.className == "VOXApplication") {
|
||||
tempTitle = (musicPlayer as VoxApplication).title
|
||||
} else if (musicPlayer.className == "SafariApplication") {
|
||||
let safariApplication = musicPlayer as SafariApplication
|
||||
let safariWindows = safariApplication.windows?().compactMap({ $0 as? SafariWindow })
|
||||
for window in safariWindows! {
|
||||
for tab in window.tabs!() {
|
||||
let tab = tab as! SafariTab
|
||||
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||
// if (!(tab.name?.hasSuffix("на Яндекс.Музыке"))!) {
|
||||
tempTitle = (tab.name)!
|
||||
break
|
||||
// }
|
||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
||||
tempTitle = (tab.name)!
|
||||
break
|
||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||
tempTitle = (tab.name)!
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if tempTitle == "" {
|
||||
ident = ""
|
||||
}
|
||||
} else if (musicPlayer.className == "GoogleChromeApplication") {
|
||||
let chromeApplication = musicPlayer as GoogleChromeApplication
|
||||
let chromeWindows = chromeApplication.windows?().compactMap({ $0 as? GoogleChromeWindow })
|
||||
for window in chromeWindows! {
|
||||
for tab in window.tabs!() {
|
||||
let tab = tab as! GoogleChromeTab
|
||||
if (tab.URL?.starts(with: "https://music.yandex.ru"))! {
|
||||
if (!(tab.title?.hasSuffix("на Яндекс.Музыке"))!) {
|
||||
tempTitle = tab.title!
|
||||
break
|
||||
}
|
||||
} else if ((tab.URL?.starts(with: "https://vk.com/audios"))! || (tab.URL?.starts(with: "https://vk.com/music"))!) {
|
||||
tempTitle = tab.title!
|
||||
break
|
||||
} else if (tab.URL?.starts(with: "https://www.youtube.com/watch"))! {
|
||||
tempTitle = tab.title!
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if tempTitle == "" {
|
||||
ident = ""
|
||||
}
|
||||
}
|
||||
|
||||
if (tempTitle == self.songTitle) {
|
||||
return
|
||||
} else {
|
||||
self.songTitle = tempTitle
|
||||
}
|
||||
|
||||
if let songTitle = self.songTitle?.ifNotEmpty {
|
||||
self.title = " " + songTitle + " "
|
||||
titleUpdated = true
|
||||
self.timer?.invalidate()
|
||||
self.timer = nil
|
||||
self.timer = Timer.scheduledTimer(timeInterval: 0.25, target: self, selector: #selector(self.marquee), userInfo: nil, repeats: true)
|
||||
}
|
||||
if let ident = ident.ifNotEmpty,
|
||||
let appPath = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: ident) {
|
||||
let image = NSWorkspace.shared.icon(forFile: appPath)
|
||||
image.size = self.buttonSize
|
||||
self.image = image
|
||||
iconUpdated = true
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DispatchQueue.main.async {
|
||||
if !iconUpdated {
|
||||
self.image = nil
|
||||
}
|
||||
|
||||
if !titleUpdated {
|
||||
self.title = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc protocol SpotifyApplication {
|
||||
@objc optional var currentTrack: SpotifyTrack {get}
|
||||
@objc optional func nextTrack()
|
||||
@objc optional func previousTrack()
|
||||
@objc optional func playpause()
|
||||
}
|
||||
extension SBApplication: SpotifyApplication{}
|
||||
|
||||
@objc protocol SpotifyTrack {
|
||||
@objc optional var artist: String {get}
|
||||
@objc optional var name: String {get}
|
||||
}
|
||||
extension SBObject: SpotifyTrack{}
|
||||
|
||||
extension SpotifyApplication {
|
||||
var title: String {
|
||||
guard let t = currentTrack else { return "" }
|
||||
return (t.artist ?? "") + " — " + (t.name ?? "")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@objc protocol iTunesApplication {
|
||||
@objc optional var currentTrack: iTunesTrack {get}
|
||||
@objc optional func playpause()
|
||||
@objc optional func nextTrack()
|
||||
@objc optional func previousTrack()
|
||||
}
|
||||
extension SBApplication: iTunesApplication{}
|
||||
|
||||
@objc protocol iTunesTrack {
|
||||
@objc optional var artist: String {get}
|
||||
@objc optional var name: String {get}
|
||||
}
|
||||
extension SBObject: iTunesTrack{}
|
||||
|
||||
extension iTunesApplication {
|
||||
var title: String {
|
||||
guard let t = currentTrack else { return "" }
|
||||
return (t.artist ?? "") + " — " + (t.name ?? "")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@objc protocol VoxApplication {
|
||||
@objc optional func playpause()
|
||||
@objc optional func next()
|
||||
@objc optional func previous()
|
||||
@objc optional var track: String {get}
|
||||
@objc optional var artist: String {get}
|
||||
}
|
||||
extension SBApplication: VoxApplication{}
|
||||
|
||||
extension VoxApplication {
|
||||
var title: String {
|
||||
return (artist ?? "") + " — " + (track ?? "")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@objc public protocol SBObjectProtocol: NSObjectProtocol {
|
||||
func get() -> Any!
|
||||
}
|
||||
|
||||
@objc public protocol SBApplicationProtocol: SBObjectProtocol {
|
||||
func activate()
|
||||
var delegate: SBApplicationDelegate! { get set }
|
||||
}
|
||||
|
||||
@objc public protocol SafariApplication: SBApplicationProtocol {
|
||||
@objc optional func windows() -> SBElementArray
|
||||
@objc optional func doJavaScript(_ x: String!, in in_: Any!) -> Any // Applies a string of JavaScript code to a document.
|
||||
}
|
||||
extension SBApplication: SafariApplication {}
|
||||
|
||||
@objc public protocol SafariWindow: SBObjectProtocol {
|
||||
@objc optional var name: String { get } // The title of the window.
|
||||
@objc optional func tabs() -> SBElementArray
|
||||
// @objc optional var document: SafariDocument { get } // The document whose contents are displayed in the window.
|
||||
// @objc optional func setCurrentTab(_ currentTab: SafariTab!) // The current tab.
|
||||
}
|
||||
extension SBObject: SafariWindow {}
|
||||
|
||||
//@objc public protocol SafariDocument: SBObjectProtocol {
|
||||
// @objc optional var name: String { get } // Its name.
|
||||
// @objc optional var URL: String { get } // The current URL of the document.
|
||||
//}
|
||||
//extension SBObject: SafariDocument {}
|
||||
|
||||
@objc public protocol SafariTab: SBObjectProtocol {
|
||||
@objc optional var URL: String { get } // The current URL of the tab.
|
||||
@objc optional var name: String { get } // The name of the tab.
|
||||
}
|
||||
extension SBObject: SafariTab {}
|
||||
|
||||
|
||||
|
||||
@objc public protocol GoogleChromeApplication: SBApplicationProtocol {
|
||||
@objc optional func windows() -> SBElementArray
|
||||
@objc optional func executeJavaScript(javascript: String!) -> Any // Applies a string of JavaScript code to a document. //, id: Any!
|
||||
}
|
||||
extension SBApplication: GoogleChromeApplication {}
|
||||
|
||||
@objc public protocol GoogleChromeWindow: SBObjectProtocol {
|
||||
@objc optional var name: String { get } // The title of the window.
|
||||
@objc optional func tabs() -> SBElementArray
|
||||
}
|
||||
extension SBObject: GoogleChromeWindow {}
|
||||
|
||||
@objc public protocol GoogleChromeTab: SBObjectProtocol {
|
||||
@objc optional var URL: String { get } // The current URL of the tab.
|
||||
@objc optional var title: String { get } // The name of the tab.
|
||||
}
|
||||
extension SBObject: GoogleChromeTab {}
|
||||
@@ -1,16 +1,14 @@
|
||||
import Cocoa
|
||||
|
||||
class TimeTouchBarItem: NSCustomTouchBarItem {
|
||||
class TimeTouchBarItem: CustomButtonTouchBarItem {
|
||||
private let dateFormatter = DateFormatter()
|
||||
private var timer: Timer!
|
||||
private let button = NSButton(title: "", target: nil, action: nil)
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, formatTemplate: String) {
|
||||
dateFormatter.setLocalizedDateFormatFromTemplate(formatTemplate)
|
||||
super.init(identifier: identifier)
|
||||
super.init(identifier: identifier, title: " ")
|
||||
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
|
||||
self.view = button
|
||||
button.bezelColor = .clear
|
||||
self.isBordered = false
|
||||
updateTime()
|
||||
}
|
||||
|
||||
@@ -19,7 +17,7 @@ class TimeTouchBarItem: NSCustomTouchBarItem {
|
||||
}
|
||||
|
||||
@objc func updateTime() {
|
||||
button.title = self.dateFormatter.string(from: Date())
|
||||
self.title = self.dateFormatter.string(from: Date())
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import Cocoa
|
||||
import AppKit
|
||||
import AVFoundation
|
||||
import CoreAudio
|
||||
|
||||
class VolumeViewController: NSCustomTouchBarItem {
|
||||
private(set) var sliderItem: CustomSlider!
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, image: NSImage? = nil) {
|
||||
super.init(identifier: identifier)
|
||||
|
||||
var forPropertyAddress = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
|
||||
mScope: kAudioDevicePropertyScopeOutput,
|
||||
mElement: kAudioObjectPropertyElementMaster)
|
||||
|
||||
AudioObjectAddPropertyListenerBlock(defaultDeviceID, &forPropertyAddress, nil, audioObjectPropertyListenerBlock)
|
||||
|
||||
if (image == nil) {
|
||||
sliderItem = CustomSlider()
|
||||
} else {
|
||||
sliderItem = CustomSlider(knob: image!)
|
||||
}
|
||||
sliderItem.target = self
|
||||
sliderItem.action = #selector(VolumeViewController.sliderValueChanged(_:))
|
||||
sliderItem.minValue = 0.0
|
||||
sliderItem.maxValue = 100.0
|
||||
sliderItem.floatValue = getInputGain()*100
|
||||
|
||||
self.view = sliderItem
|
||||
}
|
||||
|
||||
func audioObjectPropertyListenerBlock (numberAddresses: UInt32, addresses: UnsafePointer<AudioObjectPropertyAddress>) {
|
||||
DispatchQueue.main.async {
|
||||
self.sliderItem.floatValue = self.getInputGain() * 100
|
||||
}
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
deinit {
|
||||
sliderItem.unbind(NSBindingName.value)
|
||||
}
|
||||
|
||||
@objc func sliderValueChanged(_ sender: Any) {
|
||||
if let sliderItem = sender as? NSSlider {
|
||||
_ = setInputGain(Float32(sliderItem.intValue)/100.0)
|
||||
}
|
||||
}
|
||||
|
||||
private var defaultDeviceID: AudioObjectID {
|
||||
var deviceID: AudioObjectID = AudioObjectID(0)
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioObjectID>.size)
|
||||
var address: AudioObjectPropertyAddress = AudioObjectPropertyAddress()
|
||||
address.mSelector = AudioObjectPropertySelector(kAudioHardwarePropertyDefaultOutputDevice)
|
||||
address.mScope = AudioObjectPropertyScope(kAudioObjectPropertyScopeGlobal)
|
||||
address.mElement = AudioObjectPropertyElement(kAudioObjectPropertyElementMaster)
|
||||
AudioObjectGetPropertyData(AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &size, &deviceID)
|
||||
return deviceID
|
||||
}
|
||||
|
||||
private func getInputGain() -> Float32 {
|
||||
var volume: Float32 = 0.5
|
||||
var size: UInt32 = UInt32(MemoryLayout.size(ofValue: volume))
|
||||
var address: AudioObjectPropertyAddress = AudioObjectPropertyAddress()
|
||||
address.mSelector = AudioObjectPropertySelector(kAudioHardwareServiceDeviceProperty_VirtualMasterVolume)
|
||||
address.mScope = AudioObjectPropertyScope(kAudioDevicePropertyScopeOutput)
|
||||
address.mElement = AudioObjectPropertyElement(kAudioObjectPropertyElementMaster)
|
||||
AudioObjectGetPropertyData(defaultDeviceID, &address, 0, nil, &size, &volume)
|
||||
return volume
|
||||
}
|
||||
|
||||
private func setInputGain(_ volume: Float32) -> OSStatus {
|
||||
var inputVolume: Float32 = volume
|
||||
|
||||
if inputVolume == 0.0 {
|
||||
_ = setMute( mute: 1)
|
||||
} else {
|
||||
_ = setMute( mute: 0)
|
||||
}
|
||||
|
||||
let size: UInt32 = UInt32(MemoryLayout.size(ofValue: inputVolume))
|
||||
var address: AudioObjectPropertyAddress = AudioObjectPropertyAddress()
|
||||
address.mScope = AudioObjectPropertyScope(kAudioDevicePropertyScopeOutput)
|
||||
address.mElement = AudioObjectPropertyElement(kAudioObjectPropertyElementMaster)
|
||||
address.mSelector = AudioObjectPropertySelector(kAudioHardwareServiceDeviceProperty_VirtualMasterVolume)
|
||||
return AudioObjectSetPropertyData(defaultDeviceID, &address, 0, nil, size, &inputVolume)
|
||||
}
|
||||
|
||||
private func setMute( mute: Int) -> OSStatus {
|
||||
var muteVal: Int = mute
|
||||
var address: AudioObjectPropertyAddress = AudioObjectPropertyAddress()
|
||||
address.mSelector = AudioObjectPropertySelector(kAudioDevicePropertyMute)
|
||||
let size: UInt32 = UInt32(MemoryLayout.size(ofValue: muteVal))
|
||||
address.mScope = AudioObjectPropertyScope(kAudioDevicePropertyScopeOutput)
|
||||
address.mElement = AudioObjectPropertyElement(kAudioObjectPropertyElementMaster)
|
||||
return AudioObjectSetPropertyData(defaultDeviceID, &address, 0, nil, size, &muteVal)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//
|
||||
// WeatherBarItem.swift
|
||||
// MTMR
|
||||
//
|
||||
// Created by Daniel Apatin on 18.04.2018.
|
||||
// Copyright © 2018 Anton Palgunov. All rights reserved.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import CoreLocation
|
||||
|
||||
class WeatherBarItem: CustomButtonTouchBarItem, CLLocationManagerDelegate {
|
||||
private let activity: NSBackgroundActivityScheduler
|
||||
private var units: String
|
||||
private var api_key: String
|
||||
private var units_str = "°F"
|
||||
private var prev_location: CLLocation!
|
||||
private var location: CLLocation!
|
||||
private let iconsImages = ["01d": "☀️", "01n": "☀️", "02d": "⛅️", "02n": "⛅️", "03d": "☁️", "03n": "☁️", "04d": "☁️", "04n": "☁️", "09d": "⛅️", "09n": "⛅️", "10d": "🌦", "10n": "🌦", "11d": "🌩", "11n": "🌩", "13d": "❄️", "13n": "❄️", "50d": "🌫", "50n": "🌫"]
|
||||
private let iconsText = ["01d": "☀", "01n": "☀", "02d": "☁", "02n": "☁", "03d": "☁", "03n": "☁", "04d": "☁", "04n": "☁", "09d": "☂", "09n": "☂", "10d": "☂", "10n": "☂", "11d": "☈", "11n": "☈", "13d": "☃", "13n": "☃", "50d": "♨", "50n": "♨"]
|
||||
private var iconsSource: Dictionary<String, String>
|
||||
|
||||
private var manager:CLLocationManager!
|
||||
|
||||
init(identifier: NSTouchBarItem.Identifier, interval: TimeInterval, units: String, api_key: String, icon_type: String? = "text") {
|
||||
activity = NSBackgroundActivityScheduler(identifier: "\(identifier.rawValue).updatecheck")
|
||||
activity.interval = interval
|
||||
self.units = units
|
||||
self.api_key = api_key
|
||||
|
||||
if self.units == "metric" {
|
||||
units_str = "°C"
|
||||
}
|
||||
|
||||
if self.units == "imperial" {
|
||||
units_str = "°F"
|
||||
}
|
||||
|
||||
if icon_type == "images" {
|
||||
iconsSource = iconsImages
|
||||
} else {
|
||||
iconsSource = iconsText
|
||||
}
|
||||
|
||||
super.init(identifier: identifier, title: "⏳")
|
||||
|
||||
let status = CLLocationManager.authorizationStatus()
|
||||
if status == .restricted || status == .denied {
|
||||
print("User permission not given")
|
||||
return
|
||||
}
|
||||
|
||||
if !CLLocationManager.locationServicesEnabled() {
|
||||
print("Location services not enabled");
|
||||
return
|
||||
}
|
||||
|
||||
activity.repeats = true
|
||||
activity.qualityOfService = .utility
|
||||
activity.schedule { (completion: NSBackgroundActivityScheduler.CompletionHandler) in
|
||||
self.updateWeather()
|
||||
completion(NSBackgroundActivityScheduler.Result.finished)
|
||||
}
|
||||
updateWeather()
|
||||
|
||||
manager = CLLocationManager()
|
||||
manager.delegate = self
|
||||
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
|
||||
manager.startUpdatingLocation()
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
@objc func updateWeather() {
|
||||
if self.location != nil {
|
||||
let urlRequest = URLRequest(url: URL(string: "https://api.openweathermap.org/data/2.5/weather?lat=\(location.coordinate.latitude)&lon=\(location.coordinate.longitude)&units=\(self.units)&appid=\(self.api_key)")!)
|
||||
|
||||
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
|
||||
|
||||
if error == nil {
|
||||
do {
|
||||
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
|
||||
// print(json)
|
||||
var temperature: Int!
|
||||
var condition_icon = ""
|
||||
|
||||
if let main = json["main"] as? [String : AnyObject] {
|
||||
if let temp = main["temp"] as? Double {
|
||||
temperature = Int(temp)
|
||||
}
|
||||
}
|
||||
|
||||
if let weather = json["weather"] as? NSArray, let item = weather[0] as? NSDictionary {
|
||||
let icon = item["icon"] as! String
|
||||
if let test = self.iconsSource[icon] {
|
||||
condition_icon = test
|
||||
}
|
||||
}
|
||||
|
||||
if temperature != nil {
|
||||
DispatchQueue.main.async {
|
||||
self.setWeather(text: "\(condition_icon) \(temperature!)\(self.units_str)")
|
||||
}
|
||||
}
|
||||
} catch let jsonError {
|
||||
print(jsonError.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task.resume()
|
||||
}
|
||||
}
|
||||
|
||||
func setWeather(text: String) {
|
||||
self.title = text
|
||||
}
|
||||
|
||||
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
|
||||
let lastLocation = locations.last!
|
||||
self.location = lastLocation
|
||||
if prev_location == nil {
|
||||
updateWeather()
|
||||
}
|
||||
prev_location = lastLocation
|
||||
}
|
||||
|
||||
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
|
||||
print(error);
|
||||
}
|
||||
|
||||
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
|
||||
// print("inside didChangeAuthorization ");
|
||||
updateWeather()
|
||||
}
|
||||
|
||||
}
|
||||
+75
-18
@@ -1,22 +1,79 @@
|
||||
[
|
||||
{ "type": "escape" },
|
||||
{ "type": "exitTouchbar" },
|
||||
{ "type": "brightnessDown" },
|
||||
{ "type": "escape", "align": "left" },
|
||||
{ "type": "exitTouchbar", "width": 44, "align": "left" },
|
||||
{ "type": "brightnessDown", "width": 44, "align": "left" },
|
||||
{
|
||||
"type": "staticButton",
|
||||
"title": "🔆",
|
||||
"action": "keyPress",
|
||||
"keycode": 113,
|
||||
"width": 36,
|
||||
"type": "brightness",
|
||||
"width": 60,
|
||||
"align": "left",
|
||||
"image": {
|
||||
"base64":
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAIAAAACAAQMAAAD58POIAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAGUExURffLOPfLNyaSVzUAAAACdFJOU/kBxOqnWgAAAbJJREFUSMfVljtyhDAQBVulQCFH4CgcDR1NR9ERFBKoeA5GfGddtkNvwFINFKP5tED22+Zxwviv6QVKfIEc/iNoF5gkpLIeYI8SUp4PsAUJiekADQntF6isQjvxCTrhAJlFqMMBeIH9BMsD7DAb2BhvYbIyNAOCZIWqYKGTpDZJFQu9EKVd44RxQRq3IrULWD62C8wSssWUZEsR0k6wcDOrJZmoBpMKI+s5qkBQCQOUJADVOECdOsDS0gDbsgHMfT4rVwHSrZQFIN5ABka8BgDgAeZ+BztBgvUEnSgVlhNsTFJjvoF5HAZorBpdYKAiSRbqNyBIUr6AjZMdPwO72R40MElS+wZUWA+wQ6LAYkFvdIhkmA+wQSDDdIAGAZ6A34H0x0fca11gBZZsIHSIfnE/5+NjCn/OuiuUB+/aunZwDeNayjXdTpDN0wlY+r1PfWu75nfj8RogN2JuCN2Y5qgMwTI0wGPUnQw6Qarx0sVNKA5Mn6VUL22lIbZoYitDbPmlvocc9Umfl2D7adz1reC3pF8av4m+DCenp/ndZuG3E7fhuC3pH2+vnz8V3MfE+bnxBTXuuIMTrLWHAAAAAElFTkSuQmCC"
|
||||
}
|
||||
},
|
||||
{ "type": "flexSpace" },
|
||||
{ "type": "volumeDown", "width": 44 },
|
||||
{ "type": "volumeUp", "width": 44 },
|
||||
{ "type": "previous" },
|
||||
{ "type": "play" },
|
||||
{ "type": "next" },
|
||||
{ "type": "weather", "refreshInterval": 1800 },
|
||||
{ "type": "sleep" },
|
||||
{ "type": "battery" },
|
||||
{ "type": "timeButton" },
|
||||
{ "type": "brightnessUp", "width": 44, "align": "left" },
|
||||
{
|
||||
"type": "appleScriptTitledButton",
|
||||
"source": {
|
||||
"inline":
|
||||
"if application \"iTunes\" is running then\rtell application \"iTunes\"\rif player state is playing then\rreturn (get artist of current track) & \" – \" & (get name of current track)\relse\rreturn \"\"\rend if\rend tell\rend if\rreturn \"\"\r"
|
||||
},
|
||||
"action": "appleScript",
|
||||
"actionAppleScript": {
|
||||
"inline":
|
||||
"if application \"iTunes\" is running then\rtell application \"iTunes\"\rif player state is playing then\rnext track\rend if\rend tell\rend if\r"
|
||||
},
|
||||
"refreshInterval": 1,
|
||||
"image": {
|
||||
"base64":
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAADAUExURUdwTOVVZCzB+3qc0gkDBgEBAgcKEwAAAA4EBP5aVU2V95iJv7V3rtBOvH5W6jaOyclScKZGX3wuQCMuUqZN7+NQYXtDvFd9/sxYni2z6UhBhyhvnIp7sf38/PXz9ePm69/k6fHv8/j29+3q7/v6+ufq7uvu8fTw8+1egOFki/dbboVj/HNy/T+j/dNtnEul81vC8Vmf3OeRqOBVofK4xZfF7sDb7PLe6LxU1KKK79PL6vrW3fh4g5Zi4bi16daa0A3Qc90AAAAddFJOUwD3/v0uOlYNG/z+/v7998OYYztt/Le2/eDqi5jEo2rNTwAABMtJREFUWMPdl1tjqjoQhauC0Hqvta26JVxUQBQFRPBS/f//as8kISBqd/twXs5KjBDyrZkEFfP09D+WoigqFxz+mlbVXncweEZVBoNuD1x+E1vtMVZoURn01J/mob52KRNuj4k5mZjJcRueFotFpfv6EwdVRfy0tSdXSranheN0/zkRSB7x42Q6udExdBy3972Fog4o/kBg4X6bhPJaeX7eTqeT6b0MJtPpdOu6n49XQgX+dOQ8vpWEvYn/2AHiL052PpoROcsOtND17ztQ3rwTuCQz9O/moKiMf6BkG/puKBzurKQ64PmbU2bDzUxk3Uql4lZcl3Vpvt9VbxLoLZwjY7E1WcNZoB0XpbELie/3Sg6KVHG2jGPs1LTCE2UXFfgIgtBgyq8d/E/pehJq1zmZGc7kAPsMX4Ec932T25uX5vUklFcHJlDU1OT4wllkvOtn9lrSbF7dCUggNEtaMOXhQZq4WkpBcksJQBCOnyjvM4P8KqQgFW9BFJka2NMKB1gw+VMxvN9smnwI1EuzpxS+g9FWYySjsTpOtnq+H162iW01m/wyXLUPzT/5HKQoSjQmU8vE6TAElvWggbhuNRpScQa002bVtJmBCz9qNusWBkJmoyHmoHajC4yybVujhR26mJVha7lDo2FrhnA4N0aq+BpE24zjgsMoEsfU0AADaKCwemiIRZA+o6N9oygyMi/EAWk0DMNgFvCmN/5IwqCV3PCGzzIwbINrzgwykVq2iorUalm2UTZotXKWqVYz5uBjzDUoxrxWyzKQWy061LZsNIJ3PAMDIcbVauwdGmxrNblgYNnCgStN54ylBSsYoAxerwwgJsCWTS0sepym0Mdp1gYBw5lmwgDXIDEoaeHLYE36BafzuQWFQ9RASM/XQPpMD5YQ2gA/AwPArQJyZWDsgo64C+/pBRkDG4s31hdmwFNAGz1mBjPukBs8qdSgLDBA1LJm1lw/14IgWAdAQ5nhax4HY/FR7qfpHQMPUChzS0c6eFmv17MZo7HZBP3MQJHTNCnzxPMgOFUteAGtMwMmfRPIijBgc+AmNK6+9zw+9Iw05YsG8aaT/7Kro7eUcoSWw3n/1W57SxgGOZCYxl+VDDabcf6LpNTf3g6IQ4XY7TbiyyUBmhqsViswWK02cE7ITIdmtxnWlcJz6f1tPyMsha+2R4UGyJPdywotwGSHOKHdm+IMYA40BRhtkXOb42DAh8crppjw8CyB4nMBlvFtD/0WSfZebkDHguLNar2JdyTXptqRrx6OmMKZkISQc4Yv9yyDXHiiEx1qXL1OAFdhBJPAAQeRQDEiRZEm+kwnu2p1XHo64yQ8j47bL1kCZ87pDKWxuW4mQJ9O9ba31xE5Y/rnA4VoTCJQwvnyBNgk+pkDi8sSJjlKRPxhX7r3Lytz0LPMi1H1Qv7VuzwuAzh4h1ukKFi/YV9+9E8THZbne2Ezxd/xsNGQ6u+wgoeH4SH9Tl367t+2Ko/acA8Oj/DhWP7X/30Zkvj4WMYlj10MOISXf7DlkPvvH6g43u0oCzDS1U5f/sHWC3d7cn3UAQf4HeHfwxXQY4yu/HTDKNXro3Gngw4vw2FnPKrXJfUXu0fqIdeFZOnXm08FTRSxcf391pW7oNGT8vRf6i9jqljwYzAm6AAAAABJRU5ErkJggg=="
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "appleScriptTitledButton",
|
||||
"source": {
|
||||
"inline":
|
||||
"if application \"Spotify\" is running then\rtell application \"Spotify\"\rif player state is playing then\rreturn (get artist of current track) & \" – \" & (get name of current track)\relse\rreturn \"\"\rend if\rend tell\rend if\rreturn \"\"\r"
|
||||
},
|
||||
"action": "appleScript",
|
||||
"actionAppleScript": {
|
||||
"inline":
|
||||
"if application \"Spotify\" is running then\rtell application \"Spotify\"\rif player state is playing then\rnext track\rend if\rend tell\rend if\r"
|
||||
},
|
||||
"refreshInterval": 1,
|
||||
"image": {
|
||||
"base64":
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAYUExURUdwTB3WXx3UXh3VXx7XYBkXFRpVLRyURmIaeAQAAAAEdFJOUwDDO3fSqUUkAAABbklEQVRIx61VbW6DMAztoAeYNA7ApB6gkzhAWS24wIAL0HABaK6/pHFNEhy8TXu/kPzkPD/8cTj8K7KPAqB+K5NhQPCUrABCXe7HOUYYZxgVRLiG8RfY4DUgFFtC7cffAfZTFBwBdhWEKfgEq4ocEjgj4ZQifO6/QG9kkETp1dDeVWfRKx3XYSW0LoqY5kCElXDrQkyeCCuh6WL0M4nIWQIyzqixdfKU1koFDKvyCA8NJMzU4xiD+b4kfHRpsIyKc6hBwjVptFHVY51EMAINNDFGJITKDNQcdpX74Hz0CQ3rY5qwMp4EIxrlafzrsYZ2Veb0DkRgfNCUok4Y1fqEijfyi2b8RE9beWqa48Y/uvCNMcH9btfUi+/CGLR1vhL6Zz9N/vBlaCU+7lwY/cmJ67Ryen/2tj23PLqJBodZH8vgj544vOL4pxfI5acrSFxi8hrkU9TSKr78ZpnL50A8KPJJEo+afBblwyqf5j/iGys5j6ScrST2AAAAAElFTkSuQmCC"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "appleScriptTitledButton",
|
||||
"source": {
|
||||
"inline":
|
||||
"if application \"VOX\" is running then\rtell application \"VOX\"\rif player state is 1 then\rreturn (get artist) & \" – \" & (get track)\relse\rreturn \"\"\rend if\rend tell\rend if\rreturn \"\"\r"
|
||||
},
|
||||
"action": "appleScript",
|
||||
"actionAppleScript": {
|
||||
"inline":
|
||||
"if application \"VOX\" is running then\rtell application \"VOX\"\rif player state is 1 then\rnext\rend if\rend tell\rend if\r"
|
||||
},
|
||||
"refreshInterval": 1,
|
||||
"image": {
|
||||
"base64":
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAADAUExURUdwTHd7gqeqtKClrd/k7n+Di7e7xI6TnNHX4cPI0Xp9hJibpOfs9u/1/vX7/rq/yZiborK3wEpOUxgYFlFXYiIhHycpLD9ESjI0NgsLCj09O4SKk19lcbBkALhoAHJ3gT8rAzMvJJugqKhcAL5xAOSxB4I/AJ5SAGpweXuAiZJJAG8zAeXr9WNiYM+NANqeAMd9APHACfr9/e7JPrO5w6mrsA4bKC0gCHhtTyAYBFcpAZduKK2JP/fost/Eb5SUlFFfi9AAAAASdFJOUwDJE9FgWjb+/vyHppTXtbn9mDupvZ0AAAdoSURBVFjDlZcLQ6O6FoWrtgI+Owl5EGgp2DrEgnV6wD4c7f//V3ftAE7nzOj17NGxpayPtXfSZGcw+CjOh1c3N9eIm5ur4fngv8Xp8KZE+F2U5bq8GZ5+WU5qP6jzsRdTeF7e1AEoN8Ovya/LMsg9mxZJErpIksJarwnK8nr4FblfQ52EDOH0zL1KUuvVfnn9eTVOryCPoVZQuGj/FOApMAhx9Uktzq/L2ksT3FuQhIVVVVRVRa+SogA1KbzgExPD0s/xdBOmKdOqODR95IdEaZba0LAkbfzyg0rA/pgekxZKV4cmtxXTEmFUEufNodIKYJjLkcbf9UEM90mqZJU3qeJRxDkXAv/hlbJNXkmVJjCBNP5CGPq1TZSyiWB5XomIi+woRBSJKj8YUVgFQ4E//FMfQM8s40VTyIhDpLVRNIJKaWLwSNqm4mEMl/YPwrkP/9AbER+UkxtWbbcvLrbbkBlCcDa23BABHn4bi1PSM2a1PFgZwbwJty+TybSLyeRlyxQlIuNY6FgpDKd/PB+uXP2tFHEheCtvhW3Q65dtiEyQRixMrBjG4uo4gTpNFApvU9Kr6sWp77qY3BFj8lLBBJdpykOLwaqPkgioAEnFi1RCz7Z3uJ2U37sgCBB3W5ZJLm0VJQmVIXgfgSAvQpYK1ACDx7bTOT2dlA8uWsYEl0EQ3KDUKcOECvqRCGgGpApXf9M/PNx3QQwyMZ9uGWZWiGelsFAHvQFUMEx4WAku2HZC+k6+vF/ip0U4wmSrBJcFZgss9xZuYYAlWhaGC1PhMb1++R6EaAl3lRFcFUI5C7duDlAFwpCzSogsfCH93fdWvm+jRYCASs5fwkyIinGsVrBAc2FYxwVLlKhgQG3n8+kv/WwjhNhsZvveQ5+EqrhKWOHVlMNtgyUkhHkpdPjy1CZA+pl4bkOIfWcBQ/EEC1xWWmKxsi6HussA9WUwQBV0BmbPz3y32+x2nD8/z/okpvM5LAjGeEg51JiFtQeAEqHhWUIGJq0B0m9mLjYdgSxMnQVhGHIIkcP5YNjEAGjJJDfF5AnzzRnY/9K3hP3SjSUAk0oLzaQOwyJGEb41FgWVuOIymHYZCKfPGFaxzBHEcQ5cYrXD3LHNt8E3WkdDbpBY8vMdMHsW0Jui9v26MCDAggNMAfgZoghGdIDbPMXewY0RWfHzqQMsN2QgC/MAkVcZWZi1DuYAJJlQBlVM0vx2cDZOw4QAPEt/AcTzDgkkh3w8Hh8SPZvtKIc2haefKapo2mE4G5x5nQOuLQA0jwggCcAqF1SFnZQEwEwCwGZ0P+sAXQqa69gBJvgeLCUBhMS6arSWogV0NWwB2gHG5KAggDYO0OXQATghJP4QIPsFiJHCEYB2YgBE5gBzNxEyjVHYcOxKKDfquRE6u39wFXh6dADJaccG4HLsANIIEb89PnaEvSYLG2kYAG0G+3YMnh4fDxbfe4wkAS47gAAyShsA2iSWUgsiYHfJMCF2ZKDVA9AkET4WbhgvB6OxxeoiuZZRVT/2BFjQfOemMX53qNn+e5fA42OtAOCYiYXNR4PznL4LJoLA1G8rQjjCTCmxc9+GzU4oNXvonr9avTUZPc7QdyHH0j4mgIqQVZQHq1VvAgRKf7MRKISZPWAG0ONXq1Vg6WYahMIbYz24pJ6ECYIyf7EiBBGm3/da0c6KX/ifTnv9P74iu66G3iUAI4+KoCNpeNS8rha9ifnkfmlcLO+n816+WL3mEVVcY2ew4xEtqsgBjUWEQkWsfFssWhdgPM0xoBg8iKl2JF8s3kpngCtMo3jsNljkUDAmYQFVWC9+tAgHeQ93AR/8WKw9d6MMWWFdBn0OJsJsjERZLn4QomOsWmmrpk9Kn0eYxpGiMfBG7dZ0FrcW8B2N1PoV9zkEUehn1b2hy68lxg/F0owVaXzW7Y0j6kwZuiqhUIaW8M54F9Olcq0irF0R1vAkfTdAFmwaKhjDUgfCur39n+NwF9ZrFhnMWm5YiM737L0/GHkxtYD4RKIWILz1+jf86/Vv69I4fSTRTNojAxgIdPUgCE7VjXhzhHAEJ1/nUUSl4qTHKeDyuMnCycCzjiCwyUYsWK9fofzhxIC8rtcBi2SlqPeEnu7/rekGwcutwhTHhKoYHlWvEa8u6FVN17D/Or3Ncfu/Wu5R7I2bmNECRiYYRpuaYtKiBa+0u0j9K7aguMFZZvTvVvUCFuoce5ygSmA9xlcRDR8iyzaZqVq50Coc1zBw8WezfBEfmqBGX+8QXLs1HY9tV3aMMeQSp4A6aP6qdx4aNHyMWnxBHbpwzTIW9vadkGTf/1BPdYhxsqrR7zuGoD4/6pp+iKVkaY3zWGxHHx55TuJxXZa1RSmwIyAyeoGVlf4wG9CBLD755Nx1ehHHub9e+3lBpxUh+0DuuO4ef/H5AXR0gkpg+EofjQed1ej8VsTuEk6T8cno/54cRyc2zms3Bcr+4Esvazz9C/IOYWlESNseoWtU3n5V3tYCDEA8tAce5j3enFyc/scT/Pno4qSLi9HHhf8f8eOIRf9lFswAAAAASUVORK5CYII="
|
||||
}
|
||||
},
|
||||
{ "type": "previous", "width": 44 },
|
||||
{ "type": "play", "width": 44 },
|
||||
{ "type": "next", "width": 44 },
|
||||
{ "type": "weather", "icon_type": "images", "units": "metric" },
|
||||
{ "type": "currency", "from": "BTC", "to": "USD" },
|
||||
{ "type": "sleep", "width": 44 },
|
||||
{ "type": "mute", "width": 40, "align": "right" },
|
||||
{ "type": "volumeDown", "width": 34, "align": "right" },
|
||||
{ "type": "volume", "width": 60, "align": "right" },
|
||||
{ "type": "volumeUp", "width": 34, "align": "right" },
|
||||
{ "type": "inputsource", "align": "right" },
|
||||
{ "type": "battery", "align": "right" },
|
||||
{ "type": "timeButton", "align": "right" }
|
||||
]
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import XCTest
|
||||
|
||||
class AppleScriptDefinitionTests: XCTestCase {
|
||||
|
||||
func testInline() {
|
||||
let buttonNoActionFixture = """
|
||||
[ { "type": "appleScriptTitledButton", "source": { "inline": "tell everything fine" } } ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonNoActionFixture)
|
||||
guard case .appleScriptTitledButton(let source, _)? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(source.string, "tell everything fine")
|
||||
}
|
||||
|
||||
func testPath() {
|
||||
let buttonNoActionFixture = """
|
||||
[ { "type": "appleScriptTitledButton", "source": { "filePath": "/ololo/pew" } } ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonNoActionFixture)
|
||||
guard case .appleScriptTitledButton(let source, _)? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
let sourceStruct = source as? Source
|
||||
XCTAssertEqual(sourceStruct?.filePath, "/ololo/pew")
|
||||
}
|
||||
|
||||
func testRefreshInterval() {
|
||||
let buttonNoActionFixture = """
|
||||
[ { "type": "appleScriptTitledButton", "source": { "inline": "tell everything fine" }, "refreshInterval": 305} ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonNoActionFixture)
|
||||
guard case .appleScriptTitledButton(_, 305)? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import XCTest
|
||||
|
||||
class BackgroundColorTests: XCTestCase {
|
||||
|
||||
func testOpaque() {
|
||||
let buttonNoActionFixture = """
|
||||
[ { "type": "staticButton", "title": "Pew", "background": "#FF0000" } ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonNoActionFixture)
|
||||
guard case .background(let color)? = result?.first?.additionalParameters[.background] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(color, .red)
|
||||
}
|
||||
|
||||
func testAlpha() {
|
||||
let buttonNoActionFixture = """
|
||||
[ { "type": "staticButton", "title": "Pew", "background": "#FF000080" } ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonNoActionFixture)
|
||||
guard case .background(let color)? = result?.first?.additionalParameters[.background] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
XCTAssertEqual(color.alphaComponent, 0.5, accuracy: 0.01)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import XCTest
|
||||
@testable import MTMR
|
||||
|
||||
class ParseConfig: XCTestCase {
|
||||
|
||||
@@ -8,8 +7,14 @@ class ParseConfig: XCTestCase {
|
||||
[ { "type": "staticButton", "title": "Pew" } ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonNoActionFixture)
|
||||
XCTAssertEqual(result?.first?.type, .staticButton(title: "Pew"))
|
||||
XCTAssertEqual(result?.first?.action, .some(.none))
|
||||
guard case .staticButton("Pew")? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
guard case .none? = result?.first?.action else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func testButtonKeyCodeAction() {
|
||||
@@ -17,17 +22,48 @@ class ParseConfig: XCTestCase {
|
||||
[ { "type": "staticButton", "title": "Pew", "action": "hidKey", "keycode": 123} ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonKeycodeFixture)
|
||||
XCTAssertEqual(result?.first?.type, .staticButton(title: "Pew"))
|
||||
XCTAssertEqual(result?.first?.action, .hidKey(keycode: 123))
|
||||
guard case .staticButton("Pew")? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
guard case .hidKey(keycode: 123)? = result?.first?.action else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func testPredefinedItem() {
|
||||
let buttonKeycodeFixture = """
|
||||
[ { "type": "brightnessUp" } ]
|
||||
[ { "type": "escape" } ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonKeycodeFixture)
|
||||
XCTAssertEqual(result?.first?.type, .staticButton(title: "🔆"))
|
||||
XCTAssertEqual(result?.first?.action, .keyPress(keycode: 113))
|
||||
guard case .staticButton("esc")? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
guard case .keyPress(keycode: 53)? = result?.first?.action else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func testExtendedWidthForPredefinedItem() {
|
||||
let buttonKeycodeFixture = """
|
||||
[ { "type": "escape", "width": 110}, ]
|
||||
""".data(using: .utf8)!
|
||||
let result = try? JSONDecoder().decode([BarItemDefinition].self, from: buttonKeycodeFixture)
|
||||
guard case .staticButton("esc")? = result?.first?.type else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
guard case .keyPress(keycode: 53)? = result?.first?.action else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
guard case .width(110)? = result?.first?.additionalParameters[.width] else {
|
||||
XCTFail()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,12 +4,20 @@
|
||||
</p>
|
||||
|
||||
# My TouchBar. My rules
|
||||
|
||||
*The TouchBar Customization App for your MacBook Pro*
|
||||
|
||||
[](https://github.com/Toxblh/MTMR/releases)
|
||||
[](https://github.com/Toxblh/MTMR/blob/master/LICENSE) [](https://github.com/Toxblh/MTMR/releases/latest)  
|
||||
|
||||
<p align="center">
|
||||
<img src="Resources/TouchBar-v0.3.png">
|
||||
<img src="Resources/TouchBar-v0.8.1.png">
|
||||
</p>
|
||||
|
||||
**MTMR** Community:
|
||||
[<img height="24px" src="https://github.com/discourse/DiscourseMobile/raw/master/icon.png" /> Discourse](https://forum.mtmr.app)
|
||||
[<img height="24px" src="https://telegram.org/img/t_logo.png" /> Telegram](https://t.me/joinchat/AmVYGg8vW38c13_3MxdE_g)
|
||||
|
||||
My the idea is to create the program like a platform for plugins for customization TouchBar. I very like BTT and a full custom TouchBar (my [BTT preset](https://github.com/Toxblh/btt-touchbar-preset)). And I want to create it. And it's my the first Swift project for MacOS :)
|
||||
|
||||
### Roadmap
|
||||
@@ -24,17 +32,270 @@ My the idea is to create the program like a platform for plugins for customizati
|
||||
- [x] Hide from Dock
|
||||
- [x] Status menu: "preferences", "quit"
|
||||
- [x] JSON or another approch for save preset, maybe in `~/Library/Application Support/MTMR/`
|
||||
- [ ] Layout: [always left, NSSliderView for center, always right]
|
||||
- [ ] Custom buttons size, actions by click in settings
|
||||
- [x] Custom buttons size, actions by click
|
||||
- [x] Layout: [always left, NSSliderView for center, always right]
|
||||
- [ ] Overwrite default values from item types (e.g. title for brightness)
|
||||
- [ ] Custom settings for paddings and margins for buttons
|
||||
- [ ] XPC Service for scripts
|
||||
- [ ] UI for settings
|
||||
- [ ] Import config from BTT
|
||||
- [ ] System for autoupdate (maybe https://sparkle-project.org/)
|
||||
|
||||
Settings:
|
||||
- [ ] Intarface for plugins and export like presets
|
||||
- [ ] Startup at login
|
||||
- [ ] Interface for plugins and export like presets
|
||||
- [x] Startup at login
|
||||
- [ ] Show on/off in Dock
|
||||
- [ ] Show on/off in StatusBar
|
||||
- [ ] On/off Haptic Feedback
|
||||
|
||||
Maybe:
|
||||
- [ ] Refactoring the application on packages (AppleScript, JavaScript? and Swift?)
|
||||
|
||||
|
||||
## Installation
|
||||
- Download last [release](https://github.com/Toxblh/MTMR/releases)
|
||||
- Or via Homebrew `brew cask install mtmr`
|
||||
|
||||
## Preset
|
||||
|
||||
File for customize your preset for MTMR: `open ~/Library/Application\ Support/MTMR/items.json`
|
||||
|
||||
## Built-in button types:
|
||||
|
||||
- escape
|
||||
- exitTouchbar
|
||||
- brightnessUp
|
||||
- brightnessDown
|
||||
- volumeDown
|
||||
- volumeUp
|
||||
- mute
|
||||
- dock
|
||||
|
||||
> Native Plugins
|
||||
- battery
|
||||
- currency
|
||||
- weather
|
||||
- inputsource
|
||||
- music (tap for pause, longTap for next)
|
||||
|
||||
> Media Keys
|
||||
- previous
|
||||
- play
|
||||
- next
|
||||
|
||||
> AppleScript plugins
|
||||
- sleep
|
||||
- displaySleep
|
||||
|
||||
## Gestures on central part:
|
||||
- two finger slide: change you Volume
|
||||
- three finger slide: change you Brightness
|
||||
|
||||
## Built-in slider types:
|
||||
|
||||
- brightness
|
||||
- volume
|
||||
|
||||
### You can also make a custom buttons using these types
|
||||
- `staticButton`
|
||||
```json
|
||||
"type": "staticButton",
|
||||
"title": "esc",
|
||||
```
|
||||
|
||||
- `appleScriptTitledButton`
|
||||
```js
|
||||
"type": "appleScriptTitledButton",
|
||||
"refreshInterval": 60, //optional
|
||||
"source": {
|
||||
"filePath": "/Users/toxblh/Library/Application Support/MTMR/iTunes.nowPlaying.scpt",
|
||||
// or
|
||||
"inline": "tell application \"Finder\"\rmake new Finder window\rset target of front window to path to home folder as string\ractivate\rend tell",
|
||||
// or
|
||||
"base64": "StringInbase64"
|
||||
},
|
||||
```
|
||||
|
||||
- `timeButton`
|
||||
```js
|
||||
"type": "timeButton",
|
||||
"formatTemplate": "HH:mm" //optional
|
||||
```
|
||||
|
||||
## Groups
|
||||
```js
|
||||
{
|
||||
"type": "group",
|
||||
"align": "center",
|
||||
"bordered": true,
|
||||
"title": "stats",
|
||||
"items": [{ button }, {button}, ...]
|
||||
}
|
||||
```
|
||||
|
||||
## Native plugins
|
||||
- `weather`
|
||||
> Provider: https://openweathermap.org Need allowance location service
|
||||
```js
|
||||
"type": "weather",
|
||||
"refreshInterval": 600,
|
||||
"units": "metric", // or imperial
|
||||
"icon_type": "text" // or images
|
||||
"api_key": "" // you can get the key on openweather
|
||||
```
|
||||
|
||||
- `currency`
|
||||
> Provider: https://coinbase.com
|
||||
```js
|
||||
"type": "currency",
|
||||
"refreshInterval": 600,
|
||||
"align": "right",
|
||||
"from": "BTC",
|
||||
"to": "USD",
|
||||
```
|
||||
|
||||
- `music`
|
||||
```js
|
||||
{
|
||||
"type": "music",
|
||||
"align": "center",
|
||||
"width": 80,
|
||||
"bordered": false,
|
||||
"refreshInterval": 2,
|
||||
},
|
||||
```
|
||||
|
||||
## Actions:
|
||||
- `hidKey`
|
||||
> https://github.com/aosm/IOHIDFamily/blob/master/IOHIDSystem/IOKit/hidsystem/ev_keymap.h use only numbers
|
||||
```json
|
||||
"action": "hidKey",
|
||||
"keycode": 53,
|
||||
```
|
||||
|
||||
- `keyPress`
|
||||
```json
|
||||
"action": "keyPress",
|
||||
"keycode": 1,
|
||||
```
|
||||
|
||||
- `appleScript`
|
||||
```js
|
||||
"action": "appleScript",
|
||||
"actionAppleScript": {
|
||||
"inline": "tell application \"Finder\"\rmake new Finder window\rset target of front window to path to home folder as string\ractivate\rend tell"
|
||||
// "filePath" or "base64" will work as well
|
||||
},
|
||||
```
|
||||
|
||||
- `shellScript`
|
||||
```js
|
||||
"action": "shellScript",
|
||||
"executablePath": "/usr/bin/pmset",
|
||||
"shellArguments": ["sleepnow"], // optional
|
||||
|
||||
```
|
||||
|
||||
- `openUrl`
|
||||
```js
|
||||
"action": "openUrl",
|
||||
"url": "https://google.com",
|
||||
```
|
||||
|
||||
## LongActions
|
||||
This then you want to use longPress for some operations is will the same values like for Actions but different additional parameters, example:
|
||||
```js
|
||||
"longAction": "hidKey",
|
||||
"longKeycode": 53,
|
||||
```
|
||||
|
||||
- longAction
|
||||
- longKeycode
|
||||
- longActionAppleScript
|
||||
- longExecutablePath
|
||||
- longShellArguments
|
||||
- longUrl
|
||||
|
||||
## Additional parameters:
|
||||
|
||||
- `width` allow to restrict how much room a particular button will take
|
||||
```json
|
||||
"width": 34
|
||||
```
|
||||
|
||||
- `align` can stick the item to the side. default is center
|
||||
```js
|
||||
"align": "left" //or "right" or "center"
|
||||
```
|
||||
|
||||
## Example configuration:
|
||||
```json
|
||||
[
|
||||
{ "type": "escape", "width": 110 },
|
||||
{ "type": "exitTouchbar", "align": "left" },
|
||||
{
|
||||
"type": "brightnessUp",
|
||||
"align": "left",
|
||||
"width": 36
|
||||
},
|
||||
{
|
||||
"type": "staticButton",
|
||||
"align": "left",
|
||||
"title": "🔆",
|
||||
"action": "keyPress",
|
||||
"keycode": 113,
|
||||
"width": 36
|
||||
},
|
||||
|
||||
{
|
||||
"type": "appleScriptTitledButton",
|
||||
"source": {
|
||||
"filePath": "/Users/toxblh/Library/Application Support/MTMR/iTunes.nowPlaying.scpt"
|
||||
},
|
||||
"refreshInterval": 1
|
||||
},
|
||||
{
|
||||
"type": "staticButton",
|
||||
"align": "left",
|
||||
"image": { "base64" : "%base64Finder%"},
|
||||
"action": "appleScript",
|
||||
"actionAppleScript": {
|
||||
"inline": "tell application \"Finder\"\rmake new Finder window\rset target of front window to path to home folder as string\ractivate\rend tell"
|
||||
},
|
||||
"width": 36
|
||||
},
|
||||
{
|
||||
"type": "appleScriptTitledButton",
|
||||
"source": {
|
||||
"inline": "if application \"Safari\" is running then\r\ttell application \"Safari\"\r\t\trepeat with t in tabs of windows\r\t\t\ttell t\r\t\t\t\tif URL starts with \"https:\/\/music.yandex.ru\" and name does not end with \"на Яндекс.Музыке\" then\r\t\t\t\t\treturn name of t as text\r\t\t\t\tend if\r\t\t\tend tell\r\t\tend repeat\r\tend tell\rend if\rreturn \"\""
|
||||
},
|
||||
"refreshInterval": 1
|
||||
},
|
||||
{ "type": "previous", "width": 36, "align": "right" },
|
||||
{ "type": "play", "width": 36, "align": "right" },
|
||||
{ "type": "next", "width": 36, "align": "right" },
|
||||
{ "type": "sleep", "width": 36 , "align": "right"},
|
||||
{ "type": "displaySleep", "align": "right" },
|
||||
{ "type": "weather", "refreshInterval": 1800, "width": 70, "align": "right" },
|
||||
{ "type": "volumeDown", "width": 36 , "align": "right"},
|
||||
{ "type": "volumeUp", "width": 36 , "align": "right"},
|
||||
{ "type": "battery", "refreshInterval": 60 , "align": "right"},
|
||||
{ "type": "appleScriptTitledButton", "refreshInterval": 1800, "source": { "filePath": "/Users/redetection/Library/Application Support/MTMR/Weather.scpt"} , "align": "right"},
|
||||
{ "type": "timeButton", "formatTemplate": "HH:mm", "width": 64, "align": "right" }
|
||||
]
|
||||
```
|
||||
|
||||
|
||||
### Author's presets
|
||||
|
||||
[@Toxblh preset](Resources/toxblh.json)
|
||||
|
||||
[@ReDetection preset](Resources/ReDetection.json)
|
||||
|
||||
## Credits
|
||||
|
||||
<a href="https://www.buymeacoffee.com/toxblh" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>
|
||||
|
||||
Built by [@Toxblh](https://patreon.com/toxblh) and [@ReDetection](http://patreon.com/ReDetection).
|
||||
|
||||
[](https://github.com/igrigorik/ga-beacon)
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
File diff suppressed because one or more lines are too long
@@ -3,3 +3,4 @@
|
||||
* try view controllers on `NSCustomTouchBarItem` instead of subclassing item itself
|
||||
* try move away from enums when parse preset – enums are hard to extend
|
||||
* find better way to hide bar items
|
||||
* extract bar items creating from TouchBarController to separate class, cover with tests
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
NAME='MTMR'
|
||||
|
||||
rm -r Release 2>/dev/null
|
||||
|
||||
xcodebuild archive \
|
||||
-scheme "$NAME" \
|
||||
-archivePath Release/App.xcarchive
|
||||
|
||||
xcodebuild \
|
||||
-exportArchive \
|
||||
-archivePath Release/App.xcarchive \
|
||||
-exportOptionsPlist export-options.plist \
|
||||
-exportPath Release
|
||||
|
||||
cd Release
|
||||
rm -r App.xcarchive
|
||||
|
||||
# Prerequisite: npm i -g create-dmg
|
||||
NAME_DMG="${NAME}.app"
|
||||
echo $NAME_DMG
|
||||
create-dmg $NAME_DMG
|
||||
|
||||
VERSION=`mdls -raw -name kMDItemVersion ${NAME}.app`
|
||||
|
||||
echo $VERSION
|
||||
zip -r "${NAME}v${VERSION}.zip" "${NAME}.app"
|
||||
@@ -0,0 +1,10 @@
|
||||
<?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>teamID</key>
|
||||
<string>D6D8BR2QNB</string>
|
||||
<key>method</key>
|
||||
<string>mac-application</string>
|
||||
</dict>
|
||||
</plist>
|
||||
Reference in New Issue
Block a user