001/*
002 * (C) Copyright 2006-2007 Nuxeo SAS <http://nuxeo.com> and others
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Jean-Marc Orliaguet, Chalmers
011 *
012 * $Id$
013 */
014
015package org.nuxeo.theme.presets;
016
017import java.util.LinkedHashMap;
018import java.util.Map;
019import java.util.regex.Matcher;
020import java.util.regex.Pattern;
021
022public class GimpPaletteParser extends PaletteParser {
023
024    static final Pattern colorPattern = Pattern.compile("^\\s*(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3})\\t{0,1}(.*)$",
025            Pattern.MULTILINE);
026
027    public static boolean checkSanity(byte[] bytes) {
028        return new String(bytes).startsWith("GIMP Palette");
029    }
030
031    public static Map<String, String> parse(byte[] bytes) {
032        Map<String, String> entries = new LinkedHashMap<String, String>();
033        Matcher matcher = colorPattern.matcher(new String(bytes));
034        int counter = 1;
035        while (matcher.find()) {
036            String key = matcher.group(4).trim();
037            int r = Integer.parseInt(matcher.group(1));
038            int g = Integer.parseInt(matcher.group(2));
039            int b = Integer.parseInt(matcher.group(3));
040            String value = rgbToHex(r, g, b);
041            if (key.equals("Untitled")) {
042                key = String.format("Color %s", counter);
043            }
044            entries.put(key, value);
045            counter += 1;
046        }
047        return entries;
048    }
049}