def convert_and_reorder_colors(colors, settings_or_color_order): """Convert hex color strings to RGB tuples and reorder based on device color order. Args: colors: List of colors, either hex strings like "#FF0000" or RGB tuples like (255, 0, 0) settings_or_color_order: Either a Settings object or a color_order string (e.g., "rgb", "grb") Returns: List of RGB tuples reordered according to device color order """ # Get channel order from settings or color_order string if hasattr(settings_or_color_order, 'get_rgb_channel_order'): # It's a Settings object channel_order = settings_or_color_order.get_rgb_channel_order() elif isinstance(settings_or_color_order, str): # It's a color_order string, convert to channel order color_order = settings_or_color_order.lower() color_orders = { "rgb": (1, 3, 5), "rbg": (1, 5, 3), "grb": (3, 1, 5), "gbr": (3, 5, 1), "brg": (5, 1, 3), "bgr": (5, 3, 1) } hex_indices = color_orders.get(color_order, (1, 3, 5)) # Map hex string positions to RGB channel indices hex_to_channel = {1: 0, 3: 1, 5: 2} channel_order = tuple(hex_to_channel[pos] for pos in hex_indices) else: # Assume it's already a channel order tuple channel_order = settings_or_color_order converted_colors = [] for color in colors: try: # Convert "#RRGGBB" to (R, G, B) if isinstance(color, str) and color.startswith("#") and len(color) == 7: r = int(color[1:3], 16) g = int(color[3:5], 16) b = int(color[5:7], 16) rgb = (r, g, b) elif isinstance(color, (list, tuple)) and len(color) == 3: # Already a tuple/list, just coerce and clamp. rgb = tuple(max(0, min(255, int(x))) for x in color) else: # Unknown format: ignore safely. continue # Reorder based on device color order reordered = (rgb[channel_order[0]], rgb[channel_order[1]], rgb[channel_order[2]]) converted_colors.append(reordered) except (TypeError, ValueError, IndexError): # Skip malformed color entries to avoid crashing pattern loops. continue if not converted_colors: converted_colors.append((255, 255, 255)) return converted_colors