001/*
002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Jean-Marc Orliaguet, Chalmers
018 *
019 * $Id$
020 */
021
022package org.nuxeo.theme.presets;
023
024import java.util.LinkedHashMap;
025import java.util.Map;
026import java.util.regex.Matcher;
027import java.util.regex.Pattern;
028
029public class GimpPaletteParser extends PaletteParser {
030
031    static final Pattern colorPattern = Pattern.compile("^\\s*(\\d{1,3})\\s+(\\d{1,3})\\s+(\\d{1,3})\\t{0,1}(.*)$",
032            Pattern.MULTILINE);
033
034    public static boolean checkSanity(byte[] bytes) {
035        return new String(bytes).startsWith("GIMP Palette");
036    }
037
038    public static Map<String, String> parse(byte[] bytes) {
039        Map<String, String> entries = new LinkedHashMap<String, String>();
040        Matcher matcher = colorPattern.matcher(new String(bytes));
041        int counter = 1;
042        while (matcher.find()) {
043            String key = matcher.group(4).trim();
044            int r = Integer.parseInt(matcher.group(1));
045            int g = Integer.parseInt(matcher.group(2));
046            int b = Integer.parseInt(matcher.group(3));
047            String value = rgbToHex(r, g, b);
048            if (key.equals("Untitled")) {
049                key = String.format("Color %s", counter);
050            }
051            entries.put(key, value);
052            counter += 1;
053        }
054        return entries;
055    }
056}