2 * Copyright (c) 2018-2019. Developed by Hedgecode.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.hedgecode.chess.img.piece;
20 import java.io.IOException;
21 import java.util.HashMap;
24 import javax.imageio.ImageIO;
26 import org.hedgecode.chess.img.AbstractImageLoader;
27 import org.hedgecode.chess.img.ImageConstants;
28 import org.hedgecode.chess.img.ImageException;
29 import org.hedgecode.chess.img.ImageFilter;
34 * @author Dmitry Samoshin aka gotty
36 public class PieceSetLoader extends AbstractImageLoader {
38 private static final File PIECES_PATH = new File(IMAGES_PATH, ImageConstants.RESOURCE_PIECES_DIR);
40 private static final String[] PIECES_NAMES = PieceSet.getAllPieceNames();
42 private Map<String, PieceSet> pieceSetMap = new HashMap<>();
45 public PieceSet load(String name) throws ImageException {
46 PieceSet pieceSet = null;
47 if (Type.STATELESS.equals(loadType()) || !pieceSetMap.containsKey(name)) {
48 File piecePath = new File(PIECES_PATH, name);
49 if (piecePath.exists() && piecePath.isDirectory()) {
50 pieceSet = loadPieces(piecePath);
52 if (Type.STATEFUL.equals(loadType()) && pieceSet != null) {
53 pieceSetMap.put(name, pieceSet);
56 pieceSet = pieceSetMap.get(name);
62 public void unload(String name) {
63 if (Type.STATEFUL.equals(loadType()) && pieceSetMap.containsKey(name)) {
64 pieceSetMap.remove(name);
69 protected void clear() {
73 private PieceSet loadPieces(File piecePath) throws ImageException {
74 PieceSet pieceSet = PieceSet.create();
75 File[] images = piecePath.listFiles(new ImageFilter(PIECES_NAMES));
77 for (File image : images) {
79 String filename = image.getName();
82 filename.substring(0, filename.lastIndexOf('.')),
85 } catch (IOException e) {
86 throw new ImageException(e.getMessage()); // todo: locale
91 return pieceSet.isFull() ? pieceSet : null;