44import time
55import traceback
66from dataclasses import dataclass , field
7- from typing import Callable , Any , Dict , List , Optional , Tuple , Type , Union , FrozenSet , ClassVar
7+ from typing import Any , Callable , ClassVar , Dict , FrozenSet , List , Optional , Tuple , Type , Union
8+
9+ from . import config
810from ._version import __author__ , __version__ # noqa: F401
911from .exceptions import NoValidDisplayError , format_exc
10- from .helpers import (BrightnessMethod , ScreenBrightnessError ,
11- logarithmic_range , percentage )
12+ from .helpers import BrightnessMethod , ScreenBrightnessError , logarithmic_range , percentage
1213from .types import DisplayIdentifier , IntPercentage , Percentage
13- from . import config
14-
1514
1615_logger = logging .getLogger (__name__ )
1716_logger .addHandler (logging .NullHandler ())
@@ -22,7 +21,7 @@ def get_brightness(
2221 display : Optional [DisplayIdentifier ] = None ,
2322 method : Optional [str ] = None ,
2423 allow_duplicates : Optional [bool ] = None ,
25- verbose_error : bool = False
24+ verbose_error : bool = False ,
2625) -> List [Union [IntPercentage , None ]]:
2726 '''
2827 Returns the current brightness of one or more displays
@@ -57,7 +56,7 @@ def get_brightness(
5756 method = method ,
5857 meta_method = 'get' ,
5958 allow_duplicates = allow_duplicates ,
60- verbose_error = verbose_error
59+ verbose_error = verbose_error ,
6160 )
6261 # __brightness can return None depending on the `no_return` kwarg. That obviously would never happen here
6362 # but the type checker doesn't see it that way.
@@ -72,7 +71,7 @@ def set_brightness(
7271 force : bool = False ,
7372 allow_duplicates : Optional [bool ] = None ,
7473 verbose_error : bool = False ,
75- no_return : bool = True
74+ no_return : bool = True ,
7675) -> Optional [List [Union [IntPercentage , None ]]]:
7776 '''
7877 Sets the brightness level of one or more displays to a given value.
@@ -132,10 +131,13 @@ def set_brightness(
132131 value = percentage (value , lower_bound = lower_bound )
133132
134133 return __brightness (
135- value , display = display , method = method ,
136- meta_method = 'set' , no_return = no_return ,
134+ value ,
135+ display = display ,
136+ method = method ,
137+ meta_method = 'set' ,
138+ no_return = no_return ,
137139 allow_duplicates = allow_duplicates ,
138- verbose_error = verbose_error
140+ verbose_error = verbose_error ,
139141 )
140142
141143
@@ -149,7 +151,7 @@ def fade_brightness(
149151 force : bool = False ,
150152 logarithmic : bool = True ,
151153 stoppable : bool = True ,
152- ** kwargs
154+ ** kwargs ,
153155) -> Union [List [threading .Thread ], List [Union [IntPercentage , None ]]]:
154156 '''
155157 Gradually change the brightness of one or more displays
@@ -199,23 +201,25 @@ def fade_brightness(
199201 '''
200202 # make sure only compatible kwargs are passed to filter_monitors
201203 available_monitors = filter_monitors (
202- ** {k : v for k , v in kwargs .items () if k in (
203- 'display' , 'haystack' , 'method' , 'include' , 'allow_duplicates'
204- )}
204+ ** {k : v for k , v in kwargs .items () if k in ('display' , 'haystack' , 'method' , 'include' , 'allow_duplicates' )}
205205 )
206206
207207 threads = []
208208 for i in available_monitors :
209209 display = Display .from_dict (i )
210210
211- thread = threading .Thread (target = display ._fade_brightness , args = (finish ,), kwargs = {
212- 'start' : start ,
213- 'interval' : interval ,
214- 'increment' : increment ,
215- 'force' : force ,
216- 'logarithmic' : logarithmic ,
217- 'stoppable' : stoppable
218- })
211+ thread = threading .Thread (
212+ target = display ._fade_brightness ,
213+ args = (finish ,),
214+ kwargs = {
215+ 'start' : start ,
216+ 'interval' : interval ,
217+ 'increment' : increment ,
218+ 'force' : force ,
219+ 'logarithmic' : logarithmic ,
220+ 'stoppable' : stoppable ,
221+ },
222+ )
219223 thread .start ()
220224 threads .append (thread )
221225
@@ -269,9 +273,7 @@ def list_monitors_info(
269273 print('UID:', display['uid'])
270274 ```
271275 '''
272- return _OS_MODULE .list_monitors_info (
273- method = method , allow_duplicates = allow_duplicates , unsupported = unsupported
274- )
276+ return _OS_MODULE .list_monitors_info (method = method , allow_duplicates = allow_duplicates , unsupported = unsupported )
275277
276278
277279@config .default_params
@@ -329,15 +331,15 @@ def get_methods(name: Optional[str] = None) -> Dict[str, Type[BrightnessMethod]]
329331 return {name : methods [name ]}
330332
331333 _logger .debug (f'requested method { name !r} invalid' )
332- raise ValueError (
333- f'invalid method { name !r} , must be one of: { list (methods )} ' )
334+ raise ValueError (f'invalid method { name !r} , must be one of: { list (methods )} ' )
334335
335336
336337@dataclass
337- class Display () :
338+ class Display :
338339 '''
339340 Represents a single connected display.
340341 '''
342+
341343 index : int
342344 '''The index of the display relative to the method it uses.
343345 So if the index is 0 and the method is `windows.VCP`, then this is the 1st
@@ -366,8 +368,7 @@ class Display():
366368 '''A dictionary mapping display identifiers to latest fade threads for stopping fades.'''
367369
368370 def __post_init__ (self ):
369- self ._logger = _logger .getChild (self .__class__ .__name__ ).getChild (
370- str (self .get_identifier ()[1 ])[:20 ])
371+ self ._logger = _logger .getChild (self .__class__ .__name__ ).getChild (str (self .get_identifier ()[1 ])[:20 ])
371372
372373 def fade_brightness (
373374 self ,
@@ -378,7 +379,7 @@ def fade_brightness(
378379 force : bool = False ,
379380 logarithmic : bool = True ,
380381 blocking : bool = True ,
381- stoppable : bool = True
382+ stoppable : bool = True ,
382383 ) -> Optional [threading .Thread ]:
383384 '''
384385 Gradually change the brightness of this display to a set value.
@@ -405,14 +406,18 @@ def fade_brightness(
405406 thread in which the fade operation is running.
406407 Otherwise, it returns None.
407408 '''
408- thread = threading .Thread (target = self ._fade_brightness , args = (finish ,), kwargs = {
409- 'start' : start ,
410- 'interval' : interval ,
411- 'increment' : increment ,
412- 'force' : force ,
413- 'logarithmic' : logarithmic ,
414- 'stoppable' : stoppable
415- })
409+ thread = threading .Thread (
410+ target = self ._fade_brightness ,
411+ args = (finish ,),
412+ kwargs = {
413+ 'start' : start ,
414+ 'interval' : interval ,
415+ 'increment' : increment ,
416+ 'force' : force ,
417+ 'logarithmic' : logarithmic ,
418+ 'stoppable' : stoppable ,
419+ },
420+ )
416421 thread .start ()
417422
418423 if not blocking :
@@ -429,7 +434,7 @@ def _fade_brightness(
429434 increment : int = 1 ,
430435 force : bool = False ,
431436 logarithmic : bool = True ,
432- stoppable : bool = True
437+ stoppable : bool = True ,
433438 ) -> None :
434439 # Record the latest thread for this display so that other stoppable threads can be stopped
435440 display_key = frozenset ((self .method , self .index ))
@@ -443,17 +448,15 @@ def _fade_brightness(
443448 current = self .get_brightness ()
444449
445450 finish = percentage (finish , current , lower_bound )
446- start = percentage (
447- current if start is None else start , current , lower_bound )
451+ start = percentage (current if start is None else start , current , lower_bound )
448452
449453 # mypy says "object is not callable" but range is. Ignore this
450454 range_func : Callable = logarithmic_range if logarithmic else range # type: ignore[assignment]
451455 increment = abs (increment )
452456 if start > finish :
453457 increment = - increment
454458
455- self ._logger .debug (
456- f'fade { start } ->{ finish } :{ increment } :logarithmic={ logarithmic } ' )
459+ self ._logger .debug (f'fade { start } ->{ finish } :{ increment } :logarithmic={ logarithmic } ' )
457460
458461 # Record the time when the next brightness change should start
459462 next_change_start_time = time .time ()
@@ -491,7 +494,7 @@ def from_dict(cls, display: dict) -> 'Display':
491494 model = display ['model' ],
492495 name = display ['name' ],
493496 serial = display ['serial' ],
494- uid = display .get ('uid' )
497+ uid = display .get ('uid' ),
495498 )
496499
497500 def get_brightness (self ) -> IntPercentage :
@@ -530,8 +533,7 @@ def is_active(self) -> bool:
530533 return True
531534 except Exception as e :
532535 self ._logger .error (
533- f'Display.is_active: { self .get_identifier ()} failed get_brightness call'
534- f' - { format_exc (e )} '
536+ f'Display.is_active: { self .get_identifier ()} failed get_brightness call - { format_exc (e )} '
535537 )
536538 return False
537539
@@ -550,11 +552,7 @@ def set_brightness(self, value: Percentage, force: bool = False):
550552 else :
551553 lower_bound = 0
552554
553- value = percentage (
554- value ,
555- current = self .get_brightness ,
556- lower_bound = lower_bound
557- )
555+ value = percentage (value , current = self .get_brightness , lower_bound = lower_bound )
558556
559557 self .method .set_brightness (value , display = self .index )
560558
@@ -565,7 +563,7 @@ def filter_monitors(
565563 haystack : Optional [List [dict ]] = None ,
566564 method : Optional [str ] = None ,
567565 include : List [str ] = [],
568- allow_duplicates : Optional [bool ] = None
566+ allow_duplicates : Optional [bool ] = None ,
569567) -> List [dict ]:
570568 '''
571569 Searches through the information for all detected displays
@@ -596,8 +594,7 @@ def filter_monitors(
596594 ```
597595 '''
598596 if display is not None and type (display ) not in (str , int ):
599- raise TypeError (
600- f'display kwarg must be int or str, not "{ type (display ).__name__ } "' )
597+ raise TypeError (f'display kwarg must be int or str, not \" { type (display ).__name__ } \" ' )
601598
602599 def get_monitor_list ():
603600 # if we have been provided with a list of monitors to sift through then use that
@@ -606,11 +603,9 @@ def get_monitor_list():
606603 monitors_with_duplicates = haystack
607604 if method is not None :
608605 method_class = next (iter (get_methods (method ).values ()))
609- monitors_with_duplicates = [
610- i for i in haystack if i ['method' ] == method_class ]
606+ monitors_with_duplicates = [i for i in haystack if i ['method' ] == method_class ]
611607 else :
612- monitors_with_duplicates = list_monitors_info (
613- method = method , allow_duplicates = True )
608+ monitors_with_duplicates = list_monitors_info (method = method , allow_duplicates = True )
614609
615610 return monitors_with_duplicates
616611
@@ -627,7 +622,7 @@ def filter_monitor_list(to_filter):
627622 elif isinstance (display , int ):
628623 # 'display' variable should be the index of the monitor
629624 # return a list with the monitor at the index or an empty list if the index is out of range
630- return to_filter [display : display + 1 ]
625+ return to_filter [display : display + 1 ]
631626 elif isinstance (display , str ):
632627 # 'display' variable should be an identifier of the monitor
633628 # multiple monitors with the same identifier are allowed here, so return all of them
@@ -700,32 +695,26 @@ def __brightness(
700695 no_return : bool = False ,
701696 allow_duplicates : bool = False ,
702697 verbose_error : bool = False ,
703- ** kwargs : Any
698+ ** kwargs : Any ,
704699) -> Optional [List [Union [IntPercentage , None ]]]:
705700 '''Internal function used to get/set brightness'''
706- _logger .debug (
707- f"brightness { meta_method } request display { display } with method { method } " )
701+ _logger .debug (f'brightness { meta_method } request display { display } with method { method } ' )
708702
709703 output : List [Union [int , None ]] = []
710704 errors = []
711705
712706 for monitor in filter_monitors (display = display , method = method , allow_duplicates = allow_duplicates ):
713707 try :
714708 if meta_method == 'set' :
715- monitor ['method' ].set_brightness (
716- * args , display = monitor ['index' ], ** kwargs )
709+ monitor ['method' ].set_brightness (* args , display = monitor ['index' ], ** kwargs )
717710 if no_return :
718711 output .append (None )
719712 continue
720713
721- output += monitor ['method' ].get_brightness (
722- display = monitor ['index' ], ** kwargs )
714+ output += monitor ['method' ].get_brightness (display = monitor ['index' ], ** kwargs )
723715 except Exception as e :
724716 output .append (None )
725- errors .append ((
726- monitor , e .__class__ .__name__ ,
727- traceback .format_exc () if verbose_error else e
728- ))
717+ errors .append ((monitor , e .__class__ .__name__ , traceback .format_exc () if verbose_error else e ))
729718
730719 if output :
731720 output_is_none = set (output ) == {None }
@@ -735,8 +724,7 @@ def __brightness(
735724 or (
736725 # if we are setting the brightness then we CAN have a None output
737726 # but only if no_return is True.
738- meta_method == 'set'
739- and ((no_return and output_is_none ) or not output_is_none )
727+ meta_method == 'set' and ((no_return and output_is_none ) or not output_is_none )
740728 )
741729 ):
742730 return None if no_return else output
@@ -759,10 +747,11 @@ def __brightness(
759747
760748if platform .system () == 'Windows' :
761749 from . import windows
750+
762751 _OS_MODULE = windows
763752elif platform .system () == 'Linux' :
764753 from . import linux
754+
765755 _OS_MODULE = linux
766756else :
767- _logger .warning (
768- f'package imported on unsupported platform ({ platform .system ()} )' )
757+ _logger .warning (f'package imported on unsupported platform ({ platform .system ()} )' )
0 commit comments