-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathdisplay_manager.py
executable file
·1257 lines (1112 loc) · 49 KB
/
display_manager.py
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
#!/usr/bin/env python3
########################################################################
# Copyright (c) 2018 University of Utah Student Computing Labs. #
# All Rights Reserved. #
# #
# Permission to use, copy, modify, and distribute this software and #
# its documentation for any purpose and without fee is hereby granted, #
# provided that the above copyright notice appears in all copies and #
# that both that copyright notice and this permission notice appear #
# in supporting documentation, and that the name of The University #
# of Utah not be used in advertising or publicity pertaining to #
# distribution of the software without specific, written prior #
# permission. This software is supplied as is without expressed or #
# implied warranties of any kind. #
########################################################################
# Display Manager, version 1.0.1
# Command-Line Interface
# Programmatically manages Mac displays.
# Can set screen resolution, refresh rate, rotation, brightness, underscan, and screen mirroring.
import sys # Collect command-line arguments
import re # Parse command-line input
import collections # Special collections are required for CommandList
from display_manager_lib import * # The Display Manager Library
class CommandSyntaxError(Exception):
"""
Raised if commands have improper syntax
(e.g. wrong number of arguments, arguments in wrong place, invalid (sub)command(s), etc.)
"""
def __init__(self, message, verb=None):
"""
:param verb: The type of command that raised this exception
:param message: Description of what went wrong
"""
self.message = message
self.verb = verb
Exception.__init__(self, self.message)
class CommandValueError(Exception):
"""
Raised if a command's arguments have unexpected values
(e.g. values are incorrect type, values are outside expected range, etc.)
"""
def __init__(self, message, verb=None):
"""
:param verb: The type of command that raised this exception
:param message: Description of what went wrong
"""
self.message = message
self.verb = verb
Exception.__init__(self, self.message)
class CommandExecutionError(Exception):
"""
Raised if commands could not be executed (usually due to a DisplayError)
"""
def __init__(self, message, command=None):
"""
:param command: The Command which raised this exception
:param message: Description of what went wrong
"""
self.message = message
self.command = command
Exception.__init__(self, self.message)
class Command(object):
"""
Represents a user-requested command to Display Manager
"""
def __init__(self, **kwargs):
"""
:param kwargs: Includes verb ("command type"), subcommand, scope, and misc. Command values
verb: string in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"]
subcommand: string
scope: Display(s)
width: int
height: int
refresh: int
hidpi: int (0 -> all; 1 -> no HiDPI; 2 -> only HiDPI)
angle: int
brightness: float
underscan: float
source: Display
"""
# Determine verb
if "verb" in kwargs:
if kwargs["verb"] in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"]:
self.verb = kwargs["verb"]
else:
raise CommandSyntaxError("\"{}\" is not a valid command".format(kwargs["verb"]))
else:
self.verb = None
# Determine subcommand, scope
self.subcommand = kwargs["subcommand"] if "subcommand" in kwargs else None
if "scope" in kwargs:
if isinstance(kwargs["scope"], list):
self.scope = kwargs["scope"]
elif isinstance(kwargs["scope"], AbstractDisplay):
self.scope = [kwargs["scope"]]
else:
self.scope = None
else:
self.scope = None
# Determine values
self.width = int(kwargs["width"]) if "width" in kwargs else None
self.height = int(kwargs["height"]) if "height" in kwargs else None
self.refresh = int(kwargs["refresh"]) if "refresh" in kwargs else None
# For HiDPI:
# 0: fits HiDPI or non-HiDPI
# 1: fits only non-HiDPI
# 2: fits only HiDPI
self.hidpi = int(kwargs["hidpi"]) if "hidpi" in kwargs else None
self.angle = int(kwargs["angle"]) if "angle" in kwargs else None
self.brightness = float(kwargs["brightness"]) if "brightness" in kwargs else None
self.underscan = float(kwargs["underscan"]) if "underscan" in kwargs else None
self.source = kwargs["source"] if "source" in kwargs else None
# Make sure IOKit is ready for use in any/all commands
getIOKit()
# "Magic" methods
def __str__(self):
# A list to contain strings of all the arguments in the command
stringList = [self.verb]
# Determine subcommand
if self.subcommand:
stringList.append(self.subcommand)
# Determine value
if self.verb == "res":
if self.width and self.height: # can also be set by subcommand=highest
stringList.append(self.width)
stringList.append(self.height)
elif self.verb == "rotate":
stringList.append(self.angle)
elif self.verb == "brightness":
stringList.append(self.brightness)
elif self.verb == "underscan":
stringList.append(self.underscan)
elif self.verb == "mirror" and self.subcommand == "enable":
stringList.append(self.source.tag)
# Determine options
if self.verb == "show" or self.verb == "res":
if self.hidpi == 1:
stringList.append("no-hidpi")
elif self.hidpi == 2:
stringList.append("only-hidpi")
if self.verb == "res":
if self.refresh:
stringList.append("refresh {}".format(self.refresh))
# Determine scope
if self.scope:
if len(self.scope) == len(getAllDisplays()):
stringList.append("all")
else:
for display in sorted(self.scope):
stringList.append(display.tag)
# Default scope
else:
if (
self.verb == "res" or
self.verb == "rotate" or
self.verb == "brightness" or
self.verb == "underscan"
):
stringList.append("main")
elif (
self.verb == "show" or
(self.verb == "mirror" and self.subcommand == "disable")
):
stringList.append("all")
# Convert everything to a string so it can be joined
for i in range(len(stringList)):
stringList[i] = str(stringList[i])
return " ".join(stringList)
def __eq__(self, other):
def safeScopeCheckEquals(a, b):
"""
Check whether two Commands' scopes are equal in a None-safe way
:param a: The first Command
:param b: The second Command
:return: Whether the two scopes are equal
"""
if a.scope and b.scope:
return set(a.scope) == set(b.scope)
else:
return a.scope == b.scope
if isinstance(other, self.__class__):
return all([
isinstance(other, self.__class__),
self.verb == other.verb,
self.subcommand == other.subcommand,
safeScopeCheckEquals(self, other),
self.width == other.width,
self.height == other.height,
self.refresh == other.refresh,
self.hidpi == other.hidpi,
self.angle == other.angle,
self.brightness == other.brightness,
self.underscan == other.underscan,
self.source == other.source,
])
else:
return NotImplemented
def __ne__(self, other):
if isinstance(other, self.__class__):
return not self.__eq__(other)
else:
return NotImplemented
def __lt__(self, other):
if self.__eq__(other):
return False
else:
return self.__str__().lower() < self.__str__().lower()
def __gt__(self, other):
if self.__eq__(other):
return False
else:
return self.__str__().lower() > self.__str__().lower()
def __hash__(self):
return hash(self.__str__())
# Run (and its handlers)
def run(self):
"""
Runs the command this Command has stored
"""
try:
if self.verb == "help":
self.__handleHelp()
elif self.verb == "show":
self.__handleShow()
elif self.verb == "res":
self.__handleRes()
elif self.verb == "rotate":
self.__handleRotate()
elif self.verb == "brightness":
self.__handleBrightness()
elif self.verb == "underscan":
self.__handleUnderscan()
elif self.verb == "mirror":
self.__handleMirror()
except DisplayError as e:
raise CommandExecutionError(e.message, command=self)
def __handleHelp(self):
"""
Shows the user usage information (either for a specific verb, or general help)
"""
helpTypes = {
"usage": "\n".join([
"usage: display_manager.py <command>",
"",
"COMMANDS (required)",
" help Show help information about a command",
" show Show current/available display configurations",
" res Manage display resolution",
" brightness Manage display brightness",
" rotate Manage display rotation",
" underscan Manage display underscan",
" mirror Manage screen mirroring",
]), "help": "\n".join([
"usage: display_manager.py help <command>",
"",
"COMMANDS (required)",
" help Show help information about a command",
" show Show current/available display configurations",
" res Manage display resolution and refresh rate",
" brightness Manage display brightness",
" rotate Manage display rotation",
" underscan Manage display underscan",
" mirror Manage screen mirroring",
]), "show": "\n".join([
"usage: display_manager.py show [subcommand] [options] [scope...]",
"",
"SUBCOMMANDS (optional)",
" current (default) Show the current display configuration",
" default Apple's recommended default configuration",
" highest Show the highest available configuration",
" available Show all available configurations",
"",
"OPTIONS (optional; only applies to \"available\")",
" no-hidpi Don\'t show HiDPI resolutions",
" only-hidpi Only show HiDPI resolutions",
"",
" (Note: by default, both HiDPI and non-HiDPI resolutions are shown)",
"",
"SCOPE (optional)",
" main Perform this command on the main display",
" ext<N> Perform this command on external display number <N>",
" all (default) Perform this command on all connected displays",
]), "res": "\n".join([
"usage: display_manager.py res <resolution> [refresh] [options] [scope...]",
"",
"RESOLUTION (required)",
" default Apple's recommended default configuration",
" highest Set the display to the highest available configuration",
" <width> <height> Width and height (in pixels)",
" (Note: width and height must be separated by at least one space)",
"",
"REFRESH (not used by \"default\" or \"highest\" resolution; optional otherwise)",
" <refresh> Refresh rate (in Hz)",
" (Note: if refresh rate is not specified, it will default to a rate that is "
"available at the desired resolution, if possible)",
"",
"OPTIONS (optional)",
" no-hidpi Don\'t set to HiDPI resolutions",
" only-hidpi Only set to HiDPI resolutions",
"",
" (Note: by default, both HiDPI and non-HiDPI resolutions are shown)",
"",
"SCOPE (optional)",
" main (default) Perform this command on the main display",
" ext<N> Perform this command on external display number <N>",
" all Perform this command on all connected displays",
]), "rotate": "\n".join([
"usage: display_manager.py rotate <angle> [scope...]",
"",
"ANGLE (required)",
" <angle> Desired display rotation; must be a multiple of 90",
"",
"SCOPE (optional)",
" main (default) Perform this command on the main display",
" ext<N> Perform this command on external display number <N>",
" all Perform this command on all connected displays",
]), "brightness": "\n".join([
"usage: display_manager.py brightness <brightness> [scope...]",
"",
"BRIGHTNESS (required)",
" <brightness> A number between 0 and 1 (inclusive); "
"0 is minimum brightness, and 1 is maximum brightness",
"",
"SCOPE (optional)",
" main (default) Perform this command on the main display",
" ext<N> Perform this command on external display number <N>",
" all Perform this command on all connected displays",
]), "underscan": "\n".join([
"usage: display_manager.py underscan <underscan> [scope...]",
"",
"UNDERSCAN (required)",
" <underscan> A number between 0 and 1 (inclusive); "
"0 is minimum underscan, and 1 is maximum underscan",
"",
"SCOPE (optional)",
" main (default) Perform this command on the main display",
" ext<N> Perform this command on external display number <N>",
" all Perform this command on all connected displays",
]), "mirror": "\n".join([
"usage: display_manager.py mirror enable <source> <target...>",
" or: display_manager.py mirror disable [scope...]",
"",
"SUBCOMMANDS (required)",
" enable Set <target> to mirror <source>",
" disable Disable mirroring on <scope>",
"",
"SOURCE/TARGET(S) (not used by \"disable\"; required for \"enable\")",
" source The display which will be mirrored by the target(s); "
"must be a single element of <SCOPE> (see below); cannot be \"all\"",
" target(s) The display(s) which will mirror the source; "
"must be an element of <SCOPE> (see below)",
"",
"SCOPE",
" main The main display",
" ext<N> External display number <N>",
" all (default scope for \"disable\")",
" For <enable>: all connected displays besides <source>; only available to <target>",
" For <disable>: all connected displays",
])}
if self.subcommand in helpTypes:
print(helpTypes[self.subcommand])
else:
print(helpTypes["usage"])
def __handleShow(self):
"""
Shows the user information about connected displays
"""
for i, display in enumerate(self.scope):
# Always print display identifier
print("display \"{0}\":".format(display.tag))
if self.subcommand == "current":
current = display.currentMode
print(current.bigString)
if display.rotation is not None:
print("rotation: {}".format(display.rotation))
if display.brightness is not None:
print("brightness: {:.2f}".format(display.brightness))
if display.underscan is not None:
print("underscan: {:.2f}".format(display.underscan))
if display.mirrorSource is not None:
print("mirror of: {}".format(display.mirrorSource.tag))
elif self.subcommand == "default":
default = display.defaultMode
if default:
print(default.bigString)
elif self.subcommand == "highest":
highest = display.highestMode(self.hidpi)
if highest:
print(highest.bigString)
elif self.subcommand == "available":
# Categorize modes by type, in order
current = None
default = None
hidpi = []
lodpi = []
for mode in sorted(display.allModes, reverse=True):
if mode == display.currentMode:
current = mode
# Note: intentionally left "if" instead of "elif"; mode can be both current and default
if mode.isDefault:
default = mode
if mode.hidpi:
hidpi.append(mode)
if not mode.hidpi:
lodpi.append(mode)
if current:
print("\n".join([
" current mode:",
" {}".format(current.littleString),
]))
if default:
print("\n".join([
" default mode:",
" {}".format(default.littleString),
]))
if hidpi:
print(
" HiDPI modes:"
)
for mode in hidpi:
print(
" {}".format(mode.littleString)
)
if lodpi:
print(
" non-HiDPI modes:"
)
for mode in lodpi:
print(
" {}".format(mode.littleString)
)
# Leave an empty line between displays
if i < len(self.scope) - 1:
print("")
def __handleRes(self):
"""
Sets the display to the correct DisplayMode.
"""
for display in self.scope:
if self.subcommand == "default":
default = display.defaultMode
display.setMode(default)
elif self.subcommand == "highest":
highest = display.highestMode(self.hidpi)
display.setMode(highest)
else:
closest = display.closestMode(self.width, self.height, self.refresh, self.hidpi)
display.setMode(closest)
def __handleRotate(self):
"""
Sets display rotation.
"""
for display in self.scope:
display.setRotate(self.angle)
def __handleBrightness(self):
"""
Sets display brightness
"""
for display in self.scope:
display.setBrightness(self.brightness)
def __handleUnderscan(self):
"""
Sets or shows a display's underscan settings.
"""
for display in self.scope:
display.setUnderscan(self.underscan)
def __handleMirror(self):
"""
Enables or disables mirroring between two displays.
"""
if self.subcommand == "enable":
source = self.source
for target in self.scope:
target.setMirrorSource(source)
elif self.subcommand == "disable":
for target in self.scope:
# If display is a mirror of another display, disable mirroring between them
if target.mirrorSource is not None:
target.setMirrorSource(None)
class CommandList(object):
"""
Holds one or more "Command" instances, and allows smart simultaneous execution
"""
def __init__(self, commands=None):
"""
:param commands: A single Command, a list of Commands, or a CommandList
"""
# self.commands is a list that contains all the raw commands passed in to self.addCommand
self.commands = []
# self.commandDict will consist of displayID keys corresponding to commands for that display
self.commandDict = {}
if commands:
if isinstance(commands, Command):
self.addCommand(commands)
elif isinstance(commands, list):
for command in commands:
self.addCommand(command)
elif isinstance(commands, CommandList):
for command in commands.commands:
self.addCommand(command)
# "Magic" methods
def __eq__(self, other):
if isinstance(other, self.__class__):
return set(self.commands) == set(other.commands)
else:
return NotImplemented
def __ne__(self, other):
if isinstance(other, self.__class__):
return set(self.commands) != set(other.commands)
else:
return NotImplemented
def __hash__(self):
h = 0
for command in self.commands:
h = h | command.__str__()
return hash(h)
# Command interfacing
def addCommand(self, command):
"""
:param command: The Command to add to this CommandList
"""
# Break "command" into each individual action it will perform
# on each individual display in its scope, and add those actions
# to commandDict, according to their associated display
if command.scope:
if len(command.scope) == len(getAllDisplays()):
if "all" in self.commandDict:
self.commandDict["all"].append(command)
else:
self.commandDict["all"] = [command]
else:
for display in command.scope:
if display.tag in self.commandDict:
self.commandDict[display.tag].append(command)
else:
self.commandDict[display.tag] = [command]
# If there is no scope, there will be only one action.
# In this case, we simply add the command to key "None".
# Note: this should only be possible with verb="help", since every
# other verb has a default scope
else:
if None in self.commandDict:
self.commandDict[None].append(command)
else:
self.commandDict[None] = [command]
self.commands.append(command)
def run(self):
"""
Runs all stored Commands in a non-interfering fashion
"""
for displayTag in self.commandDict:
# Commands for this particular display
displayCommands = self.commandDict[displayTag]
# Group commands by subcommand. Must preserve ordering to avoid interfering commands
verbGroups = collections.OrderedDict([
("help", []),
("mirror", []),
("rotate", []),
("res", []),
("underscan", []),
("brightness", []),
("show", []),
])
for command in displayCommands:
verbGroups[command.verb].append(command)
# Run commands by subcommand
for verb in verbGroups:
# Commands for this display, of this subcommand
commands = verbGroups[verb]
if len(commands) > 0:
# Multiple commands of these types will undo each other.
# As such, just run the most recently added command (the last in the list)
if (
verb == "help" or
verb == "rotate" or
verb == "res" or
verb == "brightness" or
verb == "underscan"
):
try:
commands[-1].run()
except DisplayError as e:
raise CommandExecutionError(e.message, commands[-1])
# "show" commands don't interfere with each other, so run all of them
elif verb == "show":
for command in commands:
try:
command.run()
except DisplayError as e:
raise CommandExecutionError(e.message, command)
# "mirror" commands are the most complicated to deal with
elif verb == "mirror":
command = commands[-1]
if command.subcommand == "enable":
display = getDisplayFromTag(displayTag)
# The current Display that the above "display" is mirroring
currentMirror = display.mirrorSource
# Become a mirror of most recently requested display
mirrorDisplay = command.source
# If display is not a mirror of any other display
if currentMirror is None:
try:
display.setMirrorSource(mirrorDisplay)
except DisplayError as e:
raise CommandExecutionError(e.message, command)
# The user requested that this display mirror itself, or that it mirror a display
# which it is already mirroring. In either case, nothing should be done
elif display == currentMirror or currentMirror == mirrorDisplay:
pass
# display is already a mirror, but not of the requested display
else:
# First disable mirroring, then enable it for new mirror
display.setMirrorSource(None)
display.setMirrorSource(mirrorDisplay)
try:
display.setMirrorSource(None)
display.setMirrorSource(mirrorDisplay)
except DisplayError as e:
raise CommandExecutionError(e.message, command)
elif command.subcommand == "disable":
try:
command.run()
except DisplayError as e:
raise CommandExecutionError(e.message, command)
def getDisplayFromTag(displayTag):
"""
Returns a Display for "displayTag"
:param displayTag: The display tag to find the Display of
:return: The Display which displayTag refers to
"""
if displayTag == "main":
return getMainDisplay()
elif displayTag == "all":
return getAllDisplays()
elif re.match(r"^ext[0-9]+$", displayTag):
# Get all the external displays (in order)
externals = sorted(getAllDisplays())
for display in externals:
if display.isMain:
externals.remove(display)
break
# Get the number in displayTag
externalNum = int(displayTag[3:])
if externalNum > len(externals) - 1:
# There aren't enough displays for this externalNumber to be valid
raise CommandValueError("There is no display \"{}\"".format(displayTag))
else:
# 0 < externalNum < len(externals) - 1 means valid tag
# ("0 < externalNum" known from re.match(r"^ext[0-9]+$") above)
return externals[externalNum]
# Note: no need for final "else" here, because getDisplayFromTag will only
# be passed regex matches for "main|all|ext[0-9]+", because these are the only
# arguments added to "scopeTags"
def getCommand(commandString):
"""
Converts the commandString into a Command
:param commandString: the string to convert
:return: The Command represented by "commandString"
"""
if not commandString:
return None
# Individual words/values in the command
words = commandString.split()
# Determine verb, and remove it from words
verb = words.pop(0)
# Determine scope, and remove it from words
scopePattern = r"^(main|ext[0-9]+|all)$"
scopeTags = []
# Iterate backwards through the indices of "words"
for i in range(len(words) - 1, -1, -1):
if re.match(scopePattern, words[i]):
# If this scope tag is at the end of the list
if words[i] == words[-1]:
scopeTags.append(words.pop(i))
# This scope tag is in the wrong place
else:
raise CommandSyntaxError("Invalid placement of {}".format(words[i]), verb=verb)
# Determine positionals (all remaining words)
positionals = words
attributesDict = {
"verb": verb,
"subcommand": None,
"scope": None,
"width": None,
"height": None,
"refresh": None,
"hidpi": None,
"angle": None,
"brightness": None,
"underscan": None,
"source": None,
}
if verb == "help":
if len(positionals) == 0:
# Default (sub)command
subcommand = "usage"
elif len(positionals) == 1:
if positionals[0] in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"]:
subcommand = positionals[0]
# Invalid (sub)command
else:
raise CommandValueError("\"{}\" is not a valid command".format(positionals[0]), verb=verb)
# Too many arguments
else:
raise CommandSyntaxError("Help commands can only have one argument", verb=verb)
attributesDict["subcommand"] = subcommand
elif verb == "show":
# Determine HiDPI settings
hidpi = 0
for positional in positionals:
if positional == "no-hidpi":
# If HiDPI hasn't been set to the contrary setting
if hidpi != 2:
hidpi = 1 # doesn't match HiDPI
positionals.remove(positional)
else:
raise CommandValueError("Cannot specify both \"no-hidpi\" and \"only-hidpi\"", verb=verb)
elif positional == "only-hidpi":
# If HiDPI hasn't been set to the contrary setting
if hidpi != 1:
hidpi = 2 # only matches HiDPI
positionals.remove(positional)
else:
raise CommandValueError("Cannot specify both \"no-hidpi\" and \"only-hidpi\"", verb=verb)
if len(positionals) == 0:
# Default subcommand
subcommand = "current"
elif len(positionals) == 1:
if positionals[0] in ["current", "default", "highest", "available"]:
subcommand = positionals[0]
# Invalid subcommand
else:
raise CommandValueError("\"{}\" is not a valid subcommand".format(positionals[0]), verb=verb)
# Too many arguments
else:
raise CommandSyntaxError("Show commands can only have one subcommand", verb=verb)
# Determine scope
if len(scopeTags) > 0:
if "all" in scopeTags:
scope = getAllDisplays()
else:
scope = []
for scopeTag in scopeTags:
scope.append(getDisplayFromTag(scopeTag))
else:
# Default scope
scope = getAllDisplays()
attributesDict["subcommand"] = subcommand
attributesDict["hidpi"] = hidpi
attributesDict["scope"] = scope
elif verb == "res":
# Determine HiDPI settings
hidpi = 0
for positional in positionals:
if positional == "no-hidpi":
# If HiDPI hasn't been set to the contrary setting
if hidpi != 2:
hidpi = 1 # doesn't match HiDPI
positionals.remove(positional)
else:
raise CommandValueError("Cannot specify both \"no-hidpi\" and \'only-hidpi\"", verb=verb)
elif positional == "only-hidpi":
# If HiDPI hasn't been set to the contrary setting
if hidpi != 1:
hidpi = 2 # only matches HiDPI
positionals.remove(positional)
else:
raise CommandValueError("Cannot specify both \"no-hidpi\" and \'only-hidpi\"", verb=verb)
if len(positionals) == 0:
raise CommandSyntaxError("Res commands must specify a resolution", verb=verb)
# case: "default"/"highest"
elif len(positionals) == 1:
if positionals[0] in ["default", "highest"]:
subcommand = positionals[0]
else:
raise CommandValueError(
"Res commands must either specify both width and height or use the \"highest\" keyword",
verb=verb
)
attributesDict["subcommand"] = subcommand
attributesDict["hidpi"] = hidpi
# cases: ("default"/"highest", refresh) or (width, height)
elif len(positionals) == 2:
# case: ("default"/"highest", refresh)
if positionals[0] in ["default", "highest"]:
subcommand = positionals[0]
try:
refresh = int(positionals[1])
except ValueError:
raise CommandValueError("\"{}\" is not a valid refresh rate", verb=verb)
if refresh < 0:
raise CommandValueError("Refresh rate must be positive", verb=verb)
attributesDict["subcommand"] = subcommand
attributesDict["refresh"] = refresh
attributesDict["hidpi"] = hidpi
# case: (width, height)
else:
# Try to parse positionals as integers
wh = []
for i in range(len(positionals)):
try:
wh.append(int(positionals[i]))
except ValueError:
wh.append(None)
width, height = wh
# Neither width nor height were integers (and thus invalid pixel counts)
if width is None and height is None:
raise CommandValueError(
"Neither \"{}\" nor \"{}\" are valid widths or heights".format(
positionals[0], positionals[1]),
verb=verb
)
# width was invalid
elif width is None:
raise CommandValueError(
"\"{}\" is not a valid width".format(positionals[0]),
verb=verb
)
# height was invalid
elif height is None:
raise CommandValueError(
"\"{}\" is not a valid height".format(positionals[1]),
verb=verb
)
# no negative dimensions
if width < 0 or height < 0:
raise CommandValueError(
"Width and height must be positive",
verb=verb
)
attributesDict["width"] = width
attributesDict["height"] = height
attributesDict["hidpi"] = hidpi
# case: (width, height, refresh)
elif len(positionals) == 3:
# Try to parse width, height, and refresh as integers
whr = []
for i in range(len(positionals)):
try:
whr.append(int(positionals[i]))
except ValueError:
whr.append(None)
width, height, refresh = whr
# Nothing was an integer
if width is None and height is None and refresh is None:
raise CommandValueError(
"\"{}\"x\"{}\" is not a valid resolution, and \"{}\" is not a valid refresh rate".format(
positionals[0], positionals[1], positionals[2]),
verb=verb
)
# Neither width nor height were integers
elif width is None or height is None:
raise CommandValueError(
"\"{}\"x\"{}\" is not a valid resolution".format(
positionals[0], positionals[1]),
verb=verb
)
# refresh was not an integer
elif refresh is None:
raise CommandValueError(
"\"{}\" is not a valid refresh rate".format(positionals[2]),
verb=verb
)
# no negative dimensions or rate
if width < 0 or height < 0 or refresh < 0:
raise CommandValueError(
"Width, height, and refresh rate must be positive",
verb=verb
)
attributesDict["width"] = width
attributesDict["height"] = height
attributesDict["refresh"] = refresh
attributesDict["hidpi"] = hidpi
else:
raise CommandSyntaxError(
"Too many arguments supplied for the res command",
verb=verb
)
# Determine scope
if len(scopeTags) > 0:
if "all" in scopeTags:
scope = getAllDisplays()