| 1 | /******************************************************************************* |
| 2 | * Copyright (c) 2017 Ericsson |
| 3 | * |
| 4 | * All rights reserved. This program and the accompanying materials are |
| 5 | * made available under the terms of the Eclipse Public License v1.0 which |
| 6 | * accompanies this distribution, and is available at |
| 7 | * http://www.eclipse.org/legal/epl-v10.html |
| 8 | * |
| 9 | * Contributors: |
| 10 | * Patrick Tasse - Initial API and implementation |
| 11 | *******************************************************************************/ |
| 12 | |
| 13 | package org.eclipse.tracecompass.tmf.ui.colors; |
| 14 | |
| 15 | import java.io.BufferedReader; |
| 16 | import java.io.IOException; |
| 17 | import java.io.InputStreamReader; |
| 18 | import java.net.URL; |
| 19 | import java.util.HashMap; |
| 20 | import java.util.Map; |
| 21 | import java.util.regex.Matcher; |
| 22 | import java.util.regex.Pattern; |
| 23 | |
| 24 | import org.eclipse.swt.graphics.RGB; |
| 25 | import org.eclipse.tracecompass.internal.tmf.ui.Activator; |
| 26 | |
| 27 | /** |
| 28 | * A registry of named X11 colors. It maps certain strings to RGB color values. |
| 29 | * |
| 30 | * @see <a href= |
| 31 | * "http://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt">http://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt</a> |
| 32 | * |
| 33 | * @since 3.0 |
| 34 | */ |
| 35 | public class X11Color { |
| 36 | |
| 37 | private static final String X11_COLOR_FILE = "share/rgb.txt"; //$NON-NLS-1$ |
| 38 | private static final Pattern PATTERN = Pattern.compile("\\s*(\\d{1,3})\\s*(\\d{1,3})\\s*(\\d{1,3})\\s*(.*\\S)\\s*"); //$NON-NLS-1$ |
| 39 | private static final Map<String, RGB> COLORS = new HashMap<>(); |
| 40 | static { |
| 41 | URL url = Activator.getDefault().getBundle().getEntry(X11_COLOR_FILE); |
| 42 | try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()))) { |
| 43 | String line; |
| 44 | while ((line = reader.readLine()) != null) { |
| 45 | Matcher matcher = PATTERN.matcher(line); |
| 46 | if (matcher.matches()) { |
| 47 | int r = Integer.parseInt(matcher.group(1)); |
| 48 | int g = Integer.parseInt(matcher.group(2)); |
| 49 | int b = Integer.parseInt(matcher.group(3)); |
| 50 | RGB rgb = new RGB(r, g, b); |
| 51 | COLORS.put(matcher.group(4).toLowerCase(), rgb); |
| 52 | } |
| 53 | } |
| 54 | } catch (IOException e) { |
| 55 | e.printStackTrace(); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Get the RGB corresponding to a X11 color name. |
| 61 | * |
| 62 | * @param name |
| 63 | * the X11 color name (case insensitive) |
| 64 | * @return the corresponding RGB, or null |
| 65 | */ |
| 66 | public static RGB toRGB(String name) { |
| 67 | return COLORS.get(name.toLowerCase()); |
| 68 | } |
| 69 | } |