Пример #1
0
def parse_color(color):
    c = str(color).lower().strip()
    for k, v in _COLOR_FILTERS.items():
        c = c.replace(k, v)

    hex = None
    try:
        hc = '#' + c if not c.startswith('#') else c
        rgb = webcolors.hex_to_rgb(hc)
        if rgb:
            return hc.upper()
    except Exception:
        # probably not a hex already
        pass

    try:
        hex = webcolors.name_to_hex(c)
    except Exception:
        pass

    if '%' in c:
        try:
            hex = webcolors.rgb_percent_to_hex(
                (int(x.strip()) for x in c.split(',')))
        except Exception:
            pass
    else:
        try:
            hex = webcolors.rgb_to_hex((int(x.strip()) for x in c.split(',')))
        except Exception:
            pass

    return hex
Пример #2
0
    def test_rgb_percent_to_hex(self):
        """
        Test conversion from percent RGB triplet to hex.
        """
        test_pairs = (((u'100%', u'100%', u'0%'),
                       u'#ffff00'), ((u'0%', u'0%', u'50%'), u'#000080'),
                      ((u'85.49%', u'64.71%', u'12.5%'), u'#daa520'))

        for triplet, hex_value in test_pairs:
            self.assertEqual(hex_value, webcolors.rgb_percent_to_hex(triplet))
Пример #3
0
    def test_rgb_percent_to_hex(self):
        """
        Test conversion from percent RGB triplet to hex.
        """
        test_pairs = (((u'100%', u'100%', u'0%'), u'#ffff00'),
                      ((u'0%', u'0%', u'50%'), u'#000080'),
                      ((u'85.49%', u'64.71%', u'12.5%'), u'#daa520'))

        for triplet, hex_value in test_pairs:
            self.assertEqual(hex_value,
                             webcolors.rgb_percent_to_hex(triplet))
Пример #4
0
    def test_rgb_percent_to_hex(self):
        """
        Test conversion from percent RGB triplet to hex.

        """
        test_pairs = (
            (("100%", "100%", "0%"), "#ffff00"),
            (("0%", "0%", "50%"), "#000080"),
            (("85.49%", "64.71%", "12.5%"), "#daa520"),
        )

        for triplet, hex_value in test_pairs:
            assert hex_value == webcolors.rgb_percent_to_hex(triplet)
Пример #5
0
    def test_rgb_percent_to_hex(self):
        """
        Test conversion from percent RGB triplet to hex.

        """
        test_pairs = (
            ((u"100%", u"100%", u"0%"), u"#ffff00"),
            ((u"0%", u"0%", u"50%"), u"#000080"),
            ((u"85.49%", u"64.71%", u"12.5%"), u"#daa520"),
        )

        for triplet, hex_value in test_pairs:
            self.assertEqual(hex_value, webcolors.rgb_percent_to_hex(triplet))
Пример #6
0
def getColor(color):
    '''
    Convert any specification of a color to a hexadecimal color used by matplotlib.

    >>> graph.utilities.getColor('red')
    '#ff0000'
    >>> graph.utilities.getColor('r')
    '#ff0000'
    >>> graph.utilities.getColor('Steel Blue')
    '#4682b4'
    >>> graph.utilities.getColor('#f50')
    '#ff5500'
    >>> graph.utilities.getColor([0.5, 0.5, 0.5])
    '#808080'
    >>> graph.utilities.getColor(0.8)
    '#cccccc'
    >>> graph.utilities.getColor([0.8])
    '#cccccc'
    >>> graph.utilities.getColor([255, 255, 255])
    '#ffffff'

    Invalid colors raise GraphExceptions:

    >>> graph.utilities.getColor('l')
    Traceback (most recent call last):
    music21.graph.utilities.GraphException: invalid color abbreviation: l

    >>> graph.utilities.getColor('chalkywhitebutsortofgreenish')
    Traceback (most recent call last):
    music21.graph.utilities.GraphException: invalid color name: chalkywhitebutsortofgreenish

    >>> graph.utilities.getColor(True)
    Traceback (most recent call last):
    music21.graph.utilities.GraphException: invalid color specification: True
    '''
    # expand a single value to three
    if common.isNum(color):
        color = [color, color, color]
    if isinstance(color, str):
        if color[0] == '#':  # assume is hex
            # this will expand three-value codes, and check for badly
            # formed codes
            return webcolors.normalize_hex(color)
        color = color.lower().replace(' ', '')
        # check for one character matplotlib colors
        if len(color) == 1:
            colorMap = {'b': 'blue',
                        'g': 'green',
                        'r': 'red',
                        'c': 'cyan',
                        'm': 'magenta',
                        'y': 'yellow',
                        'k': 'black',
                        'w': 'white'}
            try:
                color = colorMap[color]
            except KeyError:
                raise GraphException(f'invalid color abbreviation: {color}')
        try:
            return webcolors.name_to_hex(color)
        except ValueError:  # no color match
            raise GraphException(f'invalid color name: {color}')

    elif common.isListLike(color):
        percent = False
        for sub in color:
            if sub < 1:
                percent = True
                break
        if percent:
            if len(color) == 1:
                color = [color[0], color[0], color[0]]
            # convert to 0 100% values as strings with % symbol
            colorStrList = [str(x * 100) + '%' for x in color]
            return webcolors.rgb_percent_to_hex(colorStrList)
        else:  # assume integers
            return webcolors.rgb_to_hex(tuple(color))
    raise GraphException(f'invalid color specification: {color}')
Пример #7
0
def main():
    parser = argparse.ArgumentParser(description='Tool to control per-key RGB keyboard backlighting on MSI laptops. https://github.com/Askannz/msi-perkeyrgb')
    parser.add_argument('-v', '--version', action='store_true', help='Prints version and exits.')
    parser.add_argument('-c', '--config', action='store', metavar='FILEPATH', help='Loads the configuration file located at FILEPATH. Refer to the README for syntax. If set to "-", '
                                                                                    'the configuration file is read from the standard input (stdin) instead.')
    parser.add_argument('-d', '--disable', action='store_true', help='Disable RGB lighting.')
    parser.add_argument('--id', action='store', metavar='VENDOR_ID:PRODUCT_ID', help='This argument allows you to specify the vendor/product id of your keyboard. You should not have to use this unless opening the keyboard fails with the default value. IDs are in hexadecimal format (example :  1038:1122)')
    parser.add_argument('--list-presets', action='store_true', help='List available presets for the given laptop model.')
    parser.add_argument('-p', '--preset', action='store', help='Use vendor preset (see --list-presets).')
    parser.add_argument('-m', '--model', action='store', help='Set laptop model (see --list-models). If not specified, will use %s as default.' % DEFAULT_MODEL)
    parser.add_argument('--list-models', action='store_true', help='List available laptop models.')
    parser.add_argument('-s', '--steady', action='store', metavar='COLOR', help='Set all of keyboard to a steady hex or css3 color e.g. 00ff00 or green.')
    parser.add_argument('-r', '--random', action='store_true', help='Set all of keyboard to a random hex color.')

    args = parser.parse_args()

    if args.version:
        print("Version : %s" % VERSION)

    elif args.list_models:
        print("Available laptop models are :")
        for msi_models, _ in AVAILABLE_MSI_KEYMAPS:
            for model in msi_models:
                print(model)
        print("\nIf your laptop is not in this list, use the closest one (with a keyboard layout as similar as possible). This tool will only work with per-key RGB models.")

    else:

        # Parse laptop model
        if not args.model:
            print("No laptop model specified, using %s as default." % DEFAULT_MODEL)
            msi_model = DEFAULT_MODEL
        else:
            try:
                msi_model = parse_model(args.model)
            except UnknownModelError:
                print("Unknown MSI model : %s" % args.model)
                sys.exit(1)

        # Parse USB vendor/product ID
        if not args.id:
            usb_id = parse_usb_id(DEFAULT_ID)
        else:
            try:
                usb_id = parse_usb_id(args.id)
            except UnknownIdError:
                print("Unknown vendor/product ID : %s" % args.id)
                sys.exit(1)

        # Loading presets
        msi_presets = MSI_Keyboard.get_model_presets(msi_model)

        if args.list_presets:
            if msi_presets == {}:
                print("No presets available for %s." % msi_model)
            else:
                print("Available presets for %s:" % msi_model)
                for preset in msi_presets.keys():
                    print("\t- %s" % preset)

        else:

            # Loading keymap
            msi_keymap = MSI_Keyboard.get_model_keymap(msi_model)

            # Loading keyboard
            try:
                kb = MSI_Keyboard(usb_id, msi_keymap, msi_presets)
            except HIDLibraryError as e:
                print("Cannot open HIDAPI library : %s. Make sure you have installed libhidapi on your system, then try running \"sudo ldconfig\" to regenerate library cache." % str(e))
                sys.exit(1)
            except HIDNotFoundError:
                if not args.id:
                    print("No MSI keyboards with a known product/vendor IDs were found. However, if you think your keyboard should work with this program, you can try overriding the ID by adding the option \"--id VENDOR_ID:PRODUCT_ID\". In that case you will also need to give yourself proper read/write permissions to the corresponding /dev/hidraw* device.")
                else:
                    print("No USB device with ID %s found." % args.id)
                sys.exit(1)
            except HIDOpenError:
                print("Cannot open keyboard. Possible causes :\n- You don't have permissions to open the HID device. Run this program as root, or give yourself read/write permissions to the corresponding /dev/hidraw*. If you have just installed this tool, reboot your computer for the udev rule to take effect.\n- The USB device is not a HID device.")
                sys.exit(1)

            # If user has requested disabling
            if args.disable:
                kb.set_color_all([0, 0, 0])
                kb.refresh()

            # If user has requested a preset
            elif args.preset:
                try:
                    preset = parse_preset(args.preset, msi_presets)
                except UnknownPresetError:
                    print("Preset %s not found for model %s. Use --list-presets for available options" % (args.preset, msi_model))
                    sys.exit(1)

                kb.set_preset(preset)
                kb.refresh()

            # If user has requested to load a config file
            elif args.config:
                try:
                    colors_map, warnings = load_config(args.config, msi_keymap)
                except ConfigError as e:
                    print("Error reading config file : %s" % str(e))
                    sys.exit(1)

                for w in warnings:
                    print("Warning :", w)

                kb.set_colors(colors_map)
                kb.refresh()

            # If user has requested to display a steady color
            elif args.steady:
                try:
                    colors_map, warnings = load_steady(webcolors.name_to_hex(args.steady)[1:], msi_keymap)
                except ValueError as e:
                    try:
                        colors_map, warnings = load_steady(args.steady, msi_keymap)
                    except ConfigError as e:
                        print("Error preparing steady color : %s" % str(e))
                        sys.exit(1)
                kb.set_colors(colors_map)
                kb.refresh()

            # If user has requested to display a random color
            elif args.random:
                try:
                    # Generate random color with 25% <= luminance < 75% and 50% <= saturation < 100%
                    # these bounds were chosen arbitrarily by inspection so that
                    # the resulting random color won't be too light or dark or desaturated.
                    # 
                    # HLS was chosen instead of HVL due to being more human-friendly
                    # see https://en.wikipedia.org/wiki/HSL_and_HSV#Motivation
                    col_rgb_percent = webcolors.PercentRGB(
                            *colorsys.hls_to_rgb(
                                random.random(),        # hue
                                random.random()*.5+.25, # lightness
                                random.random()*.5+.5   # saturation
                                )
                            )
                    col_hex = webcolors.rgb_percent_to_hex(["{:.2%}".format(val) for val in col_rgb_percent])[1:]
                    colors_map, warnings = load_steady(col_hex,msi_keymap)
                except ConfigError as e:
                    print("Error preparing steady color : %s" % str(e))
                    sys.exit(1)
                print("Setting keyboard color as #{}".format(col_hex))
                kb.set_colors(colors_map)
                kb.refresh()

            # If user has not requested anything
            else:
                print("Nothing to do ! Please specify a preset, steady, or a config file.")
Пример #8
0
	def to_hex(colorspec):

		"""
		desc:
			Converts a color specificaton to a seven-character lowercase
			hexadecimal color string, such as '#ff0000'.

		arguments:
			colorspec:
				desc:	A color specification.
				type:	[str, unicode, array-like, int]

		returns:
			desc:	A hexadecimal color specification.
			type:	unicode
		"""
		is_rgb = lambda c: hasattr(c, '__len__') \
			and len(c) == 3 \
			and all(isinstance(i, numbers.Integral) and 0 <= i <= 255 for i in c)

		if isinstance(colorspec, int):
			return webcolors.rgb_to_hex((colorspec, colorspec, colorspec))
		if is_rgb(colorspec):
			return webcolors.rgb_to_hex(colorspec)
		if isinstance(colorspec, basestring):
			try:
				colorspec = int(colorspec)
				return webcolors.rgb_to_hex((colorspec, colorspec, colorspec))
			except:
				pass
			if colorspec.startswith(u'#'):
				try:
					return webcolors.rgb_to_hex(
						webcolors.hex_to_rgb(colorspec))
				except:
					raise osexception(u'Invalid color specification: %s' \
						% safe_decode(colorspec))
			if colorspec.startswith(u'rgb'):
				if u'%' in colorspec:
					l = colorspec[4:-1].split(u',')
					if len(l) != 3:
						raise osexception(u'Invalid color specification: %s' \
							% safe_decode(colorspec))
					for v in l:
						if u'%' not in v:
							raise osexception(
								u'Invalid color specification: %s' \
								% safe_decode(colorspec))
					try:
						l = tuple([v.strip() for v in l])
					except:
						raise osexception(u'Invalid color specification: %s' \
							% safe_decode(colorspec))
					return webcolors.rgb_percent_to_hex(l)
				l = colorspec[4:-1].split(u',')
				if len(l) != 3:
					raise osexception(u'Invalid color specification: %s' \
						% safe_decode(colorspec))
				try:
					l = tuple([int(v) for v in l])
				except:
					raise osexception(u'Invalid color specification: %s' \
						% safe_decode(colorspec))
				return webcolors.rgb_to_hex(l)
			try:
				return webcolors.name_to_hex(colorspec)
			except:
				raise osexception(u'Invalid color specification: %s' \
					% safe_decode(colorspec))
		raise osexception(
			u'Invalid color specification: %s' % safe_decode(colorspec))
Пример #9
0
    def to_hex(colorspec):
        """
		desc:
			Converts a color specificaton to a seven-character lowercase
			hexadecimal color string, such as '#ff0000'.

		arguments:
			colorspec:
				desc:	A color specification.
				type:	[str, unicode, array-like, int]

		returns:
			desc:	A hexadecimal color specification.
			type:	unicode
		"""
        is_rgb = (lambda c: hasattr(c, '__len__') and len(c) == 3 and all(
            isinstance(i, numbers.Integral) and 0 <= i <= 255 for i in c))

        if isinstance(colorspec, int):
            return webcolors.rgb_to_hex((colorspec, colorspec, colorspec))
        if is_rgb(colorspec):
            return webcolors.rgb_to_hex(colorspec)
        if isinstance(colorspec, basestring):
            try:
                colorspec = int(colorspec)
                return webcolors.rgb_to_hex((colorspec, colorspec, colorspec))
            except:
                pass
            if colorspec.startswith(u'#'):
                try:
                    return webcolors.rgb_to_hex(
                        webcolors.hex_to_rgb(colorspec))
                except:
                    raise osexception(u'Invalid color specification: %s' %
                                      safe_decode(colorspec))
            if colorspec.startswith(u'rgb'):
                if u'%' in colorspec:
                    l = colorspec[4:-1].split(u',')
                    if len(l) != 3:
                        raise osexception(u'Invalid color specification: %s' %
                                          safe_decode(colorspec))
                    for v in l:
                        if u'%' not in v:
                            raise osexception(
                                u'Invalid color specification: %s' %
                                safe_decode(colorspec))
                    try:
                        l = tuple([v.strip() for v in l])
                    except:
                        raise osexception(u'Invalid color specification: %s' %
                                          safe_decode(colorspec))
                    return webcolors.rgb_percent_to_hex(l)
                l = colorspec[4:-1].split(u',')
                if len(l) != 3:
                    raise osexception(u'Invalid color specification: %s' %
                                      safe_decode(colorspec))
                try:
                    l = tuple([int(v) for v in l])
                except:
                    raise osexception(u'Invalid color specification: %s' %
                                      safe_decode(colorspec))
                return webcolors.rgb_to_hex(l)
            try:
                return webcolors.name_to_hex(colorspec)
            except:
                raise osexception(u'Invalid color specification: %s' %
                                  safe_decode(colorspec))
        raise osexception(u'Invalid color specification: %s' %
                          safe_decode(colorspec))
Пример #10
0
	def to_hex(colorspec):

		"""
		desc:
			Converts a color specificaton to a seven-character lowercase
			hexadecimal color string, such as '#ff0000'.

		arguments:
			colorspec:
				desc:	A color specification.
				type:	[str, unicode, tuple, int]

		returns:
			desc:	A hexadecimal color specification.
			type:	unicode
		"""

		if isinstance(colorspec, int):
			return webcolors.rgb_to_hex((colorspec, colorspec, colorspec))
		if isinstance(colorspec, tuple):
			if len(colorspec) != 3:
				raise osexception(
					u'Invalid color specification: %s' % str(colorspec))
			for v in colorspec:
				if not isinstance(v, int):
					raise osexception(
						u'Invalid color specification: %s' % str(colorspec))
			return webcolors.rgb_to_hex(colorspec)
		if isinstance(colorspec, basestring):
			try:
				colorspec = int(colorspec)
				return webcolors.rgb_to_hex((colorspec, colorspec, colorspec))
			except:
				pass
			if colorspec.startswith(u'#'):
				try:
					return webcolors.rgb_to_hex(
						webcolors.hex_to_rgb(colorspec))
				except:
					raise osexception(
						u'Invalid color specification: %s' % colorspec)
			if colorspec.startswith(u'rgb'):
				if u'%' in colorspec:
					l = colorspec[4:-1].split(u',')
					if len(l) != 3:
						raise osexception(
							u'Invalid color specification: %s' % colorspec)
					for v in l:
						if u'%' not in v:
							raise osexception(
								u'Invalid color specification: %s' % colorspec)
					try:
						l = tuple([v.strip() for v in l])
					except:
						raise osexception(
							u'Invalid color specification: %s' % colorspec)
					return webcolors.rgb_percent_to_hex(l)
				l = colorspec[4:-1].split(u',')
				if len(l) != 3:
					raise osexception(
						u'Invalid color specification: %s' % colorspec)
				try:
					l = tuple([int(v) for v in l])
				except:
					raise osexception(
						u'Invalid color specification: %s' % colorspec)
				return webcolors.rgb_to_hex(l)
			try:
				return webcolors.name_to_hex(colorspec)
			except:
				raise osexception(
					u'Invalid color specification: %s' % colorspec)
		raise osexception(u'Invalid color specification: %s' % colorspec)