-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
app.lua
1094 lines (1008 loc) · 36.5 KB
/
app.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- C O M M A N D P O S T --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === cp.app ===
---
--- This class assists with working with macOS apps. It provides functions for
--- finding, checking the running status, version number, path, and many other
--- values related to an application. It also provides support for launching,
--- quitting, and other activities related to applications.
---
--- This extension differs from the `hs.application` extension in several ways:
--- * `cp.app` instances are long-lived. You request it once and it will stay up-to-date even if the app quits.
--- * It makes extensive use of `cp.prop`, so you can `watch` many most properties of the app and get live notifications when they change.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local require = require
local log = require("hs.logger").new("app")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local application = require("hs.application")
local applicationwatcher = require("hs.application.watcher")
local ax = require("hs._asm.axuielement")
local fs = require("hs.fs")
local inspect = require("hs.inspect")
local task = require("hs.task")
local timer = require("hs.timer")
local printf = hs.printf
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local axutils = require("cp.ui.axutils")
local just = require("cp.just")
local languageID = require("cp.i18n.languageID")
local localeID = require("cp.i18n.localeID")
local menu = require("cp.app.menu")
local notifier = require("cp.ui.notifier")
local prefs = require("cp.app.prefs")
local prop = require("cp.prop")
local tools = require("cp.tools")
local go = require("cp.rx.go")
local Given = go.Given
local WaitUntil, Throw, If = go.WaitUntil, go.Throw, go.If
--------------------------------------------------------------------------------
-- 3rd Party Extensions:
--------------------------------------------------------------------------------
local v = require("semver")
local class = require("middleclass")
local lazy = require("cp.lazy")
--------------------------------------------------------------------------------
-- Local Lua Functions:
--------------------------------------------------------------------------------
local insert = table.insert
local format = string.format
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
-- COMMANDPOST_BUNDLE_ID -> string
-- Constant
-- CommandPost's Bundle ID string.
local COMMANDPOST_BUNDLE_ID = hs.processInfo.bundleID
-- BASE_LOCALE -> string
-- Constant
-- Base Locale.
local BASE_LOCALE = "Base"
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local app = class("app"):include(lazy)
-- keeps a log of all apps that have been created.
local apps = {}
--- cp.app.is(thing) -> boolean
--- Function
--- Checks if the provided `thing` is a `cp.app` instance.
---
--- Parameters:
--- * thing - The thing to check.
---
--- Returns:
--- * `true` if it is a `cp.app` instance, otherwise `false`.
function app.static.is(thing)
return type(thing) == "table" and thing.isInstanceOf ~= nil and thing:isInstanceOf(app)
end
--- cp.app.bundleIDs() -> table
--- Function
--- Returns a list of Bundle IDs which have been requested via [forBundleID](#forBundleID).
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list of Bundle IDs.
function app.static.bundleIDs()
local ids = {}
for id,_ in pairs(apps) do
insert(ids, id)
end
return ids
end
--- cp.app.apps() -> table
--- Function
--- Returns a list of all apps that have been requested via [forBundleID](#forBundleID), in no particular order.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list of `cp.app` instances.
function app.static.apps()
local result = {}
for _,a in pairs(apps) do
insert(result, a)
end
return result
end
local frontmostApp = nil
--- cp.app.frontmostApp <cp.prop: cp.app; read-only; live>
--- Variable
--- Returns the most recent 'registered' app that was active, other than CommandPost itself.
app.static.frontmostApp = prop(function() return frontmostApp end):label("frontmostApp")
-- notifyWatch(cpProp, notifications) -> cp.prop
-- Function
-- Utility function to help set up watchers. Adds a watch for the specified notifications
-- and then updates the property.
--
-- Parameters:
-- * cpProp - The [cp.prop](cp.prop.md) to update
-- * notifications - The list of notification types to update the prop on.
--
-- Returns:
-- * The same `cp.prop`.
local function notifyWatch(cpProp, notifications)
cpProp:preWatch(function(self)
self:notifier():watchFor(
notifications,
function() cpProp:update() end
)
end)
return cpProp
end
--- cp.app.forBundleID(bundleID)
--- Constructor
--- Returns the `cp.app` for the specified Bundle ID. If the app has already been created,
--- the same instance of `cp.app` will be returned on subsequent calls.
---
--- The Bundle ID
---
--- Parameters:
--- * bundleID - The application bundle ID to find the app for.
---
--- Returns:
--- * The `cp.app` for the bundle.
function app.static.forBundleID(bundleID)
assert(type(bundleID) == "string", "`bundleID` must be a string")
local theApp = apps[bundleID]
if not theApp then
theApp = app:new(bundleID)
apps[bundleID] = theApp
end
return theApp
end
--------------------------------------------------------------
-- cp.app instance configuration
--------------------------------------------------------------
-- cp.app:initialize(bundleID) -> cp.app
-- Constructor
-- Initializes new `cp.app` instances. This should not be called directly.
-- Rather, get them via the [forBundleID](#forBundleID) function.
--
-- Parameters:
-- * bundleID - The BundleID for the app
--
-- Returns:
-- * The new `cp.app`.
function app:initialize(bundleID)
self._bundleID = bundleID
app._initWatchers()
end
--- cp.app:bundleID() -> string
--- Method
--- Returns the Bundle ID for the app.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The Bundle ID.
function app:bundleID()
return self._bundleID
end
--- cp.app.preferences <cp.app.prefs>
--- Field
--- The current [preferences](cp.app.prefs.md) for the application.
function app.lazy.value:preferences()
return prefs.new(self:bundleID())
end
--- cp.app.hsApplication <cp.prop: hs.application; read-only; live>
--- Field
--- Returns the running `hs.application` for the application, or `nil` if it's not running.
function app.lazy.prop:hsApplication()
return notifyWatch(
prop(function()
local hsApp = self._hsApplication
if not hsApp or hsApp:bundleID() == nil or not hsApp:isRunning() then
local result = application.applicationsForBundleID(self._bundleID)
if result and #result > 0 then
hsApp = result[1] -- If there is at least one copy running, return the first one
else
hsApp = nil
end
self._hsApplication = hsApp
end
return hsApp
end),
{"AXApplicationActivated", "AXApplicationDeactivated"}
)
end
--- cp.app.pid <cp.prop: number; read-only; live>
--- Field
--- Returns the PID for the currently-running application, or `nil` if it's not running.
function app.lazy.prop:pid()
return self.hsApplication:mutate(function(original)
local hsApp = original()
return hsApp and hsApp:pid()
end)
end
--- cp.app.running <cp.prop: boolean; read-only; live>
--- Field
--- Checks if the application currently is running.
function app.lazy.prop:running()
return self.hsApplication:mutate(function(original)
local hsApp = original()
return hsApp ~= nil and hsApp:bundleID() ~= nil and hsApp:isRunning()
end)
end
--- cp.app.UI <cp.prop: hs._asm.axuielement; read-only; live>
--- Field
--- Returns the application's `axuielement`, if available.
function app.lazy.prop:UI()
return self.pid:mutate(function(original)
return axutils.cache(self, "_ui", function()
local thePid = original()
return thePid and ax.applicationElementForPID(thePid)
end)
end)
end
--- cp.app.showing <cp.prop: boolean; read-only; live>
--- Field
--- Is the app visible on screen?
function app.lazy.prop:showing()
return notifyWatch(
self.UI:mutate(function(original)
local ui = original()
return ui ~= nil and not ui:attributeValue("AXHidden")
end),
{"AXApplicationHidden", "AXApplicationShown"}
)
end
--- cp.app.frontmost <cp.prop: boolean; read-only; live>
--- Field
--- Is the application currently frontmost?
function app.lazy.prop:frontmost()
return notifyWatch(
self.UI:mutate(function(original)
local ui = original()
return ui ~= nil and ui:attributeValue("AXFrontmost")
end),
{"AXApplicationActivated", "AXApplicationDeactivated"}
)
end
--- cp.app.focusedWindowUI <cp.prop: hs._asm.axuielement; read-only; live>
--- Field
--- Returns the UI containing the currently-focused window for the app.
function app.lazy.prop:focusedWindowUI()
return notifyWatch(
self.UI:mutate(function(original)
local ui = original()
return ui and ui:attributeValue("AXFocusedWindow")
end),
{"AXFocusedWindowChanged"}
)
end
--- cp.app.mainWindowUI <cp.prop: hs._asm.axuielement; read-only; live>
--- Field
--- Returns the UI containing the currently-focused window for the app.
function app.lazy.prop:mainWindowUI()
return notifyWatch(
self.UI:mutate(function(original)
local ui = original()
return ui and ui:attributeValue("AXMainWindow")
end),
{"AXMainWindowChanged"}
)
end
--- cp.app.modalDialogOpen <cp.prop: boolean; read-only>
--- Field
--- Checks if a modal dialog window is currently opon.
function app.lazy.prop:modalDialogOpen()
return self.focusedWindowUI:mutate(function(original)
local window = original()
if window then
return window:attributeValue("AXModal") == true or window:attributeValue("AXRole") == "AXSheet"
end
return false
end)
end
--- cp.app.path <cp.prop: string; read-only; live>
--- Field
--- Path to the application, or `nil` if not found.
function app.lazy.prop:path()
return self.hsApplication:mutate(function(original)
local hsApp = original()
if hsApp and hsApp:isRunning() then
----------------------------------------------------------------------------------------
-- The app is running
----------------------------------------------------------------------------------------
local appPath = hsApp:path()
if appPath then
return appPath
else
log.ef("Failed to get running application path: %s", self)
end
else
----------------------------------------------------------------------------------------
-- The app is closed.
----------------------------------------------------------------------------------------
local result = application.pathForBundleID(self:bundleID())
if result then
return result
end
end
return nil
end)
end
--- cp.app.info <cp.prop: table; read-only; live>
--- Field
--- The info table for the application, if available.
--- If multiple versions of the app are installed, it will return the details for the running app as first priority,
--- and then it could be any installed version after that.
function app.lazy.prop:info()
return self.hsApplication:mutate(function(original)
----------------------------------------------------------------------------------------
-- Check if the app is running already...
----------------------------------------------------------------------------------------
local hsApp = original()
if hsApp and hsApp:isRunning() then
local appPath = hsApp:path()
if appPath then
return application.infoForBundlePath(appPath)
else
log.ef("Found app, but could not determine its path: %s", self:bundleID())
end
end
----------------------------------------------------------------------------------------
-- If not, grab it from the default location.
----------------------------------------------------------------------------------------
return application.infoForBundleID(self:bundleID())
end)
end
--- cp.app.versionString <cp.prop: string; read-only; live>
--- Field
--- The application version as a `string`.
---
--- Notes:
--- * If the application is running it will get the version of the active application as a string, otherwise, it will use `hs.application.infoForBundleID()` to find the version.
function app.lazy.prop:versionString()
return self.info:mutate(function(original)
local theInfo = original()
return theInfo and theInfo["CFBundleShortVersionString"]
end)
end
--- cp.app.version <cp.prop: semver; read-only; live>
--- Field
--- The application version as a [semver](https://github.com/kikito/semver.lua).
---
--- Notes:
--- * If the application is running it will get the version of the active application as a string, otherwise, it will use `hs.application.infoForBundleID()` to find the version.
function app.lazy.prop:version()
return self.versionString:mutate(function(original)
local vs = original()
return vs ~= nil and v(vs) or nil
end)
end
--- cp.app.displayName <cp.prop: string; read-only; live>
--- Field
--- The application display name as a string.
function app.lazy.prop:displayName()
return self.info:mutate(function(original)
local theInfo = original()
return theInfo and (theInfo["CFBundleDisplayName"] or theInfo["CFBundleName"])
end)
end
--- cp.app.installed <cp.prop: boolean; read-only>
--- Field
--- Checks if the application currently installed.
function app.lazy.prop:installed()
return self.info:mutate(function(original) return original() ~= nil end)
end
--- cp.app.windowsUI <cp.prop: hs._asm.axuielement; read-only; live>
--- Field
--- Returns the UI containing the list of windows in the app.
function app.lazy.prop:windowsUI()
return notifyWatch(
self.UI:mutate(function(original)
local ui = original()
local windows = ui and ui:attributeValue("AXWindows")
if windows ~= nil and #windows == 0 then
local mainWindow = ui:attributeValue("AXMainWindow")
if mainWindow then
insert(windows, mainWindow)
end
end
return windows
end),
{"AXWindowCreated", "AXDrawerCreated", "AXSheetCreated", "AXUIElementDestroyed"}
)
end
--- cp.app.baseLocale <cp.prop: cp.i18n.localeID; read-only>
--- Field
--- Returns the [localeID](cp.i18n.localeID.md) of the development region. This is the 'Base' locale for I18N.
function app.lazy.prop:baseLocale()
return self.info:mutate(function(original)
local theInfo = original()
local devRegion = theInfo and theInfo.CFBundleDevelopmentRegion or nil
return devRegion and localeID.forCode(devRegion)
end)
end
--- cp.app.supportedLocales <cp.prop: table of cp.i18n.localeID; read-only; live>
--- Field
--- Returns a list of `cp.i18n.localeID` values for locales that are supported by this app.
function app.lazy.prop:supportedLocales()
return self.path:mutate(function(original)
local locales = {}
local appPath = original()
if appPath then
local resourcesPath = fs.pathToAbsolute(appPath .. "/Contents/Resources")
if resourcesPath then
local theBaseLocale = self:baseLocale()
if theBaseLocale then
-- always add the base locale, if present.
insert(locales, theBaseLocale)
end
local iterFn, dirObj = fs.dir(resourcesPath)
if not iterFn then
log.ef("An error occured in cp.app.forBundleID: %s", dirObj)
else
for file in iterFn, dirObj do
local localeCode = file:match("(.+)%.lproj")
if localeCode then
if localeCode ~= BASE_LOCALE then
local locale = localeID.forCode(localeCode)
if locale and locale ~= theBaseLocale then
insert(locales, locale)
end
end
end
end
end
end
end
table.sort(locales)
return locales
end)
end
--- cp.app.currentLocale <cp.prop: cp.i18n.localeID; live>
--- Field
--- Gets and sets the current locale for the application.
function app.lazy.prop:currentLocale()
return prop(
function()
--------------------------------------------------------------------------------
-- If the app is not running, we next try to determine the language using
-- the 'AppleLanguages' preference...
--------------------------------------------------------------------------------
local appLanguages = self.preferences.AppleLanguages
if appLanguages then
for _,lang in ipairs(appLanguages) do
if self:isSupportedLocale(lang) then
local currentLocale = localeID.forCode(lang)
if currentLocale then
return currentLocale
end
end
end
end
--------------------------------------------------------------------------------
-- If that also fails, we try and use NSGlobalDomain AppleLanguages:
--------------------------------------------------------------------------------
local output, status = hs.execute("defaults read NSGlobalDomain AppleLanguages")
if status then
local appleLanguages = tools.lines(output)
if next(appleLanguages) ~= nil then
if appleLanguages[1] == "(" and appleLanguages[#appleLanguages] == ")" then
for i=2, #appleLanguages - 1 do
local line = appleLanguages[i]
-- match the main country code
local lang = line:match("^%s*\"?([%w%-]+)")
local theLanguage = languageID.forCode(lang)
if theLanguage then
local theLocale = theLanguage:toLocaleID()
local bestLocale = self:bestSupportedLocale(theLocale)
if bestLocale then
return bestLocale
end
end
end
end
end
end
--------------------------------------------------------------------------------
-- If that also fails, we use the base locale, or failing that, English:
--------------------------------------------------------------------------------
local locale = self:baseLocale() or localeID.forCode("en")
return locale
end,
function(value, _, theProp)
value = localeID(value)
if not localeID.is(value) then
error(format("The provided value is not a cp.i18n.localeID: %s", inspect(value)))
end
-- if the new value matches the current value, don't do anything.
if value == theProp:get() then return end
local thePrefs = self.preferences
if value == nil then
if thePrefs.AppleLanguages == nil then return end
thePrefs.AppleLanguages = nil
else
local bestLocale = self:bestSupportedLocale(value)
if bestLocale then
thePrefs.AppleLanguages = {bestLocale.code}
else
error("Unsupported language: "..value.code)
end
end
if self:running() then
self:doRestart():TimeoutAfter(20*1000):Now()
end
end
):monitor(self.running)
end
--- cp.app:menu() -> cp.app.menu
--- Method
--- Returns the main `menu` for the application.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `cp.app.menu` for the `cp.app` instance.
function app.lazy.method:menu()
return menu.new(self)
end
--- cp.app:launch([waitSeconds]) -> self
--- Method
--- Launches the application, or brings it to the front if it was already running.
---
--- Parameters:
--- * `waitSeconds` - If povided, the number of seconds to wait until the launch completes. If `nil`, it will return immediately.
---
--- Returns:
--- * The `cp.app` instance.
function app:launch(waitSeconds)
local hsApp = self:hsApplication()
if hsApp == nil or not hsApp:isFrontmost() then
-- Closed:
local ok = application.launchOrFocusByBundleID(self:bundleID())
if ok and waitSeconds then
just.doUntil(function() return self:running() end, waitSeconds, 0.1)
end
end
return self
end
--- cp.app:doLaunch() -> cp.rx.Statement <boolean>
--- Method
--- Returns a `Statement` that can be run to launch or focus the current app.
--- It will resolve to `true` when the app was launched.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Statement`, resolving to `true` after the app is frontmost.
---
--- Notes:
--- * By default the `Statement` will time out after 30 seconds, sending an error signal.
function app.lazy.method:doLaunch()
return If(self.installed):Then(
If(self.frontmost):Is(false):Then(
If(self.hsApplication):Then(function(hsApp)
hsApp:activate()
end)
:Otherwise(function()
local ok = application.launchOrFocusByBundleID(self:bundleID())
if not ok then
return Throw("Unable to launch %s.", self:displayName())
end
end)
)
:Then(WaitUntil(self.frontmost))
:Otherwise(true)
)
:Otherwise(
Throw("No app with a bundle ID of '%s' is installed.", self:bundleID())
)
:TimeoutAfter(30 * 1000, format("Unable to complete launching %s within 30 seconds", self:displayName()))
:Label(self:bundleID()..":doLaunch")
end
--- cp.app:quit(waitSeconds) -> self
--- Method
--- Asks the application to quit, if it's running. The app may not have actually quit after this
--- function runs, even if `true` is returned. The application may take some time, or may be prompting
--- the user for input, etc.
---
--- Parameters:
--- * `waitSeconds` - If povided, the number of seconds to wait until the quit completes. If `nil`, it will return immediately.
---
--- Returns:
--- * The `cp.app` instance.
function app:quit(waitSeconds)
local hsApp = self:hsApplication()
if hsApp then
hsApp:kill()
if waitSeconds then
just.doWhile(function() return self:running() end, waitSeconds, 0.1)
end
end
return self
end
--- cp.app:doQuit() -> cp.rx.go.Statement <boolean>
--- Method
--- Returns a `Statement` that will attempt to quit the app when executed.
---
--- Parameters:
--- * None.
---
--- Returns:
--- * The `Statement`, resolving to `true` if the app was running and was quit successfully, otherwise `false`.
---
--- Notes:
--- * The Statement will time out after 60 seconds by default. This can be changed by calling the `TimeoutAfter` method on the Statement before executing.
function app.lazy.method:doQuit()
return If(self.hsApplication):Then(function(hsApp)
hsApp:kill()
end)
:Then(WaitUntil(self.running):Is(false))
:Otherwise(false)
:TimeoutAfter(60 * 1000, format("%s did not quit successfully after 60 seconds.", self:displayName()))
:Label(self:bundleID()..":doQuit")
end
--- cp.app:doRestart() -> cp.rx.go.Statement <boolean>
--- Method
--- Returns a `Statement` which will attempt to restart the app. If the app
--- was not running at the time, no action is taken and `false` is returned. If it was
--- running then the app will be attempted to quit then restarted.
---
--- If you have multiple versions of the same app on your system, this will
--- restart with the same version that was running when the restart was requested.
---
--- Parameters:
--- * None.
---
--- Returns:
--- * The `Statement`, resolving to `true` if the app was running and was quit and restarted successfully, otherwise `false`.
---
--- Notes:
--- * The Statement will time out after 60 seconds by default. This can be changed by calling the `TimeoutAfter` method on the Statement before executing.
function app.lazy.method:doRestart()
return If(self.hsApplication):Then(function(hsApp)
local appPath = hsApp:path()
return Given(
self:doQuit()
)
:Then(function()
-- force the application prop to update, otherwise it isn't closed long enough to prompt an event.
self.hsApplication:update()
local output, ok = hs.execute(format('open "%s"', appPath))
if not ok then
return Throw("%s was unable to restart: %s", self:displayName(), output)
end
return WaitUntil(self.frontmost)
end)
end)
:Otherwise(false)
:TimeoutAfter(60 * 1000, format("%s did not restart successfully after 60 seconds", self:displayName()))
:Label(self:bundleID()..":doRestart")
end
--- cp.app:show() -> self
--- Method
--- Ensure the app is onscreen if it is currently running.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `cp.app` instance.
function app:show()
local hsApp = self:hsApplication()
if hsApp then
if hsApp:isHidden() then
hsApp:unhide()
end
if hsApp:isRunning() then
hsApp:activate()
end
end
return self
end
--- cp.app:doShow() -> cp.rx.go.Statement <boolean>
--- Method
--- Returns a `Statement` which will show the app if it's currently running.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `Statement`, resolving to `true` if the app is running and was successfully shown, or `false` otherwise.
function app.lazy.method:doShow()
return If(self.hsApplication):Then(function(hsApp)
if hsApp:isHidden() then
hsApp:unhide()
end
if hsApp:isRunning() then
hsApp:activate()
end
return WaitUntil(self.frontmost)
end)
:Otherwise(false)
:Label(self:bundleID()..":doShow")
end
--- cp.app:hide() -> self
--- Method
--- Hides the application, if it's currently running.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `cp.app` instance.
function app:hide()
local hsApp = self:application()
if hsApp then
hsApp:hide()
end
return self
end
--- cp.app:doHide() -> cp.rx.go.Statement <boolean>
--- Method
--- Returns a `Statement` which will hide the app if it's currently running.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A `Statement`, resolving to `true` if the app is running and was successfully hidden, or `false` otherwise.
function app.lazy.method:doHide()
return If(self.hsApplication):Then(function(hsApp)
hsApp:hide()
end)
:Then(WaitUntil(self.frontmost):Is(false))
:Otherwise(false)
:Label(self:bundleID()..":doHide")
end
--- cp.app:notifier() -> cp.ui.notifier
--- Method
--- Returns a `notifier` that is tracking the application UI element. It has already been started.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The notifier.
function app.lazy.method:notifier()
return notifier.new(self:bundleID(), function() return self:UI() end):start()
end
--- cp.app.description -> string
--- Field
--- Returns the short description of the class as "cp.app: <bundleID>"
function app.lazy.value:description()
return format("cp.app: %s", self:bundleID())
end
function app:__tostring()
return self.description
end
-- cp.app._findApp(bundleID, appName) -> cp.app
-- Function
-- Attempts to find the registered app, first by Bundle ID, then by the app name if provided.
-- It will not create a new `cp.app` instance for the Bundle ID if it does not exist.
--
-- Parameters:
-- * bundleID - The app Bundle ID
-- * appName - The app display name
--
-- Returns:
-- * The `cp.app` matching the details, or `nil` if not found.
function app.static._findApp(bundleID, appName)
local cpApp = apps[bundleID]
if cpApp == nil and bundleID == nil and appName ~= nil then
-- look harder...
for _,a in pairs(apps) do
if a:displayName() == appName then
return a
end
end
end
return cpApp
end
--- cp.app:isSupportedLocale(locale) -> boolean
--- Method
--- Checks if the specified locale is supported. The `locale` can
--- be either a string with the locale code (eg. "en_AU") or a
--- `cp.i18n.localeID`.
---
--- Parameters:
--- * locale - The locale code string or `localeID` to check.
---
--- Returns:
--- * `true` if it is supported, otherwise `false`.
function app:isSupportedLocale(locale)
locale = localeID(locale)
if localeID.is(locale) then
for _,sl in ipairs(self:supportedLocales()) do
if sl:matches(locale) > 0 then
return true
end
end
end
return false
end
--- cp.app:bestSupportedLocale(locale) -> cp.i18n.localeID or nil
--- Method
--- Finds the closest match for the specified locale. The returned locale
--- will be in the same language as the provided locale, and as close a match as possible with the region and script.
---
--- Parameters:
--- * locale - The local to match
---
--- Returns:
--- * The closest supported locale or `nil` if none are available in the language.
function app:bestSupportedLocale(locale)
-- cast to localeID
locale = localeID(locale)
if locale then
local currentLocale = nil
local currentScore = 0
for _,sl in ipairs(self:supportedLocales()) do
local score = sl:matches(locale)
if score > currentScore then
currentLocale = sl
currentScore = score
end
end
return currentLocale
end
return nil
end
--- cp.app:update() -> self
--- Method
--- Updates the app, triggering any watchers if values have changed.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `cp.app` instance.
function app:update()
self.hsApplication:update()
return self
end
local whiches = {}
local function which(cmd)
local path = whiches[cmd]
if not path then
local output, ok = hs.execute(string.format("which %q", cmd))
if ok then
path = output:match("([^\r\n]*)")
whiches[cmd] = path
else
return nil, output
end
end
return path
end
--- cp.app:searchResources(value) -> hs.task
--- Method
--- Creates a `hs.task` which will search for the specified string value in the resources
--- of the current app.
---
--- Parameters:
--- * value - The string value to search for.
---
--- Returns:
--- * `hs.task` which is already running, searching for the `value`. Results will be output in the Error Log.
---
--- Notes:
--- * This may take some time to complete, depending on how many resources the app contains.
function app:searchResources(value)
local grep = which("grep")
if grep and value then
value = tostring(value)
local finder = task.new(grep,
function(status, stdOut, stdErr)
printf("%s: Completed search for resources containing %q.", self:displayName(), value)
if stdOut then
print(stdOut)
end
if status ~= 0 then
printf("%s: ERROR #%d: %s", self:displayName(), status, stdErr)
end
end,